Refactor Compiler Pipeline: Decouple Scope Layout from Runtime Descriptor

- **Architecture:** Split `IScopeDescriptor` into `IScopeLayout` (Binder/Structure) and immutable `IScopeDescriptor` (Runtime/Types).
- **Binder:** Now produces `IScopeLayout` via `IScopeBuilder`. Restored Upvalue tracking and Lambda nesting detection.
- **TypeChecker:** Introduced `TTypeContext` to track types during traversal. Now produces the final `IScopeDescriptor`.
- **Evaluator:** Adapted to new `ILambdaExpressionNode` structure.
- **Fixes:** Resolved `Scope depth mismatch` in TypeChecker and `AccessViolation` in Evaluator due to lost parent scopes.
This commit is contained in:
Michael Schimmel
2025-11-21 12:01:14 +01:00
parent ae10f4eee0
commit 58c44079f7
18 changed files with 1236 additions and 1194 deletions
+197 -162
View File
@@ -16,16 +16,32 @@ uses
type
IAstTypeChecker = interface(IAstVisitor)
function Execute(const RootNode: IAstNode; const ADecriptor: IScopeDescriptor): IAstNode;
function Execute(const RootNode: IAstNode; const Layout: IScopeLayout): IAstNode;
end;
// 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 *replaces* all IAstTypedNodes with new nodes containing the correct type.
TTypeChecker = class(TAstTransformer, IAstTypeChecker)
private
FCurrentDescriptor: IScopeDescriptor;
type
// Helper to track types per scope during traversal (The "Scratchpad")
TTypeContext = class
private
FParent: TTypeContext;
FLayout: IScopeLayout;
FSlotTypes: TArray<IStaticType>;
FUpvalueTypes: TArray<IStaticType>; // Types of captured variables
public
constructor Create(AParent: TTypeContext; ALayout: IScopeLayout; const AUpvalueTypes: TArray<IStaticType>);
function LookupType(const Address: TResolvedAddress): IStaticType;
procedure SetType(SlotIndex: Integer; AType: IStaticType);
property Types: TArray<IStaticType> 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;
@@ -50,10 +66,12 @@ type
function VisitKeyword(const Node: IKeywordNode): IAstNode; override;
public
constructor Create(const ADescriptor: IScopeDescriptor);
function Execute(const RootNode: IAstNode; const ADescriptor: IScopeDescriptor): IAstNode;
constructor Create(const RootLayout: IScopeLayout);
destructor Destroy; override;
class function CheckTypes(const RootNode: IAstNode; const ADescriptor: IScopeDescriptor): IAstNode; static;
function Execute(const RootNode: IAstNode; const Layout: IScopeLayout): IAstNode;
class function CheckTypes(const RootNode: IAstNode; const Layout: IScopeLayout): IAstNode; static;
end;
implementation
@@ -62,58 +80,143 @@ uses
System.Generics.Defaults,
Myc.Data.Keyword;
{ TTypeChecker }
{ TTypeChecker.TTypeContext }
constructor TTypeChecker.Create(const ADescriptor: IScopeDescriptor);
constructor TTypeChecker.TTypeContext.Create(AParent: TTypeContext; ALayout: IScopeLayout; const AUpvalueTypes: TArray<IStaticType>);
begin
inherited Create;
Assert(Assigned(ADescriptor));
FCurrentDescriptor := ADescriptor;
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;
class function TTypeChecker.CheckTypes(const RootNode: IAstNode; const ADescriptor: IScopeDescriptor): IAstNode;
function TTypeChecker.TTypeContext.LookupType(const Address: TResolvedAddress): IStaticType;
var
ctx: TTypeContext;
i: Integer;
begin
var checker := TTypeChecker.Create(ADescriptor) as IAstTypeChecker;
Result := checker.Execute(RootNode, ADescriptor);
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;
function TTypeChecker.Execute(const RootNode: IAstNode; const ADescriptor: IScopeDescriptor): IAstNode;
procedure TTypeChecker.TTypeContext.SetType(SlotIndex: Integer; AType: IStaticType);
begin
FCurrentDescriptor := ADescriptor;
Result := Accept(RootNode); // Use IAstNode-returning Accept
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
// This is a leaf node.
// If the constructor couldn't set the type, nobody can
Assert(Node.StaticType.Kind <> stUnknown);
Result := Node;
end;
function TTypeChecker.VisitKeyword(const Node: IKeywordNode): IAstNode;
begin
// This is a leaf node.
// The TKeywordNode constructor *forces* the type to be TTypes.Keyword.
Assert(Node.StaticType.Kind = stKeyword);
Result := Node;
end;
function TTypeChecker.VisitIdentifier(const Node: IIdentifierNode): IAstNode;
var
symbol: TResolvedSymbol;
typ: IStaticType;
adr: TResolvedAddress;
begin
// 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);
adr := Node.Address;
// Lookup type in our scratchpad context using the address resolved by Binder
typ := FCurrentContext.LookupType(adr);
// Create a new node, copying the address and assigning the inferred type
Result := TAst.Identifier(Node.Name, adr, symbol.StaticType);
// Create a new node with the inferred type
Result := TAst.Identifier(Node.Name, adr, typ);
end;
function TTypeChecker.VisitRecurNode(const Node: IRecurNode): IAstNode;
@@ -121,12 +224,10 @@ var
newArgs: TArray<IAstNode>;
i: Integer;
begin
// 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 := TAst.Recur(newArgs, TTypes.Void);
end;
@@ -139,57 +240,43 @@ var
placeholderType: IStaticType;
i: Integer;
begin
// 1. Get the address from the bound identifier (Binder did this)
adr := Node.Identifier.Address;
initType := TTypes.Unknown; // Default
initType := TTypes.Unknown;
// 2. Check for recursive lambda and bootstrap the type
// Recursive lambda bootstrap logic
placeholderType := nil;
if (Node.Initializer <> nil) and (Node.Initializer.Kind = akLambdaExpression) then
begin
lambdaNode := Node.Initializer.AsLambdaExpression;
// Create a placeholder method type based on the *unvisited* lambda's parameter *count*.
var paramTypes: TArray<IStaticType>;
SetLength(paramTypes, Length(lambdaNode.Parameters));
for i := 0 to High(paramTypes) do
paramTypes[i] := TTypes.Unknown;
// Create the placeholder (Return type is also Unknown for now)
placeholderType := TTypes.CreateMethod(paramTypes, TTypes.Unknown);
// 3. *Update the descriptor* with the placeholder *before* visiting the initializer
FCurrentDescriptor.UpdateType(adr.SlotIndex, placeholderType);
initType := placeholderType; // Store this
// Update Context (Scratchpad)
FCurrentContext.SetType(adr.SlotIndex, placeholderType);
initType := placeholderType;
end;
// 4. Visit Initializer (if it exists)
if Assigned(Node.Initializer) then
newInitializer := Accept(Node.Initializer)
else
newInitializer := nil;
// 5. Get the *final* inferred initializer type
if Assigned(newInitializer) then
initType := newInitializer.AsTypedNode.StaticType
else if not Assigned(placeholderType) then // only if not already set
initType := TTypes.Unknown; // (def f) - no initializer
else if not Assigned(placeholderType) then
initType := TTypes.Unknown;
// 6. *Re-update* the type in the scope descriptor with the final, inferred type.
// Update Context with final type
if initType.Kind <> stUnknown then
FCurrentDescriptor.UpdateType(adr.SlotIndex, initType);
FCurrentContext.SetType(adr.SlotIndex, initType);
// 7. Create the new (typed) identifier node
newIdent := TAst.Identifier(Node.Identifier.Name, adr, initType);
// 8. Create the new VariableDeclaration node using the factory
Result :=
TAst.VarDecl(
newIdent.AsIdentifier,
newInitializer,
initType,
Node.IsBoxed // 9. Copy runtime flags
);
Result := TAst.VarDecl(newIdent.AsIdentifier, newInitializer, initType, Node.IsBoxed);
end;
function TTypeChecker.VisitAssignment(const Node: IAssignmentNode): IAstNode;
@@ -201,61 +288,49 @@ var
placeholderType: IStaticType;
i: Integer;
begin
// 1. Visit Identifier *first* to get its address and current type
newIdent := Accept(Node.Identifier);
targetType := newIdent.AsTypedNode.StaticType;
adr := newIdent.AsIdentifier.Address;
// 2. Check for recursive lambda assignment
// Recursive lambda assignment check
placeholderType := nil;
if (Node.Value <> nil) and (Node.Value.Kind = akLambdaExpression) then
begin
lambdaNode := Node.Value.AsLambdaExpression;
// Create a placeholder (only if the target is not already a method type)
if (targetType.Kind <> stMethod) then
begin
var paramTypes: TArray<IStaticType>;
SetLength(paramTypes, Length(lambdaNode.Parameters));
for i := 0 to High(paramTypes) do
paramTypes[i] := TTypes.Unknown; // We infer param types later
paramTypes[i] := TTypes.Unknown;
placeholderType := TTypes.CreateMethod(paramTypes, TTypes.Unknown);
// 3. *Update the descriptor* with the placeholder *before* visiting the value
FCurrentDescriptor.UpdateType(adr.SlotIndex, placeholderType);
FCurrentContext.SetType(adr.SlotIndex, placeholderType);
targetType := placeholderType;
end;
end;
// 4. Visit Value
newValue := Accept(Node.Value);
sourceType := newValue.AsTypedNode.StaticType;
// 5. Check assignment
if not TTypeRules.CanAssign(targetType, sourceType) then
begin
// If target was unknown, try promoting
if (targetType.Kind = stUnknown) then
begin
if not TTypeRules.CanAssign(sourceType, targetType) then // Check reverse
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;
// 6. If the target was 'Unknown' or a 'Placeholder', update the descriptor
// with the new, final inferred type.
if ((targetType.Kind = stUnknown) or Assigned(placeholderType)) and (sourceType.Kind <> stUnknown) then
begin
FCurrentDescriptor.UpdateType(adr.SlotIndex, sourceType);
// Re-create the identifier node *with the new type*
FCurrentContext.SetType(adr.SlotIndex, sourceType);
newIdent := TAst.Identifier(newIdent.AsIdentifier.Name, adr, sourceType);
targetType := sourceType;
end;
// 7. Create the new Assignment node
Result := TAst.Assign(newIdent.AsIdentifier, newValue, targetType);
end;
@@ -265,46 +340,67 @@ var
newBody: IAstNode;
bodyType, methodType: IStaticType;
paramTypes: TArray<IStaticType>;
// Upvalue Type Resolution
upvalueTypes: TArray<IStaticType>;
upvalueAddrs: TArray<TResolvedAddress>;
i: Integer;
savedDescriptor: IScopeDescriptor;
finalDescriptor: IScopeDescriptor;
begin
// 1. Enter the lambda's scope (which Binder already created)
savedDescriptor := FCurrentDescriptor;
FCurrentDescriptor := Node.ScopeDescriptor;
// 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
// 2. Visit parameters (they are already bound, just need typing)
// 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
// 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 := Node.Parameters[i];
var paramAdr := paramIdent.Address;
var newParam := TAst.Identifier(paramIdent.Name, paramAdr);
newParams[i] := newParam;
// 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;
// 3. Visit the body to infer its return type
// 4. Visit body
newBody := Accept(Node.Body);
bodyType := newBody.AsTypedNode.StaticType;
// 4. Create the final method type
// 5. Create method type
methodType := TTypes.CreateMethod(paramTypes, bodyType);
// 5. Update the type for <self> (Slot 0) in the descriptor
FCurrentDescriptor.UpdateType(0, methodType);
// 6. Update <self> type in context (Slot 0)
FCurrentContext.SetType(0, methodType);
// 7. FINALIZE: Bake the Descriptor
finalDescriptor := TScope.CreateDescriptor(Node.Layout, FCurrentContext.Types);
finally
// 6. Restore parent descriptor
FCurrentDescriptor := savedDescriptor;
// 8. Pop Context
var temp := FCurrentContext;
FCurrentContext := FCurrentContext.FParent;
temp.Free;
end;
// 7. Create the new (typed) lambda node using the factory
Result := TAst.LambdaExpr(newParams, newBody, Node.ScopeDescriptor, Node.Upvalues, Node.HasNestedLambdas, methodType);
// 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;
@@ -319,7 +415,6 @@ var
sig: IMethodSignature;
match: Boolean;
begin
// 1. Visit children first (bottom-up)
newCallee := Accept(Node.Callee);
SetLength(newArgs, Length(Node.Arguments));
SetLength(argTypes, Length(Node.Arguments));
@@ -333,53 +428,40 @@ begin
hasUnknownArgs := True;
end;
// 2. Get callee type (now inferred)
calleeType := newCallee.AsTypedNode.StaticType;
retType := TTypes.Unknown; // Default if not a method
retType := TTypes.Unknown;
// 3. Perform type checking
if calleeType.Kind = TStaticTypeKind.stMethod then
begin
// If any argument is Unknown, we cannot resolve overloads.
// The return type remains Unknown.
if not hasUnknownArgs then
begin
bestSig := nil;
for sig in calleeType.Signatures do
begin
// Check 1: Argument count
if Length(sig.ParamTypes) <> Length(argTypes) then
continue;
// Check 2: Argument types (CanAssign)
match := True;
for j := 0 to High(argTypes) do
begin
if not TTypeRules.CanAssign(sig.ParamTypes[j], argTypes[j]) then
begin
match := False;
break; // This signature doesn't match
break;
end;
end;
// Check 3: Found first match
if match then
begin
// This is the "dumb" checker logic: first match wins.
// A "smarter" checker would find the *best* match.
bestSig := sig;
break;
end;
end; // for sig
end;
// Check 4: Handle results
if Assigned(bestSig) then
begin
retType := bestSig.ReturnType;
end
retType := bestSig.ReturnType
else
begin
// No signature matched, even with known types. This is an error.
var argsStr: string := '';
for i := 0 to High(argTypes) do
argsStr := argsStr + argTypes[i].ToString + ' ';
@@ -387,20 +469,11 @@ begin
.CreateFmt('No matching signature for call with args (%s) found on method %s', [argsStr, calleeType.ToString]);
end;
end;
// else: hasUnknownArgs is True, so retType remains Unknown (as set in step 2)
end
else if calleeType.Kind <> TStaticTypeKind.stUnknown then
raise ETypeException.CreateFmt('Cannot invoke type %s as a function.', [calleeType.ToString]);
// else: calleeType is Unknown (e.g. recursive call or unbound symbol), retType remains Unknown.
// 4. Create the new (typed) call node using the factory
Result :=
TAst.FunctionCall(
newCallee,
newArgs,
retType,
Node.IsTailCall // 5. Copy runtime properties
);
Result := TAst.FunctionCall(newCallee, newArgs, retType, Node.IsTailCall);
end;
function TTypeChecker.VisitBlockExpression(const Node: IBlockExpressionNode): IAstNode;
@@ -409,18 +482,15 @@ var
newExprs: TArray<IAstNode>;
i: Integer;
begin
// 1. Visit children
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(newExprs) > 0 then
blockType := newExprs[High(newExprs)].AsTypedNode.StaticType
else
blockType := TTypes.Void;
// 3. Create new node
Result := TAst.Block(newExprs, blockType);
end;
@@ -429,17 +499,14 @@ var
conditionType, thenType, elseType, resultType: IStaticType;
newCond, newThen, newElse: IAstNode;
begin
// 1. Visit children
newCond := Accept(Node.Condition);
newThen := Accept(Node.ThenBranch);
newElse := Accept(Node.ElseBranch); // Accept handles nil
newElse := Accept(Node.ElseBranch);
// 2. Check condition
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 := newThen.AsTypedNode.StaticType;
elseType :=
if newElse <> nil then newElse.AsTypedNode.StaticType
@@ -447,7 +514,6 @@ begin
resultType := TTypeRules.Promote(thenType, elseType);
// 4. Create new node
Result := TAst.IfExpr(newCond, newThen, newElse, resultType);
end;
@@ -456,23 +522,19 @@ var
conditionType, thenType, elseType, resultType: IStaticType;
newCond, newThen, newElse: IAstNode;
begin
// 1. Visit children
newCond := Accept(Node.Condition);
newThen := Accept(Node.ThenBranch);
newElse := Accept(Node.ElseBranch);
// 2. Check condition
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 := newThen.AsTypedNode.StaticType;
elseType := newElse.AsTypedNode.StaticType;
resultType := TTypeRules.Promote(thenType, elseType);
// 4. Create new node
Result := TAst.TernaryExpr(newCond, newThen, newElse, resultType);
end;
@@ -482,15 +544,12 @@ var
fieldIndex: Integer;
newBase, newMember: IAstNode;
begin
// 1. Visit children
newBase := Accept(Node.Base);
newMember := Accept(Node.Member); // Visits the TKeywordNode
newMember := Accept(Node.Member);
// 2. Get types
baseType := newBase.AsTypedNode.StaticType;
elemType := TTypes.Unknown;
// 3. Resolve
if (baseType.Kind <> TStaticTypeKind.stUnknown) then
begin
if (baseType.Kind = TStaticTypeKind.stRecord) or (baseType.Kind = TStaticTypeKind.stRecordSeries) then
@@ -503,7 +562,7 @@ begin
if baseType.Kind = TStaticTypeKind.stRecord then
elemType := fieldType
else // stRecordSeries
else
elemType := TTypes.CreateSeries(fieldType);
end
else if (baseType.Kind = TStaticTypeKind.stGenericRecord) then
@@ -515,12 +574,9 @@ begin
elemType := genDef.Fields[fieldIndex].Value;
end
else
begin
raise ETypeException.CreateFmt('Member access requires a record type, but got %s', [baseType.ToString]);
end;
end;
// 4. Create new node
Result := TAst.MemberAccess(newBase, newMember.AsKeyword, elemType);
end;
@@ -529,16 +585,13 @@ var
baseType, indexType, elemType: IStaticType;
newBase, newIndex: IAstNode;
begin
// 1. Visit children
newBase := Accept(Node.Base);
newIndex := Accept(Node.Index);
// 2. Get types
baseType := newBase.AsTypedNode.StaticType;
indexType := newIndex.AsTypedNode.StaticType;
elemType := TTypes.Unknown;
// 3. Resolve
if (baseType.Kind <> TStaticTypeKind.stUnknown) then
begin
if (baseType.Kind <> TStaticTypeKind.stSeries) and (baseType.Kind <> TStaticTypeKind.stRecordSeries) then
@@ -549,11 +602,10 @@ begin
if baseType.Kind = TStaticTypeKind.stSeries then
elemType := baseType.ElementType
else // stRecordSeries
else
elemType := TTypes.CreateRecord(baseType.Definition);
end;
// 4. Create new node
Result := TAst.Indexer(newBase, newIndex, elemType);
end;
@@ -568,7 +620,6 @@ var
allScalar: Boolean;
newFields: TArray<TRecordFieldLiteral>;
begin
// 1. Visit all child nodes first to infer their types
SetLength(newFields, Length(Node.Fields));
for i := 0 to High(Node.Fields) do
begin
@@ -579,7 +630,6 @@ begin
SetLength(scalarDefFields, Length(newFields));
allScalar := True;
// 2. Check if this record literal can be a TScalarRecord
for i := 0 to High(newFields) do
begin
valType := newFields[i].Value.AsTypedNode.StaticType;
@@ -593,14 +643,13 @@ begin
else
begin
allScalar := False;
scalarKind := TScalar.TKind.Ordinal; // Dummy
scalarKind := TScalar.TKind.Ordinal;
end;
if allScalar then
scalarDefFields[i] := TScalarRecordField.Create(newFields[i].Key.Value, scalarKind);
end;
// 3. Create the new node and set its type/definitions
if allScalar then
begin
def := TScalarRecordRegistry.Intern(scalarDefFields);
@@ -624,9 +673,6 @@ function TTypeChecker.VisitCreateSeries(const Node: ICreateSeriesNode): IAstNode
var
elemType: IStaticType;
begin
// This is a leaf node
// Assign the type
try
elemType := TTypes.FromScalarKind(TScalar.StringToKind(Node.Definition));
except
@@ -634,7 +680,6 @@ begin
elemType := TTypes.Unknown;
end;
// Create new node
Result := TAst.CreateSeries(Node.Definition, TTypes.CreateSeries(elemType));
end;
@@ -643,16 +688,13 @@ var
seriesType, valueType: IStaticType;
newSeries, newValue, newLookback: IAstNode;
begin
// 1. Visit children
newSeries := Accept(Node.Series);
newValue := Accept(Node.Value);
newLookback := Accept(Node.Lookback); // Handles nil
newLookback := Accept(Node.Lookback);
// 2. Get types
seriesType := newSeries.AsTypedNode.StaticType;
valueType := newValue.AsTypedNode.StaticType;
// 3. Check types
if (seriesType.Kind <> stUnknown) then
begin
if (seriesType.Kind <> TStaticTypeKind.stSeries) then
@@ -670,13 +712,11 @@ begin
raise ETypeException.Create('Lookback parameter for "add" must be an ordinal value.');
end;
// 4. Create new node
Result := TAst.AddSeriesItem(newSeries.AsIdentifier, newValue, newLookback, TTypes.Void);
end;
function TTypeChecker.VisitNop(const Node: INopNode): IAstNode;
begin
// This is a leaf node. Assign its final type as Void.
Result := TAst.Nop(TTypes.Void);
end;
@@ -685,19 +725,14 @@ var
seriesType: IStaticType;
newSeries: IAstNode;
begin
// 1. Visit children
newSeries := Accept(Node.Series);
// 2. Get type
seriesType := newSeries.AsTypedNode.StaticType;
// 3. Check type
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]);
// 4. Create new node
Result := TAst.SeriesLength(newSeries.AsIdentifier, TTypes.Ordinal);
end;