about summary refs log tree commit diff stats
path: root/js/baba-yaga/index.js
diff options
context:
space:
mode:
Diffstat (limited to 'js/baba-yaga/index.js')
-rw-r--r--js/baba-yaga/index.js139
1 files changed, 89 insertions, 50 deletions
diff --git a/js/baba-yaga/index.js b/js/baba-yaga/index.js
index f663bf7..cd9da98 100644
--- a/js/baba-yaga/index.js
+++ b/js/baba-yaga/index.js
@@ -1,70 +1,109 @@
-
-// index.js
+// index.js - Main entry point for Baba Yaga (optimized by default)
 
 import fs from 'fs';
-import { createLexer } from './lexer.js';
-import { createParser } from './parser.js';
-import { createInterpreter } from './interpreter.js';
+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]');
+  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);
 }
 
-fs.readFile(filePath, 'utf8', (err, code) => {
+// 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);
   }
 
-  try {
-    const lexer = createLexer(code);
-    const tokens = lexer.allTokens();
-    
-    const parser = createParser(tokens, debugMode);
-    const ast = parser.parse();
-
-    const host = {
-      io: {
-        out: (...xs) => {
-          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(...xs.map(toDisplay));
-        },
-        in: () => {
-          try {
-            const data = fs.readFileSync(0, 'utf8');
-            return typeof data === 'string' ? data : String(data);
-          } catch {
-            return '';
+  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);
           }
-        },
-      },
-    };
-
-    const interpreter = createInterpreter(ast, host);
-    const result = interpreter.interpret();
+        }
+        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 !== undefined) {
-      console.log(result);
+  if (result.success) {
+    if (result.result !== undefined) {
+      console.log(result.result);
     }
-  } catch (error) {
-    console.error(error.message);
+    
+    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);
   }
-});
+});
\ No newline at end of file