442 lines
14 KiB
ObjectPascal
442 lines
14 KiB
ObjectPascal
unit Myc.Ast.Compiler.Macros;
|
|
|
|
interface
|
|
|
|
uses
|
|
System.SysUtils,
|
|
System.Classes,
|
|
System.Generics.Collections,
|
|
Myc.Data.Scalar,
|
|
Myc.Data.Value,
|
|
Myc.Ast.Nodes,
|
|
Myc.Ast.Visitor,
|
|
Myc.Ast.Scope,
|
|
Myc.Ast.Types,
|
|
Myc.Ast,
|
|
Myc.Ast.Environment;
|
|
|
|
type
|
|
IAstMacroExpander = interface(IAstVisitor)
|
|
function Execute(const RootNode: IAstNode): IAstNode;
|
|
end;
|
|
|
|
TEvaluateProc = reference to function(const Node: IAstNode): TDataValue;
|
|
|
|
TExpansionVisitor = class(TAstTransformer)
|
|
private
|
|
FEvaluate: TEvaluateProc;
|
|
FMacroScope: IExecutionScope;
|
|
FRenameMap: TDictionary<string, string>;
|
|
class var
|
|
FGensymCounter: Int64;
|
|
|
|
function TransformAndSpliceNodes(const ANodes: TArray<IAstNode>): TArray<IAstNode>;
|
|
function Gensym(const ABaseName: string): string;
|
|
protected
|
|
function VisitUnquote(const Node: IUnquoteNode): IAstNode; override;
|
|
function VisitUnquoteSplicing(const Node: IUnquoteSplicingNode): IAstNode; override;
|
|
function VisitFunctionCall(const Node: IFunctionCallNode): IAstNode; override;
|
|
function VisitBlockExpression(const Node: IBlockExpressionNode): IAstNode; override;
|
|
function VisitRecordLiteral(const Node: IRecordLiteralNode): IAstNode; override;
|
|
|
|
function VisitVariableDeclaration(const Node: IVariableDeclarationNode): IAstNode; override;
|
|
function VisitLambdaExpression(const Node: ILambdaExpressionNode): IAstNode; override;
|
|
function VisitIdentifier(const Node: IIdentifierNode): IAstNode; override;
|
|
public
|
|
constructor Create(const AMacroScope: IExecutionScope; const AEvaluate: TEvaluateProc);
|
|
destructor Destroy; override;
|
|
|
|
class function Expand(const MacroScope: IExecutionScope; const RootNode: IAstNode; const AEvaluate: TEvaluateProc): IAstNode;
|
|
end;
|
|
|
|
TMacroExpander = class(TAstTransformer, IAstMacroExpander)
|
|
private
|
|
FInitialScope: IExecutionScope;
|
|
FCurrentMacroRegistry: IMacroRegistry;
|
|
FEvaluatorFactory: TEvaluatorFactory;
|
|
|
|
procedure EnterMacroScope;
|
|
procedure ExitMacroScope;
|
|
|
|
protected
|
|
function VisitMacroDefinition(const Node: IMacroDefinitionNode): IAstNode; override;
|
|
function VisitFunctionCall(const Node: IFunctionCallNode): IAstNode; override;
|
|
|
|
function VisitQuasiquote(const Node: IQuasiquoteNode): IAstNode; override;
|
|
function VisitUnquote(const Node: IUnquoteNode): IAstNode; override;
|
|
function VisitUnquoteSplicing(const Node: IUnquoteSplicingNode): IAstNode; override;
|
|
|
|
function VisitBlockExpression(const Node: IBlockExpressionNode): IAstNode; override;
|
|
function VisitLambdaExpression(const Node: ILambdaExpressionNode): IAstNode; override;
|
|
|
|
public
|
|
constructor Create(
|
|
const ARootRegistry: IMacroRegistry;
|
|
const AInitialScope: IExecutionScope;
|
|
const AEvaluatorFactory: TEvaluatorFactory
|
|
);
|
|
destructor Destroy; override;
|
|
|
|
function Execute(const RootNode: IAstNode): IAstNode;
|
|
|
|
class function ExpandMacros(
|
|
const ARootRegistry: IMacroRegistry;
|
|
const AInitialScope: IExecutionScope;
|
|
const RootNode: IAstNode;
|
|
const EvaluatorFactory: TEvaluatorFactory
|
|
): IAstNode; static;
|
|
end;
|
|
|
|
implementation
|
|
|
|
uses
|
|
System.Generics.Defaults,
|
|
System.SyncObjs,
|
|
Myc.Ast.Compiler.Binder,
|
|
Myc.Ast.Evaluator,
|
|
Myc.Data.Keyword;
|
|
|
|
{ TExpansionVisitor }
|
|
|
|
constructor TExpansionVisitor.Create(const AMacroScope: IExecutionScope; const AEvaluate: TEvaluateProc);
|
|
begin
|
|
inherited Create;
|
|
FMacroScope := AMacroScope;
|
|
FEvaluate := AEvaluate;
|
|
FRenameMap := TDictionary<string, string>.Create;
|
|
end;
|
|
|
|
destructor TExpansionVisitor.Destroy;
|
|
begin
|
|
FRenameMap.Free;
|
|
inherited;
|
|
end;
|
|
|
|
function TExpansionVisitor.Gensym(const ABaseName: string): string;
|
|
begin
|
|
if not FRenameMap.TryGetValue(ABaseName, Result) then
|
|
begin
|
|
var count := TInterlocked.Add(FGensymCounter, 1);
|
|
if count < 0 then
|
|
count := -count;
|
|
Result := ABaseName + '#' + count.ToString;
|
|
FRenameMap.Add(ABaseName, Result);
|
|
end;
|
|
end;
|
|
|
|
class function TExpansionVisitor.Expand(
|
|
const MacroScope: IExecutionScope;
|
|
const RootNode: IAstNode;
|
|
const AEvaluate: TEvaluateProc
|
|
): IAstNode;
|
|
begin
|
|
var expander := TExpansionVisitor.Create(MacroScope, AEvaluate);
|
|
try
|
|
Result := expander.Accept(RootNode);
|
|
finally
|
|
expander.Free;
|
|
end;
|
|
end;
|
|
|
|
function TExpansionVisitor.TransformAndSpliceNodes(const ANodes: TArray<IAstNode>): TArray<IAstNode>;
|
|
var
|
|
newList: TList<IAstNode>;
|
|
nodeToSplice: IAstNode;
|
|
transformedNode: IAstNode;
|
|
begin
|
|
newList := TList<IAstNode>.Create;
|
|
try
|
|
for var node in ANodes do
|
|
begin
|
|
if node.Kind = akUnquoteSplicing then
|
|
begin
|
|
var spliceExpr := node.AsUnquoteSplicing.Expression;
|
|
var evaluatedSpliceValue := FEvaluate(spliceExpr);
|
|
|
|
if (not evaluatedSpliceValue.IsVoid) and (evaluatedSpliceValue.Kind = vkInterface) then
|
|
begin
|
|
nodeToSplice := evaluatedSpliceValue.AsIntf<IAstNode>;
|
|
if nodeToSplice.Kind = akBlockExpression then
|
|
newList.AddRange(nodeToSplice.AsBlockExpression.Expressions)
|
|
else
|
|
newList.Add(nodeToSplice);
|
|
end
|
|
else if (not evaluatedSpliceValue.IsVoid) then
|
|
begin
|
|
newList.Add(TAst.Constant(evaluatedSpliceValue));
|
|
end;
|
|
end
|
|
else
|
|
begin
|
|
transformedNode := Self.Accept(node);
|
|
if Assigned(transformedNode) then
|
|
newList.Add(transformedNode);
|
|
end;
|
|
end;
|
|
Result := newList.ToArray;
|
|
finally
|
|
newList.Free;
|
|
end;
|
|
end;
|
|
|
|
function TExpansionVisitor.VisitIdentifier(const Node: IIdentifierNode): IAstNode;
|
|
var
|
|
newName: string;
|
|
begin
|
|
if FRenameMap.TryGetValue(Node.Name, newName) then
|
|
begin
|
|
Result := TAst.Identifier(newName, TTypes.Unknown);
|
|
exit;
|
|
end;
|
|
Result := Node;
|
|
end;
|
|
|
|
function TExpansionVisitor.VisitVariableDeclaration(const Node: IVariableDeclarationNode): IAstNode;
|
|
var
|
|
newName: string;
|
|
newIdent: IIdentifierNode;
|
|
newInit: IAstNode;
|
|
begin
|
|
newInit := Accept(Node.Initializer);
|
|
newName := Gensym(Node.Identifier.Name);
|
|
newIdent := TAst.Identifier(newName, TTypes.Unknown);
|
|
Result := TAst.VarDecl(newIdent, newInit, TTypes.Unknown);
|
|
end;
|
|
|
|
function TExpansionVisitor.VisitLambdaExpression(const Node: ILambdaExpressionNode): IAstNode;
|
|
var
|
|
newParams: TArray<IIdentifierNode>;
|
|
newBody: IAstNode;
|
|
newName: string;
|
|
i: Integer;
|
|
begin
|
|
SetLength(newParams, Length(Node.Parameters));
|
|
for i := 0 to High(Node.Parameters) do
|
|
begin
|
|
newName := Gensym(Node.Parameters[i].Name);
|
|
newParams[i] := TAst.Identifier(newName, TTypes.Unknown);
|
|
end;
|
|
|
|
newBody := Accept(Node.Body);
|
|
|
|
Result := TAst.LambdaExpr(newParams, newBody, nil, nil, nil, False, Node.IsPure, TTypes.Unknown);
|
|
end;
|
|
|
|
function TExpansionVisitor.VisitUnquote(const Node: IUnquoteNode): IAstNode;
|
|
var
|
|
value: TDataValue;
|
|
expr: IAstNode;
|
|
addr: TResolvedAddress;
|
|
begin
|
|
expr := Node.Expression;
|
|
|
|
if expr.Kind = akIdentifier then
|
|
begin
|
|
addr := FMacroScope.Resolve(expr.AsIdentifier.Name);
|
|
|
|
if (addr.Kind = akLocalOrParent) and (addr.ScopeDepth = 0) then
|
|
begin
|
|
var argValue := FMacroScope.Values[addr];
|
|
if argValue.Kind = vkInterface then
|
|
begin
|
|
Result := argValue.AsIntf<IAstNode>;
|
|
exit;
|
|
end;
|
|
end;
|
|
end;
|
|
|
|
value := FEvaluate(expr);
|
|
|
|
if value.Kind = vkInterface then
|
|
begin
|
|
Result := value.AsIntf<IAstNode>;
|
|
exit;
|
|
end;
|
|
|
|
if value.Kind in [vkScalar, vkText, vkVoid] then
|
|
Result := TAst.Constant(value)
|
|
else
|
|
raise Exception.CreateFmt('Cannot unquote complex runtime value of type %s at compile time.', [value.Kind.ToString]);
|
|
end;
|
|
|
|
function TExpansionVisitor.VisitUnquoteSplicing(const Node: IUnquoteSplicingNode): IAstNode;
|
|
begin
|
|
raise Exception.Create('Unquote-splicing (`~@`) can only appear inside a list form.');
|
|
end;
|
|
|
|
function TExpansionVisitor.VisitFunctionCall(const Node: IFunctionCallNode): IAstNode;
|
|
var
|
|
newArgs: TArray<IAstNode>;
|
|
transformedCallee: IAstNode;
|
|
begin
|
|
transformedCallee := Self.Accept(Node.Callee);
|
|
newArgs := TransformAndSpliceNodes(Node.Arguments);
|
|
Result := TAst.FunctionCall(transformedCallee, newArgs);
|
|
end;
|
|
|
|
function TExpansionVisitor.VisitBlockExpression(const Node: IBlockExpressionNode): IAstNode;
|
|
var
|
|
newExprs: TArray<IAstNode>;
|
|
begin
|
|
newExprs := TransformAndSpliceNodes(Node.Expressions);
|
|
Result := TAst.Block(newExprs);
|
|
end;
|
|
|
|
function TExpansionVisitor.VisitRecordLiteral(const Node: IRecordLiteralNode): IAstNode;
|
|
begin
|
|
Result := inherited VisitRecordLiteral(Node);
|
|
end;
|
|
|
|
{ TMacroExpander }
|
|
|
|
constructor TMacroExpander.Create(
|
|
const ARootRegistry: IMacroRegistry;
|
|
const AInitialScope: IExecutionScope;
|
|
const AEvaluatorFactory: TEvaluatorFactory
|
|
);
|
|
begin
|
|
inherited Create;
|
|
FInitialScope := AInitialScope;
|
|
FEvaluatorFactory := AEvaluatorFactory;
|
|
FCurrentMacroRegistry := ARootRegistry.CreateChildRegistry;
|
|
end;
|
|
|
|
destructor TMacroExpander.Destroy;
|
|
begin
|
|
inherited Destroy;
|
|
end;
|
|
|
|
procedure TMacroExpander.EnterMacroScope;
|
|
begin
|
|
FCurrentMacroRegistry := FCurrentMacroRegistry.CreateChildRegistry;
|
|
end;
|
|
|
|
procedure TMacroExpander.ExitMacroScope;
|
|
begin
|
|
FCurrentMacroRegistry := FCurrentMacroRegistry.Parent;
|
|
end;
|
|
|
|
class function TMacroExpander.ExpandMacros(
|
|
const ARootRegistry: IMacroRegistry;
|
|
const AInitialScope: IExecutionScope;
|
|
const RootNode: IAstNode;
|
|
const EvaluatorFactory: TEvaluatorFactory
|
|
): IAstNode;
|
|
begin
|
|
var expander := TMacroExpander.Create(ARootRegistry, AInitialScope, EvaluatorFactory) as IAstMacroExpander;
|
|
Result := expander.Execute(RootNode);
|
|
end;
|
|
|
|
function TMacroExpander.Execute(const RootNode: IAstNode): IAstNode;
|
|
begin
|
|
Result := Accept(RootNode);
|
|
if not Assigned(Result) then
|
|
Result := TAst.Block([]);
|
|
end;
|
|
|
|
function TMacroExpander.VisitBlockExpression(const Node: IBlockExpressionNode): IAstNode;
|
|
begin
|
|
EnterMacroScope;
|
|
try
|
|
Result := inherited VisitBlockExpression(Node);
|
|
finally
|
|
ExitMacroScope;
|
|
end;
|
|
end;
|
|
|
|
function TMacroExpander.VisitLambdaExpression(const Node: ILambdaExpressionNode): IAstNode;
|
|
begin
|
|
EnterMacroScope;
|
|
try
|
|
Result := inherited VisitLambdaExpression(Node);
|
|
finally
|
|
ExitMacroScope;
|
|
end;
|
|
end;
|
|
|
|
function TMacroExpander.VisitMacroDefinition(const Node: IMacroDefinitionNode): IAstNode;
|
|
begin
|
|
FCurrentMacroRegistry.Define(Node);
|
|
Result := Node;
|
|
end;
|
|
|
|
function TMacroExpander.VisitFunctionCall(const Node: IFunctionCallNode): IAstNode;
|
|
var
|
|
calleeIdentifier: IIdentifierNode;
|
|
macroDef: IMacroDefinitionNode;
|
|
i: Integer;
|
|
begin
|
|
if Node.Callee.Kind <> akIdentifier then
|
|
exit(inherited VisitFunctionCall(Node));
|
|
|
|
calleeIdentifier := Node.Callee.AsIdentifier;
|
|
macroDef := FCurrentMacroRegistry.Find(calleeIdentifier.Name);
|
|
if macroDef = nil then
|
|
exit(inherited VisitFunctionCall(Node));
|
|
|
|
// --- Macro Expansion ---
|
|
|
|
// 1. Create temporary scope for macro arguments (parented to Initial/Global Scope)
|
|
var expansionScope := TScope.CreateScope(FInitialScope, nil, nil);
|
|
|
|
var params := macroDef.Parameters;
|
|
if Length(Node.Arguments) <> Length(params) then
|
|
raise Exception.CreateFmt('Macro %s expects %d arguments.', [calleeIdentifier.Name, Length(params)]);
|
|
|
|
// 2. Populate scope
|
|
for i := 0 to High(params) do
|
|
expansionScope.Define(params[i].Name, TDataValue.FromIntf<IAstNode>(Node.Arguments[i]));
|
|
|
|
// 3. Create Evaluator Callback
|
|
var evaluatorProc: TEvaluateProc;
|
|
evaluatorProc :=
|
|
function(const ANodeToEvaluate: IAstNode): TDataValue
|
|
var
|
|
tmpLayout: IScopeLayout;
|
|
scratchScope: IExecutionScope;
|
|
evaluator: IEvaluatorVisitor;
|
|
boundSubAst: IAstNode;
|
|
begin
|
|
// A. BINDING
|
|
// The Binder creates a virtual child scope builder.
|
|
// Symbols in expansionScope will have ScopeDepth = 1.
|
|
// We access the layout via the descriptor (which for dynamic scopes is created on demand/proxy).
|
|
// Note: expansionScope is dynamic, so its Descriptor.Layout reflects current variables.
|
|
boundSubAst := TAstBinder.Bind(expansionScope.Descriptor.Layout, ANodeToEvaluate, tmpLayout);
|
|
|
|
// B. SCOPE MATCHING (The Fix)
|
|
// We must execute in a child scope so that ScopeDepth = 1 correctly points to expansionScope.
|
|
scratchScope := TScope.CreateScope(expansionScope, nil, nil);
|
|
|
|
// C. EXECUTION
|
|
evaluator := FEvaluatorFactory(scratchScope);
|
|
Result := evaluator.Execute(boundSubAst);
|
|
end;
|
|
|
|
// 4. Expand Body
|
|
var expandedBody := TExpansionVisitor.Expand(expansionScope, macroDef.Body.AsQuasiquote.Expression, evaluatorProc);
|
|
|
|
// 5. Wrap result
|
|
var macroNode := TAst.MacroExpansionNode(Node, expandedBody);
|
|
|
|
// 6. Re-expand result
|
|
Result := Self.Accept(macroNode);
|
|
end;
|
|
|
|
function TMacroExpander.VisitQuasiquote(const Node: IQuasiquoteNode): IAstNode;
|
|
begin
|
|
Result := Node;
|
|
end;
|
|
|
|
function TMacroExpander.VisitUnquote(const Node: IUnquoteNode): IAstNode;
|
|
begin
|
|
raise Exception.Create('Unquote (`~`) can only be used inside a quasiquote.');
|
|
end;
|
|
|
|
function TMacroExpander.VisitUnquoteSplicing(const Node: IUnquoteSplicingNode): IAstNode;
|
|
begin
|
|
raise Exception.Create('Unquote-splicing (`~@`) can only be used inside a quasiquote.');
|
|
end;
|
|
|
|
end.
|