Immutable infered types

This commit is contained in:
Michael Schimmel
2025-11-04 22:10:11 +01:00
parent f73c0c67b8
commit 980919525b
6 changed files with 395 additions and 271 deletions
+194 -121
View File
@@ -22,11 +22,10 @@ type
// This transformer runs *after* the TAstBinder.
// It takes the "Bound AST" (which has addresses but mostly TTypes.Unknown)
// and traverses it bottom-up to infer and check all static types.
// It modifies the node.StaticType property and updates the IScopeDescriptor.
// It *replaces* all IAstTypedNodes with new nodes containing the correct type.
TTypeChecker = class(TAstTransformer, IAstTypeChecker)
private
FCurrentDescriptor: IScopeDescriptor;
function SetType(const Node: IAstNode; const AType: IStaticType): IAstNode;
protected
// Override all visit methods to perform type checking
function VisitIdentifier(const Node: IIdentifierNode): IAstNode; override;
@@ -88,24 +87,13 @@ begin
Result := Accept(RootNode); // Use IAstNode-returning Accept
if not Assigned(Result) then
Result := TAst.Block([]);
// (Result as TAstNode).StaticType is set by the last Visit call
end;
function TTypeChecker.SetType(const Node: IAstNode; const AType: IStaticType): IAstNode;
begin
if Assigned(Node) then
(Node as TAstNode).StaticType := AType;
Result := Node;
end;
function TTypeChecker.VisitConstant(const Node: IConstantNode): IAstNode;
var
constType: IStaticType;
begin
// This is a leaf node, call inherited (does nothing)
Result := inherited VisitConstant(Node);
// This is a leaf node.
// Assign the type based on the literal value
case Node.Value.Kind of
TDataValueKind.vkScalar: constType := TTypes.FromScalarKind(Node.Value.AsScalar.Kind);
@@ -115,34 +103,44 @@ begin
constType := TTypes.Unknown;
end;
Result := SetType(Result, constType);
// Create a new node with the correct type
Result := TConstantNode.Create(Node.Value, constType);
end;
function TTypeChecker.VisitKeyword(const Node: IKeywordNode): IAstNode;
begin
// This is a leaf node
Result := inherited VisitKeyword(Node);
Result := SetType(Result, TTypes.Keyword);
// This is a leaf node.
// The TKeywordNode constructor *forces* the type to be TTypes.Keyword.
Result := TKeywordNode.Create(Node.Value);
end;
function TTypeChecker.VisitIdentifier(const Node: IIdentifierNode): IAstNode;
var
symbol: TResolvedSymbol;
adr: TResolvedAddress;
begin
// This is a leaf node (guaranteed to be IBoundIdentifierNode)
Result := inherited VisitIdentifier(Node);
// This is a leaf node (guaranteed to be IBoundIdentifierNode by Binder)
// Get the type from the descriptor (which was populated by Binder/RTL)
symbol := FCurrentDescriptor.FindSymbol(Node.Name);
Result := SetType(Result, symbol.StaticType);
adr := Node.AsBoundIdentifierNode.Address;
// Create a new node, copying the address and assigning the inferred type
Result := TBoundIdentifierNode.Create(Node.Name, adr, symbol.StaticType);
end;
function TTypeChecker.VisitRecurNode(const Node: IRecurNode): IAstNode;
var
newArgs: TArray<IAstNode>;
i: Integer;
begin
// Visit children first
Result := inherited VisitRecurNode(Node);
// Recur always results in Void (it never returns)
Result := SetType(Result, TTypes.Void);
// 1. Visit children
SetLength(newArgs, Length(Node.Arguments));
for i := 0 to High(Node.Arguments) do
newArgs[i] := Accept(Node.Arguments[i]);
// 2. Create new node with inferred type
Result := TRecurNode.Create(newArgs, TTypes.Void);
end;
function TTypeChecker.VisitMacroDefinition(const Node: IMacroDefinitionNode): IAstNode;
@@ -159,43 +157,55 @@ end;
function TTypeChecker.VisitVariableDeclaration(const Node: IVariableDeclarationNode): IAstNode;
var
initType: IStaticType;
newInitializer, newIdent: IAstNode;
boundIdent: IIdentifierNode;
adr: TResolvedAddress;
N: TVariableDeclarationNode;
begin
// 1. Visit children first (Identifier is leaf, Initializer is traversed)
inherited;
// 1. Visit Initializer first (if it exists)
if Assigned(Node.Initializer) then
newInitializer := Accept(Node.Initializer)
else
newInitializer := nil;
// 2. Get initializer type
if Assigned(Node.Initializer) then
initType := (Node.Initializer as TAstNode).StaticType
if Assigned(newInitializer) then
initType := newInitializer.AsTypedNode.StaticType
else
initType := TTypes.Unknown; // <-- This was TTypes.Void
initType := TTypes.Unknown; // (def fib)
// 3. Get the address from the bound identifier (SAFE CAST)
boundIdent := Node.Identifier;
adr := boundIdent.AsBoundIdentifierNode.Address;
// 4. Update the type in the scope descriptor (which was set to Unknown by the binder).
// Only update if we have a concrete type (not the default Unknown).
if initType.Kind <> stUnknown then
FCurrentDescriptor.UpdateType(adr.SlotIndex, initType);
// 5. Update the static types of the nodes themselves.
(boundIdent as TAstNode).StaticType := initType;
Result := SetType(Node, initType);
// 5. Create the new (typed) identifier node
newIdent := TBoundIdentifierNode.Create(boundIdent.Name, adr, initType);
// 6. Create the new VariableDeclaration node
Result := TVariableDeclarationNode.Create(newIdent.AsIdentifier, newInitializer, initType);
// 7. Copy runtime flags (IsBoxed)
N := (Result as TVariableDeclarationNode);
N.IsBoxed := (Node as TVariableDeclarationNode).IsBoxed;
end;
function TTypeChecker.VisitAssignment(const Node: IAssignmentNode): IAstNode;
var
targetType, sourceType: IStaticType;
newIdent, newValue: IAstNode;
adr: TResolvedAddress;
begin
// 1. Visit children first (Identifier, Value)
inherited;
newValue := Accept(Node.Value);
newIdent := Accept(Node.Identifier);
// 2. Get types
targetType := (Node.Identifier as TAstNode).StaticType;
sourceType := (Node.Value as TAstNode).StaticType;
targetType := newIdent.AsTypedNode.StaticType;
sourceType := newValue.AsTypedNode.StaticType;
// 3. Check assignment
if not TTypeRules.CanAssign(targetType, sourceType) then
@@ -205,19 +215,23 @@ begin
// with the new, inferred type. This enables recursion.
if (targetType.Kind = stUnknown) and (sourceType.Kind <> stUnknown) then
begin
adr := Node.Identifier.AsBoundIdentifierNode.Address;
adr := newIdent.AsBoundIdentifierNode.Address;
FCurrentDescriptor.UpdateType(adr.SlotIndex, sourceType);
// Re-set the identifier's node type (it was visited *before* this)
(Node.Identifier as TAstNode).StaticType := sourceType;
// Re-create the identifier node *with the new type*
newIdent := TBoundIdentifierNode.Create(newIdent.AsIdentifier.Name, adr, sourceType);
targetType := sourceType;
end;
Result := SetType(Node, targetType);
// 5. Create the new Assignment node
Result := TAssignmentNode.Create(newIdent.AsIdentifier, newValue, targetType);
end;
function TTypeChecker.VisitLambdaExpression(const Node: ILambdaExpressionNode): IAstNode;
var
boundNode: TLambdaExpressionNode;
newParams: TArray<IIdentifierNode>;
newBody: IAstNode;
bodyType, methodType: IStaticType;
paramTypes: TArray<IStaticType>;
i: Integer;
@@ -229,58 +243,77 @@ begin
savedDescriptor := FCurrentDescriptor;
FCurrentDescriptor := boundNode.ScopeDescriptor;
try
// 2. Parameters are leaves, so we don't try to evaluate them
// 3. Get parameter types (currently Unknown, but required for signature)
// 2. Visit parameters (they are already bound, just need typing)
SetLength(newParams, Length(boundNode.Parameters));
SetLength(paramTypes, Length(boundNode.Parameters));
for i := 0 to High(boundNode.Parameters) do
paramTypes[i] := (boundNode.Parameters[i] as TAstNode).StaticType; // Propagates Unknown
begin
// Parameters are leaves, but we must *replace* them with typed versions
// (even if they are just TTypes.Unknown for now, for type inference placeholders)
var paramIdent := boundNode.Parameters[i];
var paramAdr := paramIdent.AsBoundIdentifierNode.Address;
var newParam := TBoundIdentifierNode.Create(paramIdent.Name, paramAdr, TTypes.Unknown);
// 4. Visit the body to infer its return type
Accept(boundNode.Body);
bodyType := (boundNode.Body as TAstNode).StaticType;
newParams[i] := newParam;
paramTypes[i] := TTypes.Unknown;
end;
// 5. Create the final method type
// 3. Visit the body to infer its return type
newBody := Accept(boundNode.Body);
bodyType := newBody.AsTypedNode.StaticType;
// 4. Create the final method type
methodType := TTypes.CreateMethod(paramTypes, bodyType);
// 6. Update the type for <self> (Slot 0) in the descriptor
// 5. Update the type for <self> (Slot 0) in the descriptor
FCurrentDescriptor.UpdateType(0, methodType);
finally
// 7. Restore parent descriptor
// 6. Restore parent descriptor
FCurrentDescriptor := savedDescriptor;
end;
// 8. Set the type of the lambda node itself
Result := SetType(boundNode, methodType);
// 7. Create the new (typed) lambda node
Result := TLambdaExpressionNode.Create(newParams, newBody, methodType);
// 8. Copy runtime properties
var newLambda := (Result as TLambdaExpressionNode);
newLambda.ScopeDescriptor := boundNode.ScopeDescriptor;
newLambda.Upvalues := boundNode.Upvalues;
newLambda.HasNestedLambdas := boundNode.HasNestedLambdas;
end;
function TTypeChecker.VisitFunctionCall(const Node: IFunctionCallNode): IAstNode;
var
calleeType, retType: IStaticType;
i: Integer;
newCallee: IAstNode;
newArgs: TArray<IAstNode>;
begin
// 1. Visit children first (bottom-up)
inherited;
newCallee := Accept(Node.Callee);
SetLength(newArgs, Length(Node.Arguments));
for i := 0 to High(Node.Arguments) do
newArgs[i] := Accept(Node.Arguments[i]);
// 2. Get callee type (now inferred)
calleeType := (Node.Callee as TAstNode).StaticType;
calleeType := newCallee.AsTypedNode.StaticType;
retType := TTypes.Unknown; // Default if not a method
// 3. Perform type checking
if calleeType.Kind = TStaticTypeKind.stMethod then
begin
var signature := calleeType.Signature;
if Length(Node.Arguments) <> Length(signature.ParamTypes) then
raise ETypeException
.CreateFmt('Function expects %d arguments, but got %d', [Length(signature.ParamTypes), Length(Node.Arguments)]);
if Length(newArgs) <> Length(signature.ParamTypes) then
raise ETypeException.CreateFmt('Function expects %d arguments, but got %d', [Length(signature.ParamTypes), Length(newArgs)]);
retType := signature.ReturnType;
// Check argument types
for i := 0 to High(Node.Arguments) do
for i := 0 to High(newArgs) do
begin
var argType := (Node.Arguments[i] as TAstNode).StaticType;
var argType := newArgs[i].AsTypedNode.StaticType;
var paramType := signature.ParamTypes[i];
if not TTypeRules.CanAssign(paramType, argType) then
raise ETypeException
@@ -290,109 +323,136 @@ begin
else if calleeType.Kind <> TStaticTypeKind.stUnknown then
raise ETypeException.CreateFmt('Cannot invoke type %s as a function.', [calleeType.ToString]);
// 4. Set the type for this call node
Result := SetType(Node, retType);
// 4. Create the new (typed) call node
Result := TFunctionCallNode.Create(newCallee, newArgs, retType);
// 5. Copy runtime properties
(Result as TFunctionCallNode).IsTailCall := (Node as TFunctionCallNode).IsTailCall;
end;
function TTypeChecker.VisitBlockExpression(const Node: IBlockExpressionNode): IAstNode;
var
blockType: IStaticType;
newExprs: TArray<IAstNode>;
i: Integer;
begin
// 1. Visit children
inherited;
SetLength(newExprs, Length(Node.Expressions));
for i := 0 to High(Node.Expressions) do
newExprs[i] := Accept(Node.Expressions[i]);
// 2. Type is type of last expression
if Length(Node.Expressions) > 0 then
blockType := (Node.Expressions[High(Node.Expressions)] as TAstNode).StaticType
if Length(newExprs) > 0 then
blockType := newExprs[High(newExprs)].AsTypedNode.StaticType
else
blockType := TTypes.Void;
Result := SetType(Node, blockType);
// 3. Create new node
Result := TBlockExpressionNode.Create(newExprs, blockType);
end;
function TTypeChecker.VisitIfExpression(const Node: IIfExpressionNode): IAstNode;
var
conditionType, thenType, elseType, resultType: IStaticType;
newCond, newThen, newElse: IAstNode;
begin
// 1. Visit children
inherited;
newCond := Accept(Node.Condition);
newThen := Accept(Node.ThenBranch);
newElse := Accept(Node.ElseBranch); // Accept handles nil
// 2. Check condition
conditionType := (Node.Condition as TAstNode).StaticType;
conditionType := newCond.AsTypedNode.StaticType;
if (conditionType.Kind <> stUnknown) and not TTypeRules.CanAssign(TTypes.Ordinal, conditionType) then
raise ETypeException.CreateFmt('If condition must be Ordinal, but got %s', [conditionType.ToString]);
// 3. Promote branch types
thenType := (Node.ThenBranch as TAstNode).StaticType;
thenType := newThen.AsTypedNode.StaticType;
elseType :=
if Node.ElseBranch <> nil then (Node.ElseBranch as TAstNode).StaticType
if newElse <> nil then newElse.AsTypedNode.StaticType
else TTypes.Void;
resultType := TTypeRules.Promote(thenType, elseType);
Result := SetType(Node, resultType);
// 4. Create new node
Result := TIfExpressionNode.Create(newCond, newThen, newElse, resultType);
end;
function TTypeChecker.VisitTernaryExpression(const Node: ITernaryExpressionNode): IAstNode;
var
conditionType, thenType, elseType, resultType: IStaticType;
newCond, newThen, newElse: IAstNode;
begin
// 1. Visit children
inherited;
newCond := Accept(Node.Condition);
newThen := Accept(Node.ThenBranch);
newElse := Accept(Node.ElseBranch);
// 2. Check condition
conditionType := (Node.Condition as TAstNode).StaticType;
conditionType := newCond.AsTypedNode.StaticType;
if (conditionType.Kind <> stUnknown) and not TTypeRules.CanAssign(TTypes.Ordinal, conditionType) then
raise ETypeException.CreateFmt('Ternary condition must be Ordinal, but got %s', [conditionType.ToString]);
// 3. Promote branch types
thenType := (Node.ThenBranch as TAstNode).StaticType;
elseType := (Node.ElseBranch as TAstNode).StaticType;
thenType := newThen.AsTypedNode.StaticType;
elseType := newElse.AsTypedNode.StaticType;
resultType := TTypeRules.Promote(thenType, elseType);
Result := SetType(Node, resultType);
// 4. Create new node
Result := TTernaryExpressionNode.Create(newCond, newThen, newElse, resultType);
end;
function TTypeChecker.VisitBinaryExpression(const Node: IBinaryExpressionNode): IAstNode;
var
leftType, rightType, resultType: IStaticType;
newLeft, newRight: IAstNode;
begin
// 1. Visit children
inherited;
newLeft := Accept(Node.Left);
newRight := Accept(Node.Right);
// 2. Get types
leftType := (Node.Left as TAstNode).StaticType;
rightType := (Node.Right as TAstNode).StaticType;
leftType := newLeft.AsTypedNode.StaticType;
rightType := newRight.AsTypedNode.StaticType;
// 3. Resolve
resultType := TTypeRules.ResolveBinaryOp(Node.Operator, leftType, rightType);
Result := SetType(Node, resultType);
// 4. Create new node
Result := TBinaryExpressionNode.Create(newLeft, Node.Operator, newRight, resultType);
end;
function TTypeChecker.VisitUnaryExpression(const Node: IUnaryExpressionNode): IAstNode;
var
rightType, resultType: IStaticType;
newRight: IAstNode;
begin
// 1. Visit children
inherited;
newRight := Accept(Node.Right);
// 2. Get types
rightType := (Node.Right as TAstNode).StaticType;
rightType := newRight.AsTypedNode.StaticType;
// 3. Resolve
resultType := TTypeRules.ResolveUnaryOp(Node.Operator, rightType);
Result := SetType(Node, resultType);
// 4. Create new node
Result := TUnaryExpressionNode.Create(Node.Operator, newRight, resultType);
end;
function TTypeChecker.VisitMemberAccess(const Node: IMemberAccessNode): IAstNode;
var
baseType, elemType: IStaticType;
fieldIndex: Integer;
newBase, newMember: IAstNode;
begin
// 1. Visit children
inherited;
newBase := Accept(Node.Base);
newMember := Accept(Node.Member); // Visits the TKeywordNode
// 2. Get types
baseType := (Node.Base as TAstNode).StaticType;
baseType := newBase.AsTypedNode.StaticType;
elemType := TTypes.Unknown;
// 3. Resolve
@@ -425,19 +485,22 @@ begin
end;
end;
Result := SetType(Node, elemType);
// 4. Create new node
Result := TMemberAccessNode.Create(newBase, newMember.AsKeyword, elemType);
end;
function TTypeChecker.VisitIndexer(const Node: IIndexerNode): IAstNode;
var
baseType, indexType, elemType: IStaticType;
newBase, newIndex: IAstNode;
begin
// 1. Visit children
inherited;
newBase := Accept(Node.Base);
newIndex := Accept(Node.Index);
// 2. Get types
baseType := (Node.Base as TAstNode).StaticType;
indexType := (Node.Index as TAstNode).StaticType;
baseType := newBase.AsTypedNode.StaticType;
indexType := newIndex.AsTypedNode.StaticType;
elemType := TTypes.Unknown;
// 3. Resolve
@@ -455,7 +518,8 @@ begin
elemType := TTypes.CreateRecord(baseType.Definition);
end;
Result := SetType(Node, elemType);
// 4. Create new node
Result := TIndexerNode.Create(newBase, newIndex, elemType);
end;
function TTypeChecker.VisitRecordLiteral(const Node: IRecordLiteralNode): IAstNode;
@@ -464,25 +528,29 @@ var
scalarDefFields: TArray<TScalarRecordField>;
def: IScalarRecordDefinition;
staticType: IStaticType;
valNode: IAstNode;
valType: IStaticType;
scalarKind: TScalar.TKind;
allScalar: Boolean;
N: TGenericRecordLiteralNode; // Parser creates this type
oldNode: TGenericRecordLiteralNode; // Parser creates this type
newFields: TArray<TRecordFieldLiteral>;
begin
oldNode := (Node as TGenericRecordLiteralNode);
// 1. Visit all child nodes first to infer their types
inherited;
SetLength(newFields, Length(oldNode.Fields));
for i := 0 to High(oldNode.Fields) do
begin
newFields[i].Key := Accept(oldNode.Fields[i].Key).AsKeyword;
newFields[i].Value := Accept(oldNode.Fields[i].Value);
end;
N := (Node as TGenericRecordLiteralNode);
SetLength(scalarDefFields, Length(N.Fields));
SetLength(scalarDefFields, Length(newFields));
allScalar := True;
// 2. Check if this record literal can be a TScalarRecord
for i := 0 to High(N.Fields) do
for i := 0 to High(newFields) do
begin
valNode := N.Fields[i].Value;
valType := (valNode as TAstNode).StaticType;
valType := newFields[i].Value.AsTypedNode.StaticType;
if (valType.Kind = stOrdinal) then
scalarKind := TScalar.TKind.Ordinal
@@ -497,31 +565,29 @@ begin
end;
if allScalar then
scalarDefFields[i] := TScalarRecordField.Create(N.Fields[i].Key.Value, scalarKind);
scalarDefFields[i] := TScalarRecordField.Create(newFields[i].Key.Value, scalarKind);
end;
// 3. Create the appropriate record type (Scalar or Generic) and mutate the node
// 3. Create the new node and set its type/definitions
if allScalar then
begin
def := TScalarRecordRegistry.Intern(scalarDefFields);
staticType := TTypes.CreateRecord(def);
N.Definition := def; // Mutate
N.GenericDefinition := nil; // Mutate
Result := TRecordLiteralNode.Create(newFields, staticType);
(Result as TRecordLiteralNode).Definition := def;
end
else
begin
var genDefFields: TArray<TPair<IKeyword, IStaticType>>;
SetLength(genDefFields, Length(N.Fields));
for i := 0 to High(N.Fields) do
genDefFields[i] := TPair<IKeyword, IStaticType>.Create(N.Fields[i].Key.Value, (N.Fields[i].Value as TAstNode).StaticType);
SetLength(genDefFields, Length(newFields));
for i := 0 to High(newFields) do
genDefFields[i] := TPair<IKeyword, IStaticType>.Create(newFields[i].Key.Value, newFields[i].Value.AsTypedNode.StaticType);
var genDef := TGenericRecordRegistry.Intern(genDefFields);
staticType := TTypes.CreateGenericRecord(genDef);
N.GenericDefinition := genDef; // Mutate
N.Definition := nil; // Mutate
Result := TGenericRecordLiteralNode.Create(newFields, staticType);
(Result as TGenericRecordLiteralNode).GenericDefinition := genDef;
end;
Result := SetType(N, staticType);
end;
function TTypeChecker.VisitCreateSeries(const Node: ICreateSeriesNode): IAstNode;
@@ -529,7 +595,6 @@ var
elemType: IStaticType;
begin
// This is a leaf node
Result := inherited VisitCreateSeries(Node);
// Assign the type
try
@@ -538,19 +603,24 @@ begin
on E: Exception do
elemType := TTypes.Unknown;
end;
Result := SetType(Result, TTypes.CreateSeries(elemType));
// Create new node
Result := TCreateSeriesNode.Create(Node.Definition, TTypes.CreateSeries(elemType));
end;
function TTypeChecker.VisitAddSeriesItem(const Node: IAddSeriesItemNode): IAstNode;
var
seriesType, valueType: IStaticType;
newSeries, newValue, newLookback: IAstNode;
begin
// 1. Visit children
inherited;
newSeries := Accept(Node.Series);
newValue := Accept(Node.Value);
newLookback := Accept(Node.Lookback); // Handles nil
// 2. Get types
seriesType := (Node.Series as TAstNode).StaticType;
valueType := (Node.Value as TAstNode).StaticType;
seriesType := newSeries.AsTypedNode.StaticType;
valueType := newValue.AsTypedNode.StaticType;
// 3. Check types
if (seriesType.Kind <> stUnknown) then
@@ -563,25 +633,27 @@ begin
.CreateFmt('Cannot add item of type %s to series of type %s', [valueType.ToString, seriesType.ElementType.ToString]);
end;
if (Node.Lookback <> nil) then
if (newLookback <> nil) then
begin
var lookbackType := (Node.Lookback as TAstNode).StaticType;
var lookbackType := newLookback.AsTypedNode.StaticType;
if (lookbackType.Kind <> stUnknown) and not (lookbackType.Kind = TStaticTypeKind.stOrdinal) then
raise ETypeException.Create('Lookback parameter for "add" must be an ordinal value.');
end;
Result := SetType(Node, TTypes.Void);
// 4. Create new node
Result := TAddSeriesItemNode.Create(newSeries.AsIdentifier, newValue, newLookback, TTypes.Void);
end;
function TTypeChecker.VisitSeriesLength(const Node: ISeriesLengthNode): IAstNode;
var
seriesType: IStaticType;
newSeries: IAstNode;
begin
// 1. Visit children
inherited;
newSeries := Accept(Node.Series);
// 2. Get type
seriesType := (Node.Series as TAstNode).StaticType;
seriesType := newSeries.AsTypedNode.StaticType;
// 3. Check type
if (seriesType.Kind <> stUnknown)
@@ -589,7 +661,8 @@ begin
and (seriesType.Kind <> TStaticTypeKind.stRecordSeries) then
raise ETypeException.CreateFmt('"length" requires a series, but got %s', [seriesType.ToString]);
Result := SetType(Node, TTypes.Ordinal);
// 4. Create new node
Result := TSeriesLengthNode.Create(newSeries.AsIdentifier, TTypes.Ordinal);
end;
end.