-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutionEngine.ts
More file actions
279 lines (235 loc) · 8.49 KB
/
executionEngine.ts
File metadata and controls
279 lines (235 loc) · 8.49 KB
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
import { ExecutionState, Variable, StackFrame, CheckpointData } from '@/types/debugger';
import { analyzeObjectRelationships, generateGraphData } from './objectRelationshipAnalyzer';
import { evaluateSafeNumericExpression } from '@/lib/safeExpression';
const DEFAULT_STEP_DELAY_MS = 50;
export interface ExecuteCodeOptions {
/** Stop before executing line index `targetLine` (0-based line index in the split source). */
targetLine?: number;
signal?: AbortSignal;
stepDelayMs?: number;
}
/**
* Analyzes code to extract variable declarations and scope information
*/
export function analyzeCode(code: string): {
variables: string[],
functions: string[],
loops: {start: number, end: number}[]
} {
// Simple static analysis - in a real implementation, this would use a proper parser
const variables: string[] = [];
const functions: string[] = [];
const loops: {start: number, end: number}[] = [];
// Extract variable names (simplified implementation)
const varRegex = /\b(let|var|const)\s+([a-zA-Z_][a-zA-Z0-9_]*)/g;
let match;
while ((match = varRegex.exec(code)) !== null) {
variables.push(match[2]);
}
// Extract function names (simplified)
const fnRegex = /\bfunction\s+([a-zA-Z_][a-zA-Z0-9_]*)/g;
while ((match = fnRegex.exec(code)) !== null) {
functions.push(match[1]);
}
// Detect loops (simplified)
const lines = code.split('\n');
const openLoops: number[] = [];
lines.forEach((line, index) => {
if (line.includes('for (') || line.includes('while (')) {
openLoops.push(index);
}
if (line.includes('}') && openLoops.length > 0) {
const start = openLoops.pop()!;
loops.push({start, end: index});
}
});
return { variables, functions, loops };
}
/**
* Execute code with state tracking for reversible debugging
*/
export function executeCode(
code: string,
onStateChange: (state: ExecutionState) => void,
options?: ExecuteCodeOptions
): Promise<ExecutionState[]> {
return new Promise((resolve) => {
const states: ExecutionState[] = [];
const lines = code.split('\n');
// Scope management for nested function calls and blocks
const callStack: StackFrame[] = [
{ name: 'global', variables: {}, startLine: 0, returnLine: -1 }
];
// Initial execution environment
let currentScope = callStack[0];
let lineIndex = 0;
let isComplete = false;
// Process execution line by line
const stepDelay = options?.stepDelayMs ?? DEFAULT_STEP_DELAY_MS;
const processNextLine = () => {
if (options?.signal?.aborted) {
isComplete = true;
resolve(states);
return;
}
if (lineIndex >= lines.length || isComplete) {
isComplete = true;
resolve(states);
return;
}
if (options?.targetLine !== undefined && lineIndex > options.targetLine) {
resolve(states);
return;
}
const line = lines[lineIndex].trim();
// Skip empty lines and comments
if (line === '' || line.startsWith('//')) {
lineIndex++;
setTimeout(processNextLine, 0);
return;
}
// Simple execution simulation for variable assignments
// In a real implementation, this would use a proper interpreter
if (line.includes('=')) {
const parts = line.split('=').map(p => p.trim());
const varName = parts[0].replace('var ', '').replace('let ', '').replace('const ', '');
try {
const rhsRaw = parts[1].replace(';', '').trim();
let value: string | number = rhsRaw;
if (/^[\d+\-*/().\s]+$/.test(rhsRaw) && /[\d.]/.test(rhsRaw)) {
try {
value = evaluateSafeNumericExpression(rhsRaw);
} catch {
/* keep as string literal if not a pure numeric expression */
}
}
currentScope.variables[varName] = value;
const lastState = states[states.length - 1];
const prevFrame = lastState?.callStack[lastState.callStack.length - 1];
const prevVal = prevFrame?.variables[varName];
const variableChanged =
states.length > 0 && currentScope.variables[varName] !== prevVal;
// Build variable state for this execution step
const variableState: Variable[] = Object.entries(currentScope.variables).map(([name, value]) => ({
name,
value,
changed: name === varName && variableChanged
}));
// Generate object relationship graph
const relationships = analyzeObjectRelationships(variableState);
const graphData = generateGraphData(relationships);
// Create execution state snapshot
const newState: ExecutionState = {
line: lineIndex + 1,
variables: variableState,
callStack: JSON.parse(JSON.stringify(callStack)),
timestamp: new Date(),
memory: calculateMemoryUsage(currentScope.variables),
objectGraph: graphData
};
states.push(newState);
// Notify listener of state change
onStateChange(newState);
} catch (e) {
console.error(`Execution error at line ${lineIndex + 1}:`, e);
}
}
// Handle function calls (simplified)
if (line.includes('function')) {
const match = /function\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/.exec(line);
if (match) {
const fnName = match[1];
// Create new stack frame for function
const newFrame: StackFrame = {
name: fnName,
variables: {},
startLine: lineIndex,
returnLine: -1, // Will be set when function returns
};
callStack.push(newFrame);
currentScope = newFrame;
}
}
// Handle function returns (simplified)
if (line.includes('return')) {
if (callStack.length > 1) {
const returningFrame = callStack.pop()!;
returningFrame.returnLine = lineIndex;
currentScope = callStack[callStack.length - 1];
// In real implementation: handle return value assignment
}
}
lineIndex++;
setTimeout(processNextLine, stepDelay);
};
// Start execution process
processNextLine();
});
}
/**
* Calculate approximate memory usage of variables
* For scientific debugging, memory tracking is important
*/
function calculateMemoryUsage(variables: Record<string, unknown>): number {
let bytes = 0;
Object.entries(variables).forEach(([key, value]) => {
bytes += key.length * 2;
if (typeof value === 'string') {
bytes += value.length * 2;
} else if (typeof value === 'number') {
bytes += 8;
} else if (typeof value === 'boolean') {
bytes += 4;
} else if (Array.isArray(value)) {
bytes += 8 + value.length * 8;
} else if (typeof value === 'object' && value !== null) {
bytes += 8 + calculateMemoryUsage(value as Record<string, unknown>);
}
});
return bytes;
}
/**
* Create a checkpoint with full state information
*/
export function createCheckpoint(
state: ExecutionState,
sessionId: string,
notes?: string
): CheckpointData {
if (!state || !sessionId) {
throw new Error('Cannot create checkpoint: Missing execution state or session ID');
}
try {
// Create a deep copy of the state to prevent reference issues
const stateCopy = JSON.parse(JSON.stringify(state));
return {
id: `cp-${Date.now()}-${Math.floor(Math.random() * 1000)}`,
sessionId: sessionId,
lineNumber: state.line,
state: JSON.stringify(stateCopy),
timestamp: new Date(),
notes: notes || `Checkpoint at line ${state.line}`,
memorySnapshot: state.memory || 0
};
} catch (err) {
console.error('Error creating checkpoint:', err);
throw new Error('Failed to create checkpoint: ' + (err instanceof Error ? err.message : 'Unknown error'));
}
}
/**
* Restore execution state from a checkpoint
*/
export function restoreFromCheckpoint(
checkpoint: CheckpointData
): ExecutionState {
try {
if (!checkpoint || !checkpoint.state) {
throw new Error('Invalid checkpoint data');
}
const state = JSON.parse(checkpoint.state) as ExecutionState;
return state;
} catch (e) {
console.error('Error restoring from checkpoint:', e);
throw new Error('Failed to restore execution state from checkpoint');
}
}