/
checker.v
8986 lines (8813 loc) · 285 KB
/
checker.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
// Copyright (c) 2019-2021 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license that can be found in the LICENSE file.
module checker
import os
import strings
import time
import v.ast
import v.vmod
import v.token
import v.pref
import v.util
import v.util.version
import v.errors
import v.pkgconfig
import v.gen.native
const int_min = int(0x80000000)
const int_max = int(0x7FFFFFFF)
const (
valid_comptime_if_os = ['windows', 'ios', 'macos', 'mach', 'darwin', 'hpux', 'gnu',
'qnx', 'linux', 'freebsd', 'openbsd', 'netbsd', 'bsd', 'dragonfly', 'android', 'solaris',
'haiku', 'serenity', 'vinix']
valid_comptime_compression_types = ['none', 'zlib']
valid_comptime_if_compilers = ['gcc', 'tinyc', 'clang', 'mingw', 'msvc', 'cplusplus']
valid_comptime_if_platforms = ['amd64', 'i386', 'aarch64', 'arm64', 'arm32', 'rv64', 'rv32']
valid_comptime_if_cpu_features = ['x64', 'x32', 'little_endian', 'big_endian']
valid_comptime_if_other = ['js', 'debug', 'prod', 'test', 'glibc', 'prealloc',
'no_bounds_checking', 'freestanding', 'threads', 'js_node', 'js_browser', 'js_freestanding']
valid_comptime_not_user_defined = all_valid_comptime_idents()
array_builtin_methods = ['filter', 'clone', 'repeat', 'reverse', 'map', 'slice',
'sort', 'contains', 'index', 'wait', 'any', 'all', 'first', 'last', 'pop']
reserved_type_names = ['bool', 'char', 'i8', 'i16', 'int', 'i64', 'byte', 'u16',
'u32', 'u64', 'f32', 'f64', 'map', 'string', 'rune']
vroot_is_deprecated_message = '@VROOT is deprecated, use @VMODROOT or @VEXEROOT instead'
)
fn all_valid_comptime_idents() []string {
mut res := []string{}
res << checker.valid_comptime_if_os
res << checker.valid_comptime_if_compilers
res << checker.valid_comptime_if_platforms
res << checker.valid_comptime_if_cpu_features
res << checker.valid_comptime_if_other
return res
}
[heap]
pub struct Checker {
pref &pref.Preferences // Preferences shared from V struct
pub mut:
table &ast.Table
file &ast.File = 0
nr_errors int
nr_warnings int
nr_notices int
should_abort bool // when too many errors/warnings/notices are accumulated, .should_abort becomes true. It is checked in statement/expression loops, so the checker can return early, instead of wasting time.
errors []errors.Error
warnings []errors.Warning
notices []errors.Notice
error_lines []int // to avoid printing multiple errors for the same line
expected_type ast.Type
expected_or_type ast.Type // fn() or { 'this type' } eg. string. expected or block type
const_decl string
const_deps []string
const_names []string
global_names []string
locked_names []string // vars that are currently locked
rlocked_names []string // vars that are currently read-locked
in_for_count int // if checker is currently in a for loop
// checked_ident string // to avoid infinite checker loops
returns bool
scope_returns bool
mod string // current module name
is_builtin_mod bool // true inside the 'builtin', 'os' or 'strconv' modules; TODO: remove the need for special casing this
inside_unsafe bool // true inside `unsafe {}` blocks
inside_const bool // true inside `const ( ... )` blocks
inside_anon_fn bool // true inside `fn() { ... }()`
inside_ref_lit bool // true inside `a := &something`
inside_defer bool // true inside `defer {}` blocks
inside_fn_arg bool // `a`, `b` in `a.f(b)`
inside_ct_attr bool // true inside `[if expr]`
skip_flags bool // should `#flag` and `#include` be skipped
fn_level int // 0 for the top level, 1 for `fn abc() {}`, 2 for a nested fn, etc
ct_cond_stack []ast.Expr
mut:
stmt_level int // the nesting level inside each stmts list;
// .stmt_level is used to check for `evaluated but not used` ExprStmts like `1 << 1`
// 1 for statements directly at each inner scope level;
// increases for `x := if cond { statement_list1} else {statement_list2}`;
// increases for `x := optfn() or { statement_list3 }`;
is_last_stmt bool
files []ast.File
expr_level int // to avoid infinite recursion segfaults due to compiler bugs
inside_sql bool // to handle sql table fields pseudo variables
cur_orm_ts ast.TypeSymbol
error_details []string
vmod_file_content string // needed for @VMOD_FILE, contents of the file, *NOT its path**
vweb_gen_types []ast.Type // vweb route checks
prevent_sum_type_unwrapping_once bool // needed for assign new values to sum type, stopping unwrapping then
loop_label string // set when inside a labelled for loop
timers &util.Timers = util.get_timers()
comptime_fields_type map[string]ast.Type
fn_scope &ast.Scope = voidptr(0)
main_fn_decl_node ast.FnDecl
match_exhaustive_cutoff_limit int = 10
// TODO: these are here temporarily and used for deprecations; remove soon
using_new_err_struct bool
inside_selector_expr bool
inside_println_arg bool
inside_decl_rhs bool
inside_if_guard bool // true inside the guard condition of `if x := opt() {}`
need_recheck_generic_fns bool // need recheck generic fns because there are cascaded nested generic fn
}
pub fn new_checker(table &ast.Table, pref &pref.Preferences) &Checker {
mut timers_should_print := false
$if time_checking ? {
timers_should_print = true
}
return &Checker{
table: table
pref: pref
timers: util.new_timers(should_print: timers_should_print, label: 'checker')
match_exhaustive_cutoff_limit: pref.checker_match_exhaustive_cutoff_limit
}
}
fn (mut c Checker) reset_checker_state_at_start_of_new_file() {
c.expected_type = ast.void_type
c.expected_or_type = ast.void_type
c.const_decl = ''
c.in_for_count = 0
c.returns = false
c.scope_returns = false
c.mod = ''
c.is_builtin_mod = false
c.inside_unsafe = false
c.inside_const = false
c.inside_anon_fn = false
c.inside_ref_lit = false
c.inside_defer = false
c.inside_fn_arg = false
c.inside_ct_attr = false
c.skip_flags = false
c.fn_level = 0
c.expr_level = 0
c.stmt_level = 0
c.inside_sql = false
c.cur_orm_ts = ast.TypeSymbol{}
c.prevent_sum_type_unwrapping_once = false
c.loop_label = ''
c.using_new_err_struct = false
c.inside_selector_expr = false
c.inside_println_arg = false
c.inside_decl_rhs = false
c.inside_if_guard = false
}
pub fn (mut c Checker) check(ast_file_ &ast.File) {
mut ast_file := ast_file_
c.reset_checker_state_at_start_of_new_file()
c.change_current_file(ast_file)
for i, ast_import in ast_file.imports {
for sym in ast_import.syms {
full_name := ast_import.mod + '.' + sym.name
if full_name in c.const_names {
c.error('cannot selectively import constant `$sym.name` from `$ast_import.mod`, import `$ast_import.mod` and use `$full_name` instead',
sym.pos)
}
}
for j in 0 .. i {
if ast_import.mod == ast_file.imports[j].mod {
c.error('`$ast_import.mod` was already imported on line ${
ast_file.imports[j].mod_pos.line_nr + 1}', ast_import.mod_pos)
}
}
}
c.stmt_level = 0
for mut stmt in ast_file.stmts {
if stmt in [ast.ConstDecl, ast.ExprStmt] {
c.expr_level = 0
c.stmt(stmt)
}
if c.should_abort {
return
}
}
//
c.stmt_level = 0
for mut stmt in ast_file.stmts {
if stmt is ast.GlobalDecl {
c.expr_level = 0
c.stmt(stmt)
}
if c.should_abort {
return
}
}
//
c.stmt_level = 0
for mut stmt in ast_file.stmts {
if stmt !is ast.ConstDecl && stmt !is ast.GlobalDecl && stmt !is ast.ExprStmt {
c.expr_level = 0
c.stmt(stmt)
}
if c.should_abort {
return
}
}
//
c.check_scope_vars(c.file.scope)
}
pub fn (mut c Checker) check_scope_vars(sc &ast.Scope) {
if !c.pref.is_repl && !c.file.is_test {
for _, obj in sc.objects {
match obj {
ast.Var {
if !obj.is_used && obj.name[0] != `_` {
c.warn('unused variable: `$obj.name`', obj.pos)
}
if obj.is_mut && !obj.is_changed && !c.is_builtin_mod && obj.name != 'it' {
// if obj.is_mut && !obj.is_changed && !c.is_builtin { //TODO C error bad field not checked
// c.warn('`$obj.name` is declared as mutable, but it was never changed',
// obj.pos)
}
}
else {}
}
}
}
for child in sc.children {
c.check_scope_vars(child)
}
}
// not used right now
pub fn (mut c Checker) check2(ast_file &ast.File) []errors.Error {
c.change_current_file(ast_file)
for stmt in ast_file.stmts {
c.stmt(stmt)
}
return c.errors
}
pub fn (mut c Checker) change_current_file(file &ast.File) {
c.file = unsafe { file }
c.vmod_file_content = ''
c.mod = file.mod.name
}
pub fn (mut c Checker) check_files(ast_files []&ast.File) {
// c.files = ast_files
mut has_main_mod_file := false
mut has_main_fn := false
mut files_from_main_module := []&ast.File{}
for i in 0 .. ast_files.len {
mut file := unsafe { ast_files[i] }
c.timers.start('checker_check $file.path')
c.check(file)
if file.mod.name == 'main' {
files_from_main_module << file
has_main_mod_file = true
if c.file_has_main_fn(file) {
has_main_fn = true
}
}
c.timers.show('checker_check $file.path')
}
if has_main_mod_file && !has_main_fn && files_from_main_module.len > 0 {
if c.pref.is_script && !c.pref.is_test {
// files_from_main_module contain preludes at the start
mut the_main_file := files_from_main_module.last()
the_main_file.stmts << ast.FnDecl{
name: 'main.main'
mod: 'main'
is_main: true
file: the_main_file.path
return_type: ast.void_type
scope: &ast.Scope{
parent: 0
}
}
has_main_fn = true
}
}
c.timers.start('checker_post_process_generic_fns')
last_file := c.file
// post process generic functions. must be done after all files have been
// checked, to eunsure all generic calls are processed as this information
// is needed when the generic type is auto inferred from the call argument
// Check more times if there are more new registered fn concrete types
for {
for file in ast_files {
if file.generic_fns.len > 0 {
c.change_current_file(file)
c.post_process_generic_fns()
}
}
if !c.need_recheck_generic_fns {
break
}
c.need_recheck_generic_fns = false
}
// restore the original c.file && c.mod after post processing
c.change_current_file(last_file)
c.timers.show('checker_post_process_generic_fns')
c.timers.start('checker_verify_all_vweb_routes')
c.verify_all_vweb_routes()
c.timers.show('checker_verify_all_vweb_routes')
if c.pref.is_test {
mut n_test_fns := 0
for _, f in c.table.fns {
if f.is_test {
n_test_fns++
}
}
if n_test_fns == 0 {
c.add_error_detail('The name of a test function in V, should start with `test_`.')
c.add_error_detail('The test function should take 0 parameters, and no return type. Example:')
c.add_error_detail('fn test_xyz(){ assert 2 + 2 == 4 }')
c.error('a _test.v file should have *at least* one `test_` function', token.Position{})
}
}
// Make sure fn main is defined in non lib builds
if c.pref.build_mode == .build_module || c.pref.is_test {
return
}
if c.pref.is_shared {
// shared libs do not need to have a main
return
}
if c.pref.no_builtin {
// `v -no-builtin module/` do not necessarily need to have a `main` function
// This is useful for compiling linux kernel modules for example.
return
}
if !has_main_mod_file {
c.error('project must include a `main` module or be a shared library (compile with `v -shared`)',
token.Position{})
} else if !has_main_fn {
c.error('function `main` must be declared in the main module', token.Position{})
}
}
// do checks specific to files in main module
// returns `true` if a main function is in the file
fn (mut c Checker) file_has_main_fn(file &ast.File) bool {
mut has_main_fn := false
for stmt in file.stmts {
if stmt is ast.FnDecl {
if stmt.name == 'main.main' {
if has_main_fn {
c.error('function `main` is already defined', stmt.pos)
}
has_main_fn = true
if stmt.params.len > 0 {
c.error('function `main` cannot have arguments', stmt.pos)
}
if stmt.return_type != ast.void_type {
c.error('function `main` cannot return values', stmt.pos)
}
if stmt.no_body {
c.error('function `main` must declare a body', stmt.pos)
}
} else if stmt.attrs.contains('console') {
c.error('only `main` can have the `[console]` attribute', stmt.pos)
}
}
}
return has_main_fn
}
fn (mut c Checker) check_valid_snake_case(name string, identifier string, pos token.Position) {
if !c.pref.is_vweb && !c.pref.translated && name.len > 0
&& (name[0] == `_` || name.contains('._')) {
c.error('$identifier `$name` cannot start with `_`', pos)
}
if !c.pref.experimental && !c.pref.translated && util.contains_capital(name) {
c.error('$identifier `$name` cannot contain uppercase letters, use snake_case instead',
pos)
}
}
fn stripped_name(name string) string {
idx := name.last_index('.') or { -1 }
return name[(idx + 1)..]
}
fn (mut c Checker) check_valid_pascal_case(name string, identifier string, pos token.Position) {
sname := stripped_name(name)
if sname.len > 0 && !sname[0].is_capital() && !c.pref.translated {
c.error('$identifier `$name` must begin with capital letter', pos)
}
}
pub fn (mut c Checker) type_decl(node ast.TypeDecl) {
match node {
ast.AliasTypeDecl { c.alias_type_decl(node) }
ast.FnTypeDecl { c.fn_type_decl(node) }
ast.SumTypeDecl { c.sum_type_decl(node) }
}
}
pub fn (mut c Checker) alias_type_decl(node ast.AliasTypeDecl) {
// TODO Remove when `u8` isn't an alias in builtin anymore
if c.file.mod.name != 'builtin' {
c.check_valid_pascal_case(node.name, 'type alias', node.pos)
}
c.ensure_type_exists(node.parent_type, node.type_pos) or { return }
typ_sym := c.table.get_type_symbol(node.parent_type)
if typ_sym.kind in [.placeholder, .int_literal, .float_literal] {
c.error('unknown type `$typ_sym.name`', node.type_pos)
} else if typ_sym.kind == .alias {
orig_sym := c.table.get_type_symbol((typ_sym.info as ast.Alias).parent_type)
c.error('type `$typ_sym.str()` is an alias, use the original alias type `$orig_sym.name` instead',
node.type_pos)
} else if typ_sym.kind == .chan {
c.error('aliases of `chan` types are not allowed.', node.type_pos)
}
}
pub fn (mut c Checker) fn_type_decl(node ast.FnTypeDecl) {
c.check_valid_pascal_case(node.name, 'fn type', node.pos)
typ_sym := c.table.get_type_symbol(node.typ)
fn_typ_info := typ_sym.info as ast.FnType
fn_info := fn_typ_info.func
c.ensure_type_exists(fn_info.return_type, fn_info.return_type_pos) or {}
ret_sym := c.table.get_type_symbol(fn_info.return_type)
if ret_sym.kind == .placeholder {
c.error('unknown type `$ret_sym.name`', fn_info.return_type_pos)
}
for arg in fn_info.params {
c.ensure_type_exists(arg.typ, arg.type_pos) or { return }
arg_sym := c.table.get_type_symbol(arg.typ)
if arg_sym.kind == .placeholder {
c.error('unknown type `$arg_sym.name`', arg.type_pos)
}
}
}
pub fn (mut c Checker) sum_type_decl(node ast.SumTypeDecl) {
c.check_valid_pascal_case(node.name, 'sum type', node.pos)
mut names_used := []string{}
for variant in node.variants {
if variant.typ.is_ptr() {
c.error('sum type cannot hold a reference type', variant.pos)
}
c.ensure_type_exists(variant.typ, variant.pos) or {}
mut sym := c.table.get_type_symbol(variant.typ)
if sym.name in names_used {
c.error('sum type $node.name cannot hold the type `$sym.name` more than once',
variant.pos)
} else if sym.kind in [.placeholder, .int_literal, .float_literal] {
c.error('unknown type `$sym.name`', variant.pos)
} else if sym.kind == .interface_ && sym.language != .js {
c.error('sum type cannot hold an interface', variant.pos)
} else if sym.kind == .struct_ && sym.language == .js {
c.error('sum type cannot hold an JS struct', variant.pos)
}
if sym.name.trim_prefix(sym.mod + '.') == node.name {
c.error('sum type cannot hold itself', variant.pos)
}
names_used << sym.name
}
}
pub fn (mut c Checker) expand_iface_embeds(idecl &ast.InterfaceDecl, level int, iface_embeds []ast.InterfaceEmbedding) []ast.InterfaceEmbedding {
// eprintln('> expand_iface_embeds: idecl.name: $idecl.name | level: $level | iface_embeds.len: $iface_embeds.len')
if level > 100 {
c.error('too many interface embedding levels: $level, for interface `$idecl.name`',
idecl.pos)
return []
}
if iface_embeds.len == 0 {
return []
}
mut res := map[int]ast.InterfaceEmbedding{}
mut ares := []ast.InterfaceEmbedding{}
for ie in iface_embeds {
if iface_decl := c.table.interfaces[ie.typ] {
mut list := iface_decl.ifaces
if !iface_decl.are_ifaces_expanded {
list = c.expand_iface_embeds(idecl, level + 1, iface_decl.ifaces)
c.table.interfaces[ie.typ].ifaces = list
c.table.interfaces[ie.typ].are_ifaces_expanded = true
}
for partial in list {
res[partial.typ] = partial
}
}
res[ie.typ] = ie
}
for _, v in res {
ares << v
}
return ares
}
pub fn (mut c Checker) interface_decl(mut node ast.InterfaceDecl) {
c.check_valid_pascal_case(node.name, 'interface name', node.pos)
mut decl_sym := c.table.get_type_symbol(node.typ)
is_js := node.language == .js
if mut decl_sym.info is ast.Interface {
if node.ifaces.len > 0 {
all_ifaces := c.expand_iface_embeds(node, 0, node.ifaces)
// eprintln('> node.name: $node.name | node.ifaces.len: $node.ifaces.len | all_ifaces: $all_ifaces.len')
node.ifaces = all_ifaces
mut emnames := map[string]int{}
mut emnames_ds := map[string]bool{}
mut emnames_ds_info := map[string]bool{}
mut efnames := map[string]int{}
mut efnames_ds_info := map[string]bool{}
for i, m in node.methods {
emnames[m.name] = i
emnames_ds[m.name] = true
emnames_ds_info[m.name] = true
}
for i, f in node.fields {
efnames[f.name] = i
efnames_ds_info[f.name] = true
}
//
for iface in all_ifaces {
isym := c.table.get_type_symbol(iface.typ)
if isym.kind != .interface_ {
c.error('interface `$node.name` tries to embed `$isym.name`, but `$isym.name` is not an interface, but `$isym.kind`',
iface.pos)
continue
}
isym_info := isym.info as ast.Interface
for f in isym_info.fields {
if !efnames_ds_info[f.name] {
efnames_ds_info[f.name] = true
decl_sym.info.fields << f
}
}
for m in isym_info.methods {
if !emnames_ds_info[m.name] {
emnames_ds_info[m.name] = true
decl_sym.info.methods << m.new_method_with_receiver_type(node.typ)
}
}
for m in isym.methods {
if !emnames_ds[m.name] {
emnames_ds[m.name] = true
decl_sym.methods << m.new_method_with_receiver_type(node.typ)
}
}
if iface_decl := c.table.interfaces[iface.typ] {
for f in iface_decl.fields {
if f.name in efnames {
// already existing method name, check for conflicts
ifield := node.fields[efnames[f.name]]
if field := c.table.find_field_with_embeds(isym, f.name) {
if ifield.typ != field.typ {
exp := c.table.type_to_str(ifield.typ)
got := c.table.type_to_str(field.typ)
c.error('embedded interface `$iface_decl.name` conflicts existing field: `$ifield.name`, expecting type: `$exp`, got type: `$got`',
ifield.pos)
}
}
} else {
efnames[f.name] = node.fields.len
node.fields << f
}
}
for m in iface_decl.methods {
if m.name in emnames {
// already existing field name, check for conflicts
imethod := node.methods[emnames[m.name]]
if em_fn := decl_sym.find_method(imethod.name) {
if m_fn := isym.find_method(m.name) {
msg := c.table.is_same_method(m_fn, em_fn)
if msg.len > 0 {
em_sig := c.table.fn_signature(em_fn, skip_receiver: true)
m_sig := c.table.fn_signature(m_fn, skip_receiver: true)
c.error('embedded interface `$iface_decl.name` causes conflict: $msg, for interface method `$em_sig` vs `$m_sig`',
imethod.pos)
}
}
}
} else {
emnames[m.name] = node.methods.len
mut new_method := m.new_method_with_receiver_type(node.typ)
new_method.pos = iface.pos
node.methods << new_method
}
}
}
}
}
for i, method in node.methods {
if node.language == .v {
c.check_valid_snake_case(method.name, 'method name', method.pos)
}
c.ensure_type_exists(method.return_type, method.return_type_pos) or { return }
if is_js {
mtyp := c.table.get_type_symbol(method.return_type)
if !mtyp.is_js_compatible() {
c.error('method $method.name returns non JS type', method.pos)
}
}
for j, param in method.params {
if j == 0 && is_js {
continue // no need to check first param
}
c.ensure_type_exists(param.typ, param.pos) or { return }
if param.name in checker.reserved_type_names {
c.error('invalid use of reserved type `$param.name` as a parameter name',
param.pos)
}
if is_js {
ptyp := c.table.get_type_symbol(param.typ)
if !ptyp.is_js_compatible() && !(j == method.params.len - 1
&& method.is_variadic) {
c.error('method `$method.name` accepts non JS type as parameter',
method.pos)
}
}
}
for field in node.fields {
field_sym := c.table.get_type_symbol(field.typ)
if field.name == method.name && field_sym.kind == .function {
c.error('type `$decl_sym.name` has both field and method named `$method.name`',
method.pos)
}
}
for j in 0 .. i {
if method.name == node.methods[j].name {
c.error('duplicate method name `$method.name`', method.pos)
}
}
}
for i, field in node.fields {
if node.language == .v {
c.check_valid_snake_case(field.name, 'field name', field.pos)
}
c.ensure_type_exists(field.typ, field.pos) or { return }
if is_js {
tsym := c.table.get_type_symbol(field.typ)
if !tsym.is_js_compatible() {
c.error('field `$field.name` uses non JS type', field.pos)
}
}
if field.typ == node.typ && node.language != .js {
c.error('recursive interface fields are not allowed because they cannot be initialised',
field.type_pos)
}
for j in 0 .. i {
if field.name == node.fields[j].name {
c.error('field name `$field.name` duplicate', field.pos)
}
}
}
}
}
pub fn (mut c Checker) struct_decl(mut node ast.StructDecl) {
if node.language == .v && !c.is_builtin_mod {
c.check_valid_pascal_case(node.name, 'struct name', node.pos)
}
mut struct_sym := c.table.find_type(node.name) or { ast.invalid_type_symbol }
mut has_generic_types := false
if mut struct_sym.info is ast.Struct {
for embed in node.embeds {
if embed.typ.has_flag(.generic) {
has_generic_types = true
}
embed_sym := c.table.get_type_symbol(embed.typ)
if embed_sym.kind != .struct_ {
c.error('`$embed_sym.name` is not a struct', embed.pos)
} else {
info := embed_sym.info as ast.Struct
if info.is_heap && !embed.typ.is_ptr() {
struct_sym.info.is_heap = true
}
}
}
for attr in node.attrs {
if attr.name == 'typedef' && node.language != .c {
c.error('`typedef` attribute can only be used with C structs', node.pos)
}
}
for i, field in node.fields {
if field.typ == ast.any_type {
c.error('struct field cannot be the `any` type, use generics instead',
field.type_pos)
}
c.ensure_type_exists(field.typ, field.type_pos) or { return }
if field.typ.has_flag(.generic) {
has_generic_types = true
}
if node.language == .v {
c.check_valid_snake_case(field.name, 'field name', field.pos)
}
sym := c.table.get_type_symbol(field.typ)
for j in 0 .. i {
if field.name == node.fields[j].name {
c.error('field name `$field.name` duplicate', field.pos)
}
}
if sym.kind == .struct_ {
info := sym.info as ast.Struct
if info.is_heap && !field.typ.is_ptr() {
struct_sym.info.is_heap = true
}
}
if field.has_default_expr {
c.expected_type = field.typ
mut field_expr_type := c.expr(field.default_expr)
if !field.typ.has_flag(.optional) {
c.check_expr_opt_call(field.default_expr, field_expr_type)
}
struct_sym.info.fields[i].default_expr_typ = field_expr_type
c.check_expected(field_expr_type, field.typ) or {
if sym.kind == .interface_
&& c.type_implements(field_expr_type, field.typ, field.pos) {
if !field_expr_type.is_ptr() && !field_expr_type.is_pointer()
&& !c.inside_unsafe {
field_expr_type_sym := c.table.get_type_symbol(field_expr_type)
if field_expr_type_sym.kind != .interface_ {
c.mark_as_referenced(mut &node.fields[i].default_expr,
true)
}
}
} else {
c.error('incompatible initializer for field `$field.name`: $err.msg',
field.default_expr.position())
}
}
// Check for unnecessary inits like ` = 0` and ` = ''`
if field.typ.is_ptr() {
continue
}
if field.default_expr is ast.IntegerLiteral {
if field.default_expr.val == '0' {
c.warn('unnecessary default value of `0`: struct fields are zeroed by default',
field.default_expr.pos)
}
} else if field.default_expr is ast.StringLiteral {
if field.default_expr.val == '' {
c.warn("unnecessary default value of '': struct fields are zeroed by default",
field.default_expr.pos)
}
} else if field.default_expr is ast.BoolLiteral {
if field.default_expr.val == false {
c.warn('unnecessary default value `false`: struct fields are zeroed by default',
field.default_expr.pos)
}
}
}
}
if node.generic_types.len == 0 && has_generic_types {
c.error('generic struct declaration must specify the generic type names, e.g. Foo<T>',
node.pos)
}
}
}
pub fn (mut c Checker) struct_init(mut node ast.StructInit) ast.Type {
if node.typ == ast.void_type {
// Short syntax `({foo: bar})`
if c.expected_type == ast.void_type {
c.error('unexpected short struct syntax', node.pos)
return ast.void_type
}
sym := c.table.get_type_symbol(c.expected_type)
if sym.kind == .array {
node.typ = c.table.value_type(c.expected_type)
} else {
node.typ = c.expected_type
}
}
struct_sym := c.table.get_type_symbol(node.typ)
if struct_sym.info is ast.Struct {
if struct_sym.info.generic_types.len > 0 && struct_sym.info.concrete_types.len == 0
&& c.table.cur_concrete_types.len == 0 {
c.error('generic struct init must specify type parameter, e.g. Foo<int>',
node.pos)
}
} else if struct_sym.info is ast.Alias {
parent_sym := c.table.get_type_symbol(struct_sym.info.parent_type)
// e.g. ´x := MyMapAlias{}´, should be a cast to alias type ´x := MyMapAlias(map[...]...)´
if parent_sym.kind == .map {
alias_str := c.table.type_to_str(node.typ)
map_str := c.table.type_to_str(struct_sym.info.parent_type)
c.error('direct map alias init is not possible, use `${alias_str}($map_str{})` instead',
node.pos)
return ast.void_type
}
}
// register generic struct type when current fn is generic fn
if c.table.cur_fn.generic_names.len > 0 {
c.table.unwrap_generic_type(node.typ, c.table.cur_fn.generic_names, c.table.cur_concrete_types)
}
c.ensure_type_exists(node.typ, node.pos) or {}
type_sym := c.table.get_type_symbol(node.typ)
if !c.inside_unsafe && type_sym.kind == .sum_type {
c.note('direct sum type init (`x := SumType{}`) will be removed soon', node.pos)
}
// Make sure the first letter is capital, do not allow e.g. `x := string{}`,
// but `x := T{}` is ok.
if !c.is_builtin_mod && !c.inside_unsafe && type_sym.language == .v
&& c.table.cur_concrete_types.len == 0 {
pos := type_sym.name.last_index('.') or { -1 }
first_letter := type_sym.name[pos + 1]
if !first_letter.is_capital() {
c.error('cannot initialize builtin type `$type_sym.name`', node.pos)
}
}
if type_sym.kind == .sum_type && node.fields.len == 1 {
sexpr := node.fields[0].expr.str()
c.error('cast to sum type using `${type_sym.name}($sexpr)` not `$type_sym.name{$sexpr}`',
node.pos)
}
if type_sym.kind == .interface_ && type_sym.language != .js {
c.error('cannot instantiate interface `$type_sym.name`', node.pos)
}
if type_sym.info is ast.Alias {
if type_sym.info.parent_type.is_number() {
c.error('cannot instantiate number type alias `$type_sym.name`', node.pos)
return ast.void_type
}
}
// allow init structs from generic if they're private except the type is from builtin module
if !type_sym.is_public && type_sym.kind != .placeholder && type_sym.language != .c
&& (type_sym.mod != c.mod && !(node.typ.has_flag(.generic) && type_sym.mod != 'builtin')) {
c.error('type `$type_sym.name` is private', node.pos)
}
if type_sym.kind == .struct_ {
info := type_sym.info as ast.Struct
if info.attrs.len > 0 && info.attrs[0].name == 'noinit' && type_sym.mod != c.mod {
c.error('struct `$type_sym.name` is declared with a `[noinit]` attribute, so ' +
'it cannot be initialized with `$type_sym.name{}`', node.pos)
}
}
if type_sym.name.len == 1 && c.table.cur_fn.generic_names.len == 0 {
c.error('unknown struct `$type_sym.name`', node.pos)
return 0
}
match type_sym.kind {
.placeholder {
c.error('unknown struct: $type_sym.name', node.pos)
return ast.void_type
}
// string & array are also structs but .kind of string/array
.struct_, .string, .array, .alias {
mut info := ast.Struct{}
if type_sym.kind == .alias {
info_t := type_sym.info as ast.Alias
sym := c.table.get_type_symbol(info_t.parent_type)
if sym.kind == .placeholder { // pending import symbol did not resolve
c.error('unknown struct: $type_sym.name', node.pos)
return ast.void_type
}
if sym.kind == .struct_ {
info = sym.info as ast.Struct
} else {
c.error('alias type name: $sym.name is not struct type', node.pos)
}
} else {
info = type_sym.info as ast.Struct
}
if node.is_short {
exp_len := info.fields.len
got_len := node.fields.len
if exp_len != got_len {
amount := if exp_len < got_len { 'many' } else { 'few' }
c.error('too $amount fields in `$type_sym.name` literal (expecting $exp_len, got $got_len)',
node.pos)
}
}
mut inited_fields := []string{}
for i, mut field in node.fields {
mut field_info := ast.StructField{}
mut field_name := ''
if node.is_short {
if i >= info.fields.len {
// It doesn't make sense to check for fields that don't exist.
// We should just stop here.
break
}
field_info = info.fields[i]
field_name = field_info.name
node.fields[i].name = field_name
} else {
field_name = field.name
mut exists := true
field_info = c.table.find_field_with_embeds(type_sym, field_name) or {
exists = false
ast.StructField{}
}
if !exists {
c.error('unknown field `$field.name` in struct literal of type `$type_sym.name`',
field.pos)
continue
}
if field_name in inited_fields {
c.error('duplicate field name in struct literal: `$field_name`',
field.pos)
continue
}
}
mut expr_type := ast.Type(0)
mut expected_type := ast.Type(0)
inited_fields << field_name
field_type_sym := c.table.get_type_symbol(field_info.typ)
expected_type = field_info.typ
c.expected_type = expected_type
expr_type = c.expr(field.expr)
if !field_info.typ.has_flag(.optional) {
expr_type = c.check_expr_opt_call(field.expr, expr_type)
}
expr_type_sym := c.table.get_type_symbol(expr_type)
if field_type_sym.kind == .interface_ {
if c.type_implements(expr_type, field_info.typ, field.pos) {
if !expr_type.is_ptr() && !expr_type.is_pointer()
&& expr_type_sym.kind != .interface_ && !c.inside_unsafe {
c.mark_as_referenced(mut &field.expr, true)
}
}
} else if expr_type != ast.void_type && expr_type_sym.kind != .placeholder {
c.check_expected(c.unwrap_generic(expr_type), c.unwrap_generic(field_info.typ)) or {
c.error('cannot assign to field `$field_info.name`: $err.msg',
field.pos)
}
}
if field_info.typ.has_flag(.shared_f) {
if !expr_type.has_flag(.shared_f) && expr_type.is_ptr() {
c.error('`shared` field must be initialized with `shared` or value',
field.pos)
}
} else {
if field_info.typ.is_ptr() && !expr_type.is_ptr() && !expr_type.is_pointer()
&& !expr_type.is_number() {
c.error('reference field must be initialized with reference',
field.pos)
}
}
node.fields[i].typ = expr_type
node.fields[i].expected_type = field_info.typ
if field_info.typ.has_flag(.optional) {
c.error('field `$field_info.name` is optional, but initialization of optional fields currently unsupported',
field.pos)
}
if expr_type.is_ptr() && expected_type.is_ptr() {
if mut field.expr is ast.Ident {
if mut field.expr.obj is ast.Var {
mut obj := unsafe { &field.expr.obj }
if c.fn_scope != voidptr(0) {
obj = c.fn_scope.find_var(obj.name) or { obj }
}
if obj.is_stack_obj && !c.inside_unsafe {
sym := c.table.get_type_symbol(obj.typ.set_nr_muls(0))
if !sym.is_heap() && !c.pref.translated {
suggestion := if sym.kind == .struct_ {
'declaring `$sym.name` as `[heap]`'
} else {
'wrapping the `$sym.name` object in a `struct` declared as `[heap]`'
}
c.error('`$field.expr.name` cannot be assigned outside `unsafe` blocks as it might refer to an object stored on stack. Consider ${suggestion}.',
field.expr.pos)
}
}
}
}
}
}
// Check uninitialized refs/sum types
for field in info.fields {
if field.has_default_expr || field.name in inited_fields {
continue
}
if field.typ.is_ptr() && !field.typ.has_flag(.shared_f) && !node.has_update_expr
&& !c.pref.translated {
c.error('reference field `${type_sym.name}.$field.name` must be initialized',
node.pos)
}
// Do not allow empty uninitialized interfaces
sym := c.table.get_type_symbol(field.typ)
if sym.kind == .interface_ {
// TODO: should be an error instead, but first `ui` needs updating.
c.note('interface field `${type_sym.name}.$field.name` must be initialized',
node.pos)
}
// Do not allow empty uninitialized sum types
/*
sym := c.table.get_type_symbol(field.typ)
if sym.kind == .sum_type {
c.warn('sum type field `${type_sym.name}.$field.name` must be initialized',
node.pos)
}
*/