-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
checker.v
4901 lines (4758 loc) · 153 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-2023 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 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
const (
int_min = int(0x80000000)
int_max = int(0x7FFFFFFF)
// prevent stack overflows by restricting too deep recursion:
expr_level_cutoff_limit = 40
stmt_level_cutoff_limit = 40
iface_level_cutoff_limit = 100
generic_fn_cutoff_limit_per_fn = 10_000 // how many times post_process_generic_fns, can visit the same function before bailing out
generic_fn_postprocess_iterations_cutoff_limit = 1000_000 // how many times the compiler will try to resolve all remaining generic functions
)
pub const (
array_builtin_methods = ['filter', 'clone', 'repeat', 'reverse', 'map', 'slice', 'sort',
'contains', 'index', 'wait', 'any', 'all', 'first', 'last', 'pop', 'delete']
array_builtin_methods_chk = token.new_keywords_matcher_from_array_trie(array_builtin_methods)
// TODO: remove `byte` from this list when it is no longer supported
reserved_type_names = ['byte', 'bool', 'char', 'i8', 'i16', 'int', 'i64', 'u8', 'u16',
'u32', 'u64', 'f32', 'f64', 'map', 'string', 'rune', 'usize', 'isize', 'voidptr']
reserved_type_names_chk = token.new_keywords_matcher_from_array_trie(reserved_type_names)
vroot_is_deprecated_message = '@VROOT is deprecated, use @VMODROOT or @VEXEROOT instead'
)
[heap; minify]
pub struct Checker {
pref &pref.Preferences = unsafe { nil } // Preferences shared from V struct
pub mut:
table &ast.Table = unsafe { nil }
file &ast.File = unsafe { nil }
nr_errors int
nr_warnings int
nr_notices int
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
expected_expr_type ast.Type // if/match is_expr: expected_type
mod string // current module name
const_var &ast.ConstField = unsafe { nil } // the current constant, when checking const declarations
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
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.
returns bool
scope_returns bool
is_builtin_mod bool // true inside the 'builtin', 'os' or 'strconv' modules; TODO: remove the need for special casing this
is_just_builtin_mod bool // true only inside 'builtin'
is_generated bool // true for `[generated] module xyz` .v files
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]`
inside_x_is_type bool // true inside the Type expression of `if x is Type {`
inside_comptime_for_field bool
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
smartcast_mut_pos token.Pos // match mut foo, if mut foo is Foo
smartcast_cond_pos token.Pos // match cond
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 }`;
files []ast.File
expr_level int // to avoid infinite recursion segfaults due to compiler bugs
ensure_generic_type_level int // to avoid infinite recursion segfaults in ensure_generic_type_specify_type_names
cur_orm_ts ast.TypeSymbol
cur_anon_fn &ast.AnonFn = unsafe { nil }
error_details []string
vmod_file_content string // needed for @VMOD_FILE, contents of the file, *NOT its path**
loop_label string // set when inside a labelled for loop
vweb_gen_types []ast.Type // vweb route checks
timers &util.Timers = util.get_timers()
comptime_for_field_var string
comptime_fields_default_type ast.Type
comptime_fields_type map[string]ast.Type
comptime_for_field_value ast.StructField // value of the field variable
comptime_enum_field_value string // current enum value name
fn_scope &ast.Scope = unsafe { nil }
main_fn_decl_node ast.FnDecl
match_exhaustive_cutoff_limit int = 10
is_last_stmt bool
prevent_sum_type_unwrapping_once bool // needed for assign new values to sum type, stopping unwrapping then
using_new_err_struct bool
need_recheck_generic_fns bool // need recheck generic fns because there are cascaded nested generic fn
inside_sql bool // to handle sql table fields pseudo variables
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() {}`
inside_assign bool
is_index_assign bool
comptime_call_pos int // needed for correctly checking use before decl for templates
goto_labels map[string]ast.GotoLabel // to check for unused goto labels
enum_data_type ast.Type
fn_return_type ast.Type
}
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_var = unsafe { nil }
c.in_for_count = 0
c.returns = false
c.scope_returns = false
c.mod = ''
c.is_builtin_mod = false
c.is_just_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.inside_x_is_type = 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(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 {
// Imports with the same path and name (self-imports and module name conflicts with builtin module imports)
if c.mod == ast_import.mod {
c.error('cannot import `${ast_import.mod}` into a module with the same name',
ast_import.mod_pos)
}
// Duplicates of regular imports with the default alias (modname) and `as` imports with a custom alias
if c.mod == ast_import.alias {
if c.mod == ast_import.mod.all_after_last('.') {
c.error('cannot import `${ast_import.mod}` into a module with the same name',
ast_import.mod_pos)
}
c.error('cannot import `${ast_import.mod}` as `${ast_import.alias}` into a module with the same name',
ast_import.alias_pos)
}
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)
} else if ast_import.mod == ast_file.imports[j].alias {
c.error('`${ast_file.imports[j].mod}` was already imported as `${ast_import.alias}` on line ${
ast_file.imports[j].mod_pos.line_nr + 1}', ast_import.mod_pos)
} else if ast_import.alias == ast_file.imports[j].alias {
c.error('`${ast_file.imports[j].mod}` was already imported on line ${
ast_file.imports[j].alias_pos.line_nr + 1}', ast_import.alias_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(mut 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(mut stmt)
}
if c.should_abort {
return
}
}
c.stmt_level = 0
for mut stmt in ast_file.stmts {
if stmt !in [ast.ConstDecl, ast.GlobalDecl, ast.ExprStmt] {
c.expr_level = 0
c.stmt(mut stmt)
}
if c.should_abort {
return
}
}
c.check_scope_vars(c.file.scope)
c.check_unused_labels()
}
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(mut ast_file ast.File) []errors.Error {
c.change_current_file(ast_file)
for mut stmt in ast_file.stmts {
c.stmt(mut 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
c.is_generated = file.is_generated
}
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
unsafe {
mut files_from_main_module := []&ast.File{}
for i in 0 .. ast_files.len {
mut file := ast_files[i]
c.timers.start('checker_check ${file.path}')
c.check(mut 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 ensure all generic calls are processed, as this information
// is needed when the generic type is auto inferred from the call argument.
// we may have to loop several times, if there were more concrete types found.
mut post_process_generic_fns_iterations := 0
post_process_iterations_loop: for post_process_generic_fns_iterations <= checker.generic_fn_postprocess_iterations_cutoff_limit {
$if trace_post_process_generic_fns_loop ? {
eprintln('>>>>>>>>> recheck_generic_fns loop iteration: ${post_process_generic_fns_iterations}')
}
for file in ast_files {
if file.generic_fns.len > 0 {
$if trace_post_process_generic_fns_loop ? {
eprintln('>> file.path: ${file.path:-40} | file.generic_fns:' +
file.generic_fns.map(it.name).str())
}
c.change_current_file(file)
c.post_process_generic_fns() or { break post_process_iterations_loop }
}
}
if !c.need_recheck_generic_fns {
break
}
c.need_recheck_generic_fns = false
post_process_generic_fns_iterations++
}
$if trace_post_process_generic_fns_loop ? {
eprintln('>>>>>>>>> recheck_generic_fns loop done, iteration: ${post_process_generic_fns_iterations}')
}
// 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.Pos{})
}
}
// 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.Pos{})
} else if !has_main_fn && !c.pref.is_o {
c.error('function `main` must be declared in the main module', token.Pos{})
}
}
// 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.Pos) {
if c.pref.translated || c.file.is_translated {
return
}
if !c.pref.is_vweb && name.len > 0 && (name[0] == `_` || name.contains('._')) {
c.error('${identifier} `${name}` cannot start with `_`', pos)
}
if !c.pref.experimental && 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.Pos) {
if c.pref.translated || c.file.is_translated {
return
}
sname := stripped_name(name)
if sname.len > 0 && !sname[0].is_capital() {
c.error('${identifier} `${name}` must begin with capital letter', pos)
}
}
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) }
}
}
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)
}
if !c.ensure_type_exists(node.parent_type, node.type_pos) {
return
}
mut parent_typ_sym := c.table.sym(node.parent_type)
if node.parent_type.has_flag(.result) {
c.add_error_detail('Result types cannot be stored and have to be unwrapped immediately')
c.error('cannot make an alias of Result type', node.type_pos)
}
match parent_typ_sym.kind {
.placeholder, .int_literal, .float_literal {
c.error('unknown aliased type `${parent_typ_sym.name}`', node.type_pos)
}
.alias {
orig_sym := c.table.sym((parent_typ_sym.info as ast.Alias).parent_type)
c.error('type `${parent_typ_sym.str()}` is an alias, use the original alias type `${orig_sym.name}` instead',
node.type_pos)
}
.chan {
c.error('aliases of `chan` types are not allowed', node.type_pos)
}
.thread {
c.error('aliases of `thread` types are not allowed', node.type_pos)
}
.multi_return {
c.error('aliases of function multi return types are not allowed', node.type_pos)
}
.void {
c.error('aliases of the void type are not allowed', node.type_pos)
}
.function {
orig_sym := c.table.type_to_str(node.parent_type)
c.error('type `${parent_typ_sym.str()}` is an alias, use the original alias type `${orig_sym}` instead',
node.type_pos)
}
.struct_ {
if mut parent_typ_sym.info is ast.Struct {
// check if the generic param types have been defined
for ct in parent_typ_sym.info.concrete_types {
ct_sym := c.table.sym(ct)
if ct_sym.kind == .placeholder {
c.error('unknown type `${ct_sym.name}`', node.type_pos)
}
}
}
}
.array {
c.check_alias_vs_element_type_of_parent(node, (parent_typ_sym.info as ast.Array).elem_type,
'array')
}
.array_fixed {
c.check_alias_vs_element_type_of_parent(node, (parent_typ_sym.info as ast.ArrayFixed).elem_type,
'fixed array')
}
.map {
info := parent_typ_sym.info as ast.Map
c.check_alias_vs_element_type_of_parent(node, info.key_type, 'map key')
c.check_alias_vs_element_type_of_parent(node, info.value_type, 'map value')
}
.sum_type {
// TODO: decide whether the following should be allowed. Note that it currently works,
// while `type Sum = int | Sum` is explicitly disallowed:
// type Sum = int | Alias
// type Alias = Sum
}
// The rest of the parent symbol kinds are also allowed, since they are either primitive types,
// that in turn do not allow recursion, or are abstract enough so that they can not be checked at comptime:
else {}
/*
.voidptr, .byteptr, .charptr {}
.char, .rune, .bool {}
.string, .enum_, .none_, .any {}
.i8, .i16, .int, .i64, .isize {}
.u8, .u16, .u32, .u64, .usize {}
.f32, .f64 {}
.interface_ {}
.generic_inst {}
.aggregate {}
*/
}
}
fn (mut c Checker) check_alias_vs_element_type_of_parent(node ast.AliasTypeDecl, element_type_of_parent ast.Type, label string) {
if node.typ.idx() != element_type_of_parent.idx() {
return
}
c.error('recursive declarations of aliases are not allowed - the alias `${node.name}` is used in the ${label}',
node.type_pos)
}
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.sym(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)
ret_sym := c.table.sym(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 {
if !c.ensure_type_exists(arg.typ, arg.type_pos) {
return
}
arg_sym := c.table.sym(arg.typ)
if arg_sym.kind == .placeholder {
c.error('unknown type `${arg_sym.name}`', arg.type_pos)
}
}
}
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 {
c.ensure_type_exists(variant.typ, variant.pos)
sym := c.table.sym(variant.typ)
if variant.typ.is_ptr() {
variant_name := sym.name.all_after_last('.')
lb, rb := if sym.kind == .struct_ { '{', '}' } else { '(', ')' }
c.add_error_detail('declare the sum type with non-reference types: `${node.name} = ${variant_name} | ...`
and use a reference to the sum type instead: `var := &${node.name}(${variant_name}${lb}val${rb})`')
c.error('sum type cannot hold a reference type', variant.pos)
}
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 a JS struct', variant.pos)
} else if sym.info is ast.Struct {
if sym.info.is_generic {
if !variant.typ.has_flag(.generic) {
c.error('generic struct `${sym.name}` must specify generic type names, e.g. ${sym.name}[T]',
variant.pos)
}
if node.generic_types.len == 0 {
c.error('generic sumtype `${node.name}` must specify generic type names, e.g. ${node.name}[T]',
node.name_pos)
} else {
for typ in sym.info.generic_types {
if typ !in node.generic_types {
sumtype_type_names := node.generic_types.map(c.table.type_to_str(it)).join(', ')
generic_sumtype_name := '${node.name}<${sumtype_type_names}>'
variant_type_names := sym.info.generic_types.map(c.table.type_to_str(it)).join(', ')
generic_variant_name := '${sym.name}<${variant_type_names}>'
c.error('generic type name `${c.table.sym(typ).name}` of generic struct `${generic_variant_name}` is not mentioned in sumtype `${generic_sumtype_name}`',
variant.pos)
}
}
}
}
} else if sym.info is ast.FnType {
if c.table.sym(sym.info.func.return_type).name.ends_with('.${node.name}') {
c.error('sum type `${node.name}` cannot be defined recursively', variant.pos)
}
for param in sym.info.func.params {
if c.table.sym(param.typ).name.ends_with('.${node.name}') {
c.error('sum type `${node.name}` cannot be defined recursively', variant.pos)
}
}
}
if sym.name.trim_string_left(sym.mod + '.') == node.name {
c.error('sum type cannot hold itself', variant.pos)
}
names_used << sym.name
}
}
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 > checker.iface_level_cutoff_limit {
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.embeds.clone()
if !iface_decl.are_embeds_expanded {
list = c.expand_iface_embeds(idecl, level + 1, iface_decl.embeds)
c.table.interfaces[ie.typ].embeds = list
c.table.interfaces[ie.typ].are_embeds_expanded = true
}
for partial in list {
res[partial.typ] = partial
}
}
res[ie.typ] = ie
}
for _, v in res {
ares << v
}
return ares
}
// returns name and position of variable that needs write lock
// also sets `is_changed` to true (TODO update the name to reflect this?)
fn (mut c Checker) fail_if_immutable(mut expr ast.Expr) (string, token.Pos) {
mut to_lock := '' // name of variable that needs lock
mut pos := token.Pos{} // and its position
mut explicit_lock_needed := false
match mut expr {
ast.CastExpr {
// TODO
return '', expr.pos
}
ast.ComptimeSelector {
mut expr_left := expr.left
if mut expr.left is ast.Ident {
if mut expr.left.obj is ast.Var {
if expr.left.obj.ct_type_var != .generic_param {
c.fail_if_immutable(mut expr_left)
}
}
}
return '', expr.pos
}
ast.Ident {
if mut expr.obj is ast.Var {
if !expr.obj.is_mut && !c.pref.translated && !c.file.is_translated
&& !c.inside_unsafe {
if c.inside_anon_fn {
c.error('the closure copy of `${expr.name}` is immutable, declare it with `mut` to make it mutable',
expr.pos)
} else {
c.error('`${expr.name}` is immutable, declare it with `mut` to make it mutable',
expr.pos)
}
}
expr.obj.is_changed = true
if expr.obj.typ.share() == .shared_t {
if expr.name !in c.locked_names {
if c.locked_names.len > 0 || c.rlocked_names.len > 0 {
if expr.name in c.rlocked_names {
c.error('${expr.name} has an `rlock` but needs a `lock`',
expr.pos)
} else {
c.error('${expr.name} must be added to the `lock` list above',
expr.pos)
}
}
to_lock = expr.name
pos = expr.pos
}
}
} else if expr.obj is ast.ConstField && expr.name in c.const_names {
if !c.inside_unsafe && !c.pref.translated {
// TODO fix this in c2v, do not allow modification of all consts
// in translated code
c.error('cannot modify constant `${expr.name}`', expr.pos)
}
}
}
ast.IndexExpr {
if expr.left_type == 0 {
return to_lock, pos
}
left_sym := c.table.sym(expr.left_type)
mut elem_type := ast.Type(0)
mut kind := ''
match left_sym.info {
ast.Array {
elem_type, kind = left_sym.info.elem_type, 'array'
}
ast.ArrayFixed {
elem_type, kind = left_sym.info.elem_type, 'fixed array'
}
ast.Map {
elem_type, kind = left_sym.info.value_type, 'map'
}
else {}
}
if elem_type.has_flag(.shared_f) {
c.error('you have to create a handle and `lock` it to modify `shared` ${kind} element',
expr.left.pos().extend(expr.pos))
}
to_lock, pos = c.fail_if_immutable(mut expr.left)
}
ast.ParExpr {
to_lock, pos = c.fail_if_immutable(mut expr.expr)
}
ast.PrefixExpr {
if expr.op == .mul && expr.right is ast.Ident {
// Do not fail if dereference is immutable:
// `*x = foo()` doesn't modify `x`
} else {
to_lock, pos = c.fail_if_immutable(mut expr.right)
}
}
ast.PostfixExpr {
to_lock, pos = c.fail_if_immutable(mut expr.expr)
}
ast.SelectorExpr {
if expr.expr_type == 0 {
return '', expr.pos
}
// retrieve ast.Field
if !c.ensure_type_exists(expr.expr_type, expr.pos) {
return '', expr.pos
}
mut typ_sym := c.table.final_sym(c.unwrap_generic(expr.expr_type))
match typ_sym.kind {
.struct_ {
mut has_field := true
mut field_info := c.table.find_field_with_embeds(typ_sym, expr.field_name) or {
has_field = false
ast.StructField{}
}
if !has_field {
type_str := c.table.type_to_str(expr.expr_type)
c.error('unknown field `${type_str}.${expr.field_name}`', expr.pos)
return '', expr.pos
}
if field_info.typ.has_flag(.shared_f) {
expr_name := '${expr.expr}.${expr.field_name}'
if expr_name !in c.locked_names {
if c.locked_names.len > 0 || c.rlocked_names.len > 0 {
if expr_name in c.rlocked_names {
c.error('${expr_name} has an `rlock` but needs a `lock`',
expr.pos)
} else {
c.error('${expr_name} must be added to the `lock` list above',
expr.pos)
}
return '', expr.pos
}
to_lock = expr_name
pos = expr.pos
}
} else {
if !field_info.is_mut && !c.pref.translated && !c.file.is_translated {
type_str := c.table.type_to_str(expr.expr_type)
c.error('field `${expr.field_name}` of struct `${type_str}` is immutable',
expr.pos)
}
to_lock, pos = c.fail_if_immutable(mut expr.expr)
}
if to_lock != '' {
// No automatic lock for struct access
explicit_lock_needed = true
}
}
.interface_ {
interface_info := typ_sym.info as ast.Interface
mut field_info := interface_info.find_field(expr.field_name) or {
type_str := c.table.type_to_str(expr.expr_type)
c.error('unknown field `${type_str}.${expr.field_name}`', expr.pos)
return '', expr.pos
}
if !field_info.is_mut {
type_str := c.table.type_to_str(expr.expr_type)
c.error('field `${expr.field_name}` of interface `${type_str}` is immutable',
expr.pos)
return '', expr.pos
}
c.fail_if_immutable(mut expr.expr)
}
.sum_type {
sumtype_info := typ_sym.info as ast.SumType
mut field_info := sumtype_info.find_field(expr.field_name) or {
type_str := c.table.type_to_str(expr.expr_type)
c.error('unknown field `${type_str}.${expr.field_name}`', expr.pos)
return '', expr.pos
}
if !field_info.is_mut {
type_str := c.table.type_to_str(expr.expr_type)
c.error('field `${expr.field_name}` of sumtype `${type_str}` is immutable',
expr.pos)
return '', expr.pos
}
c.fail_if_immutable(mut expr.expr)
}
.array, .string {
// should only happen in `builtin` and unsafe blocks
inside_builtin := c.file.mod.name == 'builtin'
if !inside_builtin && !c.inside_unsafe {
c.error('`${typ_sym.kind}` can not be modified', expr.pos)
return '', expr.pos
}
}
.aggregate, .placeholder {
c.fail_if_immutable(mut expr.expr)
}
else {
c.error('unexpected symbol `${typ_sym.kind}`', expr.pos)
return '', expr.pos
}
}
}
ast.CallExpr {
// TODO: should only work for builtin method
if expr.name == 'slice' {
to_lock, pos = c.fail_if_immutable(mut expr.left)
if to_lock != '' {
// No automatic lock for array slicing (yet(?))
explicit_lock_needed = true
}
}
}
ast.ArrayInit {
c.error('array literal can not be modified', expr.pos)
return '', expr.pos
}
ast.StructInit {
return '', expr.pos
}
ast.InfixExpr {
return '', expr.pos
}
else {
if !expr.is_pure_literal() {
c.error('unexpected expression `${expr.type_name()}`', expr.pos())
return '', expr.pos()
}
}
}
if explicit_lock_needed {
c.error('`${to_lock}` is `shared` and needs explicit lock for `${expr.type_name()}`',
pos)
to_lock = ''
}
return to_lock, pos
}
fn (mut c Checker) type_implements(typ ast.Type, interface_type ast.Type, pos token.Pos) bool {
if typ == interface_type {
return true
}
$if debug_interface_type_implements ? {
eprintln('> type_implements typ: ${typ.debug()} (`${c.table.type_to_str(typ)}`) | inter_typ: ${interface_type.debug()} (`${c.table.type_to_str(interface_type)}`)')
}
utyp := c.unwrap_generic(typ)
typ_sym := c.table.sym(utyp)
mut inter_sym := c.table.sym(interface_type)
// small hack for JS.Any type. Since `any` in regular V is getting deprecated we have our own JS.Any type for JS backend.
if typ_sym.name == 'JS.Any' {
return true
}
if mut inter_sym.info is ast.Interface {
mut generic_type := interface_type
mut generic_info := inter_sym.info
if inter_sym.info.parent_type.has_flag(.generic) {
parent_sym := c.table.sym(inter_sym.info.parent_type)
if parent_sym.info is ast.Interface {
generic_type = inter_sym.info.parent_type
generic_info = parent_sym.info
}
}
mut inferred_type := interface_type
if generic_info.is_generic {
inferred_type = c.resolve_generic_interface(typ, generic_type, pos)
if inferred_type == 0 {
return false
}
}
if inter_sym.info.is_generic {
if inferred_type == interface_type {
// terminate early, since otherwise we get an infinite recursion/segfault:
return false
}
return c.type_implements(typ, inferred_type, pos)
}
}
// do not check the same type more than once
if mut inter_sym.info is ast.Interface {
for t in inter_sym.info.types {
if t.idx() == utyp.idx() {
return true
}
}
}
if utyp.idx() == interface_type.idx() {
// same type -> already casted to the interface
return true
}
if interface_type.idx() == ast.error_type_idx && utyp.idx() == ast.none_type_idx {
// `none` "implements" the Error interface
return true
}
styp := c.table.type_to_str(utyp)
if typ_sym.kind == .interface_ && inter_sym.kind == .interface_ && !styp.starts_with('JS.')
&& !inter_sym.name.starts_with('JS.') {
c.error('cannot implement interface `${inter_sym.name}` with a different interface `${styp}`',
pos)
}
imethods := if inter_sym.kind == .interface_ {
(inter_sym.info as ast.Interface).methods
} else {
inter_sym.methods
}
// voidptr is an escape hatch, it should be allowed to be passed
if utyp != ast.voidptr_type && utyp != ast.nil_type {
mut are_methods_implemented := true
// Verify methods
for imethod in imethods {
method := c.table.find_method_with_embeds(typ_sym, imethod.name) or {
// >> Hack to allow old style custom error implementations
// TODO: remove once deprecation period for `IError` methods has ended
if inter_sym.idx == ast.error_type_idx
&& (imethod.name == 'msg' || imethod.name == 'code') {
c.note("`${styp}` doesn't implement method `${imethod.name}` of interface `${inter_sym.name}`. The usage of fields is being deprecated in favor of methods.",
pos)
return false
}
// <<
typ_sym.find_method_with_generic_parent(imethod.name) or {
c.error("`${styp}` doesn't implement method `${imethod.name}` of interface `${inter_sym.name}`",
pos)
are_methods_implemented = false
continue
}
}
msg := c.table.is_same_method(imethod, method)
if msg.len > 0 {
sig := c.table.fn_signature(imethod, skip_receiver: false)
typ_sig := c.table.fn_signature(method, skip_receiver: false)
c.add_error_detail('${inter_sym.name} has `${sig}`')
c.add_error_detail(' ${typ_sym.name} has `${typ_sig}`')
c.error('`${styp}` incorrectly implements method `${imethod.name}` of interface `${inter_sym.name}`: ${msg}',
pos)
return false
}
}
if !are_methods_implemented {
return false
}