-
-
Notifications
You must be signed in to change notification settings - Fork 726
/
Copy pathcheck_expr.cpp
12056 lines (10551 loc) · 351 KB
/
check_expr.cpp
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
enum CallArgumentError {
CallArgumentError_None,
CallArgumentError_NoneProcedureType,
CallArgumentError_WrongTypes,
CallArgumentError_NonVariadicExpand,
CallArgumentError_VariadicTuple,
CallArgumentError_MultipleVariadicExpand,
CallArgumentError_AmbiguousPolymorphicVariadic,
CallArgumentError_ArgumentCount,
CallArgumentError_TooFewArguments,
CallArgumentError_TooManyArguments,
CallArgumentError_InvalidFieldValue,
CallArgumentError_ParameterNotFound,
CallArgumentError_ParameterMissing,
CallArgumentError_DuplicateParameter,
CallArgumentError_NoneConstantParameter,
CallArgumentError_OutOfOrderParameters,
CallArgumentError_MAX,
};
gb_global char const *CallArgumentError_strings[CallArgumentError_MAX] = {
"None",
"NoneProcedureType",
"WrongTypes",
"NonVariadicExpand",
"VariadicTuple",
"MultipleVariadicExpand",
"AmbiguousPolymorphicVariadic",
"ArgumentCount",
"TooFewArguments",
"TooManyArguments",
"InvalidFieldValue",
"ParameterNotFound",
"ParameterMissing",
"DuplicateParameter",
"NoneConstantParameter",
"OutOfOrderParameters",
};
enum struct CallArgumentErrorMode {
NoErrors,
ShowErrors,
};
struct CallArgumentData {
Entity *gen_entity;
i64 score;
Type * result_type;
};
struct PolyProcData {
Entity * gen_entity;
ProcInfo *proc_info;
};
struct ValidIndexAndScore {
isize index;
i64 score;
};
gb_internal int valid_index_and_score_cmp(void const *a, void const *b) {
i64 si = (cast(ValidIndexAndScore const *)a)->score;
i64 sj = (cast(ValidIndexAndScore const *)b)->score;
return sj < si ? -1 : sj > si;
}
gb_internal void check_expr (CheckerContext *c, Operand *operand, Ast *expression);
gb_internal void check_multi_expr (CheckerContext *c, Operand *operand, Ast *expression);
gb_internal void check_multi_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression);
gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint);
gb_internal void check_expr_or_type (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
gb_internal ExprKind check_expr_base (CheckerContext *c, Operand *operand, Ast *expression, Type *type_hint);
gb_internal void check_expr_with_type_hint (CheckerContext *c, Operand *o, Ast *e, Type *t);
gb_internal Type * check_type (CheckerContext *c, Ast *expression);
gb_internal Type * check_type_expr (CheckerContext *c, Ast *expression, Type *named_type);
gb_internal Type * make_optional_ok_type (Type *value, bool typed=true);
gb_internal Entity * check_selector (CheckerContext *c, Operand *operand, Ast *node, Type *type_hint);
gb_internal Entity * check_ident (CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name);
gb_internal void check_not_tuple (CheckerContext *c, Operand *operand);
gb_internal void convert_to_typed (CheckerContext *c, Operand *operand, Type *target_type);
gb_internal gbString expr_to_string (Ast *expression);
gb_internal gbString expr_to_string (Ast *expression, gbAllocator allocator);
gb_internal void update_untyped_expr_type (CheckerContext *c, Ast *e, Type *type, bool final);
gb_internal bool check_is_terminating (Ast *node, String const &label);
gb_internal bool check_has_break (Ast *stmt, String const &label, bool implicit);
gb_internal void check_stmt (CheckerContext *c, Ast *node, u32 flags);
gb_internal void check_stmt_list (CheckerContext *c, Slice<Ast *> const &stmts, u32 flags);
gb_internal void check_init_constant (CheckerContext *c, Entity *e, Operand *operand);
gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value);
gb_internal bool check_procedure_type (CheckerContext *c, Type *type, Ast *proc_type_node, Array<Operand> const *operands = nullptr);
gb_internal void check_struct_type (CheckerContext *c, Type *struct_type, Ast *node, Array<Operand> *poly_operands,
Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
gb_internal void check_union_type (CheckerContext *c, Type *union_type, Ast *node, Array<Operand> *poly_operands,
Type *named_type = nullptr, Type *original_type_for_poly = nullptr);
gb_internal Type * check_init_variable (CheckerContext *c, Entity *e, Operand *operand, String context_name);
gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0);
gb_internal void add_map_key_type_dependencies(CheckerContext *ctx, Type *key);
gb_internal Type *make_soa_struct_fixed(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem, i64 count, Type *generic_type);
gb_internal Type *make_soa_struct_slice(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
gb_internal Type *make_soa_struct_dynamic_array(CheckerContext *ctx, Ast *array_typ_expr, Ast *elem_expr, Type *elem);
gb_internal bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 id, Type *type_hint);
gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand=true);
gb_internal void check_or_else_right_type(CheckerContext *c, Ast *expr, String const &name, Type *right_type);
gb_internal void check_or_else_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
gb_internal void check_or_else_expr_no_value_error(CheckerContext *c, String const &name, Operand const &x, Type *type_hint);
gb_internal void check_or_return_split_types(CheckerContext *c, Operand *x, String const &name, Type **left_type_, Type **right_type_);
gb_internal bool is_diverging_expr(Ast *expr);
gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_);
gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr);
gb_internal Entity *find_polymorphic_record_entity(GenTypesData *found_gen_types, isize param_count, Array<Operand> const &ordered_operands);
gb_internal bool complete_soa_type(Checker *checker, Type *t, bool wait_to_finish);
gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y);
gb_internal bool is_exact_value_zero(ExactValue const &v);
enum LoadDirectiveResult {
LoadDirective_Success = 0,
LoadDirective_Error = 1,
LoadDirective_NotFound = 2,
};
gb_internal bool is_load_directive_call(Ast *call) {
call = unparen_expr(call);
if (call->kind != Ast_CallExpr) {
return false;
}
ast_node(ce, CallExpr, call);
if (ce->proc->kind != Ast_BasicDirective) {
return false;
}
ast_node(bd, BasicDirective, ce->proc);
String name = bd->name.string;
return name == "load";
}
gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
auto results = did_you_mean_results(d);
if (results.count != 0) {
error_line("\tSuggestion: Did you mean?\n");
for (auto const &result : results) {
String const &target = result.target;
error_line("\t\t%s%.*s\n", prefix, LIT(target));
// error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
}
}
}
gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
if (e->kind != Entity_TypeName) {
return;
}
if (e->TypeName.objc_metadata == nullptr) {
return;
}
TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
Type *t = base_type(e->type);
GB_ASSERT(t->kind == Type_Struct);
if (is_type) {
for (auto const &entry : objc_metadata->type_entries) {
string_set_add(set, entry.name);
}
} else {
for (auto const &entry : objc_metadata->value_entries) {
string_set_add(set, entry.name);
}
}
for (Entity *f : t->Struct.fields) {
if (f->flags & EntityFlag_Using && f->type != nullptr) {
if (f->type->kind == Type_Named && f->type->Named.type_name) {
populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
}
}
}
}
gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
if (build_context.terse_errors) { return; }
ERROR_BLOCK();
GB_ASSERT(e->kind == Entity_TypeName);
GB_ASSERT(e->TypeName.objc_metadata != nullptr);
auto *objc_metadata = e->TypeName.objc_metadata;
MUTEX_GUARD(objc_metadata->mutex);
StringSet set = {};
defer (string_set_destroy(&set));
populate_check_did_you_mean_objc_entity(&set, e, is_type);
DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
defer (did_you_mean_destroy(&d));
for (String const &target : set) {
did_you_mean_append(&d, target);
}
check_did_you_mean_print(&d, prefix);
}
gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
if (build_context.terse_errors) { return; }
ERROR_BLOCK();
DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
defer (did_you_mean_destroy(&d));
for (Entity *e : fields) {
did_you_mean_append(&d, e->token.string);
}
check_did_you_mean_print(&d, prefix);
}
gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
if (build_context.terse_errors) { return; }
ERROR_BLOCK();
DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
defer (did_you_mean_destroy(&d));
for (Entity *e : fields) {
did_you_mean_append(&d, e->token.string);
}
check_did_you_mean_print(&d, prefix);
}
gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
if (build_context.terse_errors) { return; }
ERROR_BLOCK();
DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
defer (did_you_mean_destroy(&d));
rw_mutex_shared_lock(&scope->mutex);
for (auto const &entry : scope->elements) {
Entity *e = entry.value;
did_you_mean_append(&d, e->token.string);
}
rw_mutex_shared_unlock(&scope->mutex);
check_did_you_mean_print(&d, prefix);
}
gb_internal Entity *entity_from_expr(Ast *expr) {
expr = unparen_expr(expr);
switch (expr->kind) {
case Ast_Ident:
return expr->Ident.entity;
case Ast_SelectorExpr:
return entity_from_expr(expr->SelectorExpr.selector);
}
return nullptr;
}
gb_internal void error_operand_not_expression(Operand *o) {
if (o->mode == Addressing_Type) {
gbString err = expr_to_string(o->expr);
error(o->expr, "'%s' is not an expression but a type", err);
gb_string_free(err);
o->mode = Addressing_Invalid;
}
}
gb_internal void error_operand_no_value(Operand *o) {
if (o->mode == Addressing_NoValue) {
Ast *x = unparen_expr(o->expr);
if (x->kind == Ast_CallExpr) {
Ast *p = unparen_expr(x->CallExpr.proc);
if (p->kind == Ast_BasicDirective) {
String tag = p->BasicDirective.name.string;
if (tag == "panic" ||
tag == "assert") {
return;
}
}
}
gbString err = expr_to_string(o->expr);
if (x->kind == Ast_CallExpr) {
error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
} else {
error(o->expr, "'%s' used as a value", err);
}
gb_string_free(err);
o->mode = Addressing_Invalid;
}
}
gb_internal void add_map_get_dependencies(CheckerContext *c) {
if (build_context.dynamic_map_calls) {
add_package_dependency(c, "runtime", "__dynamic_map_get");
} else {
add_package_dependency(c, "runtime", "map_desired_position");
add_package_dependency(c, "runtime", "map_probe_distance");
}
}
gb_internal void add_map_set_dependencies(CheckerContext *c) {
init_core_source_code_location(c->checker);
if (t_map_set_proc == nullptr) {
Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
}
if (build_context.dynamic_map_calls) {
add_package_dependency(c, "runtime", "__dynamic_map_set");
} else {
add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
}
}
gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
init_core_source_code_location(c->checker);
add_package_dependency(c, "runtime", "__dynamic_map_reserve");
}
gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
Scope *s = c->scope;
check_collect_entities(c, nodes);
for (auto const &entry : s->elements) {
Entity *e = entry.value;
switch (e->kind) {
case Entity_Constant:
case Entity_TypeName:
case Entity_Procedure:
break;
default:
continue;
}
DeclInfo *d = decl_info_of_entity(e);
if (d != nullptr) {
check_entity_decl(c, e, d, nullptr);
}
}
}
gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
///////////////////////////////////////////////////////////////////////////////
// //
// TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
// //
///////////////////////////////////////////////////////////////////////////////
CheckerInfo *info = old_c->info;
if (base_entity == nullptr) {
return false;
}
if (!is_type_proc(base_entity->type)) {
return false;
}
if (base_entity->flags & EntityFlag_Disabled) {
return false;
}
String name = base_entity->token.string;
Type *src = base_type(base_entity->type);
Type *dst = nullptr;
if (type != nullptr) {
dst = base_type(type);
}
if (param_operands == nullptr) {
GB_ASSERT(dst != nullptr);
}
if (param_operands != nullptr) {
GB_ASSERT(dst == nullptr);
}
if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
return false;
}
if (dst != nullptr) {
if (dst->Proc.is_polymorphic) {
return false;
}
if (dst->Proc.param_count != src->Proc.param_count ||
dst->Proc.result_count != src->Proc.result_count) {
return false;
}
}
DeclInfo *old_decl = decl_info_of_entity(base_entity);
if (old_decl == nullptr) {
return false;
}
gbAllocator a = heap_allocator();
Array<Operand> operands = {};
if (param_operands) {
operands = *param_operands;
} else {
operands = array_make<Operand>(a, 0, dst->Proc.param_count);
for (isize i = 0; i < dst->Proc.param_count; i++) {
Entity *param = dst->Proc.params->Tuple.variables[i];
Operand o = {Addressing_Value};
o.type = param->type;
array_add(&operands, o);
}
}
defer (if (param_operands == nullptr) {
array_free(&operands);
});
CheckerContext nctx = *old_c;
Scope *scope = create_scope(info, base_entity->scope);
scope->flags |= ScopeFlag_Proc;
nctx.scope = scope;
nctx.allow_polymorphic_types = true;
if (nctx.polymorphic_scope == nullptr) {
nctx.polymorphic_scope = scope;
}
auto *pt = &src->Proc;
// NOTE(bill): This is slightly memory leaking if the type already exists
// Maybe it's better to check with the previous types first?
Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
if (!success) {
return false;
}
GenProcsData *gen_procs = nullptr;
GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
GB_ASSERT(base_entity->kind == Entity_Procedure);
mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
gen_procs = base_entity->Procedure.gen_procs;
if (gen_procs) {
rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
for (Entity *other : gen_procs->procs) {
Type *pt = base_type(other->type);
if (are_types_identical(pt, final_proc_type)) {
rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
if (poly_proc_data) {
poly_proc_data->gen_entity = other;
}
return true;
}
}
rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
} else {
gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
gen_procs->procs.allocator = heap_allocator();
base_entity->Procedure.gen_procs = gen_procs;
mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
}
{
// LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
nctx.no_polymorphic_errors = false;
// NOTE(bill): Reset scope from the failed procedure type
scope->head_child.store(nullptr, std::memory_order_relaxed);
string_map_clear(&scope->elements);
ptr_set_clear(&scope->imported);
// LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
Ast *cloned_proc_type_node = clone_ast(pt->node);
success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
if (!success) {
return false;
}
rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
for (Entity *other : gen_procs->procs) {
Type *pt = base_type(other->type);
if (are_types_identical(pt, final_proc_type)) {
rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
if (poly_proc_data) {
poly_proc_data->gen_entity = other;
}
DeclInfo *decl = other->decl_info;
if (decl->proc_checked_state != ProcCheckedState_Checked) {
ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
proc_info->file = other->file;
proc_info->token = other->token;
proc_info->decl = decl;
proc_info->type = other->type;
proc_info->body = decl->proc_lit->ProcLit.body;
proc_info->tags = other->Procedure.tags;;
proc_info->generated_from_polymorphic = true;
proc_info->poly_def_node = poly_def_node;
check_procedure_later(nctx.checker, proc_info);
}
return true;
}
}
rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
}
Ast *proc_lit = clone_ast(old_decl->proc_lit);
ast_node(pl, ProcLit, proc_lit);
// NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
final_proc_type->Proc.is_poly_specialized = true;
final_proc_type->Proc.is_polymorphic = true;
final_proc_type->Proc.variadic = src->Proc.variadic;
final_proc_type->Proc.require_results = src->Proc.require_results;
final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
final_proc_type->Proc.diverging = src->Proc.diverging;
final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
final_proc_type->Proc.enable_target_feature = src->Proc.enable_target_feature;
final_proc_type->Proc.require_target_feature = src->Proc.require_target_feature;
for (isize i = 0; i < operands.count; i++) {
Operand o = operands[i];
if (final_proc_type == o.type ||
base_entity->type == o.type) {
// NOTE(bill): Cycle
final_proc_type->Proc.is_poly_specialized = false;
break;
}
}
u64 tags = base_entity->Procedure.tags;
Ast *ident = clone_ast(base_entity->identifier);
Token token = ident->Ident.token;
DeclInfo *d = make_decl_info(scope, old_decl->parent);
d->gen_proc_type = final_proc_type;
d->type_expr = pl->type;
d->proc_lit = proc_lit;
d->proc_checked_state = ProcCheckedState_Unchecked;
d->defer_use_checked = false;
Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
entity->state.store(EntityState_Resolved);
entity->identifier = ident;
add_entity_and_decl_info(&nctx, ident, entity, d);
// NOTE(bill): Set the scope afterwards as this is not real overloading
entity->scope = scope->parent;
entity->file = base_entity->file;
entity->pkg = base_entity->pkg;
entity->flags = 0;
entity->Procedure.optimization_mode = base_entity->Procedure.optimization_mode;
if (base_entity->flags & EntityFlag_Cold) {
entity->flags |= EntityFlag_Cold;
}
if (base_entity->flags & EntityFlag_Disabled) {
entity->flags |= EntityFlag_Disabled;
}
d->entity = entity;
AstFile *file = nullptr;
{
Scope *s = entity->scope;
while (s != nullptr && s->file == nullptr) {
file = s->file;
s = s->parent;
}
}
rw_mutex_lock(&gen_procs->mutex); // @local-mutex
array_add(&gen_procs->procs, entity);
rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
proc_info->file = file;
proc_info->token = token;
proc_info->decl = d;
proc_info->type = final_proc_type;
proc_info->body = pl->body;
proc_info->tags = tags;
proc_info->generated_from_polymorphic = true;
proc_info->poly_def_node = poly_def_node;
if (poly_proc_data) {
poly_proc_data->gen_entity = entity;
poly_proc_data->proc_info = proc_info;
entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
}
// NOTE(bill): Check the newly generated procedure body
check_procedure_later(nctx.checker, proc_info);
return true;
}
gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
if (operand->expr == nullptr) return false;
Entity *base_entity = entity_of_node(operand->expr);
if (base_entity == nullptr) return false;
return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
}
gb_internal bool find_or_generate_polymorphic_procedure_from_parameters(CheckerContext *c, Entity *base_entity, Array<Operand> const *operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
}
gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
#define MAXIMUM_TYPE_DISTANCE 10
gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming) {
if (c == nullptr) {
GB_ASSERT(operand->mode == Addressing_Value);
GB_ASSERT(is_type_typed(operand->type));
}
if (operand->mode == Addressing_Invalid ||
type == t_invalid) {
return -1;
}
if (operand->mode == Addressing_Builtin) {
return -1;
}
if (operand->mode == Addressing_Type) {
if (is_type_typeid(type)) {
if (is_type_polymorphic(operand->type)) {
return -1;
}
add_type_info_type(c, operand->type);
return 4;
}
return -1;
}
if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
return -1;
}
Type *s = operand->type;
if (are_types_identical(s, type)) {
return 0;
}
Type *src = base_type(s);
Type *dst = base_type(type);
if (is_type_untyped_uninit(src)) {
return 1;
}
if (is_type_untyped_nil(src)) {
if (type_has_nil(dst)) {
return 1;
}
return -1;
}
if (is_type_untyped(src)) {
if (is_type_any(dst)) {
// NOTE(bill): Anything can cast to 'Any'
add_type_info_type(c, s);
return MAXIMUM_TYPE_DISTANCE;
}
if (dst->kind == Type_Basic) {
if (operand->mode == Addressing_Constant) {
if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
if (is_type_typed(dst) && src->kind == Type_Basic) {
switch (src->Basic.kind) {
case Basic_UntypedBool:
if (is_type_boolean(dst)) {
return 1;
}
break;
case Basic_UntypedRune:
if (is_type_integer(dst) || is_type_rune(dst)) {
return 1;
}
break;
case Basic_UntypedInteger:
if (is_type_integer(dst) || is_type_rune(dst)) {
return 1;
}
break;
case Basic_UntypedString:
if (is_type_string(dst)) {
return 1;
}
break;
case Basic_UntypedFloat:
if (is_type_float(dst)) {
return 1;
}
break;
case Basic_UntypedComplex:
if (is_type_complex(dst)) {
return 1;
}
if (is_type_quaternion(dst)) {
return 2;
}
break;
case Basic_UntypedQuaternion:
if (is_type_quaternion(dst)) {
return 1;
}
break;
}
}
return 2;
}
return -1;
}
if (src->kind == Type_Basic) {
Type *d = base_array_type(dst);
i64 score = -1;
switch (src->Basic.kind) {
case Basic_UntypedBool:
if (is_type_boolean(d)) {
score = 1;
}
break;
case Basic_UntypedRune:
if (is_type_integer(d) || is_type_rune(d)) {
score = 1;
}
break;
case Basic_UntypedInteger:
if (is_type_integer(d) || is_type_rune(d)) {
score = 1;
}
break;
case Basic_UntypedString:
if (is_type_string(d)) {
score = 1;
}
break;
case Basic_UntypedFloat:
if (is_type_float(d)) {
score = 1;
}
break;
case Basic_UntypedComplex:
if (is_type_complex(d)) {
score = 1;
}
if (is_type_quaternion(d)) {
score = 2;
}
break;
case Basic_UntypedQuaternion:
if (is_type_quaternion(d)) {
score = 1;
}
break;
}
if (score > 0) {
if (is_type_typed(d)) {
score += 1;
}
if (d != dst) {
score += 6;
}
}
return score;
}
}
}
if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
if (c->in_enum_type) {
return 3;
}
}
{
isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
if (subtype_level > 0) {
return 4 + subtype_level;
}
}
// rawptr <- ^T
if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
return 5;
}
// rawptr <- [^]T
if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
return 5;
}
// ^T <- [^]T
if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
return 4;
}
}
// [^]T <- ^T
if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
return 4;
}
}
if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
bool modify_type = !c->no_polymorphic_errors;
if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
return 2;
}
}
if (is_type_union(dst)) {
for (Type *vt : dst->Union.variants) {
if (are_types_identical(vt, s)) {
return 1;
}
}
if (dst->Union.variants.count == 1) {
Type *vt = dst->Union.variants[0];
i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
if (score >= 0) {
return score+2;
}
} else if (is_type_untyped(src)) {
i64 prev_lowest_score = -1;
i64 lowest_score = -1;
for (Type *vt : dst->Union.variants) {
i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
if (score >= 0) {
if (lowest_score < 0) {
lowest_score = score;
} else {
if (prev_lowest_score < 0) {
prev_lowest_score = lowest_score;
} else {
prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
}
lowest_score = gb_min(lowest_score, score);
}
}
}
if (lowest_score >= 0) {
if (prev_lowest_score != lowest_score) { // remove possible ambiguities
return lowest_score+2;
}
}
}
}
if (is_type_relative_pointer(dst)) {
i64 score = check_distance_between_types(c, operand, dst->RelativePointer.pointer_type, allow_array_programming);
if (score >= 0) {
return score+2;
}
}
if (is_type_relative_multi_pointer(dst)) {
i64 score = check_distance_between_types(c, operand, dst->RelativeMultiPointer.pointer_type, allow_array_programming);
if (score >= 0) {
return score+2;
}
}
if (is_type_proc(dst)) {
if (are_types_identical(src, dst)) {
return 3;
}
PolyProcData poly_proc_data = {};
if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
Entity *e = poly_proc_data.gen_entity;
add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
add_entity_use(c, operand->expr, e);
return 4;
}
}
if (is_type_complex_or_quaternion(dst)) {
Type *elem = base_complex_elem_type(dst);
if (are_types_identical(elem, base_type(src))) {
return 5;
}
}
if (allow_array_programming) {
if (is_type_array(dst)) {
Type *elem = base_array_type(dst);
i64 distance = check_distance_between_types(c, operand, elem, allow_array_programming);
if (distance >= 0) {
return distance + 6;
}
}
if (is_type_simd_vector(dst)) {
Type *dst_elem = base_array_type(dst);
i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
if (distance >= 0) {
return distance + 6;
}
}
}
if (is_type_matrix(dst)) {
if (are_types_identical(src, dst)) {
return 5;
}
if (dst->Matrix.row_count == dst->Matrix.column_count) {
Type *dst_elem = base_array_type(dst);
i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
if (distance >= 0) {
return distance + 7;
}
}
}
if (is_type_any(dst)) {
if (!is_type_polymorphic(src)) {
if (operand->mode == Addressing_Context && operand->type == t_context) {
return -1;
} else {
// NOTE(bill): Anything can cast to 'Any'
add_type_info_type(c, s);
return MAXIMUM_TYPE_DISTANCE;
}
}
}
Ast *expr = unparen_expr(operand->expr);
if (expr != nullptr) {
if (expr->kind == Ast_AutoCast) {
Operand x = *operand;
x.expr = expr->AutoCast.expr;
if (check_cast_internal(c, &x, type)) {
return MAXIMUM_TYPE_DISTANCE;
}
}
}
return -1;
}
gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
// 3*x^2 + 1 > x^2 + x + 1 (for positive x)
i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
// TODO(bill): A decent score function
i64 d = distance*distance; // x^2
if (is_variadic && d >= 0) {
d += distance + 1; // x^2 + x + 1