about summary refs log tree commit diff stats
path: root/js/baba-yaga/index.js
blob: cd9da9890c4248c7c5fc06ee9439483eea049219 (plain) (blame)
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
// index.js - Main entry point for Baba Yaga (optimized by default)

import fs from 'fs';
import { BabaYagaEngine, createEngine } from './src/core/engine.js';
import { BabaYagaConfig } from './src/core/config.js';

const filePath = process.argv[2];
const debugMode = process.argv.includes('--debug');
const profileMode = process.argv.includes('--profile');
const strictMode = process.argv.includes('--strict');
const legacyMode = process.argv.includes('--legacy');

if (!filePath) {
  console.error('Usage: bun run index.js <file_path> [--debug] [--profile] [--strict] [--legacy]');
  console.error('');
  console.error('Options:');
  console.error('  --debug     Enable verbose debugging output');
  console.error('  --profile   Show detailed performance timing');
  console.error('  --strict    Enable strict mode validation');
  console.error('  --legacy    Use legacy (non-optimized) engine');
  process.exit(1);
}

// Create configuration based on command line flags
const config = new BabaYagaConfig({
  enableOptimizations: false, // Optimizations disabled by default due to lexer bug
  enableDebugMode: debugMode,
  enableProfiling: profileMode,
  strictMode: strictMode,
  showTimings: profileMode,
  verboseErrors: true,
  colorOutput: true
});

const engine = new BabaYagaEngine(config);

fs.readFile(filePath, 'utf8', async (err, code) => {
  if (err) {
    console.error(`Error reading file: ${err.message}`);
    process.exit(1);
  }

  const result = await engine.execute(code, {
    filename: filePath,
    onOutput: (...args) => {
      const toDisplay = (arg) => {
        if (arg && typeof arg.value === 'number') return arg.value;
        if (Array.isArray(arg)) return JSON.stringify(arg.map(toDisplay));
        if (arg && typeof arg === 'object') {
          // Pretty-print known runtime objects
          if (arg.type === 'NativeFunction' || arg.type === 'Function') return '<fn>';
          if (arg.type === 'Result') return `${arg.variant} ${toDisplay(arg.value)}`;
          if (arg.type === 'Object' && arg.properties instanceof Map) {
            const obj = Object.fromEntries(Array.from(arg.properties.entries()).map(([k,v]) => [k, toDisplay(v)]));
            return JSON.stringify(obj);
          }
        }
        return String(arg);
      };
      console.log(...args.map(toDisplay));
    },
    onInput: () => {
      try {
        const data = fs.readFileSync(0, 'utf8');
        return typeof data === 'string' ? data : String(data);
      } catch {
        return '';
      }
    }
  });

  if (result.success) {
    if (result.result !== undefined) {
      console.log(result.result);
    }
    
    if (profileMode) {
      const stats = engine.getStats();
      console.error(`\n[PROFILE] Execution time: ${result.executionTime.toFixed(2)}ms`);
      if (result.breakdown) {
        console.error(`[PROFILE] Breakdown: Lex ${result.breakdown.lexingTime.toFixed(2)}ms, Parse ${result.breakdown.parsingTime.toFixed(2)}ms, Interpret ${result.breakdown.interpretingTime.toFixed(2)}ms`);
      }
      console.error(`[PROFILE] Total executions: ${stats.totalExecutions}`);
      console.error(`[PROFILE] Average time: ${stats.averageTime.toFixed(2)}ms`);
      
      if (stats.optimizations && config.enableOptimizations) {
        console.error(`[PROFILE] Built-in optimizations: ${(stats.optimizations.builtinOptimizationRate * 100).toFixed(1)}%`);
        console.error(`[PROFILE] AST pool hit rate: ${(stats.optimizations.astPoolHitRate * 100).toFixed(1)}%`);
      }
    }
    
    if (debugMode && config.enableOptimizations) {
      console.error('\n[DEBUG] Optimizations enabled - using high-performance engine');
    } else if (debugMode && !config.enableOptimizations) {
      console.error('\n[DEBUG] Legacy mode - using original engine');
    }
  } else {
    console.error(result.error);
    
    if (debugMode && result.suggestions?.length > 0) {
      console.error('\nSuggestions:');
      result.suggestions.forEach(suggestion => {
        console.error(`  - ${suggestion}`);
      });
    }
    
    process.exit(1);
  }
});