Ast Binding

This commit is contained in:
Michael Schimmel
2025-09-04 01:41:09 +02:00
parent de052cab64
commit 9c90a92b04
6 changed files with 394 additions and 382 deletions
+140 -271
View File
@@ -28,7 +28,8 @@ uses
Myc.Ast.Evaluator,
Myc.Ast.Printer,
FMX.Layouts,
FMX.Objects; // Added for TExecutionScope
FMX.Objects,
Myc.Ast.Scope; // Added for TExecutionScope
type
// A test record
@@ -80,6 +81,8 @@ type
FWorkspace: TAuraWorkspace;
function CreateVisitor(const AScope: IExecutionScope): IAstVisitor;
procedure WorkspaceMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
// New helper function to encapsulate the Bind -> Evaluate pattern
function ExecuteAst(const ANode: IExpressionNode; const AScope: IExecutionScope): TAstValue;
public
{ Public declarations }
end;
@@ -90,7 +93,7 @@ var
implementation
uses
Myc.Ast.Scope,
// Myc.Ast.Scope is now in the interface uses
Myc.Data.Scalar.JSON,
Myc.Data.Decimal,
System.Diagnostics; // For TStopwatch
@@ -115,6 +118,17 @@ begin
Result := TEvaluatorVisitor.Create(AScope);
end;
function TForm1.ExecuteAst(const ANode: IExpressionNode; const AScope: IExecutionScope): TAstValue;
begin
// STEP 1: BIND
// The binder uses the provided scope to know about native functions etc.
TAst.Bind(ANode, AScope);
// STEP 2: EVALUATE
var visitor := CreateVisitor(AScope);
Result := ANode.Accept(visitor);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FWorkspace := TAuraWorkspace.Create(Panel2);
@@ -124,7 +138,9 @@ begin
FWorkspace.OnMouseDown := WorkspaceMouseDown;
// Create and prepare the global scope once
FGScope := TExecutionScope.Create(nil);
RegisterNativeFunctions(FGScope);
end;
procedure TForm1.DebugButtonClick(Sender: TObject);
@@ -137,7 +153,6 @@ begin
if not Assigned(FLastAst) then
begin
Memo1.Lines.Add('No AST has been generated yet.');
Memo1.Lines.Add('Click "Test 1" or "Test 2" first.');
exit;
end;
@@ -146,7 +161,9 @@ begin
Memo1.Lines.Clear;
Memo1.Lines.Add('--- Debug Evaluator Trace ---');
// This button ALWAYS uses the debug visitor, regardless of the checkbox.
// Manually bind and evaluate to use the debug visitor
TAst.Bind(FLastAst, scope);
visitor := TDebugEvaluatorVisitor.Create(scope, Memo1.Lines, ShowScopeBox.IsChecked, 0);
sw := TStopwatch.StartNew;
@@ -156,67 +173,18 @@ begin
Memo1.Lines.Add('-----------------------------');
Memo1.Lines.Add(Format('Final script result: %s', [result.ToString]));
Memo1.Lines.Add(Format('Execution time: %d ms', [sw.ElapsedMilliseconds]));
Memo1.Lines.Add('');
Memo1.Lines.Add('(AST structure stored. Click "Pretty Print" to view.)');
end;
procedure TForm1.FibonacciButtonClick(Sender: TObject);
function NativeFib(n: Integer): Int64;
begin
// The identical, naive recursive algorithm in native Delphi code.
if (n < 2) then
Result := n
else
Result := NativeFib(n - 1) + NativeFib(n - 2);
end;
var
scope: IExecutionScope;
visitor: IAstVisitor;
root: IExpressionNode;
result: TAstValue;
sw: TStopwatch;
result20, result30, result40: Int64;
time20, time30, time40: Int64;
scope: IExecutionScope;
begin
FGScope.Clear;
Memo1.Lines.Clear;
Memo1.Lines.Add('--- Native Delphi Fibonacci Performance ---');
Memo1.Lines.Add('Calculating fib(30) and fib(40)...');
Application.ProcessMessages; // Update UI before blocking
// --- Calculate fib(30) ---
sw := TStopwatch.StartNew;
result20 := NativeFib(20);
sw.Stop;
time20 := sw.ElapsedMilliseconds;
// --- Calculate fib(30) ---
sw := TStopwatch.StartNew;
result30 := NativeFib(30);
sw.Stop;
time30 := sw.ElapsedMilliseconds;
// --- Calculate fib(40) ---
sw.Reset;
sw.Start;
result40 := NativeFib(40);
sw.Stop;
time40 := sw.ElapsedMilliseconds;
sw.Reset;
Memo1.Lines.Add('');
Memo1.Lines.Add(Format('fib(20) = %d (calculated in %d ms)', [result20, time20]));
Memo1.Lines.Add(Format('fib(30) = %d (calculated in %d ms)', [result30, time30]));
Memo1.Lines.Add(Format('fib(40) = %d (calculated in %d ms)', [result40, time40]));
Memo1.Lines.Add('');
Memo1.Lines.Add('');
Memo1.Lines.Add('--- Recursive fib with AST---');
Application.ProcessMessages; // Update UI before blocking
sw.Start;
sw := TStopwatch.StartNew;
root :=
TAst.Block(
@@ -225,12 +193,9 @@ begin
TAst.Identifier('fib'),
TAst.LambdaExpr(
[TAst.Identifier('n')],
// The body is now a single ternary expression that returns a value.
TAst.TernaryExpr(
TAst.BinaryExpr(TAst.Identifier('n'), boLess, TAst.Constant(TScalar.FromInt64(2))),
// The value if true.
TAst.Identifier('n'),
// The value if false.
TAst.BinaryExpr(
TAst.FunctionCall(
TAst.Identifier('fib'),
@@ -250,21 +215,17 @@ begin
);
FLastAst := root;
scope := TExecutionScope.Create(nil);
scope := TExecutionScope.Create(nil); // No global scope needed for this pure function
result := ExecuteAst(root, scope);
visitor := CreateVisitor(scope);
result := root.Accept(visitor);
sw.Stop;
Memo1.Lines.Add(Format('Result: fib(30) %s (calculated in %d ms)', [result.ToString, sw.ElapsedMilliseconds]));
Memo1.Lines.Add('');
Memo1.Lines.Add('(AST structure stored. Click "Pretty Print" or "Debug" to view.)');
end;
procedure TForm1.PrettyPrintButtonClick(Sender: TObject);
var
visitor: TPrettyPrintVisitor;
sw: TStopwatch;
begin
Memo1.Lines.Clear;
Memo1.Lines.Add('--- AST Pretty Print ---');
@@ -272,38 +233,24 @@ begin
if not Assigned(FLastAst) then
begin
Memo1.Lines.Add('No AST has been generated yet.');
Memo1.Lines.Add('Click "Test 1" or "Test 2" first.');
exit;
end;
visitor := TPrettyPrintVisitor.Create;
try
sw := TStopwatch.StartNew;
FLastAst.Accept(visitor);
sw.Stop;
Memo1.Lines.Add(visitor.GetResult);
Memo1.Lines.Add(Format('(AST rendered in %d ms)', [sw.ElapsedMilliseconds]));
finally
// Visitor is an interfaced object and managed automatically.
end;
FLastAst.Accept(visitor);
Memo1.Lines.Add(visitor.GetResult);
end;
procedure TForm1.RecursionButtonClick(Sender: TObject);
var
scope: IExecutionScope;
visitor: IAstVisitor;
root: IExpressionNode;
result: TAstValue;
sw: TStopwatch;
scope: IExecutionScope;
begin
FGScope.Clear;
sw := TStopwatch.Create;
Memo1.Lines.Clear;
Memo1.Lines.Add('--- Recursive factorial(20) ---');
sw.Start;
sw := TStopwatch.StartNew;
root :=
TAst.Block(
@@ -312,21 +259,17 @@ begin
TAst.Identifier('factorial'),
TAst.LambdaExpr(
[TAst.Identifier('n')],
TAst.Block(
[
TAst.TernaryExpr(
TAst.BinaryExpr(TAst.Identifier('n'), boLess, TAst.Constant(TScalar.FromInt64(2))),
TAst.Constant(TScalar.FromInt64(1)),
TAst.BinaryExpr(
TAst.Identifier('n'),
boMultiply,
TAst.FunctionCall(
TAst.Identifier('factorial'),
[TAst.BinaryExpr(TAst.Identifier('n'), boSubtract, TAst.Constant(TScalar.FromInt64(1)))]
)
)
TAst.TernaryExpr(
TAst.BinaryExpr(TAst.Identifier('n'), boLess, TAst.Constant(TScalar.FromInt64(2))),
TAst.Constant(TScalar.FromInt64(1)),
TAst.BinaryExpr(
TAst.Identifier('n'),
boMultiply,
TAst.FunctionCall(
TAst.Identifier('factorial'),
[TAst.BinaryExpr(TAst.Identifier('n'), boSubtract, TAst.Constant(TScalar.FromInt64(1)))]
)
]
)
)
)
),
@@ -337,43 +280,31 @@ begin
FLastAst := root;
scope := TExecutionScope.Create(nil);
visitor := CreateVisitor(scope);
result := root.Accept(visitor);
sw.Stop;
result := ExecuteAst(root, scope);
sw.Stop;
Memo1.Lines.Add(Format('Result: %s (calculated in %d ms)', [result.ToString, sw.ElapsedMilliseconds]));
Memo1.Lines.Add('');
Memo1.Lines.Add('(AST structure stored. Click "Pretty Print" or "Debug" to view.)');
end;
procedure TForm1.SeriesTestButtonClick(Sender: TObject);
var
jsonDef: string;
recordDef: TScalarRecordDefinition;
series: TScalarRecordSeries;
recordValue: TScalarRecord;
visitor: IAstVisitor;
ast: IExpressionNode;
scope: IExecutionScope;
ast, callAst: IExpressionNode;
resultValue: TAstValue;
series: TScalarRecordSeries;
recordDef: TScalarRecordDefinition;
i: Integer;
begin
Memo1.Lines.Clear;
Memo1.Lines.Add('--- Series Test ---');
// --- 1. Arrange (in Delphi) ---
Memo1.Lines.Add('1. Arranging test data in Delphi...');
FGScope.Clear;
RegisterNativeFunctions(FGScope);
jsonDef := TRttiAstHelper.RecordDefinitionToJson(TypeInfo(TOHLCV));
FGScope.SetValue('ohlcvDef', TAstValue.FromText(jsonDef));
Memo1.Lines.Add(' - Generated and injected JSON definition for TOHLCV.');
recordDef := TRttiAstHelper.JsonToRecordDefinition(jsonDef);
// 1. Arrange: Create a new scope and populate it with Delphi data
scope := TExecutionScope.Create(FGScope); // Inherits native functions
recordDef := TRttiAstHelper.JsonToRecordDefinition(TRttiAstHelper.RecordDefinitionToJson(TypeInfo(TOHLCV)));
series := TScalarRecordSeries.Create(recordDef);
for i := 0 to 4 do
begin
recordValue :=
series.Add(
TScalarRecord.Create(
recordDef,
[
@@ -384,17 +315,12 @@ begin
TScalarValue.FromDouble(102.0 + i),
TScalarValue.FromInt64(10000 * (i + 1))
]
);
series.Add(recordValue);
)
);
end;
scope.Define('ohlcvSeries', TAstValue.FromRecordSeries(series));
FGScope.SetValue('ohlcvSeries', TAstValue.FromRecordSeries(series));
Memo1.Lines.Add(Format(' - Created and injected a series with %d records.', [series.TotalCount]));
Memo1.Lines.Add('');
// --- 2. Act (in Script) ---
Memo1.Lines.Add('2. Executing script...');
// 2. Act: Define and execute the script AST
ast :=
TAst.LambdaExpr(
[],
@@ -404,69 +330,31 @@ begin
TAst.Identifier('closeColumn'),
TAst.MemberAccess(TAst.Identifier('ohlcvSeries'), TAst.Identifier('Close'))
),
TAst.VarDecl(
TAst.Identifier('secondClose'),
TAst.Indexer(TAst.Identifier('closeColumn'), TAst.Constant(TScalar.FromInt64(1)))
)
TAst.Indexer(TAst.Identifier('closeColumn'), TAst.Constant(TScalar.FromInt64(1)))
]
)
);
FLastAst := ast;
callAst := TAst.FunctionCall(ast, []);
resultValue := ExecuteAst(callAst, scope);
visitor := CreateVisitor(FGScope);
resultValue := TAst.FunctionCall(ast, []).Accept(visitor);
Memo1.Lines.Add(' - Script finished.');
Memo1.Lines.Add(Format(' - Script returned value of type: %s', [GetEnumName(TypeInfo(TAstValueKind), Ord(resultValue.Kind))]));
Memo1.Lines.Add('');
// --- 3. Assert (in Delphi) ---
Memo1.Lines.Add('3. Asserting results in Delphi...');
if (resultValue.Kind <> avkScalar) then
begin
Memo1.Lines.Add('TEST FAILED: Script did not return a scalar value.');
exit;
end;
Memo1.Lines.Add(' - Result is a scalar, as expected.');
var resultScalar := resultValue.AsScalar;
if (resultScalar.Kind <> skDouble) then
begin
Memo1.Lines.Add('TEST FAILED: Returned scalar is not a Double.');
exit;
end;
Memo1.Lines.Add(' - Returned scalar is a Double, as expected.');
var closeValue := resultScalar.Value.AsDouble;
// The script asks for index [1], which is the second-to-last element.
// The data was generated for i in 0..4, so the second-to-last is i=3.
var expectedClose := 102.0 + 3;
if (abs(closeValue - expectedClose) > 0.001) then
begin
Memo1.Lines.Add(Format('TEST FAILED: Expected Close price %f, but got %f.', [expectedClose, closeValue]));
exit;
end;
Memo1.Lines.Add(Format(' - Verified Close price: %f.', [closeValue]));
Memo1.Lines.Add('');
Memo1.Lines.Add('--- TEST PASSED ---');
// 3. Assert (logging only)
Memo1.Lines.Add(Format('Result of script: %s', [resultValue.ToString]));
end;
procedure TForm1.Test1ButtonClick(Sender: TObject);
var
scope: IExecutionScope;
visitor: IAstVisitor;
main, callAst: IExpressionNode;
result: TAstValue;
sw: TStopwatch;
scope: IExecutionScope;
begin
FGScope.Clear;
sw := TStopwatch.Create;
Memo1.Lines.Clear;
Memo1.Lines.Add('--- Simple AST Execution ---');
sw := TStopwatch.StartNew;
sw.Start;
var main :=
main :=
TAst.LambdaExpr(
[],
TAst.Block(
@@ -482,35 +370,25 @@ begin
);
FLastAst := main;
callAst := TAst.FunctionCall(main, []);
scope := TExecutionScope.Create(FGScope);
visitor := CreateVisitor(scope);
result := TAst.FunctionCall(main, []).Accept(visitor);
sw.Stop;
result := ExecuteAst(callAst, scope);
if not result.IsVoid then
Memo1.Lines.Add(Format('Result: %s (calculated in %d ms)', [result.ToString, sw.ElapsedMilliseconds]))
else
Memo1.Lines.Add(Format('<undefined result> (calculated in %d ms)', [sw.ElapsedMilliseconds]));
Memo1.Lines.Add('');
Memo1.Lines.Add('(AST structure stored. Click "Pretty Print" to view.)');
sw.Stop;
Memo1.Lines.Add(Format('Result: %s (calculated in %d ms)', [result.ToString, sw.ElapsedMilliseconds]));
end;
procedure TForm1.Test2ButtonClick(Sender: TObject);
var
scope: IExecutionScope;
visitor: IAstVisitor;
root: IExpressionNode;
result: TAstValue;
sw: TStopwatch;
scope: IExecutionScope;
begin
FGScope.Clear;
sw := TStopwatch.Create;
Memo1.Lines.Clear;
Memo1.Lines.Add('--- Factory Pattern Demo ---');
sw.Start;
sw := TStopwatch.StartNew;
root :=
TAst.Block(
@@ -533,34 +411,26 @@ begin
);
FLastAst := root;
scope := TExecutionScope.Create(FGScope);
visitor := CreateVisitor(scope);
result := root.Accept(visitor);
sw.Stop;
result := ExecuteAst(root, scope);
Memo1.Lines.Add('The entire script has been executed.');
sw.Stop;
Memo1.Lines.Add(Format('Result of the final expression: %s (calculated in %d ms)', [result.ToString, sw.ElapsedMilliseconds]));
Memo1.Lines.Add('');
Memo1.Lines.Add('(AST structure stored. Click "Pretty Print" to view.)');
end;
procedure TForm1.CrerateTriggerExampleButtonClick(Sender: TObject);
var
visitor: IAstVisitor;
closureValue: TAstValue;
blk: IExpressionNode;
begin
// This button now only creates the AST. The persistent scope is managed by FGScope.
FGScope.Clear;
// Create an AST that gets a "tick" in DoTriggerButtonClick.
// This simulates a simple Blueprint-like event system.
// It maintains state via a persistent execution scope.
RegisterNativeFunctions(FGScope); // Re-register natives after clearing
Memo1.Lines.Clear;
Memo1.Lines.Add('--- Creating Trigger Blueprint ---');
var blk :=
blk :=
TAst.Block(
[
TAst.VarDecl(TAst.Identifier('X'), TAst.Constant(TScalar.FromInt64(0))),
@@ -574,77 +444,65 @@ begin
]
);
// Evaluate the lambda to create a closure and store it in the scope.
// The closure captures the scope where 'X' is defined.
visitor := CreateVisitor(FGScope);
blk.Accept(visitor);
// Bind and execute the setup block against the persistent global scope
ExecuteAst(blk, FGScope);
// FLastAst is not used for this parameterized example.
FLastAst := blk;
FLastAst := blk; // Store for visualization
Memo1.Lines.Add('Variable "X" initialized to 0 in persistent scope.');
Memo1.Lines.Add('Blueprint function "tickHandler(summand)" created.');
Memo1.Lines.Add('Click "Do Trigger" or "Do Trigger 2" to execute.');
Memo1.Lines.Add('Variable "X" and function "tickHandler" defined in persistent scope.');
Memo1.Lines.Add('Click "Do Trigger" to execute.');
end;
procedure TForm1.DoTriggerButtonClick(Sender: TObject);
var
visitor: IAstVisitor;
currentValue: TAstValue;
callAst: IFunctionCallNode;
currentValue: TAstValue;
depth, index: Integer;
identAst: IIdentifierNode;
begin
// A "tick" executes the stored AST using the persistent scope.
// Create an AST to call the stored handler with argument 1.
// AST for: tickHandler(1)
callAst := TAst.FunctionCall(TAst.Identifier('tickHandler'), [TAst.Constant(TScalar.FromInt64(1))]);
// Execute the call AST.
visitor := CreateVisitor(FGScope);
callAst.Accept(visitor);
FLastAst := callAst;
// Get the updated value of 'X' from the scope and display it.
if FGScope.FindValue('X', currentValue) then
// Bind and execute the call against the persistent scope
ExecuteAst(callAst, FGScope);
// To get the value of 'X', we first need to bind an identifier for it
// so we know its location.
identAst := TAst.Identifier('X');
TAst.Bind(identAst, FGScope);
if identAst.Resolve(depth, index) then
begin
currentValue := FGScope.GetValue(depth, index);
Memo1.Lines.Add(Format('Tick(1)! New value of X: %s', [currentValue.ToString]));
end
else
begin
// This should not happen if setup was correct.
Memo1.Lines.Add('Error: Variable "X" not found in scope.');
end;
end;
procedure TForm1.DoTrigger2ButtonClick(Sender: TObject);
var
visitor: IAstVisitor;
currentValue: TAstValue;
callAst: IFunctionCallNode;
currentValue: TAstValue;
depth, index: Integer;
identAst: IIdentifierNode;
begin
// A "tick" that adds 2, using the same blueprint function.
// Create an AST to call the stored handler with argument 2.
// AST for: tickHandler(2)
callAst := TAst.FunctionCall(TAst.Identifier('tickHandler'), [TAst.Constant(TScalar.FromInt64(2))]);
FLastAst := callAst;
// Execute the call AST.
visitor := CreateVisitor(FGScope);
callAst.Accept(visitor);
// Bind and execute the call against the persistent scope
ExecuteAst(callAst, FGScope);
// Get the updated value of 'X' from the scope and display it.
if FGScope.FindValue('X', currentValue) then
// Inspection requires binding an identifier for 'X'
identAst := TAst.Identifier('X');
TAst.Bind(identAst, FGScope);
if identAst.Resolve(depth, index) then
begin
currentValue := FGScope.GetValue(depth, index);
Memo1.Lines.Add(Format('Tick(2)! New value of X: %s', [currentValue.ToString]));
end
else
begin
// This should not happen if setup was correct.
Memo1.Lines.Add('Error: Variable "X" not found in scope.');
end;
end;
procedure TForm1.WorkspaceMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
@@ -663,22 +521,22 @@ end;
procedure TForm1.OHLCButtonClick(Sender: TObject);
const
numRecs = 1000;
lookback = 50;
smaSlowLength = 20;
smaFastLength = 5;
numRecs = 1000000;
lookback = 100;
smaSlowLength = 50;
smaFastLength = 20;
var
recordDef: TScalarRecordDefinition;
series: TScalarRecordSeries;
setupAst: IExpressionNode;
callAst: IExpressionNode;
setupAst, callAst: IExpressionNode;
visitor: IAstVisitor;
i: Integer;
i, depth, index: Integer;
lastClose: Double;
ohlcvRec: TOHLCV;
recordValue: TScalarRecord;
resultValue: TAstValue;
sw: TStopwatch;
currentSeriesIdent: IIdentifierNode;
begin
// 1. Setup
Memo1.Lines.Clear;
@@ -687,14 +545,10 @@ begin
RegisterNativeFunctions(FGScope);
sw := TStopwatch.StartNew;
recordDef := TRttiAstHelper.JsonToRecordDefinition(TRttiAstHelper.RecordDefinitionToJson(TypeInfo(TOHLCV)));
series := TScalarRecordSeries.Create(recordDef);
// 2. Create the setup AST with the optimized O(1) SMA implementation
// 2. Create the setup AST with the strategy logic
setupAst :=
TAst.Block(
[
// This factory is now much simpler. It only manages sum and a counter.
TAst.VarDecl(
TAst.Identifier('CreateSMA'),
TAst.LambdaExpr(
@@ -703,7 +557,6 @@ begin
[
TAst.VarDecl(TAst.Identifier('sum'), TAst.Constant(TScalar.FromDouble(0.0))),
TAst.VarDecl(TAst.Identifier('count'), TAst.Constant(TScalar.FromInt64(0))),
// The returned closure now takes the full series and the new value.
TAst.LambdaExpr(
[TAst.Identifier('series'), TAst.Identifier('val')],
TAst.Block(
@@ -716,7 +569,6 @@ begin
TAst.Identifier('count'),
TAst.BinaryExpr(TAst.Identifier('count'), boAdd, TAst.Constant(TScalar.FromInt64(1)))
),
// If the indicator is "full", subtract the value that just fell out of the window (at index 'len').
TAst.IfExpr(
TAst.BinaryExpr(TAst.Identifier('count'), boGreater, TAst.Identifier('len')),
TAst.Assign(
@@ -729,7 +581,6 @@ begin
),
nil
),
// Calculate and return the average. Divisor is capped at 'len'.
TAst.BinaryExpr(
TAst.Identifier('sum'),
boDivide,
@@ -746,7 +597,6 @@ begin
)
)
),
// Instantiation remains the same.
TAst.VarDecl(
TAst.Identifier('smaFast'),
TAst.FunctionCall(TAst.Identifier('CreateSMA'), [TAst.Constant(TScalar.FromInt64(smaFastLength))])
@@ -755,7 +605,6 @@ begin
TAst.Identifier('smaSlow'),
TAst.FunctionCall(TAst.Identifier('CreateSMA'), [TAst.Constant(TScalar.FromInt64(smaSlowLength))])
),
// The main strategy now passes the full close series to the indicators.
TAst.VarDecl(
TAst.Identifier('maCrossStrategy'),
TAst.LambdaExpr(
@@ -795,13 +644,30 @@ begin
)
]
);
FLastAst := setupAst;
visitor := CreateVisitor(FGScope);
setupAst.Accept(visitor);
callAst := TAst.FunctionCall(TAst.Identifier('maCrossStrategy'), [TAst.Identifier('current_series')]);
// Bind and execute the setup script once.
ExecuteAst(setupAst, FGScope);
// 3. Simulation Loop
// 3. Prepare for the simulation loop
recordDef := TRttiAstHelper.JsonToRecordDefinition(TRttiAstHelper.RecordDefinitionToJson(TypeInfo(TOHLCV)));
series := TScalarRecordSeries.Create(recordDef);
visitor := CreateVisitor(FGScope);
// Declare the series variable in the scope BEFORE binding the call AST
FGScope.Define('current_series', TAstValue.Void);
// Create the call AST that will be executed in the loop
currentSeriesIdent := TAst.Identifier('current_series');
callAst := TAst.FunctionCall(TAst.Identifier('maCrossStrategy'), [currentSeriesIdent]);
// Bind the call AST once, before the loop.
TAst.Bind(callAst, FGScope);
// Get the resolved address of 'current_series' for fast updates
if not currentSeriesIdent.Resolve(depth, index) then
raise EInvalidOpException.Create('Could not resolve loop variable ''current_series''.');
// 4. Simulation Loop
Memo1.Lines.Add('Starting simulation...');
Application.ProcessMessages;
@@ -836,11 +702,14 @@ begin
if series.TotalCount >= smaSlowLength then
begin
FGScope.SetValue('current_series', TAstValue.FromRecordSeries(series));
// Update the 'current_series' value in the scope using the FAST index-based assignment
FGScope.AssignValue(depth, index, TAstValue.FromRecordSeries(series));
// Execute the PRE-BOUND call AST
resultValue := callAst.Accept(visitor);
Memo1.Lines.Add(Format('Tick %d/%d: Close = %.2f, Signal = %s', [i, numRecs, ohlcvRec.Close, resultValue.ToString]));
Application.ProcessMessages;
// Memo1.Lines.Add(Format('Tick %d/%d: Close = %.2f, Signal = %s', [i, numRecs, ohlcvRec.Close, resultValue.ToString]));
// Application.ProcessMessages;
end;
end;