unit Myc.Ast.Compiler.TypeChecker; 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; type IAstTypeChecker = interface(IAstVisitor) function Execute(const RootNode: IAstNode; const Layout: IScopeLayout): IAstNode; end; TTypeChecker = class(TAstTransformer, IAstTypeChecker) private type // Helper to track types per scope during traversal (The "Scratchpad") TTypeContext = class private FParent: TTypeContext; FLayout: IScopeLayout; FSlotTypes: TArray; FUpvalueTypes: TArray; // Types of captured variables public constructor Create(AParent: TTypeContext; ALayout: IScopeLayout; const AUpvalueTypes: TArray); function LookupType(const Address: TResolvedAddress): IStaticType; procedure SetType(SlotIndex: Integer; AType: IStaticType); property Types: TArray read FSlotTypes; end; private FCurrentContext: TTypeContext; // Helper to recursively rebuild the context stack from the layout hierarchy function CreateContextChain(L: IScopeLayout): TTypeContext; protected // Override all visit methods to perform type checking function VisitIdentifier(const Node: IIdentifierNode): IAstNode; override; function VisitVariableDeclaration(const Node: IVariableDeclarationNode): IAstNode; override; function VisitAssignment(const Node: IAssignmentNode): IAstNode; override; function VisitLambdaExpression(const Node: ILambdaExpressionNode): IAstNode; override; function VisitFunctionCall(const Node: IFunctionCallNode): IAstNode; override; function VisitBlockExpression(const Node: IBlockExpressionNode): IAstNode; override; function VisitIfExpression(const Node: IIfExpressionNode): IAstNode; override; function VisitTernaryExpression(const Node: ITernaryExpressionNode): IAstNode; override; function VisitMemberAccess(const Node: IMemberAccessNode): IAstNode; override; function VisitIndexer(const Node: IIndexerNode): IAstNode; override; function VisitRecordLiteral(const Node: IRecordLiteralNode): IAstNode; override; function VisitCreateSeries(const Node: ICreateSeriesNode): IAstNode; override; function VisitAddSeriesItem(const Node: IAddSeriesItemNode): IAstNode; override; function VisitSeriesLength(const Node: ISeriesLengthNode): IAstNode; override; function VisitRecurNode(const Node: IRecurNode): IAstNode; override; function VisitNop(const Node: INopNode): IAstNode; override; // Base cases (types are now set here) function VisitConstant(const Node: IConstantNode): IAstNode; override; function VisitKeyword(const Node: IKeywordNode): IAstNode; override; public constructor Create(const RootLayout: IScopeLayout); destructor Destroy; override; function Execute(const RootNode: IAstNode; const Layout: IScopeLayout): IAstNode; class function CheckTypes(const RootNode: IAstNode; const Layout: IScopeLayout): IAstNode; static; end; implementation uses System.Generics.Defaults, Myc.Data.Keyword; { TTypeChecker.TTypeContext } constructor TTypeChecker.TTypeContext.Create(AParent: TTypeContext; ALayout: IScopeLayout; const AUpvalueTypes: TArray); begin inherited Create; FParent := AParent; FLayout := ALayout; FUpvalueTypes := AUpvalueTypes; // Initialize slot types with Unknown if Assigned(FLayout) then begin SetLength(FSlotTypes, FLayout.SlotCount); for var i := 0 to High(FSlotTypes) do FSlotTypes[i] := TTypes.Unknown; end; end; function TTypeChecker.TTypeContext.LookupType(const Address: TResolvedAddress): IStaticType; var ctx: TTypeContext; i: Integer; begin case Address.Kind of akLocalOrParent: begin ctx := Self; for i := 1 to Address.ScopeDepth do begin if not Assigned(ctx.FParent) then raise Exception.CreateFmt('Scope depth mismatch during type lookup. Requested Depth: %d.', [Address.ScopeDepth]); ctx := ctx.FParent; end; if (Address.SlotIndex >= 0) and (Address.SlotIndex < Length(ctx.FSlotTypes)) then Result := ctx.FSlotTypes[Address.SlotIndex] else Result := TTypes.Unknown; end; akUpvalue: begin // Look up type in our local upvalue type cache if (Address.SlotIndex >= 0) and (Address.SlotIndex < Length(FUpvalueTypes)) then Result := FUpvalueTypes[Address.SlotIndex] else Result := TTypes.Unknown; end; else Result := TTypes.Unknown; end; end; procedure TTypeChecker.TTypeContext.SetType(SlotIndex: Integer; AType: IStaticType); begin if (SlotIndex >= 0) and (SlotIndex < Length(FSlotTypes)) then FSlotTypes[SlotIndex] := AType; end; { TTypeChecker } function TTypeChecker.CreateContextChain(L: IScopeLayout): TTypeContext; var p: TTypeContext; begin if L = nil then exit(nil); // Recursively build parent context p := CreateContextChain(L.Parent); // Create context for current layout level // Note: We don't know UpvalueTypes for these static/parent layouts here, so [] is passed. // Also: Slot types will be initialized to Unknown. Result := TTypeContext.Create(p, L, []); end; constructor TTypeChecker.Create(const RootLayout: IScopeLayout); begin inherited Create; // Build the full context chain based on the Layout's parent hierarchy // This ensures that ScopeDepth lookups can traverse up to the root. FCurrentContext := CreateContextChain(RootLayout); // Fallback if RootLayout is nil (should not happen in valid pipeline) if FCurrentContext = nil then FCurrentContext := TTypeContext.Create(nil, nil, []); end; destructor TTypeChecker.Destroy; begin // Cleanup context stack while Assigned(FCurrentContext) do begin var temp := FCurrentContext; FCurrentContext := FCurrentContext.FParent; temp.Free; end; inherited; end; class function TTypeChecker.CheckTypes(const RootNode: IAstNode; const Layout: IScopeLayout): IAstNode; begin var checker := TTypeChecker.Create(Layout) as IAstTypeChecker; Result := checker.Execute(RootNode, Layout); end; function TTypeChecker.Execute(const RootNode: IAstNode; const Layout: IScopeLayout): IAstNode; begin // Note: Layout passed here matches what was passed to Create/Constructor (via recursed ContextChain) Result := Accept(RootNode); if not Assigned(Result) then Result := TAst.Block([]); end; function TTypeChecker.VisitConstant(const Node: IConstantNode): IAstNode; begin Assert(Node.StaticType.Kind <> stUnknown); Result := Node; end; function TTypeChecker.VisitKeyword(const Node: IKeywordNode): IAstNode; begin Assert(Node.StaticType.Kind = stKeyword); Result := Node; end; function TTypeChecker.VisitIdentifier(const Node: IIdentifierNode): IAstNode; var typ: IStaticType; adr: TResolvedAddress; begin adr := Node.Address; // Lookup type in our scratchpad context using the address resolved by Binder typ := FCurrentContext.LookupType(adr); // Create a new node with the inferred type Result := TAst.Identifier(Node.Name, adr, typ); end; function TTypeChecker.VisitRecurNode(const Node: IRecurNode): IAstNode; var newArgs: TArray; i: Integer; begin SetLength(newArgs, Length(Node.Arguments)); for i := 0 to High(Node.Arguments) do newArgs[i] := Accept(Node.Arguments[i]); Result := TAst.Recur(newArgs, TTypes.Void); end; function TTypeChecker.VisitVariableDeclaration(const Node: IVariableDeclarationNode): IAstNode; var initType: IStaticType; newInitializer, newIdent: IAstNode; adr: TResolvedAddress; lambdaNode: ILambdaExpressionNode; placeholderType: IStaticType; i: Integer; begin adr := Node.Identifier.Address; initType := TTypes.Unknown; // Recursive lambda bootstrap logic placeholderType := nil; if (Node.Initializer <> nil) and (Node.Initializer.Kind = akLambdaExpression) then begin lambdaNode := Node.Initializer.AsLambdaExpression; var paramTypes: TArray; SetLength(paramTypes, Length(lambdaNode.Parameters)); for i := 0 to High(paramTypes) do paramTypes[i] := TTypes.Unknown; placeholderType := TTypes.CreateMethod(paramTypes, TTypes.Unknown); // Update Context (Scratchpad) FCurrentContext.SetType(adr.SlotIndex, placeholderType); initType := placeholderType; end; if Assigned(Node.Initializer) then newInitializer := Accept(Node.Initializer) else newInitializer := nil; if Assigned(newInitializer) then initType := newInitializer.AsTypedNode.StaticType else if not Assigned(placeholderType) then initType := TTypes.Unknown; // Update Context with final type if initType.Kind <> stUnknown then FCurrentContext.SetType(adr.SlotIndex, initType); newIdent := TAst.Identifier(Node.Identifier.Name, adr, initType); Result := TAst.VarDecl(newIdent.AsIdentifier, newInitializer, initType, Node.IsBoxed); end; function TTypeChecker.VisitAssignment(const Node: IAssignmentNode): IAstNode; var targetType, sourceType: IStaticType; newIdent, newValue: IAstNode; adr: TResolvedAddress; lambdaNode: ILambdaExpressionNode; placeholderType: IStaticType; i: Integer; begin newIdent := Accept(Node.Identifier); targetType := newIdent.AsTypedNode.StaticType; adr := newIdent.AsIdentifier.Address; // Recursive lambda assignment check placeholderType := nil; if (Node.Value <> nil) and (Node.Value.Kind = akLambdaExpression) then begin lambdaNode := Node.Value.AsLambdaExpression; if (targetType.Kind <> stMethod) then begin var paramTypes: TArray; SetLength(paramTypes, Length(lambdaNode.Parameters)); for i := 0 to High(paramTypes) do paramTypes[i] := TTypes.Unknown; placeholderType := TTypes.CreateMethod(paramTypes, TTypes.Unknown); FCurrentContext.SetType(adr.SlotIndex, placeholderType); targetType := placeholderType; end; end; newValue := Accept(Node.Value); sourceType := newValue.AsTypedNode.StaticType; if not TTypeRules.CanAssign(targetType, sourceType) then begin if (targetType.Kind = stUnknown) then begin if not TTypeRules.CanAssign(sourceType, targetType) then raise ETypeException.CreateFmt('Cannot assign type %s to %s', [sourceType.ToString, targetType.ToString]); end else raise ETypeException.CreateFmt('Cannot assign type %s to %s', [sourceType.ToString, targetType.ToString]); end; if ((targetType.Kind = stUnknown) or Assigned(placeholderType)) and (sourceType.Kind <> stUnknown) then begin FCurrentContext.SetType(adr.SlotIndex, sourceType); newIdent := TAst.Identifier(newIdent.AsIdentifier.Name, adr, sourceType); targetType := sourceType; end; Result := TAst.Assign(newIdent.AsIdentifier, newValue, targetType); end; function TTypeChecker.VisitLambdaExpression(const Node: ILambdaExpressionNode): IAstNode; var newParams: TArray; newBody: IAstNode; bodyType, methodType: IStaticType; paramTypes: TArray; // Upvalue Type Resolution upvalueTypes: TArray; upvalueAddrs: TArray; i: Integer; finalDescriptor: IScopeDescriptor; begin // 1. Resolve Upvalue Types *in the current (parent) context* upvalueAddrs := Node.Upvalues; SetLength(upvalueTypes, Length(upvalueAddrs)); for i := 0 to High(upvalueAddrs) do begin // We look up the physical address (from Binder) in the current context chain upvalueTypes[i] := FCurrentContext.LookupType(upvalueAddrs[i]); end; // 2. Create new TypeContext for this lambda scope, PASSING the upvalue types // We use the layout from the Binder-Result-Node FCurrentContext := TTypeContext.Create(FCurrentContext, Node.Layout, upvalueTypes); try // 3. Set parameter types in the context SetLength(newParams, Length(Node.Parameters)); SetLength(paramTypes, Length(Node.Parameters)); for i := 0 to High(Node.Parameters) do begin var paramIdent := Node.Parameters[i]; var paramAdr := paramIdent.Address; // Here we could infer types if we had type annotations. For now, parameters are Unknown. paramTypes[i] := TTypes.Unknown; // Update context so body can resolve params FCurrentContext.SetType(paramAdr.SlotIndex, paramTypes[i]); newParams[i] := TAst.Identifier(paramIdent.Name, paramAdr, paramTypes[i]); end; // 4. Visit body newBody := Accept(Node.Body); bodyType := newBody.AsTypedNode.StaticType; // 5. Create method type methodType := TTypes.CreateMethod(paramTypes, bodyType); // 6. Update type in context (Slot 0) FCurrentContext.SetType(0, methodType); // 7. FINALIZE: Bake the Descriptor finalDescriptor := TScope.CreateDescriptor(Node.Layout, FCurrentContext.Types); finally // 8. Pop Context var temp := FCurrentContext; FCurrentContext := FCurrentContext.FParent; temp.Free; end; // 9. Create new node with the Descriptor attached! Result := TAst.LambdaExpr(newParams, newBody, Node.Layout, finalDescriptor, Node.Upvalues, Node.HasNestedLambdas, methodType); end; function TTypeChecker.VisitFunctionCall(const Node: IFunctionCallNode): IAstNode; var calleeType, retType: IStaticType; i, j: Integer; newCallee: IAstNode; newArgs: TArray; argTypes: TArray; hasUnknownArgs: Boolean; bestSig: IMethodSignature; sig: IMethodSignature; match: Boolean; begin newCallee := Accept(Node.Callee); SetLength(newArgs, Length(Node.Arguments)); SetLength(argTypes, Length(Node.Arguments)); hasUnknownArgs := False; for i := 0 to High(Node.Arguments) do begin newArgs[i] := Accept(Node.Arguments[i]); argTypes[i] := newArgs[i].AsTypedNode.StaticType; if argTypes[i].Kind = stUnknown then hasUnknownArgs := True; end; calleeType := newCallee.AsTypedNode.StaticType; retType := TTypes.Unknown; if calleeType.Kind = TStaticTypeKind.stMethod then begin if not hasUnknownArgs then begin bestSig := nil; for sig in calleeType.Signatures do begin if Length(sig.ParamTypes) <> Length(argTypes) then continue; match := True; for j := 0 to High(argTypes) do begin if not TTypeRules.CanAssign(sig.ParamTypes[j], argTypes[j]) then begin match := False; break; end; end; if match then begin bestSig := sig; break; end; end; if Assigned(bestSig) then retType := bestSig.ReturnType else begin var argsStr: string := ''; for i := 0 to High(argTypes) do argsStr := argsStr + argTypes[i].ToString + ' '; raise ETypeException .CreateFmt('No matching signature for call with args (%s) found on method %s', [argsStr, calleeType.ToString]); end; end; end else if calleeType.Kind <> TStaticTypeKind.stUnknown then raise ETypeException.CreateFmt('Cannot invoke type %s as a function.', [calleeType.ToString]); Result := TAst.FunctionCall(newCallee, newArgs, retType, Node.IsTailCall); end; function TTypeChecker.VisitBlockExpression(const Node: IBlockExpressionNode): IAstNode; var blockType: IStaticType; newExprs: TArray; i: Integer; begin SetLength(newExprs, Length(Node.Expressions)); for i := 0 to High(Node.Expressions) do newExprs[i] := Accept(Node.Expressions[i]); if Length(newExprs) > 0 then blockType := newExprs[High(newExprs)].AsTypedNode.StaticType else blockType := TTypes.Void; Result := TAst.Block(newExprs, blockType); end; function TTypeChecker.VisitIfExpression(const Node: IIfExpressionNode): IAstNode; var conditionType, thenType, elseType, resultType: IStaticType; newCond, newThen, newElse: IAstNode; begin newCond := Accept(Node.Condition); newThen := Accept(Node.ThenBranch); newElse := Accept(Node.ElseBranch); 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]); thenType := newThen.AsTypedNode.StaticType; elseType := if newElse <> nil then newElse.AsTypedNode.StaticType else TTypes.Void; resultType := TTypeRules.Promote(thenType, elseType); Result := TAst.IfExpr(newCond, newThen, newElse, resultType); end; function TTypeChecker.VisitTernaryExpression(const Node: ITernaryExpressionNode): IAstNode; var conditionType, thenType, elseType, resultType: IStaticType; newCond, newThen, newElse: IAstNode; begin newCond := Accept(Node.Condition); newThen := Accept(Node.ThenBranch); newElse := Accept(Node.ElseBranch); 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]); thenType := newThen.AsTypedNode.StaticType; elseType := newElse.AsTypedNode.StaticType; resultType := TTypeRules.Promote(thenType, elseType); Result := TAst.TernaryExpr(newCond, newThen, newElse, resultType); end; function TTypeChecker.VisitMemberAccess(const Node: IMemberAccessNode): IAstNode; var baseType, elemType: IStaticType; fieldIndex: Integer; newBase, newMember: IAstNode; begin newBase := Accept(Node.Base); newMember := Accept(Node.Member); baseType := newBase.AsTypedNode.StaticType; elemType := TTypes.Unknown; if (baseType.Kind <> TStaticTypeKind.stUnknown) then begin if (baseType.Kind = TStaticTypeKind.stRecord) or (baseType.Kind = TStaticTypeKind.stRecordSeries) then begin fieldIndex := baseType.Definition.IndexOf(Node.Member.Value); if fieldIndex < 0 then raise ETypeException.CreateFmt('Member "%s" not found in type %s', [Node.Member.Value.Name, baseType.ToString]); var fieldType := TTypes.FromScalarKind(baseType.Definition.Fields[fieldIndex].Value); if baseType.Kind = TStaticTypeKind.stRecord then elemType := fieldType else elemType := TTypes.CreateSeries(fieldType); end else if (baseType.Kind = TStaticTypeKind.stGenericRecord) then begin var genDef := baseType.GenericDefinition; fieldIndex := genDef.IndexOf(Node.Member.Value); if fieldIndex < 0 then raise ETypeException.CreateFmt('Member "%s" not found in type %s', [Node.Member.Value.Name, baseType.ToString]); elemType := genDef.Fields[fieldIndex].Value; end else raise ETypeException.CreateFmt('Member access requires a record type, but got %s', [baseType.ToString]); end; Result := TAst.MemberAccess(newBase, newMember.AsKeyword, elemType); end; function TTypeChecker.VisitIndexer(const Node: IIndexerNode): IAstNode; var baseType, indexType, elemType: IStaticType; newBase, newIndex: IAstNode; begin newBase := Accept(Node.Base); newIndex := Accept(Node.Index); baseType := newBase.AsTypedNode.StaticType; indexType := newIndex.AsTypedNode.StaticType; elemType := TTypes.Unknown; if (baseType.Kind <> TStaticTypeKind.stUnknown) then begin if (baseType.Kind <> TStaticTypeKind.stSeries) and (baseType.Kind <> TStaticTypeKind.stRecordSeries) then raise ETypeException.CreateFmt('Indexer `[]` can only be applied to series types, but got %s', [baseType.ToString]); if (indexType.Kind <> stUnknown) and not TTypeRules.CanAssign(TTypes.Ordinal, indexType) then raise ETypeException.CreateFmt('Indexer `[]` requires an Ordinal index, but got %s', [indexType.ToString]); if baseType.Kind = TStaticTypeKind.stSeries then elemType := baseType.ElementType else elemType := TTypes.CreateRecord(baseType.Definition); end; Result := TAst.Indexer(newBase, newIndex, elemType); end; function TTypeChecker.VisitRecordLiteral(const Node: IRecordLiteralNode): IAstNode; var i: Integer; scalarDefFields: TArray; def: IScalarRecordDefinition; staticType: IStaticType; valType: IStaticType; scalarKind: TScalar.TKind; allScalar: Boolean; newFields: TArray; begin SetLength(newFields, Length(Node.Fields)); for i := 0 to High(Node.Fields) do begin newFields[i].Key := Accept(Node.Fields[i].Key).AsKeyword; newFields[i].Value := Accept(Node.Fields[i].Value); end; SetLength(scalarDefFields, Length(newFields)); allScalar := True; for i := 0 to High(newFields) do begin valType := newFields[i].Value.AsTypedNode.StaticType; if (valType.Kind = stOrdinal) then scalarKind := TScalar.TKind.Ordinal else if (valType.Kind = stFloat) then scalarKind := TScalar.TKind.Float else if (valType.Kind = stKeyword) then scalarKind := TScalar.TKind.Keyword else begin allScalar := False; scalarKind := TScalar.TKind.Ordinal; end; if allScalar then scalarDefFields[i] := TScalarRecordField.Create(newFields[i].Key.Value, scalarKind); end; if allScalar then begin def := TScalarRecordRegistry.Intern(scalarDefFields); staticType := TTypes.CreateRecord(def); Result := TAst.RecordLiteral(newFields, def, nil, staticType); end else begin var genDefFields: TArray>; SetLength(genDefFields, Length(newFields)); for i := 0 to High(newFields) do genDefFields[i] := TPair.Create(newFields[i].Key.Value, newFields[i].Value.AsTypedNode.StaticType); var genDef := TGenericRecordRegistry.Intern(genDefFields); staticType := TTypes.CreateGenericRecord(genDef); Result := TAst.RecordLiteral(newFields, nil, genDef, staticType); end; end; function TTypeChecker.VisitCreateSeries(const Node: ICreateSeriesNode): IAstNode; var elemType: IStaticType; begin try elemType := TTypes.FromScalarKind(TScalar.StringToKind(Node.Definition)); except on E: Exception do elemType := TTypes.Unknown; end; Result := TAst.CreateSeries(Node.Definition, TTypes.CreateSeries(elemType)); end; function TTypeChecker.VisitAddSeriesItem(const Node: IAddSeriesItemNode): IAstNode; var seriesType, valueType: IStaticType; newSeries, newValue, newLookback: IAstNode; begin newSeries := Accept(Node.Series); newValue := Accept(Node.Value); newLookback := Accept(Node.Lookback); seriesType := newSeries.AsTypedNode.StaticType; valueType := newValue.AsTypedNode.StaticType; if (seriesType.Kind <> stUnknown) then begin if (seriesType.Kind <> TStaticTypeKind.stSeries) then raise ETypeException.CreateFmt('"add" requires a series as its first argument, but got %s', [seriesType.ToString]); if not TTypeRules.CanAssign(seriesType.ElementType, valueType) then raise ETypeException .CreateFmt('Cannot add item of type %s to series of type %s', [valueType.ToString, seriesType.ElementType.ToString]); end; if (newLookback <> nil) then begin 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 := TAst.AddSeriesItem(newSeries.AsIdentifier, newValue, newLookback, TTypes.Void); end; function TTypeChecker.VisitNop(const Node: INopNode): IAstNode; begin Result := TAst.Nop(TTypes.Void); end; function TTypeChecker.VisitSeriesLength(const Node: ISeriesLengthNode): IAstNode; var seriesType: IStaticType; newSeries: IAstNode; begin newSeries := Accept(Node.Series); seriesType := newSeries.AsTypedNode.StaticType; if (seriesType.Kind <> stUnknown) and (seriesType.Kind <> TStaticTypeKind.stSeries) and (seriesType.Kind <> TStaticTypeKind.stRecordSeries) then raise ETypeException.CreateFmt('"length" requires a series, but got %s', [seriesType.ToString]); Result := TAst.SeriesLength(newSeries.AsIdentifier, TTypes.Ordinal); end; end.