/
fn.v
2795 lines (2728 loc) · 99.8 KB
/
fn.v
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
module checker
import v.ast
import v.pref
import v.util
import v.token
fn (mut c Checker) fn_decl(mut node ast.FnDecl) {
$if trace_post_process_generic_fns_types ? {
if node.generic_names.len > 0 {
eprintln('>>> post processing node.name: ${node.name:-30} | ${node.generic_names} <=> ${c.table.cur_concrete_types}')
}
}
// notice vweb route methods (non-generic method)
if node.generic_names.len > 0 {
typ_vweb_result := c.table.find_type_idx('vweb.Result')
if node.return_type == typ_vweb_result {
rec_sym := c.table.sym(node.receiver.typ)
if rec_sym.kind == .struct_ {
if _ := c.table.find_field_with_embeds(rec_sym, 'Context') {
c.note('generic method routes of vweb will be skipped', node.pos)
}
}
}
}
if node.generic_names.len > 0 && c.table.cur_concrete_types.len == 0 {
// Just remember the generic function for now.
// It will be processed later in c.post_process_generic_fns,
// after all other normal functions are processed.
// This is done so that all generic function calls can
// have a chance to populate c.table.fn_generic_types with
// the correct concrete types.
c.file.generic_fns << node
c.need_recheck_generic_fns = true
return
}
node.ninstances++
// save all the state that fn_decl or inner statements/expressions
// could potentially modify, since functions can be nested, due to
// anonymous function support, and ensure that it is restored, when
// fn_decl returns:
prev_fn_scope := c.fn_scope
prev_in_for_count := c.in_for_count
prev_inside_defer := c.inside_defer
prev_inside_unsafe := c.inside_unsafe
prev_inside_anon_fn := c.inside_anon_fn
prev_returns := c.returns
prev_stmt_level := c.stmt_level
c.fn_level++
c.in_for_count = 0
c.inside_defer = false
c.inside_unsafe = false
c.returns = false
defer {
c.stmt_level = prev_stmt_level
c.fn_level--
c.returns = prev_returns
c.inside_anon_fn = prev_inside_anon_fn
c.inside_unsafe = prev_inside_unsafe
c.inside_defer = prev_inside_defer
c.in_for_count = prev_in_for_count
c.fn_scope = prev_fn_scope
}
// Check generics fn/method without generic type parameters
mut need_generic_names := false
if node.generic_names.len == 0 {
if node.return_type.has_flag(.generic) {
need_generic_names = true
} else {
for param in node.params {
if param.typ.has_flag(.generic) {
need_generic_names = true
break
}
}
}
if need_generic_names {
if node.is_method {
c.add_error_detail('use `fn (r SomeType[T]) foo[T]() {`, not just `fn (r SomeType[T]) foo() {`')
c.error('generic method declaration must specify generic type names',
node.pos)
} else {
c.add_error_detail('use `fn foo[T](x T) {`, not just `fn foo(x T) {`')
c.error('generic function declaration must specify generic type names',
node.pos)
}
}
}
if node.language == .v && !c.is_builtin_mod && !node.is_anon {
c.check_valid_snake_case(node.get_name(), 'function name', node.pos)
if !node.is_method && node.mod == 'main' && node.short_name in c.table.builtin_pub_fns {
c.error('cannot redefine builtin public function `${node.short_name}`', node.pos)
}
}
if node.name == 'main.main' {
c.main_fn_decl_node = *node
}
if node.language == .v && node.attrs.len > 0 {
if attr_export := node.attrs.find_first('export') {
if attr_export.arg == '' {
c.error('missing argument for [export] attribute', attr_export.pos)
}
}
}
c.fn_return_type = node.return_type
if node.return_type != ast.void_type {
if ct_attr_idx := node.attrs.find_comptime_define() {
sexpr := node.attrs[ct_attr_idx].ct_expr.str()
c.error('only functions that do NOT return values can have `[if ${sexpr}]` tags',
node.pos)
}
if node.generic_names.len > 0 {
gs := c.table.sym(node.return_type)
if gs.info is ast.Struct {
if gs.info.is_generic && !node.return_type.has_flag(.generic) {
c.error('return generic struct `${gs.name}` in fn declaration must specify the generic type names, e.g. ${gs.name}[T]',
node.return_type_pos)
}
}
}
return_sym := c.table.sym(node.return_type)
if return_sym.info is ast.Alias {
parent_sym := c.table.sym(return_sym.info.parent_type)
if parent_sym.info is ast.ArrayFixed {
c.table.find_or_register_array_fixed(parent_sym.info.elem_type, parent_sym.info.size,
parent_sym.info.size_expr, true)
}
}
final_return_sym := c.table.final_sym(node.return_type)
if final_return_sym.info is ast.MultiReturn {
for multi_type in final_return_sym.info.types {
if multi_type == ast.error_type {
c.error('type `IError` cannot be used in multi-return, return an Option instead',
node.return_type_pos)
} else if multi_type.has_flag(.result) {
c.error('result cannot be used in multi-return, return a Result instead',
node.return_type_pos)
}
}
}
// Ensure each generic type of the parameter was declared in the function's definition
if node.return_type.has_flag(.generic) {
generic_names := c.table.generic_type_names(node.return_type)
for name in generic_names {
if name !in node.generic_names {
fn_generic_names := node.generic_names.join(', ')
c.error('generic type name `${name}` is not mentioned in fn `${node.name}[${fn_generic_names}]`',
node.return_type_pos)
}
}
}
} else {
for mut a in node.attrs {
if a.kind == .comptime_define {
node.should_be_skipped = c.evaluate_once_comptime_if_attribute(mut a)
}
}
}
if node.is_method {
if node.receiver.typ.has_flag(.option) {
c.error('option types cannot have methods', node.receiver_pos)
}
mut sym := c.table.sym(node.receiver.typ)
if sym.kind == .array && !c.is_builtin_mod && node.name == 'map' {
// TODO `node.map in array_builtin_methods`
c.error('method overrides built-in array method', node.pos)
} else if sym.kind == .sum_type && node.name == 'type_name' {
c.error('method overrides built-in sum type method', node.pos)
} else if sym.kind == .sum_type && node.name == 'type_idx' {
c.error('method overrides built-in sum type method', node.pos)
} else if sym.kind == .multi_return {
c.error('cannot define method on multi-value', node.method_type_pos)
}
if sym.name.len == 1 {
// One letter types are reserved for generics.
c.error('unknown type `${sym.name}`', node.receiver_pos)
return
}
// make sure interface does not implement its own interface methods
if mut sym.info is ast.Interface && sym.has_method(node.name) {
// if the method is in info.methods then it is an interface method
if sym.info.has_method(node.name) {
c.error('interface `${sym.name}` cannot implement its own interface method `${node.name}`',
node.pos)
}
}
if mut sym.info is ast.Struct {
if field := c.table.find_field(sym, node.name) {
field_sym := c.table.sym(field.typ)
if field_sym.kind == .function {
c.error('type `${sym.name}` has both field and method named `${node.name}`',
node.pos)
}
}
if node.name == 'free' {
if node.return_type != ast.void_type {
c.error('`.free()` methods should not have a return type', node.return_type_pos)
}
if !node.receiver.typ.is_ptr() {
tname := sym.name.after_char(`.`)
c.error('`.free()` methods should be defined on either a `(mut x &${tname})`, or a `(x &${tname})` receiver',
node.receiver_pos)
}
if node.params.len != 1 {
c.error('`.free()` methods should have 0 arguments', node.pos)
}
}
}
// needed for proper error reporting during vweb route checking
if node.method_idx < sym.methods.len {
sym.methods[node.method_idx].source_fn = voidptr(node)
} else {
c.error('method index: ${node.method_idx} >= sym.methods.len: ${sym.methods.len}',
node.pos)
}
}
if node.language == .v {
// Make sure all types are valid
for mut param in node.params {
if !c.ensure_type_exists(param.typ, param.type_pos) {
return
}
if reserved_type_names_chk.matches(param.name) {
c.error('invalid use of reserved type `${param.name}` as a parameter name',
param.pos)
}
if param.typ.has_flag(.result) {
c.error('Result type argument is not supported currently', param.type_pos)
}
arg_typ_sym := c.table.sym(param.typ)
if arg_typ_sym.info is ast.Struct {
if !param.typ.is_ptr() && arg_typ_sym.info.is_heap { // set auto_heap to promote value parameter
mut v := node.scope.find_var(param.name) or { continue }
v.is_auto_heap = true
}
if arg_typ_sym.info.generic_types.len > 0 && !param.typ.has_flag(.generic)
&& arg_typ_sym.info.concrete_types.len == 0 {
c.error('generic struct `${arg_typ_sym.name}` in fn declaration must specify the generic type names, e.g. ${arg_typ_sym.name}[T]',
param.type_pos)
}
} else if arg_typ_sym.info is ast.Interface {
if arg_typ_sym.info.generic_types.len > 0 && !param.typ.has_flag(.generic)
&& arg_typ_sym.info.concrete_types.len == 0 {
c.error('generic interface `${arg_typ_sym.name}` in fn declaration must specify the generic type names, e.g. ${arg_typ_sym.name}[T]',
param.type_pos)
}
} else if arg_typ_sym.info is ast.SumType {
if arg_typ_sym.info.generic_types.len > 0 && !param.typ.has_flag(.generic)
&& arg_typ_sym.info.concrete_types.len == 0 {
c.error('generic sumtype `${arg_typ_sym.name}` in fn declaration must specify the generic type names, e.g. ${arg_typ_sym.name}[T]',
param.type_pos)
}
}
// Ensure each generic type of the parameter was declared in the function's definition
if param.typ.has_flag(.generic) {
generic_names := c.table.generic_type_names(param.typ)
for name in generic_names {
if name !in node.generic_names {
fn_generic_names := node.generic_names.join(', ')
c.error('generic type name `${name}` is not mentioned in fn `${node.name}[${fn_generic_names}]`',
param.type_pos)
}
}
}
if param.name == node.mod && param.name != 'main' {
c.add_error_detail('Module name duplicates will become errors after 2023/10/31.')
c.note('duplicate of a module name `${param.name}`', param.pos)
}
// Check if parameter name is already registered as imported module symbol
if c.check_import_sym_conflict(param.name) {
c.error('duplicate of an import symbol `${param.name}`', param.pos)
}
}
// Check if function name is already registered as imported module symbol
if !node.is_method && c.check_import_sym_conflict(node.short_name) {
c.error('duplicate of an import symbol `${node.short_name}`', node.pos)
}
}
if node.language == .v && node.name.after_char(`.`) == 'init' && !node.is_method
&& node.params.len == 0 {
if node.is_pub {
c.error('fn `init` must not be public', node.pos)
}
if node.return_type != ast.void_type {
c.error('fn `init` cannot have a return type', node.pos)
}
}
if node.language == .v && node.mod == 'main' && node.name.after_char(`.`) in reserved_type_names
&& !node.is_method && !c.is_builtin_mod {
c.error('top level declaration cannot shadow builtin type', node.pos)
}
if node.return_type != ast.Type(0) {
if !c.ensure_type_exists(node.return_type, node.return_type_pos) {
return
}
if node.language == .v && node.is_method && node.name == 'str' {
if node.return_type != ast.string_type {
c.error('.str() methods should return `string`', node.pos)
}
if node.params.len != 1 {
c.error('.str() methods should have 0 arguments', node.pos)
}
}
if node.language == .v && node.is_method
&& node.name in ['+', '-', '*', '%', '/', '<', '=='] {
if node.params.len != 2 {
c.error('operator methods should have exactly 1 argument', node.pos)
} else {
receiver_type := node.receiver.typ
receiver_sym := c.table.sym(receiver_type)
param_type := node.params[1].typ
param_sym := c.table.sym(param_type)
if param_sym.kind == .string && receiver_sym.kind == .string {
// bypass check for strings
// TODO there must be a better way to handle that
} else if param_sym.kind !in [.struct_, .alias]
|| receiver_sym.kind !in [.struct_, .alias] {
c.error('operator methods are only allowed for struct and type alias',
node.pos)
} else {
parent_sym := c.table.final_sym(node.receiver.typ)
if node.rec_mut {
c.error('receiver cannot be `mut` for operator overloading', node.receiver_pos)
} else if node.params[1].is_mut {
c.error('argument cannot be `mut` for operator overloading', node.pos)
} else if !c.check_same_type_ignoring_pointers(node.receiver.typ,
node.params[1].typ) {
c.error('expected `${receiver_sym.name}` not `${param_sym.name}` - both operands must be the same type for operator overloading',
node.params[1].type_pos)
} else if node.name in ['<', '=='] && node.return_type != ast.bool_type {
c.error('operator comparison methods should return `bool`', node.pos)
} else if parent_sym.is_primitive() {
// aliases of primitive types are explicitly allowed
} else if receiver_type != param_type {
srtype := c.table.type_to_str(receiver_type)
sptype := c.table.type_to_str(param_type)
c.error('the receiver type `${srtype}` should be the same type as the operand `${sptype}`',
node.pos)
}
}
}
}
}
// TODO c.pref.is_vet
if c.file.is_test && (!node.is_method && (node.short_name.starts_with('test_')
|| node.short_name.starts_with('testsuite_'))) {
if !c.pref.is_test {
// simple heuristic
for st in node.stmts {
if st is ast.AssertStmt {
c.warn('tests will not be run, because filename does not end with `_test.v`',
node.pos)
break
}
}
}
if node.params.len != 0 {
c.error('test functions should take 0 parameters', node.pos)
}
if node.return_type != ast.void_type_idx
&& node.return_type.clear_flag(.option) != ast.void_type_idx
&& node.return_type.clear_flag(.result) != ast.void_type_idx {
c.error('test functions should either return nothing at all, or be marked to return `?` or `!`',
node.pos)
}
}
c.expected_type = ast.void_type
c.table.cur_fn = unsafe { node }
// c.table.cur_fn = node
// Add return if `fn(...) ? {...}` have no return at end
if node.return_type != ast.void_type && node.return_type.has_flag(.option)
&& (node.stmts.len == 0 || node.stmts.last() !is ast.Return) {
sym := c.table.sym(node.return_type)
if sym.kind == .void {
node.stmts << ast.Return{
pos: node.pos
}
}
}
// same for result `fn (...) ! { ... }`
if node.return_type != ast.void_type && node.return_type.has_flag(.result)
&& (node.stmts.len == 0 || node.stmts.last() !is ast.Return) {
sym := c.table.sym(node.return_type)
if sym.kind == .void {
node.stmts << ast.Return{
pos: node.pos
}
}
}
c.fn_scope = node.scope
c.stmts(mut node.stmts)
node_has_top_return := has_top_return(node.stmts)
node.has_return = c.returns || node_has_top_return
c.check_noreturn_fn_decl(mut node)
if node.language == .v && !node.no_body && node.return_type != ast.void_type && !node.has_return
&& !node.is_noreturn {
if c.inside_anon_fn {
c.error('missing return at the end of an anonymous function', node.pos)
} else if !node.attrs.contains('_naked') {
c.error('missing return at end of function `${node.name}`', node.pos)
}
}
node.source_file = c.file
if node.name in c.table.fns && node.name != 'main.main' {
mut dep_names := []string{}
for stmt in node.stmts {
dnames := c.table.dependent_names_in_stmt(stmt)
for dname in dnames {
if dname in dep_names {
continue
}
dep_names << dname
}
}
if dep_names.len > 0 {
c.table.fns[node.name].dep_names = dep_names
}
}
// vweb checks
if node.attrs.len > 0 && c.file.imports.filter(it.mod == 'vweb').len > 0 {
// If it's a vweb action (has the ['/url'] attribute), make sure it returns a vweb.Result
for attr in node.attrs {
if attr.name.starts_with('/') {
if c.table.sym(node.return_type).name != 'vweb.Result' {
c.error('vweb actions must return `vweb.Result`', node.pos)
}
break
}
}
}
}
// check_same_type_ignoring_pointers util function to check if the Types are the same, including all
// corner cases.
// FIXME: if the optimization is done after the checker, we can safely remove this util function
fn (c Checker) check_same_type_ignoring_pointers(type_a ast.Type, type_b ast.Type) bool {
// FIXME: if possible pass the ast.Node and check the property `is_auto_rec`
if type_a != type_b {
// before failing we must be sure that the parser didn't optimize the function
clean_type_a := type_a.set_nr_muls(0)
clean_type_b := type_b.set_nr_muls(0)
return clean_type_a == clean_type_b
}
return true
}
fn (mut c Checker) anon_fn(mut node ast.AnonFn) ast.Type {
keep_fn := c.table.cur_fn
keep_inside_anon := c.inside_anon_fn
keep_anon_fn := c.cur_anon_fn
defer {
c.table.cur_fn = keep_fn
c.inside_anon_fn = keep_inside_anon
c.cur_anon_fn = keep_anon_fn
}
if node.decl.no_body {
c.error('anonymous function must declare a body', node.decl.pos)
}
for param in node.decl.params {
if param.name.len == 0 {
c.error('use `_` to name an unused parameter', param.pos)
}
}
c.table.cur_fn = unsafe { &node.decl }
c.inside_anon_fn = true
c.cur_anon_fn = unsafe { &node }
mut has_generic := false
for mut var in node.inherited_vars {
parent_var := node.decl.scope.parent.find_var(var.name) or {
panic('unexpected checker error: cannot find parent of inherited variable `${var.name}`')
}
if var.is_mut && !parent_var.is_mut {
c.error('original `${parent_var.name}` is immutable, declare it with `mut` to make it mutable',
var.pos)
}
var.typ = parent_var.typ
if var.typ.has_flag(.generic) {
has_generic = true
}
node.decl.scope.update_var_type(var.name, var.typ)
}
if has_generic && node.decl.generic_names.len == 0 {
c.error('generic closure fn must specify type parameter, e.g. fn [foo] [T]()',
node.decl.pos)
}
c.stmts(mut node.decl.stmts)
c.fn_decl(mut node.decl)
return node.typ
}
fn (mut c Checker) call_expr(mut node ast.CallExpr) ast.Type {
// Check whether the inner function definition is before the call
if var := node.scope.find_var(node.name) {
if var.expr is ast.AnonFn && var.pos.pos > node.pos.pos {
c.error('unknown function: ${node.name}', node.pos)
}
}
// If the left expr has an or_block, it needs to be checked for legal or_block statement.
left_type := c.expr(mut node.left)
c.check_expr_opt_call(node.left, left_type)
// TODO merge logic from method_call and fn_call
// First check everything that applies to both fns and methods
old_inside_fn_arg := c.inside_fn_arg
c.inside_fn_arg = true
mut continue_check := true
// Now call `method_call` or `fn_call` for specific checks.
typ := if node.is_method {
c.method_call(mut node)
} else {
c.fn_call(mut node, mut continue_check)
}
if !continue_check {
return ast.void_type
}
c.inside_fn_arg = old_inside_fn_arg
// autofree: mark args that have to be freed (after saving them in tmp exprs)
free_tmp_arg_vars := c.pref.autofree && !c.is_builtin_mod && node.args.len > 0
&& !c.inside_const && !node.args[0].typ.has_flag(.option)
&& !node.args[0].typ.has_flag(.result) && !(node.args[0].expr is ast.CallExpr
&& (node.args[0].expr.return_type.has_flag(.option)
|| node.args[0].expr.return_type.has_flag(.result)))
if free_tmp_arg_vars {
for i, arg in node.args {
if arg.typ != ast.string_type {
continue
}
if arg.expr in [ast.Ident, ast.StringLiteral, ast.SelectorExpr] {
// Simple expressions like variables, string literals, selector expressions
// (`x.field`) can't result in allocations and don't need to be assigned to
// temporary vars.
// Only expressions like `str + 'b'` need to be freed.
continue
}
node.args[i].is_tmp_autofree = true
}
// TODO copy pasta from above
if node.receiver_type == ast.string_type
&& node.left !in [ast.Ident, ast.StringLiteral, ast.SelectorExpr] {
node.free_receiver = true
}
}
c.expected_or_type = node.return_type.clear_flag(.result)
c.stmts_ending_with_expression(mut node.or_block.stmts)
c.expected_or_type = ast.void_type
if !c.inside_const && c.table.cur_fn != unsafe { nil } && !c.table.cur_fn.is_main
&& !c.table.cur_fn.is_test {
// TODO: use just `if node.or_block.kind == .propagate_result && !c.table.cur_fn.return_type.has_flag(.result) {` after the deprecation for ?!Type
if node.or_block.kind == .propagate_result && !c.table.cur_fn.return_type.has_flag(.result)
&& !c.table.cur_fn.return_type.has_flag(.option) {
c.add_instruction_for_result_type()
c.error('to propagate the Result call, `${c.table.cur_fn.name}` must return a Result',
node.or_block.pos)
}
if node.or_block.kind == .propagate_option && !c.table.cur_fn.return_type.has_flag(.option) {
c.add_instruction_for_option_type()
c.error('to propagate the Option call, `${c.table.cur_fn.name}` must return an Option',
node.or_block.pos)
}
}
return typ
}
fn (mut c Checker) builtin_args(mut node ast.CallExpr, fn_name string, func ast.Fn) {
c.inside_casting_to_str = true
c.expected_type = ast.string_type
node.args[0].typ = c.expr(mut node.args[0].expr)
arg := node.args[0]
c.check_expr_opt_call(arg.expr, arg.typ)
if arg.typ.is_void() {
c.error('`${fn_name}` can not print void expressions', node.pos)
} else if arg.typ == ast.char_type && arg.typ.nr_muls() == 0 {
c.error('`${fn_name}` cannot print type `char` directly, print its address or cast it to an integer instead',
node.pos)
}
c.fail_if_unreadable(arg.expr, arg.typ, 'argument to print')
c.inside_casting_to_str = false
node.return_type = ast.void_type
c.set_node_expected_arg_types(mut node, func)
/*
// TODO: optimize `struct T{} fn (t &T) str() string {return 'abc'} mut a := []&T{} a << &T{} println(a[0])`
// It currently generates:
// `println(T_str_no_ptr(*(*(T**)array_get(a, 0))));`
// ... which works, but could be just:
// `println(T_str(*(T**)array_get(a, 0)));`
prexpr := node.args[0].expr
prtyp := node.args[0].typ
prtyp_sym := c.table.sym(prtyp)
prtyp_is_ptr := prtyp.is_ptr()
prhas_str, prexpects_ptr, prnr_args := prtyp_sym.str_method_info()
eprintln('>>> println hack typ: ${prtyp} | sym.name: ${prtyp_sym.name} | is_ptr: $prtyp_is_ptr | has_str: $prhas_str | expects_ptr: $prexpects_ptr | nr_args: $prnr_args | expr: ${prexpr.str()} ')
*/
}
fn (mut c Checker) needs_unwrap_generic_type(typ ast.Type) bool {
if typ == 0 || !typ.has_flag(.generic) {
return false
}
sym := c.table.sym(typ)
match sym.info {
ast.Struct, ast.Interface, ast.SumType {
return true
}
ast.Array {
return c.needs_unwrap_generic_type(sym.info.elem_type)
}
ast.ArrayFixed {
return c.needs_unwrap_generic_type(sym.info.elem_type)
}
ast.Map {
if c.needs_unwrap_generic_type(sym.info.key_type) {
return true
}
if c.needs_unwrap_generic_type(sym.info.value_type) {
return true
}
}
ast.Chan {
return c.needs_unwrap_generic_type(sym.info.elem_type)
}
ast.Thread {
return c.needs_unwrap_generic_type(sym.info.return_type)
}
else {
return false
}
}
return false
}
fn (mut c Checker) fn_call(mut node ast.CallExpr, mut continue_check &bool) ast.Type {
fn_name := node.name
if fn_name == 'main' {
c.error('the `main` function cannot be called in the program', node.pos)
}
mut has_generic := false // foo[T]() instead of foo[int]()
mut concrete_types := []ast.Type{}
node.concrete_types = node.raw_concrete_types
for concrete_type in node.concrete_types {
if concrete_type.has_flag(.generic) {
has_generic = true
concrete_types << c.unwrap_generic(concrete_type)
} else {
concrete_types << concrete_type
}
}
if c.table.cur_fn != unsafe { nil } && c.table.cur_concrete_types.len == 0 && has_generic {
c.error('generic fn using generic types cannot be called outside of generic fn',
node.pos)
}
if concrete_types.len > 0 {
mut no_exists := true
if fn_name.contains('.') {
no_exists = c.table.register_fn_concrete_types(node.fkey(), concrete_types)
} else {
no_exists = c.table.register_fn_concrete_types(c.mod + '.' + node.fkey(),
concrete_types)
// if the generic fn does not exist in the current fn calling module, continue
// to look in builtin module
if !no_exists {
no_exists = c.table.register_fn_concrete_types(node.fkey(), concrete_types)
}
}
if no_exists {
c.need_recheck_generic_fns = true
}
}
if fn_name == 'JS.await' {
if node.args.len > 1 {
c.error('JS.await expects 1 argument, a promise value (e.g `JS.await(fs.read())`',
node.pos)
return ast.void_type
}
typ := c.expr(mut node.args[0].expr)
tsym := c.table.sym(typ)
if !tsym.name.starts_with('Promise[') {
c.error('JS.await: first argument must be a promise, got `${tsym.name}`',
node.pos)
return ast.void_type
}
if c.table.cur_fn != unsafe { nil } {
c.table.cur_fn.has_await = true
}
match tsym.info {
ast.Struct {
mut ret_type := tsym.info.concrete_types[0]
ret_type = ret_type.set_flag(.option)
node.return_type = ret_type
return ret_type
}
else {
c.error('JS.await: Promise must be a struct type', node.pos)
return ast.void_type
}
}
panic('unreachable')
} else if node.args.len > 0 && fn_name == 'json.encode' && node.args[0].typ.has_flag(.shared_f) {
c.error('json.encode cannot handle shared data', node.pos)
return ast.void_type
} else if node.args.len > 0 && fn_name == 'json.decode' {
if node.args.len != 2 {
c.error("json.decode expects 2 arguments, a type and a string (e.g `json.decode(T, '')`)",
node.pos)
return ast.void_type
}
expr := node.args[0].expr
if expr is ast.TypeNode {
mut unwrapped_typ := c.unwrap_generic(expr.typ)
if c.needs_unwrap_generic_type(expr.typ) {
unwrapped_typ = c.table.unwrap_generic_type(expr.typ, c.table.cur_fn.generic_names,
c.table.cur_concrete_types)
}
sym := c.table.sym(unwrapped_typ)
if c.table.known_type(sym.name) && sym.kind != .placeholder {
mut kind := sym.kind
if sym.info is ast.Alias {
kind = c.table.sym(sym.info.parent_type).kind
}
if kind !in [.struct_, .sum_type, .map, .array] {
c.error('json.decode: expected sum type, struct, map or array, found ${kind}',
expr.pos)
}
} else {
c.error('json.decode: unknown type `${sym.name}`', node.pos)
}
} else {
typ := expr.type_name()
c.error('json.decode: first argument needs to be a type, got `${typ}`', node.pos)
return ast.void_type
}
c.expected_type = ast.string_type
node.args[1].typ = c.expr(mut node.args[1].expr)
if node.args[1].typ != ast.string_type {
c.error('json.decode: second argument needs to be a string', node.pos)
}
typ := expr as ast.TypeNode
ret_type := typ.typ.set_flag(.result)
node.return_type = ret_type
return ret_type
} else if fn_name == '__addr' {
if !c.inside_unsafe {
c.error('`__addr` must be called from an unsafe block', node.pos)
}
if node.args.len != 1 {
c.error('`__addr` requires 1 argument', node.pos)
return ast.void_type
}
typ := c.expr(mut node.args[0].expr)
node.args[0].typ = typ
node.return_type = typ.ref()
return node.return_type
}
// look for function in format `mod.fn` or `fn` (builtin)
mut func := ast.Fn{}
mut found := false
mut found_in_args := false
// anon fn direct call
if node.left is ast.AnonFn {
// it was set to anon for checker errors, clear for gen
node.name = ''
c.expr(mut node.left)
left := node.left as ast.AnonFn
if left.typ != ast.Type(0) {
anon_fn_sym := c.table.sym(left.typ)
func = (anon_fn_sym.info as ast.FnType).func
found = true
}
}
// try prefix with current module as it would have never gotten prefixed
if !found && !fn_name.contains('.') && node.mod != 'builtin' {
name_prefixed := '${node.mod}.${fn_name}'
if f := c.table.find_fn(name_prefixed) {
node.name = name_prefixed
found = true
func = f
c.table.fns[name_prefixed].usages++
}
}
if !found && node.left is ast.IndexExpr {
c.expr(mut node.left)
left := node.left as ast.IndexExpr
sym := c.table.final_sym(left.left_type)
if sym.info is ast.Array {
elem_sym := c.table.sym(sym.info.elem_type)
if elem_sym.info is ast.FnType {
func = elem_sym.info.func
found = true
node.is_fn_var = true
node.fn_var_type = sym.info.elem_type
} else {
c.error('cannot call the element of the array, it is not a function',
node.pos)
}
} else if sym.info is ast.Map {
value_sym := c.table.sym(sym.info.value_type)
if value_sym.info is ast.FnType {
func = value_sym.info.func
found = true
node.is_fn_var = true
node.fn_var_type = sym.info.value_type
} else {
c.error('cannot call the value of the map, it is not a function', node.pos)
}
} else if sym.info is ast.ArrayFixed {
elem_sym := c.table.sym(sym.info.elem_type)
if elem_sym.info is ast.FnType {
func = elem_sym.info.func
found = true
node.is_fn_var = true
node.fn_var_type = sym.info.elem_type
} else {
c.error('cannot call the element of the array, it is not a function',
node.pos)
}
}
}
if !found && node.left is ast.CallExpr {
c.expr(mut node.left)
left := node.left as ast.CallExpr
if left.return_type != 0 {
sym := c.table.sym(left.return_type)
if sym.info is ast.FnType {
node.return_type = sym.info.func.return_type
found = true
func = sym.info.func
}
}
}
// already prefixed (mod.fn) or C/builtin/main
if !found {
if f := c.table.find_fn(fn_name) {
found = true
func = f
c.table.fns[fn_name].usages++
}
}
// already imported symbol (static Foo.new() in another module)
if !found && fn_name.contains('__static__') && fn_name[0].is_capital() {
if index := fn_name.index('__static__') {
owner_name := fn_name#[..index]
for import_sym in c.file.imports.filter(it.syms.any(it.name == owner_name)) {
qualified_name := '${import_sym.mod}.${fn_name}'
if f := c.table.find_fn(qualified_name) {
found = true
func = f
node.name = qualified_name
c.table.fns[qualified_name].usages++
break
}
}
}
if fn_name.ends_with('from_string') {
enum_name := fn_name.all_before('__static__')
full_enum_name := if !enum_name.contains('.') {
c.mod + '.' + enum_name
} else {
enum_name
}
idx := c.table.type_idxs[full_enum_name]
ret_typ := ast.Type(idx).set_flag(.option)
if node.args.len != 1 {
c.error('expected 1 argument, but got ${node.args.len}', node.pos)
} else {
node.args[0].typ = c.expr(mut node.args[0].expr)
if node.args[0].typ != ast.string_type {
styp := c.table.type_to_str(node.args[0].typ)
c.error('expected `string` argument, but got `${styp}`', node.pos)
}
}
node.return_type = ret_typ
return ret_typ
}
}
mut is_native_builtin := false
if !found && c.pref.backend == .native {
if fn_name in ast.native_builtins {
c.table.fns[fn_name].usages++
found = true
func = c.table.fns[fn_name]
is_native_builtin = true
}
}
if !found && c.pref.is_vsh {
// TODO: test this hack more extensively
os_name := 'os.${fn_name}'
if f := c.table.find_fn(os_name) {
if f.generic_names.len == node.concrete_types.len {
node_alias_name := node.fkey()
mut existing := c.table.fn_generic_types[os_name] or { [] }
existing << c.table.fn_generic_types[node_alias_name]
existing << node.concrete_types
c.table.fn_generic_types[os_name] = existing
}
node.name = os_name
found = true
func = f
c.table.fns[os_name].usages++
}
}
if is_native_builtin {
if node.args.len > 0 && fn_name in ['println', 'print', 'eprintln', 'eprint', 'panic'] {
c.builtin_args(mut node, fn_name, func)
return func.return_type
}
return ast.void_type
}
// check for arg (var) of fn type
if !found {
mut typ := 0
if mut obj := node.scope.find(node.name) {
match mut obj {
ast.GlobalField {
typ = obj.typ
node.is_fn_var = true
node.fn_var_type = typ
}
ast.Var {
if obj.smartcasts.len != 0 {
typ = obj.smartcasts.last()
} else {
if obj.typ == 0 {
if mut obj.expr is ast.IfGuardExpr {
typ = c.expr(mut obj.expr.expr)
} else {
typ = c.expr(mut obj.expr)
}
} else {
typ = obj.typ
}
}
node.is_fn_var = true
node.fn_var_type = typ
}
else {}
}
}
if typ != 0 {
generic_vts := c.table.final_sym(typ)
if generic_vts.info is ast.FnType {
func = generic_vts.info.func
found = true
found_in_args = true
} else {
vts := c.table.sym(c.unwrap_generic(typ))
if vts.info is ast.FnType {
func = vts.info.func
found = true
found_in_args = true
}
}
}
}
// global fn?
if !found {
if obj := c.file.global_scope.find(fn_name) {
if obj.typ != 0 {
sym := c.table.sym(obj.typ)
if sym.info is ast.FnType {
func = sym.info.func
found = true
}
}
}
}
// a same module constant?
if !found {
// allow for `const abc = myfunc`, then calling `abc()`
qualified_const_name := if fn_name.contains('.') { fn_name } else { '${c.mod}.${fn_name}' }
if mut obj := c.table.global_scope.find_const(qualified_const_name) {
if obj.typ == 0 {
obj.typ = c.expr(mut obj.expr)
}
if obj.typ != 0 {
sym := c.table.sym(obj.typ)
if sym.info is ast.FnType {
// at this point, the const metadata should be already known,
// and we are sure that it is just a function
c.table.fns[qualified_const_name].usages++
c.table.fns[func.name].usages++
found = true
func = sym.info.func
node.is_fn_a_const = true
node.fn_var_type = obj.typ
node.const_name = qualified_const_name
}
}
}
}