/
parser.v
4502 lines (4336 loc) · 113 KB
/
parser.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.
[has_globals]
module parser
import v.scanner
import v.ast
import v.token
import v.pref
import v.util
import v.vet
import v.errors
import os
import hash.fnv1a
[minify]
pub struct Parser {
pref &pref.Preferences = unsafe { nil }
mut:
file_base string // "hello.v"
file_name string // "/home/user/hello.v"
file_name_dir string // "/home/user"
file_display_path string // just "hello.v", when your current folder for the compilation is "/home/user/", otherwise the full path "/home/user/hello.v"
unique_prefix string // a hash of p.file_name, used for making anon fn generation unique
file_backend_mode ast.Language // .c for .c.v|.c.vv|.c.vsh files; .js for .js.v files, .amd64/.rv32/other arches for .amd64.v/.rv32.v/etc. files, .v otherwise.
comments_mode scanner.CommentsMode = .skip_comments
// see comment in parse_file
tok token.Token
prev_tok token.Token
peek_tok token.Token
table &ast.Table = unsafe { nil }
language ast.Language
fn_language ast.Language // .c for `fn C.abcd()` declarations
expr_level int // prevent too deep recursions for pathological programs
inside_vlib_file bool // true for all vlib/ files
inside_test_file bool // when inside _test.v or _test.vv file
inside_if bool
inside_comptime_if bool
inside_if_expr bool
inside_if_cond bool
inside_ct_if_expr bool
inside_or_expr bool
inside_for bool
inside_fn bool // true even with implicit main
inside_fn_return bool
inside_call_args bool // true inside f( .... )
inside_unsafe_fn bool
inside_str_interp bool
inside_array_lit bool
inside_in_array bool
inside_infix bool
inside_match bool // to separate `match A { }` from `Struct{}`
inside_select bool // to allow `ch <- Struct{} {` inside `select`
inside_match_case bool // to separate `match_expr { }` from `Struct{}`
inside_match_body bool // to fix eval not used TODO
inside_unsafe bool
inside_sum_type bool // to prevent parsing inline sum type again
inside_asm_template bool
inside_asm bool
inside_defer bool
inside_generic_params bool // indicates if parsing between `<` and `>` of a method/function
inside_receiver_param bool // indicates if parsing the receiver parameter inside the first `(` and `)` of a method
inside_struct_field_decl bool
inside_struct_attr_decl bool
inside_map_init bool
inside_orm bool
inside_chan_decl bool
inside_attr_decl bool
fixed_array_dim int // fixed array dim parsing level
or_is_handled bool // ignore `or` in this expression
builtin_mod bool // are we in the `builtin` module?
mod string // current module name
is_manualfree bool // true when `[manualfree] module abc`, makes *all* fns in the current .v file, opt out of autofree
has_globals bool // `[has_globals] module abc` - allow globals declarations, even without -enable-globals, in that single .v file __only__
is_generated bool // `[generated] module abc` - turn off compiler notices for that single .v file __only__.
is_translated bool // `[translated] module abc` - mark a file as translated, to relax some compiler checks for translated code.
attrs []ast.Attr // attributes before next decl stmt
expr_mod string // for constructing full type names in parse_type()
scope &ast.Scope = unsafe { nil }
imports map[string]string // alias => mod_name
ast_imports []ast.Import // mod_names
used_imports []string // alias
auto_imports []string // imports, the user does not need to specify
imported_symbols map[string]string
is_amp bool // for generating the right code for `&Foo{}`
returns bool
is_stmt_ident bool // true while the beginning of a statement is an ident/selector
expecting_type bool // `is Type`, expecting type
cur_fn_name string
label_names []string
name_error bool // indicates if the token is not a name or the name is on another line
n_asm int // controls assembly labels
global_labels []string
comptime_if_cond bool
defer_vars []ast.Ident
should_abort bool // when too many errors/warnings/notices are accumulated, should_abort becomes true, and the parser should stop
codegen_text string
anon_struct_decl ast.StructDecl
struct_init_generic_types []ast.Type
if_cond_comments []ast.Comment
left_comments []ast.Comment
script_mode bool
script_mode_start_token token.Token
pub mut:
scanner &scanner.Scanner = unsafe { nil }
errors []errors.Error
warnings []errors.Warning
notices []errors.Notice
vet_errors []vet.Error
vet_notices []vet.Error
template_paths []string // record all compiled $tmpl files; needed for `v watch run webserver.v`
}
__global codegen_files = unsafe { []&ast.File{} }
// for tests
pub fn parse_stmt(text string, table &ast.Table, scope &ast.Scope) ast.Stmt {
$if trace_parse_stmt ? {
eprintln('> ${@MOD}.${@FN} text: ${text}')
}
mut p := Parser{
scanner: scanner.new_scanner(text, .skip_comments, &pref.Preferences{})
inside_test_file: true
table: table
pref: &pref.Preferences{}
scope: scope
}
p.init_parse_fns()
util.timing_start('PARSE stmt')
defer {
util.timing_measure_cumulative('PARSE stmt')
}
p.read_first_token()
return p.stmt(false)
}
pub fn parse_comptime(tmpl_path string, text string, table &ast.Table, pref_ &pref.Preferences, scope &ast.Scope) &ast.File {
$if trace_parse_comptime ? {
eprintln('> ${@MOD}.${@FN} text: ${text}')
}
mut p := Parser{
file_name: tmpl_path
scanner: scanner.new_scanner(text, .skip_comments, pref_)
table: table
pref: pref_
scope: scope
errors: []errors.Error{}
warnings: []errors.Warning{}
}
res := p.parse()
unsafe { p.free_scanner() }
return res
}
pub fn parse_text(text string, path string, table &ast.Table, comments_mode scanner.CommentsMode, pref_ &pref.Preferences) &ast.File {
$if trace_parse_text ? {
eprintln('> ${@MOD}.${@FN} comments_mode: ${comments_mode:-20} | path: ${path:-20} | text: ${text}')
}
mut p := Parser{
scanner: scanner.new_scanner(text, comments_mode, pref_)
comments_mode: comments_mode
table: table
pref: pref_
scope: &ast.Scope{
start_pos: 0
parent: table.global_scope
}
errors: []errors.Error{}
warnings: []errors.Warning{}
}
p.set_path(path)
res := p.parse()
unsafe { p.free_scanner() }
return res
}
[unsafe]
pub fn (mut p Parser) free() {
unsafe { p.free_scanner() }
}
[unsafe]
fn (mut p Parser) free_scanner() {
unsafe {
if p.scanner != 0 {
p.scanner.free()
p.scanner = &scanner.Scanner(nil)
}
}
}
const normalised_working_folder = (os.real_path(os.getwd()) + os.path_separator).replace('\\',
'/')
pub fn (mut p Parser) set_path(path string) {
p.file_name = path
p.file_base = os.base(path)
p.file_name_dir = os.dir(path)
p.file_display_path = os.real_path(p.file_name).replace_once(parser.normalised_working_folder,
'').replace('\\', '/')
p.inside_vlib_file = p.file_name_dir.contains('vlib')
p.inside_test_file = p.file_base.ends_with('_test.v') || p.file_base.ends_with('_test.vv')
|| p.file_base.all_before_last('.v').all_before_last('.').ends_with('_test')
hash := fnv1a.sum64_string(path)
p.unique_prefix = hash.hex_full()
p.file_backend_mode = .v
before_dot_v := path.all_before_last('.v') // also works for .vv and .vsh
language := before_dot_v.all_after_last('.')
language_with_underscore := before_dot_v.all_after_last('_')
if language == before_dot_v && language_with_underscore == before_dot_v {
return
}
actual_language := if language == before_dot_v { language_with_underscore } else { language }
match actual_language {
'c' {
p.file_backend_mode = .c
}
'js' {
p.file_backend_mode = .js
}
else {
arch := pref.arch_from_string(actual_language) or { pref.Arch._auto }
p.file_backend_mode = ast.pref_arch_to_table_language(arch)
if arch == ._auto {
p.file_backend_mode = .v
}
}
}
}
pub fn parse_file(path string, table &ast.Table, comments_mode scanner.CommentsMode, pref_ &pref.Preferences) &ast.File {
// Note: when comments_mode == .toplevel_comments,
// the parser gives feedback to the scanner about toplevel statements, so that the scanner can skip
// all the tricky inner comments. This is needed because we do not have a good general solution
// for handling them, and should be removed when we do (the general solution is also needed for vfmt)
$if trace_parse_file ? {
eprintln('> ${@MOD}.${@FN} comments_mode: ${comments_mode:-20} | path: ${path}')
}
mut p := Parser{
scanner: scanner.new_scanner_file(path, comments_mode, pref_) or { panic(err) }
comments_mode: comments_mode
table: table
pref: pref_
scope: &ast.Scope{
start_pos: 0
parent: table.global_scope
}
errors: []errors.Error{}
warnings: []errors.Warning{}
}
p.set_path(path)
res := p.parse()
unsafe { p.free_scanner() }
return res
}
pub fn parse_vet_file(path string, table_ &ast.Table, pref_ &pref.Preferences) (&ast.File, []vet.Error, []vet.Error) {
$if trace_parse_vet_file ? {
eprintln('> ${@MOD}.${@FN} path: ${path}')
}
global_scope := &ast.Scope{
parent: 0
}
mut p := Parser{
scanner: scanner.new_scanner_file(path, .parse_comments, pref_) or { panic(err) }
comments_mode: .parse_comments
table: table_
pref: pref_
scope: &ast.Scope{
start_pos: 0
parent: global_scope
}
errors: []errors.Error{}
warnings: []errors.Warning{}
}
p.set_path(path)
if p.scanner.text.contains_any_substr(['\n ', ' \n']) {
source_lines := os.read_lines(path) or { []string{} }
for lnumber, line in source_lines {
if line.starts_with(' ') {
p.vet_error('Looks like you are using spaces for indentation.', lnumber,
.vfmt, .space_indent)
}
if line.ends_with(' ') {
p.vet_error('Looks like you have trailing whitespace.', lnumber, .unknown,
.trailing_space)
}
}
}
p.vet_errors << p.scanner.vet_errors
file := p.parse()
unsafe { p.free_scanner() }
return file, p.vet_errors, p.vet_notices
}
pub fn (mut p Parser) parse() &ast.File {
util.timing_start('PARSE')
defer {
util.timing_measure_cumulative('PARSE')
}
// comments_mode: comments_mode
p.init_parse_fns()
p.read_first_token()
mut stmts := []ast.Stmt{}
for p.tok.kind == .comment {
stmts << p.comment_stmt()
}
// module
module_decl := p.module_decl()
if module_decl.is_skipped {
stmts.insert(0, ast.Stmt(module_decl))
} else {
stmts << module_decl
}
// imports
for {
if p.tok.kind == .key_import {
stmts << p.import_stmt()
continue
}
if p.tok.kind == .comment {
stmts << p.comment_stmt()
continue
}
break
}
for {
if p.tok.kind == .eof {
p.check_unused_imports()
break
}
stmt := p.top_stmt()
// clear the attributes after each statement
if !(stmt is ast.ExprStmt && stmt.expr is ast.Comment) {
p.attrs = []
}
stmts << stmt
if p.should_abort {
break
}
}
p.scope.end_pos = p.tok.pos
mut errors_ := p.errors.clone()
mut warnings := p.warnings.clone()
mut notices := p.notices.clone()
if p.pref.check_only {
errors_ << p.scanner.errors
warnings << p.scanner.warnings
notices << p.scanner.notices
}
// codegen
if p.codegen_text.len > 0 && !p.pref.is_fmt {
ptext := 'module ' + p.mod.all_after_last('.') + p.codegen_text
codegen_files << parse_text(ptext, p.file_name, p.table, p.comments_mode, p.pref)
}
return &ast.File{
path: p.file_name
path_base: p.file_base
is_test: p.inside_test_file
is_generated: p.is_generated
is_translated: p.is_translated
nr_lines: p.scanner.line_nr
nr_bytes: p.scanner.text.len
mod: module_decl
imports: p.ast_imports
imported_symbols: p.imported_symbols
auto_imports: p.auto_imports
stmts: stmts
scope: p.scope
global_scope: p.table.global_scope
errors: errors_
warnings: warnings
notices: notices
global_labels: p.global_labels
template_paths: p.template_paths
unique_prefix: p.unique_prefix
}
}
/*
struct Queue {
mut:
idx int
mu &sync.Mutex = sync.new_mutex()
mu2 &sync.Mutex = sync.new_mutex()
paths []string
table &ast.Table = unsafe { nil }
parsed_ast_files []&ast.File
pref &pref.Preferences = unsafe { nil }
global_scope &ast.Scope = unsafe { nil }
}
fn (mut q Queue) run() {
for {
q.mu.lock()
idx := q.idx
if idx >= q.paths.len {
q.mu.unlock()
return
}
q.idx++
q.mu.unlock()
println('run(idx=$idx)')
path := q.paths[idx]
file := parse_file(path, q.table, .skip_comments, q.pref, q.global_scope)
q.mu2.lock()
q.parsed_ast_files << file
q.mu2.unlock()
println('run done(idx=$idx)')
}
}
*/
pub fn parse_files(paths []string, table &ast.Table, pref_ &pref.Preferences) []&ast.File {
mut timers := util.new_timers(should_print: false, label: 'parse_files: ${paths}')
$if time_parsing ? {
timers.should_print = true
}
$if macos {
/*
if !pref.no_parallel && paths[0].contains('/array.v') {
println('\n\n\nparse_files() nr_files=$paths.len')
println(paths)
nr_cpus := runtime.nr_cpus()
mut q := &Queue{
paths: paths
table: table
pref: pref
global_scope: global_scope
mu: sync.new_mutex()
mu2: sync.new_mutex()
}
for _ in 0 .. nr_cpus - 1 {
go q.run()
}
time.sleep(time.second)
println('all done')
return q.parsed_ast_files
}
*/
}
unsafe {
mut files := []&ast.File{cap: paths.len}
for path in paths {
timers.start('parse_file ${path}')
files << parse_file(path, table, .skip_comments, pref_)
timers.show('parse_file ${path}')
}
if codegen_files.len > 0 {
files << codegen_files
codegen_files.clear()
}
return files
}
}
// codegen allows you to generate V code, so that it can be parsed,
// checked, markused, cgen-ed etc further, just like user's V code.
pub fn (mut p Parser) codegen(code string) {
$if debug_codegen ? {
eprintln('parser.codegen:\n ${code}')
}
p.codegen_text += '\n' + code
}
fn (mut p Parser) init_parse_fns() {
// p.prefix_parse_fns = make(100, 100, sizeof(PrefixParseFn))
// p.prefix_parse_fns[token.Kind.name] = parse_name
}
fn (mut p Parser) read_first_token() {
// need to call next() 2 times to get peek token and current token
p.next()
p.next()
}
[inline]
fn (p &Parser) peek_token(n int) token.Token {
return p.scanner.peek_token(n - 2)
}
// peek token in if guard `if x,y := opt()` after var_list `x,y`
fn (p &Parser) peek_token_after_var_list() token.Token {
mut n := 0
mut tok := p.tok
for {
if tok.kind == .eof {
break
}
if tok.kind == .key_mut {
n += 2
} else {
n++
}
tok = p.scanner.peek_token(n - 2)
if tok.kind != .comma {
break
} else {
n++
tok = p.scanner.peek_token(n - 2)
}
}
return tok
}
// peek token `type Fn = fn () int`
fn (p &Parser) is_fn_type_decl() bool {
mut n := 1
mut tok := p.tok
mut prev_tok := p.tok
cur_ln := p.tok.line_nr
for {
tok = p.scanner.peek_token(n)
if tok.kind == .eof {
break
}
if tok.kind in [.lpar, .rpar] {
n++
prev_tok = tok
continue
}
if tok.kind == .pipe {
if tok.pos - prev_tok.pos > prev_tok.len {
return false
}
}
if tok.line_nr > cur_ln {
break
}
prev_tok = tok
n++
}
return true
}
fn (p &Parser) is_array_type() bool {
mut i := 1
mut tok := p.tok
line_nr := p.tok.line_nr
for {
tok = p.peek_token(i)
if tok.line_nr != line_nr {
return false
}
if tok.kind in [.name, .amp] {
return true
}
i++
if tok.kind == .lsbr || tok.kind != .rsbr {
continue
}
}
return false
}
fn (mut p Parser) open_scope() {
p.scope = &ast.Scope{
parent: p.scope
start_pos: p.tok.pos
}
}
fn (mut p Parser) close_scope() {
// p.scope.end_pos = p.tok.pos
// NOTE: since this is usually called after `p.parse_block()`
// ie. when `prev_tok` is rcbr `}` we most likely want `prev_tok`
// we could do the following, but probably not needed in 99% of cases:
// `end_pos = if p.prev_tok.kind == .rcbr { p.prev_tok.pos } else { p.tok.pos }`
p.scope.end_pos = p.prev_tok.pos
p.scope.parent.children << p.scope
p.scope = p.scope.parent
}
fn (mut p Parser) parse_block() []ast.Stmt {
p.open_scope()
stmts := p.parse_block_no_scope(false)
p.close_scope()
return stmts
}
fn (mut p Parser) parse_block_no_scope(is_top_level bool) []ast.Stmt {
p.check(.lcbr)
mut stmts := []ast.Stmt{cap: 20}
if p.tok.kind != .rcbr {
mut count := 0
for p.tok.kind !in [.eof, .rcbr] {
stmts << p.stmt(is_top_level)
count++
if count % 100000 == 0 {
eprintln('parsed ${count} statements so far from fn ${p.cur_fn_name} ...')
}
if count > 1000000 {
p.error_with_pos('parsed over ${count} statements from fn ${p.cur_fn_name}, the parser is probably stuck',
p.tok.pos())
return []
}
}
}
if is_top_level {
p.top_level_statement_end()
}
p.check(.rcbr)
return stmts
}
fn (mut p Parser) next() {
p.prev_tok = p.tok
p.tok = p.peek_tok
p.peek_tok = p.scanner.scan()
}
fn (mut p Parser) check(expected token.Kind) {
p.name_error = false
if _likely_(p.tok.kind == expected) {
p.next()
} else {
if expected == .name {
p.name_error = true
}
mut s := expected.str()
// quote keywords, punctuation, operators
if token.is_key(s) || (s.len > 0 && !s[0].is_letter()) {
s = '`${s}`'
}
p.unexpected(expecting: s)
}
}
[params]
struct ParamsForUnexpected {
got string
expecting string
prepend_msg string
additional_msg string
}
fn (mut p Parser) unexpected(params ParamsForUnexpected) ast.NodeError {
return p.unexpected_with_pos(p.tok.pos(), params)
}
fn (mut p Parser) unexpected_with_pos(pos token.Pos, params ParamsForUnexpected) ast.NodeError {
mut msg := if params.got != '' {
'unexpected ${params.got}'
} else {
'unexpected ${p.tok}'
}
if params.expecting != '' {
msg += ', expecting ${params.expecting}'
}
if params.prepend_msg != '' {
msg = '${params.prepend_msg} ' + msg
}
if params.additional_msg != '' {
msg += ', ${params.additional_msg}'
}
return p.error_with_pos(msg, pos)
}
// JS functions can have multiple dots in their name:
// JS.foo.bar.and.a.lot.more.dots()
fn (mut p Parser) check_js_name() string {
mut name := ''
for p.peek_tok.kind == .dot {
name += '${p.tok.lit}.'
p.next() // .name
p.next() // .dot
}
// last .name
name += p.tok.lit
p.next()
return name
}
fn (mut p Parser) check_name() string {
pos := p.tok.pos()
name := p.tok.lit
if p.peek_tok.kind == .dot && name in p.imports {
p.register_used_import(name)
}
match p.tok.kind {
.key_struct { p.check(.key_struct) }
.key_enum { p.check(.key_enum) }
.key_interface { p.check(.key_interface) }
else { p.check(.name) }
}
if !p.inside_orm && !p.inside_attr_decl && name == 'sql' {
p.error_with_pos('unexpected keyword `sql`, expecting name', pos)
}
return name
}
[if trace_parser ?]
fn (p &Parser) trace_parser(label string) {
eprintln('parsing: ${p.file_name:-30}|tok.pos: ${p.tok.pos().line_str():-39}|tok.kind: ${p.tok.kind:-10}|tok.lit: ${p.tok.lit:-10}|${label}')
}
fn (mut p Parser) top_stmt() ast.Stmt {
p.trace_parser('top_stmt')
for {
match p.tok.kind {
.key_pub {
match p.peek_tok.kind {
.key_const {
return p.const_decl()
}
.key_fn {
return p.fn_decl()
}
.key_struct, .key_union {
return p.struct_decl(false)
}
.key_interface {
return p.interface_decl()
}
.key_enum {
return p.enum_decl()
}
.key_type {
return p.type_decl()
}
else {
return p.error('wrong pub keyword usage')
}
}
}
.at {
if p.peek_tok.kind == .lsbr {
p.attributes()
continue
} else {
return p.error('@[attr] expected')
}
}
.lsbr {
// attrs are stored in `p.attrs`
p.attributes()
continue
}
.key_asm {
return p.asm_stmt(true)
}
.key_interface {
return p.interface_decl()
}
.key_import {
p.error_with_pos('`import x` can only be declared at the beginning of the file',
p.tok.pos())
return p.import_stmt()
}
.key_global {
return p.global_decl()
}
.key_const {
return p.const_decl()
}
.key_fn {
return p.fn_decl()
}
.key_struct {
return p.struct_decl(false)
}
.dollar {
if p.peek_tok.kind == .eof {
return p.unexpected(got: 'eof')
}
if p.peek_tok.kind == .key_for {
comptime_for_stmt := p.comptime_for()
return p.other_stmts(comptime_for_stmt)
} else if p.peek_tok.kind == .key_if {
if_expr := p.if_expr(true)
cur_stmt := ast.ExprStmt{
expr: if_expr
pos: if_expr.pos
}
if p.pref.is_fmt || comptime_if_expr_contains_top_stmt(if_expr) {
return cur_stmt
} else {
return p.other_stmts(cur_stmt)
}
} else {
return p.unexpected()
}
}
.hash {
return p.hash()
}
.key_type {
return p.type_decl()
}
.key_enum {
return p.enum_decl()
}
.key_union {
return p.struct_decl(false)
}
.comment {
return p.comment_stmt()
}
.semicolon {
return p.semicolon_stmt()
}
else {
return p.other_stmts(ast.empty_stmt)
}
}
if p.should_abort {
break
}
}
// TODO remove dummy return statement
// the compiler complains if it's not there
return ast.empty_stmt
}
fn comptime_if_expr_contains_top_stmt(if_expr ast.IfExpr) bool {
for branch in if_expr.branches {
for stmt in branch.stmts {
if stmt is ast.ExprStmt {
if stmt.expr is ast.IfExpr {
if !comptime_if_expr_contains_top_stmt(stmt.expr) {
return false
}
} else if stmt.expr is ast.CallExpr {
return false
}
} else if stmt is ast.AssignStmt {
return false
} else if stmt is ast.HashStmt {
return true
}
}
}
return true
}
fn (mut p Parser) other_stmts(cur_stmt ast.Stmt) ast.Stmt {
p.inside_fn = true
if p.pref.is_script && !p.pref.is_test {
p.script_mode = true
p.script_mode_start_token = p.tok
if p.table.known_fn('main.main') {
p.error('function `main` is already defined, put your script statements inside it')
}
p.open_scope()
p.cur_fn_name = 'main.main'
mut stmts := []ast.Stmt{}
if cur_stmt != ast.empty_stmt {
stmts << cur_stmt
}
for p.tok.kind != .eof {
stmts << p.stmt(false)
}
p.close_scope()
p.script_mode = false
return ast.FnDecl{
name: 'main.main'
short_name: 'main'
mod: 'main'
is_main: true
stmts: stmts
file: p.file_name
return_type: ast.void_type
scope: p.scope
label_names: p.label_names
}
} else if p.pref.is_fmt || p.pref.is_vet {
return p.stmt(false)
} else {
return p.error('bad top level statement ' + p.tok.str())
}
}
// TODO [if vfmt]
fn (mut p Parser) check_comment() ast.Comment {
if p.tok.kind == .comment {
return p.comment()
}
return ast.Comment{}
}
fn (mut p Parser) comment() ast.Comment {
mut pos := p.tok.pos()
text := p.tok.lit
num_newlines := text.count('\n')
is_multi := num_newlines > 0
pos.last_line = pos.line_nr + num_newlines
p.next()
// Filter out false positive space indent vet errors inside comments
if p.vet_errors.len > 0 && is_multi {
p.vet_errors = p.vet_errors.filter(it.typ != .space_indent
|| it.pos.line_nr - 1 > pos.last_line || it.pos.line_nr - 1 <= pos.line_nr)
}
return ast.Comment{
text: text
is_multi: is_multi
pos: pos
}
}
fn (mut p Parser) comment_stmt() ast.ExprStmt {
comment := p.comment()
return ast.ExprStmt{
expr: comment
pos: comment.pos
}
}
[params]
struct EatCommentsConfig {
same_line bool // Only eat comments on the same line as the previous token
follow_up bool // Comments directly below the previous token as long as there is no empty line
}
fn (mut p Parser) eat_comments(cfg EatCommentsConfig) []ast.Comment {
mut line := p.prev_tok.line_nr
mut comments := []ast.Comment{}
for {
if p.tok.kind != .comment || (cfg.same_line && p.tok.line_nr > line)
|| (cfg.follow_up && (p.tok.line_nr > line + 1 || p.tok.lit.contains('\n'))) {
break
}
comments << p.comment()
if cfg.follow_up {
line = p.prev_tok.line_nr
}
}
return comments
}
fn (mut p Parser) stmt(is_top_level bool) ast.Stmt {
p.trace_parser('stmt(${is_top_level})')
p.is_stmt_ident = p.tok.kind == .name
match p.tok.kind {
.lcbr {
mut pos := p.tok.pos()
stmts := p.parse_block()
pos.last_line = p.prev_tok.line_nr
return ast.Block{
stmts: stmts
pos: pos
}
}
.key_assert {
p.next()
mut pos := p.tok.pos()
expr := p.expr(0)
pos.update_last_line(p.prev_tok.line_nr)
mut extra := ast.empty_expr
mut extra_pos := p.tok.pos()
if p.tok.kind == .comma {
p.next()
extra_pos = p.tok.pos()
extra = p.expr(0)
// dump(extra)
extra_pos = extra_pos.extend(p.tok.pos())
}
return ast.AssertStmt{
expr: expr
extra: extra
extra_pos: extra_pos
pos: pos.extend(p.tok.pos())
is_used: p.inside_test_file || !p.pref.is_prod
}
}
.key_for {
return p.for_stmt()
}
.name {
if p.tok.lit == 'sql' && p.peek_tok.kind == .name {
return p.sql_stmt()
}
if p.peek_tok.kind == .colon {
// `label:`
spos := p.tok.pos()
name := p.check_name()
if name in p.label_names {
return p.error_with_pos('duplicate label `${name}`', spos)
}
p.label_names << name
p.next()
if p.tok.kind == .key_for {
for_pos := p.tok.pos()
mut stmt := p.stmt(is_top_level)
match mut stmt {
ast.ForStmt {
stmt.label = name
return stmt
}
ast.ForInStmt {
stmt.label = name