-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSema.cpp
More file actions
1874 lines (1765 loc) · 63.4 KB
/
Copy pathSema.cpp
File metadata and controls
1874 lines (1765 loc) · 63.4 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
#include "Sema.h"
#include <cctype>
#include <set>
#include <map>
using namespace QLang;
using namespace std;
// A member's declared type is only recorded on the typed AST when it is a
// CONCRETE type — never when it names one of the enclosing struct's generic
// parameters (e.g. Box<T>'s `T value`). Codegen substitutes those at
// monomorphization time; recording the bare parameter would make codegen read
// "T" instead of the concrete argument. Sema leaves such nodes nullptr so
// codegen keeps its substitution path (FR-010/FR-011).
static bool isGenericParamName( StructDefinition *structDef, const string &typeName )
{
if ( structDef == nullptr )
return false;
for ( const auto &gp : structDef->getGenericParams() )
if ( gp.mName == typeName )
return true;
return false;
}
// True when `t` MENTIONS one of the struct's generic params anywhere — the
// param itself (`V value`) or nested in type arguments (`Array<K> keys`). Such
// a type is NOT concrete: recording it on the typed AST would make codegen read
// "K"/"V" instead of performing the instance substitution.
static bool mentionsGenericParam( StructDefinition *structDef, Type *t )
{
if ( t == nullptr )
return false;
if ( isGenericParamName( structDef, t->getName() ) )
return true;
for ( int i = 0; i < t->getNumTypeParams(); i++ )
if ( mentionsGenericParam( structDef, t->getTypeParam( i ) ) )
return true;
return false;
}
// ---------------------------------------------------------------------------
// U4: type compatibility (closed conversion set — design decision 6)
// ---------------------------------------------------------------------------
// Scalar primitives that interconvert implicitly. Integer-width promotion is the
// documented implicit conversion; float<->double and the fact that bool/char are
// lowered to integers (true/false parse as ConstInteger "int") make the scalar
// family mutually compatible — matching codegen's existing coercions. Rejecting
// within this set would false-positive on pervasive bool/int/char/float mixing.
static bool isScalarTypeName( const string &n )
{
return n == "int" || n == "long" || n == "short" || n == "byte" ||
n == "char" || n == "bool" || n == "float" || n == "double";
}
// A single upper-case letter is, by house convention, a generic type parameter
// (T, U, K, V). Treat it as compatible so U4 never rejects generic code (U5 owns
// constraint checking).
static bool looksGenericParam( const string &n )
{
return n.size() == 1 && isupper( (unsigned char)n[0] );
}
// isCheckableType: a type whose values U4 can confidently compare. Scalars,
// string, and concrete user structs qualify. Enums (Result/Option/user), generic
// parameters, inferred `var`, `fn` function types, Array<T>, and unknown names do
// NOT — their values are not fully typed by U3, so U4 must not judge them.
bool Sema::isCheckableType( Type *t )
{
if ( t == nullptr )
return false;
const string &n = t->getName();
if ( n.empty() )
return false;
if ( isScalarTypeName( n ) || n == "string" )
return true;
return dynamic_cast<StructDefinition *>( mScope->findSymbol( n ) ) != nullptr;
}
// typesCompatible returns true (do NOT reject) unless BOTH types are concretely
// checkable and provably incompatible. nullptr / empty / non-checkable / generic
// types are never rejected — U3 leaves many nodes untyped and later units type
// them; U4 only fires on clearly determinable, clearly incompatible pairs to
// avoid false positives (FR-001/004/006). The only implicit conversions are the
// scalar family (integer width promotion + bool/char/float interchange).
bool Sema::typesCompatible( Type *from, Type *to )
{
if ( from == nullptr || to == nullptr )
return true;
const string &f = from->getName();
const string &t = to->getName();
if ( f.empty() || t.empty() )
return true;
if ( f == t )
return true;
if ( looksGenericParam( f ) || looksGenericParam( t ) )
return true;
// Container/enum kinds are mutually incompatible even though their generic
// type arguments keep them out of the "checkable" set below: e.g. assigning
// a `query T |> first` result (Option<T>) to an Array<T> is always wrong.
{
auto isContainerKind = []( const string &n ) {
return n == "Array" || n == "Option" || n == "Result" ||
n == "Buffer" || n == "Map" || n == "Set";
};
if ( isContainerKind( f ) && isContainerKind( t ) )
return false; // both containers, different kinds (f != t here)
}
if ( !isCheckableType( from ) || !isCheckableType( to ) )
return true;
if ( isScalarTypeName( f ) && isScalarTypeName( t ) )
return true;
return false;
}
static string typeName( Type *t )
{
return ( t != nullptr && !t->getName().empty() ) ? t->getName() : string( "<unknown>" );
}
// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------
bool Sema::analyze( Module *module, Scope *scope, DiagnosticEngine &diag )
{
if ( module == nullptr || module->isExtern() )
return true;
Sema sema( scope, diag, module->getDefiningFile() );
for ( auto &s : module->mStructList )
sema.visitStruct( s );
// The reserved "__" family covers every kind of source declaration, so the
// documented rule matches the enforced one.
for ( const auto &e : module->getEnumList() )
{
if ( e == nullptr )
continue;
sema.checkReservedName( e->getName(), e->getLocation(), "enum" );
// P9 (4): an enum's variants and payloads ARE its API (D17), and the
// .bmod ships them, so a payload naming a private type would emit a
// reference the interface never declares.
if ( e->isPublic() )
{
for ( const auto &v : e->getVariants() )
for ( const auto &pt : v.mAssociatedTypes )
sema.checkExportedTypeRef( (const Type *)pt, e->getLocation(),
"payload of exported enum '" + e->getName() +
"' variant '" + v.mName + "'" );
}
}
for ( const auto &p : module->getProtocolList() )
{
if ( p != nullptr )
sema.checkReservedName( p->getName(), p->getLocation(), "protocol" );
}
for ( auto &f : module->mFunctionList )
{
// `extern fn` names a foreign C symbol (the runtime's __blang_* entry
// points), so it is exempt from both the reserved-family rule and the
// body requirement.
if ( f != nullptr && !f->isExtern() )
{
sema.checkReservedName( f->getName(), f->getLocation(), "function" );
// P9 (1): an exported function's parameter and return types.
if ( f->isPublic() )
sema.checkExportedSignature( f, "exported function '" + f->getName() + "'" );
}
sema.checkBodylessMember( f, std::string() );
sema.visitFunction( f );
}
return !sema.mReported;
}
// ---------------------------------------------------------------------------
// Declaration walk
// ---------------------------------------------------------------------------
void Sema::visitStruct( StructDefinition *structDef )
{
if ( structDef == nullptr )
return;
// Table structs map fields 1:1 to SQL columns, so every field must have a
// column representation (primitive or string). The row mapper would leave a
// nested struct/array field silently null — a guaranteed null-deref on
// first access — so reject it here, located, in all build modes.
if ( structDef->isTable() )
{
for ( const auto &f : structDef->getFields() )
{
const Type *ft = f->getVariableType();
string fn = ( ft != nullptr ) ? ft->getName() : string();
if ( !isScalarTypeName( fn ) && fn != "string" )
{
mDiag.error( structDef->getLocation(),
"table struct '" + structDef->getName() + "' field '" +
f->getName() + "' has type '" + fn +
"', which has no SQL column mapping (columns support "
"int/long/short/char/bool/float/double/string)" );
mReported = true;
}
}
}
checkReservedName( structDef->getName(), structDef->getLocation(), "struct" );
// P9. Only an EXPORTED struct's signatures cross a boundary.
if ( structDef->isPublic() )
{
const string sname = structDef->getName();
// (3) FIELD types of an exported DATA-CONTRACT struct only (U5 narrowing).
//
// U3 checked every `pub struct`'s field types, because at that point the
// emitter shipped field layout for all of them, so every field type
// crossed the boundary. U5 (format 4) DROPS field layout for a plain
// `pub struct` — its field types no longer cross, so a private field type
// is fine there and this check would be a false positive. A `table`/`@json`
// struct still ships its fields as D15 metadata, so its field types still
// cross and still must be exported. This is exactly the narrowing U3's
// comment anticipated ("once layout is dropped, only table/@json structs
// keep field metadata, and only those fields still need to be exported").
if ( isExportedDataContract( structDef ) )
{
for ( const auto &f : structDef->getFields() )
{
if ( f == nullptr )
continue;
checkExportedTypeRef( f->getVariableType(), structDef->getLocation(),
"field '" + f->getName() +
"' of exported data-contract struct '" + sname + "'" );
}
}
// (5) A protocol named in an exported conformance record. U2's emitter
// SKIPS such a record rather than emitting a dangling reference; this is
// where the combination is actually rejected.
for ( const auto &proto : structDef->getConformedProtocols() )
{
Symbol *psym = mScope->findSymbol( proto );
ProtocolDefinition *pd = dynamic_cast<ProtocolDefinition *>( psym );
if ( pd == nullptr )
continue;
if ( !pd->isPublic() )
{
mDiag.error( structDef->getLocation(),
"exported struct '" + sname + "' conforms to protocol '" + proto +
"', which is not exported; add 'pub' to protocol '" + proto +
"' or drop the conformance" );
mReported = true;
continue;
}
// (6) The conformance record is EXPORTED, so a consumer will believe
// the type satisfies the protocol — but the methods that satisfy it
// are filtered out of the interface unless they are `pub`. That ships
// a library that builds green and a .bmod whose promise the consumer
// cannot use.
//
// Rejecting here (rather than implicitly exporting the method) keeps
// `pub` meaning exactly one thing — "this is API" — and keeps the
// error at the library that caused it. Implicit export would make a
// method's visibility depend on a conformance declared elsewhere in
// the file, so reading `fn to_string(...)` would no longer tell you
// whether it crosses the boundary.
//
// NON-GENERIC ONLY. A generic struct ships ALL its method bodies in
// the .bmod (A6) — the `pub` filter never runs on it, because a
// consumer monomorphizes from those bodies and public methods call
// private helpers. So a non-`pub` conformance method on a generic
// struct IS reachable, and the premise of this rule does not hold.
// Rejecting it would force `pub` onto helpers that D9 says are
// private, for no gain.
if ( structDef->isGeneric() )
continue;
for ( const auto &rsp : pd->getRequiredMethods() )
{
FunctionDefinition *req = const_cast<FunctionDefinition *>(
(const FunctionDefinition *)rsp );
if ( req == nullptr )
continue;
for ( const auto &msp : structDef->getMethods() )
{
FunctionDefinition *m = const_cast<FunctionDefinition *>(
(const FunctionDefinition *)msp );
if ( m == nullptr || m->getName() != req->getName() )
continue;
if ( !m->isPublic() )
{
mDiag.error( m->getLocation(),
"method '" + m->getName() + "' of exported struct '" + sname +
"' implements exported conformance to protocol '" + proto +
"', so it must be 'pub'; otherwise the interface promises a "
"conformance a consumer cannot call" );
mReported = true;
}
break;
}
}
}
}
for ( const auto &f : structDef->getFields() )
{
if ( f != nullptr )
checkReservedName( f->getName(), f->getLocation(), "field" );
}
for ( auto &method : structDef->mMethods )
{
checkBodylessMember( method, structDef->getName() );
if ( structDef->isPublic() && method != nullptr && method->isPublic() )
checkExportedSignature( method,
string( method->isInit() ? "constructor" : "method '" + method->getName() + "'" ) +
" of exported struct '" + structDef->getName() + "'" );
if ( !method->isInit() )
checkReservedName( method->getName(), method->getLocation(), "method" );
visitFunction( method );
}
if ( structDef->mInitMethod != nullptr )
visitFunction( structDef->mInitMethod );
}
void Sema::checkBodylessMember( FunctionDefinition *func, const string &ownerName )
{
if ( func == nullptr || func->isExtern() || func->mFuncBody != nullptr )
return;
if ( func->isInit() )
mDiag.error( func->getLocation(),
"constructor of struct '" + ownerName + "' has no body; "
"a bodyless 'init' is only valid in a .bmod interface file" );
else if ( ownerName.empty() )
mDiag.error( func->getLocation(),
"function '" + func->getName() + "' has no body; a bodyless "
"declaration is only valid in a .bmod interface file (use "
"'extern fn' to declare a foreign symbol)" );
else
mDiag.error( func->getLocation(),
"method '" + func->getName() + "' of struct '" + ownerName +
"' has no body; a bodyless method is only valid in a .bmod "
"interface file" );
mReported = true;
}
// ---- P9: exported declarations may only reference exported types ----
bool Sema::isExportedDataContract( StructDefinition *structDef ) const
{
// A `table` or `@json` struct's SHAPE is its data contract — DB columns,
// JSON keys — so its field types genuinely cross the module boundary and
// must themselves be exported (design record D15). An ordinary struct's
// fields never cross, so a private field type is fine there.
if ( structDef->isTable() )
return true;
for ( const auto &ann : structDef->getAnnotations() )
if ( ann.mName == "json" )
return true;
return false;
}
void Sema::checkExportedTypeRef( const Type *type, const SourceLocation &loc,
const string &what )
{
if ( type == nullptr )
return;
const string &name = type->getName();
if ( name.empty() || name == "self" || name == "void" )
return;
// Generic ARGUMENTS travel with the type, so they must be checked BEFORE any
// early return below. `Box<Secret>` and `Array<Secret>` both export Secret
// even though `Box` and `Array` are themselves fine — checking only after
// the container passed its own test made this branch unreachable for exactly
// the cases it was written for.
for ( int i = 0; i < const_cast<Type *>( type )->getNumTypeParams(); i++ )
checkExportedTypeRef( const_cast<Type *>( type )->getTypeParam( i ), loc, what );
// Only user-declared types can be non-exported. A name that resolves to no
// symbol is a primitive, a generic parameter, or already-diagnosed; leaving
// it alone means this check never invents an error.
Symbol *sym = mScope->findSymbol( name );
if ( sym == nullptr )
return;
bool isPublic = true;
const char *kind = "type";
if ( auto *sd = dynamic_cast<StructDefinition *>( sym ) )
{
isPublic = sd->isPublic();
kind = "struct";
}
else if ( auto *ed = dynamic_cast<EnumDefinition *>( sym ) )
{
isPublic = ed->isPublic();
kind = "enum";
}
else if ( auto *pd = dynamic_cast<ProtocolDefinition *>( sym ) )
{
isPublic = pd->isPublic();
kind = "protocol";
}
else
{
return; // not a type symbol
}
if ( isPublic )
return;
mDiag.error( loc, what + " references " + kind + " '" + name +
"', which is not exported; add 'pub' to " + kind + " '" + name +
"' or remove it from the exported signature" );
mReported = true;
}
void Sema::checkExportedSignature( FunctionDefinition *func, const string &what )
{
if ( func == nullptr )
return;
for ( auto ¶m : func->mParameters )
{
if ( param == nullptr )
continue;
const Type *pt = param->getVariableType();
if ( pt != nullptr && pt->getName() == "self" )
continue;
checkExportedTypeRef( pt, func->getLocation(), what );
}
checkExportedTypeRef( func->getReturnType(), func->getLocation(), what );
}
void Sema::checkReservedName( const string &name, const SourceLocation &loc,
const string &kind )
{
if ( name.size() < 2 || name[0] != '_' || name[1] != '_' )
return;
mDiag.error( loc, kind + " name '" + name +
"' is reserved: names beginning with '__' belong to the compiler's "
"generated-symbol family" );
mReported = true;
}
void Sema::visitFunction( FunctionDefinition *func )
{
if ( func == nullptr || func->isExtern() )
return;
for ( auto &req : func->mRequiresClauses )
visitExpr( req );
for ( auto &ens : func->mEnsuresClauses )
visitExpr( ens );
FunctionDefinition *saved = mCurrentFunc;
mCurrentFunc = func;
mMoved.clear();
mDeclLoopDepth.clear();
mDeclSpawnDepth.clear();
mLocalDecls.clear();
mReferencedNames.clear();
mLoopDepth = 0;
mSpawnDepth = 0;
if ( func->mFuncBody != nullptr )
visitStmt( func->mFuncBody );
// U1: warn on local variables declared but never referenced anywhere in the
// function body. A pure lint (severity Warning); it does NOT set mReported, so
// the compile still succeeds unless -Werror promotes it.
for ( VariableDefinition *v : mLocalDecls )
{
if ( v != nullptr && mReferencedNames.count( v->getName() ) == 0 )
mDiag.warning( v->getLocation(),
"unused variable '" + v->getName() + "'", "unused-variable" );
}
mCurrentFunc = saved;
}
// ---------------------------------------------------------------------------
// Statement walk
// ---------------------------------------------------------------------------
void Sema::visitStmt( Statement *stmt )
{
if ( stmt == nullptr )
return;
if ( auto *e = dynamic_cast<Expression *>( stmt ) )
{
visitExpr( e );
return;
}
if ( auto *s = dynamic_cast<Block *>( stmt ) )
{
for ( auto &child : s->mStatementList )
visitStmt( child );
}
else if ( auto *s = dynamic_cast<ReturnStatement *>( stmt ) )
{
Type *vt = visitExpr( s->mExpression );
// Return-type checking (FR-001, FR-002). mCurrentFunc is null inside a
// lambda body (see visitExpr LambdaExpression) so lambda returns are not
// checked against the enclosing function.
if ( mCurrentFunc != nullptr )
{
Type *rt = mCurrentFunc->getReturnType(); // nullptr = void
bool hasValue = ( s->mExpression != nullptr );
if ( rt != nullptr && !hasValue )
{
mDiag.error( s->getLocation(),
"return with no value in function '" + mCurrentFunc->getName() +
"' returning '" + typeName( rt ) + "'" );
mReported = true;
}
else if ( rt != nullptr && hasValue && !typesCompatible( vt, rt ) )
{
mDiag.error( s->getLocation(),
"cannot return '" + typeName( vt ) + "' from function '" +
mCurrentFunc->getName() + "' returning '" + typeName( rt ) + "'" );
mReported = true;
}
}
}
else if ( auto *s = dynamic_cast<IfStatement *>( stmt ) )
{
visitExpr( s->mIfExpression );
visitStmt( s->mStatement );
visitStmt( s->mElseStatement );
}
else if ( auto *s = dynamic_cast<WhileStatement *>( stmt ) )
{
visitExpr( s->mLoopExpression );
mLoopDepth++;
visitStmt( s->mLoopStatement );
mLoopDepth--;
}
else if ( auto *s = dynamic_cast<ForInStatement *>( stmt ) )
{
Type *iterType = visitExpr( s->mIterableExpression );
// Type the loop variable from the iterable — the parser declares it as
// the "var" placeholder. Array<T> iteration yields T; a range yields
// int. Without this, expressions over the loop variable that need its
// type (string concatenation, method calls) fail the operator checks
// with 'var'. Key/value iteration and infinite loops are left as-is.
if ( !s->mIsInfinite && s->mSecondVariableName.empty() )
{
Type *elemType = nullptr;
if ( iterType != nullptr && iterType->getName() == "Array" &&
iterType->getNumTypeParams() > 0 )
{
elemType = iterType->getTypeParam( 0 );
}
else if ( dynamic_cast<RangeExpression *>(
(Expression *)s->mIterableExpression ) != nullptr )
{
mIntType = new Type( "int" );
elemType = mIntType;
}
if ( elemType != nullptr )
{
if ( auto *b = dynamic_cast<Block *>( (Statement *)s->mBody ) )
{
if ( b->mScope != nullptr )
{
Symbol *ls = b->mScope->findSymbol( s->mVariableName );
if ( auto *lv = dynamic_cast<VariableDefinition *>( ls ) )
{
Type *cur = lv->getVariableType();
if ( cur == nullptr || cur->getName() == "var" )
lv->setType( elemType );
}
}
}
}
}
mLoopDepth++;
visitStmt( s->mBody );
mLoopDepth--;
}
else if ( auto *s = dynamic_cast<VariableDeclaration *>( stmt ) )
{
for ( auto &decl : s->mVariables )
{
// U1: track this local as an unused-variable-lint candidate.
if ( decl.mVaribale != nullptr )
{
mLocalDecls.push_back( decl.mVaribale );
checkReservedName( decl.mVaribale->getName(),
decl.mVaribale->getLocation(), "variable" );
}
Type *initType = visitExpr( decl.mInitialValue );
// modules-v2-graph U6b — `var` type inference. A `var` declaration
// carries a "var" placeholder type from the parser; resolve it to the
// initializer's type here (Sema runs before codegen, on the shared AST,
// so the concrete type reaches codegen's variable/method dispatch). This
// is what makes D7 use-capability real: `var b = midx.get_box(7)` holds a
// foreign `Box<int>` and dispatches `b.get()` WITHOUT ever naming Box —
// no name-capability (import of Box's owner) required. It also repairs a
// latent bug where a `var` bound to a non-int value was mistyped `i32`.
if ( decl.mVaribale != nullptr && initType != nullptr &&
initType->getName() != "var" )
{
Type *declType = decl.mVaribale->getVariableType();
if ( declType != nullptr && declType->getName() == "var" )
decl.mVaribale->setType( initType );
}
// Initializer compatibility (FR-004). Only when both types are
// determinable and provably incompatible.
if ( decl.mInitialValue != nullptr && decl.mVaribale != nullptr )
{
Type *declType = decl.mVaribale->getVariableType();
if ( declType != nullptr && !typesCompatible( initType, declType ) )
{
mDiag.error( decl.mInitialValue->getLocation(),
"cannot initialize '" + typeName( declType ) +
"' from a value of type '" + typeName( initType ) + "'" );
mReported = true;
}
}
// Channel element types are restricted to value types. A channel
// transfers elements by raw byte copy (__blang_chan_send/recv), so a
// refcounted heap element (string/Array/Buffer/struct) would be
// copied without a reference count — its owner releases it at scope
// exit, leaving the channel (and any recv) with a dangling pointer,
// and undrained elements would leak at channel teardown. Origin's
// channel feature only supports value elements; reject the rest with a
// located diagnostic (reject, don't coerce) rather than crashing/leaking.
if ( decl.mVaribale != nullptr )
{
Type *vt = decl.mVaribale->getVariableType();
if ( vt != nullptr && vt->getName() == "chan" &&
vt->getNumTypeParams() > 0 &&
isHeapType( vt->getTypeParam( 0 ) ) )
{
mDiag.error( s->getLocation(),
"channel element type '" +
typeName( vt->getTypeParam( 0 ) ) +
"' is not supported: channels carry value types only "
"(a refcounted element would be copied without ownership)" );
mReported = true;
}
}
// U6: record the declaration's loop/spawn nesting for this variable.
if ( decl.mVaribale != nullptr )
{
mDeclLoopDepth[ decl.mVaribale ] = mLoopDepth;
mDeclSpawnDepth[ decl.mVaribale ] = mSpawnDepth;
}
// U6: an `own` value initialised from another `own` variable moves the
// source. Moving in a loop (source declared outside the loop) is a
// located error; otherwise the source is marked moved.
if ( auto *ve = dynamic_cast<VariableExpression *>( (Expression *)decl.mInitialValue ) )
{
VariableDefinition *src = ve->getVariable();
if ( src != nullptr && src->getOwnership() == OwnershipQualifier::kOwnership_Own )
{
int declDepth = mDeclLoopDepth.count( src ) ? mDeclLoopDepth[ src ] : 0;
if ( mLoopDepth > declDepth )
{
mDiag.error( decl.mInitialValue->getLocation(),
"move of own variable '" + src->getName() + "' inside a loop" );
mReported = true;
}
else
mMoved.insert( src );
}
}
}
}
else if ( auto *s = dynamic_cast<AssertStatement *>( stmt ) )
{
visitExpr( s->mExpression );
}
else if ( auto *s = dynamic_cast<WaitStatement *>( stmt ) )
{
visitExpr( s->mExpr );
}
else if ( auto *s = dynamic_cast<EventHandler *>( stmt ) )
{
visitExpr( s->mEventExpression );
visitStmt( s->mBody );
}
}
// ---------------------------------------------------------------------------
// Expression walk + resolution/annotation
// ---------------------------------------------------------------------------
Type *Sema::visitExpr( Expression *expr )
{
if ( expr == nullptr )
return nullptr;
if ( dynamic_cast<ConstInteger *>( expr ) )
{
Type *t = mScope->findType( "int" );
expr->setResolvedType( t );
return t;
}
if ( dynamic_cast<ConstFloat *>( expr ) )
{
Type *t = mScope->findType( "double" );
expr->setResolvedType( t );
return t;
}
if ( dynamic_cast<ConstString *>( expr ) || dynamic_cast<StringInterpolation *>( expr ) )
{
if ( auto *si = dynamic_cast<StringInterpolation *>( expr ) )
for ( auto &p : si->mParts )
visitExpr( p );
Type *t = mScope->findType( "string" );
expr->setResolvedType( t );
return t;
}
if ( dynamic_cast<ConstChar *>( expr ) )
{
Type *t = mScope->findType( "char" );
expr->setResolvedType( t );
return t;
}
if ( auto *ve = dynamic_cast<VariableExpression *>( expr ) )
{
VariableDefinition *var = ve->getVariable();
// U1: a variable read counts as a reference (suppresses the unused lint).
if ( var != nullptr )
mReferencedNames.insert( var->getName() );
if ( var != nullptr && var->getOwnership() == OwnershipQualifier::kOwnership_Own )
{
// U6: use of a moved own value.
if ( mMoved.count( var ) )
{
mDiag.error( ve->getLocation(),
"use of moved variable '" + var->getName() + "'" );
mReported = true;
}
// U6: an own value cannot be captured across a spawn boundary.
int declSpawn = mDeclSpawnDepth.count( var ) ? mDeclSpawnDepth[ var ] : 0;
if ( mSpawnDepth > declSpawn )
{
mDiag.error( ve->getLocation(),
"cannot capture own variable '" + var->getName() +
"' across a spawn boundary" );
mReported = true;
}
}
Type *t = ( var != nullptr ) ? var->getVariableType() : nullptr;
expr->setResolvedType( t );
return t;
}
if ( auto *ce = dynamic_cast<CallExpression *>( expr ) )
{
for ( auto &p : ce->mParams )
visitExpr( p );
FunctionDefinition *callee = ce->mFunction;
Type *t = ( callee != nullptr ) ? callee->getReturnType() : nullptr;
expr->setResolvedType( t );
// Builtin to_json(value) requires a @json-annotated struct argument.
// Reject a plain (non-@json) struct here with a located error in ALL
// build modes (the codegen dispatches to the generated StructName_to_json,
// which only exists for @json structs).
if ( callee != nullptr && callee->isBuiltin() && callee->getName() == "to_json" )
{
validateToJsonArg( ce );
return t;
}
// Call arity + argument-type checking (FR-005, FR-006). Skip variadic,
// generic, and builtin callees (their own paths validate). Argument-TYPE
// checking additionally skips extern callees, whose string<->cstring /
// carray FFI conversions are legitimate at the boundary.
if ( callee != nullptr && !callee->isVariadic() && !callee->isGeneric() &&
!callee->isBuiltin() )
{
int np = callee->getNumberParams();
int na = (int)ce->mParams.size();
if ( na != np )
{
mDiag.error( ce->getLocation(),
"wrong number of arguments to '" + callee->getName() +
"': expected " + to_string( np ) + ", got " + to_string( na ) );
mReported = true;
}
else if ( !callee->isExtern() )
{
for ( int i = 0; i < np; i++ )
{
Type *at = ce->mParams[i]->getResolvedType();
Type *pt = callee->getParamType( i );
if ( pt != nullptr && !typesCompatible( at, pt ) )
{
mDiag.error( ce->mParams[i]->getLocation(),
"argument " + to_string( i + 1 ) + " to '" + callee->getName() +
"': cannot pass '" + typeName( at ) + "' as '" + typeName( pt ) + "'" );
mReported = true;
}
}
}
}
// U6: passing an `own` variable to an `own` parameter moves it (mirrors
// codegen's move-on-own-argument). Params were visited above, so a
// use-after-move on the argument itself is already reported.
if ( callee != nullptr )
{
int np2 = callee->getNumberParams();
for ( int i = 0; i < (int)ce->mParams.size() && i < np2; i++ )
{
VariableDefinition *pd = callee->getParam( i );
if ( pd == nullptr || pd->getOwnership() != OwnershipQualifier::kOwnership_Own )
continue;
if ( auto *ve = dynamic_cast<VariableExpression *>( (Expression *)ce->mParams[i] ) )
{
VariableDefinition *av = ve->getVariable();
if ( av != nullptr && av->getOwnership() == OwnershipQualifier::kOwnership_Own )
mMoved.insert( av );
}
}
}
// Generic constraint checking (REQ-008): for an explicit-type-argument call
// to a generic function, each type argument bound to a constrained generic
// parameter must satisfy that protocol constraint. Inferred (no explicit
// type args) instantiations are left unchecked in U5.
if ( callee != nullptr && callee->isGeneric() && !ce->mTypeArgs.empty() )
{
const auto &gps = callee->getGenericParams();
for ( size_t i = 0; i < gps.size() && i < ce->mTypeArgs.size(); i++ )
{
if ( gps[i].mConstraint.empty() )
continue;
checkConstraint( ce->mTypeArgs[i], gps[i].mConstraint, gps[i].mName,
ce->getLocation() );
}
}
return t;
}
if ( auto *ic = dynamic_cast<IndirectCallExpression *>( expr ) )
{
for ( auto &p : ic->mParams )
visitExpr( p );
// U1: calling through a fn-typed variable is a use of that variable.
if ( ic->mFnVariable != nullptr )
mReferencedNames.insert( ic->mFnVariable->getName() );
Type *t = nullptr;
if ( ic->mFnVariable != nullptr )
{
if ( auto *ft = dynamic_cast<FunctionType *>( (Type *)ic->mFnVariable->getVariableType() ) )
t = ft->getReturnType();
}
expr->setResolvedType( t );
return t;
}
// Database query/insert/update/delete: validate that every referenced column
// exists on the table struct, in ALL build modes, with a located error
// (reject, don't coerce). The codegen retains a non-located backstop, but
// Sema is the source of truth so query_bad_field is a fail/sema fixture.
if ( auto *q = dynamic_cast<QueryExpression *>( expr ) )
{
validateTableSteps( q->mTableName, q->mSteps, q );
// Annotate the query's value type: Array<T> for a row set, Option<T>
// when the pipeline ends in |> first (single row or none). Codegen and
// match-exhaustiveness read this — e.g. a match over a query-first
// result must handle `none`, and the temp-subject payload release needs
// the concrete T.
bool hasFirst = false;
for ( const auto &step : q->mSteps )
{
if ( step.mType == QueryPipelineStep::FIRST )
{
hasFirst = true;
break;
}
}
Type *resultType = new Type( hasFirst ? "Option" : "Array" );
resultType->addTypeParam( new Type( q->mTableName ) );
q->setResolvedType( resultType );
return resultType;
}
if ( auto *u = dynamic_cast<UpdateExpression *>( expr ) )
{
validateTableSteps( u->mTableName, u->mSteps, u );
return nullptr;
}
if ( auto *d = dynamic_cast<DeleteExpression *>( expr ) )
{
validateTableSteps( d->mTableName, d->mSteps, d );
return nullptr;
}
if ( auto *ins = dynamic_cast<InsertExpression *>( expr ) )
{
StructDefinition *table = tableStructFor( ins->mTableName, ins );
if ( table != nullptr )
{
for ( const auto &name : ins->mFieldNames )
checkTableField( table, name, ins->getLocation() );
}
return nullptr;
}
if ( auto *fa = dynamic_cast<FieldAccessExpression *>( expr ) )
{
Type *baseType = visitExpr( fa->getObject() );
resolveFieldAccess( fa, baseType );
return fa->getResolvedType();
}
if ( auto *mc = dynamic_cast<MethodCallExpression *>( expr ) )
{
Type *baseType = visitExpr( mc->mObject );
for ( auto &a : mc->mArgs )
visitExpr( a );
resolveMethodCall( mc, baseType );
return mc->getResolvedType();
}
if ( auto *ie = dynamic_cast<IndexExpression *>( expr ) )
{
Type *baseType = visitExpr( ie->getObject() );
visitExpr( ie->getIndex() );
Type *t = nullptr;
if ( baseType != nullptr && baseType->getName() == "Array" &&
baseType->getNumTypeParams() > 0 )
t = baseType->getTypeParam( 0 );
expr->setResolvedType( t );
return t;
}
if ( auto *op = dynamic_cast<OperationsExpression *>( expr ) )
{
Type *lt = visitExpr( op->mOp1 );
Type *rt = visitExpr( op->mOp2 );
// Operand validity (FR-007), conservative: reject arithmetic operators
// applied to a determinable NON-scalar, NON-string operand (a struct/enum
// value) — BLang has no operator overloading, so this is always invalid.
// String '+' (concat) and any operand of unknown type are left alone.
const string &oper = op->mOperation;
bool isArith = ( oper == "+" || oper == "-" || oper == "*" ||
oper == "/" || oper == "%" );
// Comparison and logical operators yield bool, not the operand type.
bool isBoolResult = ( oper == "==" || oper == "!=" || oper == "<" ||
oper == ">" || oper == "<=" || oper == ">=" ||
oper == "&&" || oper == "||" );
if ( isArith )
{
for ( Type *o : { lt, rt } )
{
if ( o != nullptr && !o->getName().empty() &&
!isScalarTypeName( o->getName() ) &&
o->getName() != "string" && o->getName() != "Array" &&
!looksGenericParam( o->getName() ) &&
structForType( o ) != nullptr )
{
mDiag.error( op->getLocation(),
"operator '" + oper +
"' cannot be applied to a value of type '" + typeName( o ) + "'" );
mReported = true;
break;
}
}
}
// String '+' is concatenation and requires BOTH operands to be string.
// `"k" + i` (string + int) is a type error — not an implicit int→string
// coercion (BLang is explicit-over-implicit; use interpolation `"k{i}"`).
// Without this it reaches codegen as `add ptr, i32` → IR-verify ICE.
if ( oper == "+" && lt != nullptr && rt != nullptr &&
!lt->getName().empty() && !rt->getName().empty() &&
!looksGenericParam( lt->getName() ) &&
!looksGenericParam( rt->getName() ) )
{
bool lStr = ( lt->getName() == "string" );
bool rStr = ( rt->getName() == "string" );
if ( lStr != rStr ) // exactly one operand is a string
{
mDiag.error( op->getLocation(),
"operator '+' cannot be applied to 'string' and '" +
typeName( lStr ? rt : lt ) + "' (use string interpolation)" );
mReported = true;
}
}
Type *resultType = isBoolResult ? mScope->findType( "bool" ) : lt;
expr->setResolvedType( resultType );
return resultType;