-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathstatement.go
More file actions
1186 lines (1091 loc) · 33.5 KB
/
Copy pathstatement.go
File metadata and controls
1186 lines (1091 loc) · 33.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2026 Synnax Labs, Inc.
//
// Use of this software is governed by the Business Source License included in the file
// licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with the Business Source
// License, use of this software will be governed by the Apache License, Version 2.0,
// included in the file licenses/APL.txt.
// Package statement implements semantic analysis for Arc statements including variable
// declarations, assignments, conditionals, and channel operations.
package statement
import (
"github.com/antlr4-go/antlr/v4"
"github.com/synnaxlabs/arc/analyzer/context"
"github.com/synnaxlabs/arc/analyzer/expression"
atypes "github.com/synnaxlabs/arc/analyzer/types"
"github.com/synnaxlabs/arc/analyzer/units"
"github.com/synnaxlabs/arc/diagnostics"
"github.com/synnaxlabs/arc/ir"
"github.com/synnaxlabs/arc/parser"
"github.com/synnaxlabs/arc/symbol"
"github.com/synnaxlabs/arc/types"
"github.com/synnaxlabs/x/errors"
"github.com/synnaxlabs/x/query"
)
// AnalyzeBlock validates a block of statements in a new scope.
func AnalyzeBlock(ctx context.Context[parser.IBlockContext]) {
blockScope, err := ctx.Scope.Add(ctx, symbol.Symbol{
Kind: symbol.KindBlock,
AST: ctx.AST,
})
if err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
return
}
for _, stmt := range ctx.AST.AllStatement() {
Analyze(context.Child(ctx, stmt).WithScope(blockScope))
}
}
// Analyze validates a statement and dispatches to specialized handlers based on statement type.
func Analyze(ctx context.Context[parser.IStatementContext]) {
switch {
case ctx.AST.VariableDeclaration() != nil:
analyzeVariableDeclaration(context.Child(ctx, ctx.AST.VariableDeclaration()))
case ctx.AST.IfStatement() != nil:
analyzeIfStatement(context.Child(ctx, ctx.AST.IfStatement()))
case ctx.AST.ReturnStatement() != nil:
analyzeReturnStatement(context.Child(ctx, ctx.AST.ReturnStatement()))
case ctx.AST.Assignment() != nil:
analyzeAssignment(context.Child(ctx, ctx.AST.Assignment()))
case ctx.AST.Expression() != nil:
expression.Analyze(context.Child(ctx, ctx.AST.Expression()))
}
}
func analyzeVariableDeclaration(ctx context.Context[parser.IVariableDeclarationContext]) {
if local := ctx.AST.LocalVariable(); local != nil {
analyzeLocalVariable(context.Child(ctx, local))
return
}
if stateful := ctx.AST.StatefulVariable(); stateful != nil {
analyzeStatefulVariable(context.Child(ctx, stateful))
}
}
func analyzeVariableDeclarationType[ASTNode antlr.ParserRuleContext](
ctx context.Context[ASTNode],
name string,
expression parser.IExpressionContext,
typeCtx parser.ITypeContext,
) types.Type {
if typeCtx != nil {
varType, err := atypes.InferFromTypeContext(typeCtx)
if err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
return types.Type{}
}
if expression != nil {
exprType := atypes.InferFromExpression(context.Child(ctx, expression))
if exprType.IsValid() && varType.IsValid() {
// Check magnitude safety for unit conversions (warnings only)
if varType.Unit != nil && exprType.Unit != nil {
units.CheckAssignmentScaleSafety(ctx, exprType, varType, nil)
}
// If either type is a type variable, add a constraint instead of checking directly
if exprType.Kind == types.KindVariable || varType.Kind == types.KindVariable {
if err := atypes.Check(ctx.Constraints, varType, exprType, ctx.AST, "assignment type compatibility"); err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
return types.Type{}
}
} else {
isLiteral := isLiteralExpression(context.Child(ctx, expression))
if (isLiteral && !atypes.LiteralAssignmentCompatible(varType, exprType)) || (!isLiteral && !atypes.Compatible(varType, exprType)) {
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST, "type mismatch: cannot assign %s to '%s' (type %s)", exprType, name, varType,
))
return types.Type{}
}
}
}
}
return varType
}
if expression != nil {
return atypes.InferFromExpression(context.Child(ctx, expression))
}
ctx.Diagnostics.Add(diagnostics.Errorf(ctx.AST, "no type declaration found"))
return types.Type{}
}
func isLiteralExpression(ctx context.Context[parser.IExpressionContext]) bool {
primary := parser.GetPrimaryExpression(ctx.AST)
return primary != nil && primary.Literal() != nil
}
func analyzeLocalVariable(ctx context.Context[parser.ILocalVariableContext]) {
name := ctx.AST.IDENTIFIER().GetText()
expr := ctx.AST.Expression()
if expr != nil && ctx.AST.Type_() == nil {
childCtx := context.Child(ctx, expr)
if chanSym := getChannelSymbol(childCtx); chanSym != nil {
// Global channel - create a variable that holds the channel key
// Use KindVariable so it gets a WASM local assigned
sourceID := chanSym.ID
_, err := childCtx.Scope.Add(ctx, symbol.Symbol{
Name: name,
Kind: symbol.KindVariable,
Type: chanSym.Type, // Keep Chan(F32) type
AST: ctx.AST,
SourceID: &sourceID,
})
if err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
}
return
}
}
if expr != nil {
expression.Analyze(context.Child(ctx, expr))
}
varType := analyzeVariableDeclarationType(
ctx,
name,
expr,
ctx.AST.Type_(),
)
if !varType.IsValid() {
_, _ = ctx.Scope.Add(ctx, symbol.Symbol{
Name: name,
Type: types.Type{},
AST: ctx.AST,
})
return
}
// If assigning from a symbol with channel type, propagate its SourceID
var sourceID *int
if varType.Kind == types.KindChan && expr != nil {
sourceID = getChannelSourceFromExpr(ctx, expr)
}
_, err := ctx.Scope.Add(ctx, symbol.Symbol{
Name: name,
Type: varType,
AST: ctx.AST,
SourceID: sourceID,
})
if err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
}
}
// getChannelSymbol checks if an expression is a simple identifier referencing
// a global channel symbol (KindChannel). Returns the symbol if so, nil otherwise.
func getChannelSymbol(ctx context.Context[parser.IExpressionContext]) *symbol.Symbol {
primary := parser.GetPrimaryExpression(ctx.AST)
if primary == nil || primary.IDENTIFIER() == nil {
return nil
}
sym, err := ctx.Scope.Resolve(ctx, primary.IDENTIFIER().GetText())
if err != nil {
return nil
}
// Must be an actual channel symbol (KindChannel), not just a symbol with channel type.
// Config params with channel type (KindConfig) should be read from, not aliased.
if sym.Kind == symbol.KindChannel && sym.Type.Kind == types.KindChan {
return &sym.Symbol
}
return nil
}
// getChannelSourceFromExpr extracts the source ID from an expression that references
// a symbol with channel type. Returns a pointer to the source ID, or nil if not found.
func getChannelSourceFromExpr[ASTNode antlr.ParserRuleContext](
ctx context.Context[ASTNode],
expr parser.IExpressionContext,
) *int {
primary := parser.GetPrimaryExpression(expr)
if primary == nil || primary.IDENTIFIER() == nil {
return nil
}
sym, err := ctx.Scope.Resolve(ctx, primary.IDENTIFIER().GetText())
if err != nil {
return nil
}
if sym.Type.Kind != types.KindChan {
return nil
}
// If the symbol already has a SourceID, propagate it
if sym.SourceID != nil {
return sym.SourceID
}
// Otherwise, this symbol IS the source (e.g., a config param)
id := sym.ID
return &id
}
func analyzeStatefulVariable(ctx context.Context[parser.IStatefulVariableContext]) {
name := ctx.AST.IDENTIFIER().GetText()
expr := ctx.AST.Expression()
varType := analyzeVariableDeclarationType(
ctx,
name,
expr,
ctx.AST.Type_(),
)
if !varType.IsValid() {
_, _ = ctx.Scope.Add(ctx, symbol.Symbol{
Name: name,
Kind: symbol.KindStatefulVariable,
Type: types.Type{},
AST: ctx.AST,
})
return
}
// Stateful variables store VALUES, not channel references.
// If initialized from a channel, unwrap to get the value type.
if varType.Kind == types.KindChan {
varType = varType.Unwrap()
}
_, err := ctx.Scope.Add(ctx, symbol.Symbol{
Name: name,
Kind: symbol.KindStatefulVariable,
Type: varType,
AST: ctx.AST,
})
if err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
return
}
if expr != nil {
expression.Analyze(context.Child(ctx, expr))
}
}
func analyzeIfStatement(ctx context.Context[parser.IIfStatementContext]) {
if expr := ctx.AST.Expression(); expr != nil {
expression.Analyze(context.Child(ctx, expr))
}
if block := ctx.AST.Block(); block != nil {
AnalyzeBlock(context.Child(ctx, block))
}
for _, elseIfClause := range ctx.AST.AllElseIfClause() {
if expr := elseIfClause.Expression(); expr != nil {
expression.Analyze(context.Child(ctx, expr))
}
if block := elseIfClause.Block(); block != nil {
AnalyzeBlock(context.Child(ctx, block))
}
}
if elseClause := ctx.AST.ElseClause(); elseClause != nil {
if block := elseClause.Block(); block != nil {
AnalyzeBlock(context.Child(ctx, block))
}
}
}
func analyzeReturnStatement(ctx context.Context[parser.IReturnStatementContext]) {
enclosingScope, err := ctx.Scope.ClosestAncestorOfKind(symbol.KindFunction)
if err != nil {
enclosingScope, err = ctx.Scope.ClosestAncestorOfKind(symbol.KindFunction)
if err != nil {
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST,
"return statement can only be used inside a function body",
))
return
}
}
funcName := enclosingScope.Name
var expectedReturnType types.Type
if enclosingScope.Kind == symbol.KindFunction {
if param, ok := enclosingScope.Type.Outputs.Get(ir.DefaultOutputParam); ok {
expectedReturnType = param.Type
}
}
returnExpr := ctx.AST.Expression()
if returnExpr != nil {
expression.Analyze(context.Child(ctx, returnExpr))
actualReturnType := atypes.InferFromExpression(context.Child(ctx, returnExpr).WithTypeHint(expectedReturnType)).UnwrapChan()
// Check for void function first - this error applies even in type inference mode
if !expectedReturnType.IsValid() && !ctx.InTypeInferenceMode {
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST,
"cannot return a value from a function with no return type",
))
return
}
// Skip type compatibility validation in type inference mode - we're just collecting types
if ctx.InTypeInferenceMode {
return
}
if actualReturnType.IsValid() && expectedReturnType.IsValid() {
// If either type is a type variable, add a constraint instead of checking directly
if actualReturnType.Kind == types.KindVariable || expectedReturnType.Kind == types.KindVariable {
if err = atypes.Check(
ctx.Constraints,
expectedReturnType,
actualReturnType,
ctx.AST,
"return type compatibility",
); err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
return
}
} else {
isLiteral := isLiteralExpression(context.Child(ctx, returnExpr))
useLiteralRules := isLiteral || (actualReturnType.IsNumeric() && expectedReturnType.IsNumeric())
if useLiteralRules {
if !atypes.LiteralAssignmentCompatible(expectedReturnType, actualReturnType) {
ctx.Diagnostics.Add(diagnostics.Errorf(ctx.AST,
"cannot return %s from '%s': expected %s",
actualReturnType,
funcName,
expectedReturnType,
))
return
}
} else {
if !atypes.Compatible(expectedReturnType, actualReturnType) {
ctx.Diagnostics.Add(diagnostics.Errorf(ctx.AST,
"cannot return %s from '%s': expected %s",
actualReturnType,
funcName,
expectedReturnType,
))
return
}
}
}
}
return
}
if expectedReturnType.IsValid() {
ctx.Diagnostics.Add(diagnostics.Errorf(ctx.AST,
"return statement in '%s' missing value of type %s",
funcName,
expectedReturnType,
))
}
}
func analyzeChannelAssignment(ctx context.Context[parser.IAssignmentContext], channelSym *symbol.Symbol) {
// Validate we're in a function context (channel writes only allowed in imperative context)
fn, fnErr := ctx.Scope.ClosestAncestorOfKind(symbol.KindFunction)
if errors.Skip(fnErr, query.ErrNotFound) != nil {
ctx.Diagnostics.Add(diagnostics.Error(fnErr, ctx.AST))
return
}
if fn != nil {
// Use SourceID if available (for variables assigned from config params),
// otherwise use the symbol's own ID
writeID := uint32(channelSym.ID)
if channelSym.SourceID != nil {
writeID = uint32(*channelSym.SourceID)
}
fn.Channels.Write.Add(writeID)
}
// Track this as a channel write in the function
// Analyze and type-check the expression
expr := ctx.AST.Expression()
if expr == nil {
return
}
expression.Analyze(context.Child(ctx, expr))
exprType := atypes.InferFromExpression(context.Child(ctx, expr))
chanValueType := channelSym.Type.Unwrap()
if !exprType.IsValid() || !chanValueType.IsValid() {
return
}
// Check magnitude safety for unit conversions (warnings only)
if chanValueType.Unit != nil && exprType.Unit != nil {
units.CheckAssignmentScaleSafety(ctx, exprType, chanValueType, nil)
}
// If either type is a type variable, add a constraint instead of checking directly
if exprType.Kind == types.KindVariable || chanValueType.Kind == types.KindVariable {
if err := atypes.Check(
ctx.Constraints,
chanValueType,
exprType,
ctx.AST,
"channel write type compatibility",
); err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
return
}
} else {
isLiteral := isLiteralExpression(context.Child(ctx, expr))
if (isLiteral && !atypes.LiteralAssignmentCompatible(chanValueType, exprType)) || (!isLiteral && !atypes.Compatible(chanValueType, exprType)) {
channelName := ctx.AST.IDENTIFIER().GetText()
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST, "type mismatch: cannot write %s to channel '%s' (type %s)",
exprType,
channelName,
chanValueType,
))
}
}
}
// analyzeIndexedAssignment validates indexed assignment statements (series[i] = value)
func analyzeIndexedAssignment(
ctx context.Context[parser.IAssignmentContext],
varScope *symbol.Scope,
indexOrSlice parser.IIndexOrSliceContext,
) {
// 1. Verify base is a series type
if varScope.Type.Kind != types.KindSeries {
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST,
"indexed assignment only supported on series types",
))
return
}
// 2. Only support single index (not slices) for now
if indexOrSlice.COLON() != nil {
ctx.Diagnostics.Add(diagnostics.Errorf(ctx.AST, "slice assignment not supported"))
return
}
// 3. Analyze index expression
indexExprs := indexOrSlice.AllExpression()
if len(indexExprs) != 1 {
return
}
expression.Analyze(context.Child(ctx, indexExprs[0]))
// 4. Analyze value expression and check type compatibility
valueExpr := ctx.AST.Expression()
expression.Analyze(context.Child(ctx, valueExpr))
elemType := *varScope.Type.Elem
exprType := atypes.InferFromExpression(context.Child(ctx, valueExpr))
if !exprType.IsValid() || !elemType.IsValid() {
return
}
// If either type is a type variable, add a constraint instead of checking directly
if exprType.Kind == types.KindVariable || elemType.Kind == types.KindVariable {
if err := atypes.Check(
ctx.Constraints,
elemType,
exprType,
ctx.AST,
"indexed assignment type compatibility",
); err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
}
return
}
isLiteral := isLiteralExpression(context.Child(ctx, valueExpr))
if (isLiteral && !atypes.LiteralAssignmentCompatible(elemType, exprType)) ||
(!isLiteral && !atypes.Compatible(elemType, exprType)) {
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST,
"type mismatch: cannot assign %s to series element of type %s",
exprType,
elemType,
))
}
}
// analyzeIndexedCompoundAssignment validates indexed compound assignment statements (series[i] += value)
func analyzeIndexedCompoundAssignment(
ctx context.Context[parser.IAssignmentContext],
varScope *symbol.Scope,
indexOrSlice parser.IIndexOrSliceContext,
compoundOp parser.ICompoundOpContext,
) {
if varScope.Type.Kind != types.KindSeries {
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST,
"indexed compound assignment only supported on series types",
))
return
}
if indexOrSlice.COLON() != nil {
ctx.Diagnostics.Add(diagnostics.Errorf(ctx.AST, "slice compound assignment not supported"))
return
}
elemType := *varScope.Type.Elem
if elemType.Kind == types.KindString {
if compoundOp.PLUS_ASSIGN() == nil {
ctx.Diagnostics.Add(diagnostics.Errorf(ctx.AST, "string series elements only support += operator"))
return
}
} else if !elemType.IsNumeric() {
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST,
"compound assignment requires numeric element type, got %s",
elemType,
))
return
}
indexExpressions := indexOrSlice.AllExpression()
if len(indexExpressions) != 1 {
return
}
expression.Analyze(context.Child(ctx, indexExpressions[0]))
expr := ctx.AST.Expression()
if expr == nil {
return
}
expression.Analyze(context.Child(ctx, expr))
exprType := atypes.InferFromExpression(context.Child(ctx, expr))
if !exprType.IsValid() || !elemType.IsValid() {
return
}
if exprType.Kind == types.KindVariable || elemType.Kind == types.KindVariable {
if err := atypes.Check(ctx.Constraints, elemType, exprType, ctx.AST,
"indexed compound assignment type compatibility"); err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
}
return
}
isLiteral := isLiteralExpression(context.Child(ctx, expr))
if (isLiteral && !atypes.LiteralAssignmentCompatible(elemType, exprType)) ||
(!isLiteral && !atypes.Compatible(elemType, exprType)) {
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST,
"type mismatch: cannot use %s in compound assignment to series element of type %s",
exprType,
elemType,
))
}
}
// analyzeSeriesCompoundAssignment validates whole-series compound assignment (series += value)
// Supports both series += scalar (broadcast) and series += series (element-wise)
func analyzeSeriesCompoundAssignment(
ctx context.Context[parser.IAssignmentContext],
varScope *symbol.Scope,
compoundOp parser.ICompoundOpContext,
) {
elemType := *varScope.Type.Elem
if elemType.Kind == types.KindString {
if compoundOp.PLUS_ASSIGN() == nil {
ctx.Diagnostics.Add(diagnostics.Errorf(ctx.AST, "string series only support += operator"))
return
}
} else if !elemType.IsNumeric() {
ctx.Diagnostics.Add(diagnostics.Errorf(ctx.AST, "compound assignment requires numeric element type, got %s", elemType))
return
}
expr := ctx.AST.Expression()
if expr == nil {
return
}
expression.Analyze(context.Child(ctx, expr))
exprType := atypes.InferFromExpression(context.Child(ctx, expr))
if !exprType.IsValid() || !elemType.IsValid() {
return
}
if exprType.Kind == types.KindVariable || elemType.Kind == types.KindVariable {
targetType := elemType
if exprType.Kind == types.KindSeries {
targetType = *exprType.Elem
}
if err := atypes.Check(ctx.Constraints, elemType, targetType, ctx.AST,
"series compound assignment type compatibility"); err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
}
return
}
// Type compatibility: RHS must be scalar or series with matching element type
if exprType.Kind == types.KindSeries {
rhsElemType := *exprType.Elem
if !atypes.Compatible(elemType, rhsElemType) {
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST,
"type mismatch: cannot use %s in compound assignment to %s",
exprType,
varScope.Type,
))
}
} else {
isLiteral := isLiteralExpression(context.Child(ctx, expr))
if (isLiteral && !atypes.LiteralAssignmentCompatible(elemType, exprType)) ||
(!isLiteral && !atypes.Compatible(elemType, exprType)) {
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST,
"type mismatch: cannot use %s in compound assignment to series of %s",
exprType,
elemType,
))
}
}
}
func analyzeCompoundAssignment(
ctx context.Context[parser.IAssignmentContext],
varScope *symbol.Scope,
compoundOp parser.ICompoundOpContext,
) {
if indexOrSlice := ctx.AST.IndexOrSlice(); indexOrSlice != nil {
analyzeIndexedCompoundAssignment(ctx, varScope, indexOrSlice, compoundOp)
return
}
varType := varScope.Type
if varType.Kind == types.KindChan {
ctx.Diagnostics.Add(diagnostics.Errorf(ctx.AST, "compound assignment not supported on channels"))
return
}
if varType.Kind == types.KindSeries {
analyzeSeriesCompoundAssignment(ctx, varScope, compoundOp)
return
}
if varType.Kind == types.KindString {
if compoundOp.PLUS_ASSIGN() == nil {
ctx.Diagnostics.Add(diagnostics.Errorf(ctx.AST, "strings only support += operator"))
return
}
} else if !varType.IsNumeric() {
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST,
"compound assignment requires numeric type, got %s",
varType,
))
return
}
expr := ctx.AST.Expression()
if expr == nil {
return
}
expression.Analyze(context.Child(ctx, expr))
exprType := atypes.InferFromExpression(context.Child(ctx, expr))
if !exprType.IsValid() || !varType.IsValid() {
return
}
if exprType.Kind == types.KindVariable || varType.Kind == types.KindVariable {
if err := atypes.Check(
ctx.Constraints,
varType,
exprType,
ctx.AST,
"compound assignment type compatibility",
); err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
}
return
}
if atypes.Compatible(varType, exprType) {
return
}
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST,
"type mismatch: cannot use %s in compound assignment to %s",
exprType,
varType,
))
}
func analyzeAssignment(ctx context.Context[parser.IAssignmentContext]) {
name := ctx.AST.IDENTIFIER().GetText()
varScope, err := ctx.Scope.Resolve(ctx, name)
if err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
return
}
if compoundOp := ctx.AST.CompoundOp(); compoundOp != nil {
analyzeCompoundAssignment(ctx, varScope, compoundOp)
return
}
if indexOrSlice := ctx.AST.IndexOrSlice(); indexOrSlice != nil {
analyzeIndexedAssignment(ctx, varScope, indexOrSlice)
return
}
if varScope.Type.Kind == types.KindChan {
analyzeChannelAssignment(ctx, &varScope.Symbol)
return
}
expr := ctx.AST.Expression()
if expr == nil {
return
}
expression.Analyze(context.Child(ctx, expr))
exprType := atypes.InferFromExpression(context.Child(ctx, expr))
if !exprType.IsValid() || !varScope.Type.IsValid() {
return
}
varType := varScope.Type
// Check magnitude safety for unit conversions (warnings only)
if varType.Unit != nil && exprType.Unit != nil {
units.CheckAssignmentScaleSafety(ctx, exprType, varType, nil)
}
// Check structural compatibility (series/channel structure must match)
if !types.StructuralMatch(varType, exprType) {
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST, "type mismatch: cannot assign %s to '%s' (type %s)", exprType, name, varType,
))
return
}
// If either type is a type variable, add a constraint instead of checking directly
if exprType.Kind == types.KindVariable || varType.Kind == types.KindVariable {
if err := atypes.Check(ctx.Constraints, varType, exprType, ctx.AST, "assignment type compatibility"); err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
}
return
}
if atypes.AssignmentCompatible(varType, exprType) {
return
}
ctx.Diagnostics.Add(diagnostics.Errorf(
ctx.AST, "type mismatch: cannot assign %s to '%s' (type %s)", exprType, name, varType,
))
}
// AnalyzeFunctionBody analyzes a block and infers its return type by examining
// all return statements across control flow paths.
// Returns the inferred return type (invalid if error occurred).
func AnalyzeFunctionBody(ctx context.Context[parser.IBlockContext]) types.Type {
ctx.InTypeInferenceMode = true
funcScope, err := ctx.Scope.Add(ctx, symbol.Symbol{
Kind: symbol.KindFunction,
Type: types.Function(types.FunctionProperties{}),
AST: ctx.AST,
})
if err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
return types.Type{}
}
blockScope, err := funcScope.Add(ctx, symbol.Symbol{
Kind: symbol.KindBlock,
AST: ctx.AST,
})
if err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
return types.Type{}
}
var collectedReturnTypes []types.Type
for _, stmt := range ctx.AST.AllStatement() {
Analyze(context.Child(ctx, stmt).WithScope(blockScope))
returnTypes := collectStatementReturnTypes(
context.Child(ctx, stmt).WithScope(blockScope),
)
for _, rt := range returnTypes {
if rt.IsValid() {
collectedReturnTypes = append(collectedReturnTypes, rt)
}
}
}
inferredType, err := unifyReturnTypes(collectedReturnTypes)
if err != nil {
ctx.Diagnostics.Add(diagnostics.Error(err, ctx.AST))
return types.Type{}
}
return inferredType.Unwrap()
}
// collectStatementReturnTypes extracts all return types from a statement.
// Returns a slice of types (empty if no returns).
func collectStatementReturnTypes(
ctx context.Context[parser.IStatementContext],
) []types.Type {
switch {
case ctx.AST.ReturnStatement() != nil:
returnStmt := ctx.AST.ReturnStatement()
returnExpr := returnStmt.Expression()
if returnExpr == nil {
// Return statement with no expression (void return)
return []types.Type{{}}
}
returnType := atypes.InferFromExpression(context.Child(ctx, returnExpr))
if returnType.IsValid() {
return []types.Type{returnType}
}
return []types.Type{}
case ctx.AST.IfStatement() != nil:
_, returnTypes := getIfStatementReturnTypes(
context.Child(ctx, ctx.AST.IfStatement()),
)
return returnTypes
default:
return []types.Type{}
}
}
// getIfStatementReturnTypes recursively extracts return types from if/else branches.
// Returns (allPathsReturn bool, returnTypes []types.Type)
func getIfStatementReturnTypes(
ctx context.Context[parser.IIfStatementContext],
) (bool, []types.Type) {
var returnTypes []types.Type
allPathsReturn := true
// Check main if block
if block := ctx.AST.Block(); block != nil {
hasReturn, blockTypes := getBlockReturnTypes(
context.Child(ctx, block),
)
if hasReturn {
returnTypes = append(returnTypes, blockTypes...)
} else {
allPathsReturn = false
}
}
// Check else-if clauses
for _, elseIfClause := range ctx.AST.AllElseIfClause() {
if block := elseIfClause.Block(); block != nil {
hasReturn, blockTypes := getBlockReturnTypes(
context.Child(ctx, block),
)
if hasReturn {
returnTypes = append(returnTypes, blockTypes...)
} else {
allPathsReturn = false
}
}
}
// Check else clause
if elseClause := ctx.AST.ElseClause(); elseClause != nil {
if block := elseClause.Block(); block != nil {
hasReturn, blockTypes := getBlockReturnTypes(
context.Child(ctx, block),
)
if hasReturn {
returnTypes = append(returnTypes, blockTypes...)
} else {
allPathsReturn = false
}
}
} else {
// No else clause means not all paths return
allPathsReturn = false
}
return allPathsReturn, returnTypes
}
// getBlockReturnTypes extracts all return types from a block's statements.
// Returns (hasReturn bool, returnTypes []types.Type)
func getBlockReturnTypes(
ctx context.Context[parser.IBlockContext],
) (bool, []types.Type) {
var returnTypes []types.Type
for _, stmt := range ctx.AST.AllStatement() {
stmtTypes := collectStatementReturnTypes(context.Child(ctx, stmt))
for _, rt := range stmtTypes {
if rt.IsValid() {
returnTypes = append(returnTypes, rt)
}
}
}
return len(returnTypes) > 0, returnTypes
}
// unifyReturnTypes unifies multiple return types to find the smallest reasonable common type.
func unifyReturnTypes(
returnTypes []types.Type,
) (types.Type, error) {
if len(returnTypes) == 0 {
return types.Type{}, nil
}
// Unwrap all types first (Chan(T) -> T, Series(T) -> T) for consistent handling
unwrappedTypes := make([]types.Type, len(returnTypes))
for i, t := range returnTypes {
unwrappedTypes[i] = t.Unwrap()
}
if len(unwrappedTypes) == 1 {
t := unwrappedTypes[0]
// If it's a type variable (literal), resolve it to a concrete default type
if t.Kind == types.KindVariable {
if t.Constraint != nil && t.Constraint.Kind == types.KindIntegerConstant {
return types.I64(), nil
}
if t.Constraint != nil && t.Constraint.Kind == types.KindFloatConstant {
return types.F64(), nil
}
if t.Constraint != nil && t.Constraint.Kind == types.KindNumericConstant {
return types.F64(), nil
}
if t.Constraint != nil && t.Constraint.Kind == types.KindExactIntegerFloatConstant {
return types.F64(), nil
}
}
return t, nil
}
// Separate type variables from concrete types (now all unwrapped)
var concreteTypes []types.Type
var typeVariables []types.Type
for _, t := range unwrappedTypes {
if t.Kind == types.KindVariable {
typeVariables = append(typeVariables, t)
} else {
concreteTypes = append(concreteTypes, t)
}
}
// If all are type variables (all literals), unify them to a concrete default type
if len(concreteTypes) == 0 {
// All literals should unify to a default concrete type
// For integers, default to i64; for floats, default to f64
firstVar := typeVariables[0]
if firstVar.Constraint != nil && firstVar.Constraint.Kind == types.KindIntegerConstant {
return types.I64(), nil
}
if firstVar.Constraint != nil && firstVar.Constraint.Kind == types.KindFloatConstant {
return types.F64(), nil
}
if firstVar.Constraint != nil && firstVar.Constraint.Kind == types.KindNumericConstant {
return types.F64(), nil
}
if firstVar.Constraint != nil && firstVar.Constraint.Kind == types.KindExactIntegerFloatConstant {
return types.F64(), nil
}
return typeVariables[0], nil
}
// If we have concrete types, use them to guide the unification
// Replace type variables with types compatible with the concrete types
resolvedTypes := make([]types.Type, 0, len(unwrappedTypes))
for _, t := range unwrappedTypes {
if t.Kind == types.KindVariable {
// Infer appropriate type based on concrete types present
resolved := resolveTypeVariableWithContext(t, concreteTypes)
resolvedTypes = append(resolvedTypes, resolved)
} else {
resolvedTypes = append(resolvedTypes, t)
}
}
firstType := resolvedTypes[0]
allEqual := true
for _, t := range resolvedTypes[1:] {
if !types.Equal(firstType, t) {
allEqual = false
break
}