-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathparser.v
More file actions
3356 lines (3242 loc) · 88.9 KB
/
parser.v
File metadata and controls
3356 lines (3242 loc) · 88.9 KB
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-2024 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 parser
import v.scanner
import v.ast
import v.token
import v.pref
import v.util
import v.errors
import os
import hash.fnv1a
import strings
@[minify]
pub struct Parser {
pub:
pref &pref.Preferences = unsafe { nil }
mut:
file_base string // "hello.v"
file_path string // "/home/user/hello.v"
file_idx i16 // file idx in the global table `filelist`
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_path, 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.
// see comment in parse_file
tok token.Token
prev_tok token.Token
peek_tok token.Token
language ast.Language
fn_language ast.Language // .c for `fn C.abcd()` declarations
struct_language ast.Language // for `struct C.abcd{ embedded struct/union }` 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_for_expr bool
inside_fn bool // true even with implicit main
inside_fn_return bool
inside_fn_concrete_type bool // parsing fn_name[concrete_type]() call expr
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_assign_rhs bool // rhs assignment
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_ct_match bool
inside_ct_match_case bool
inside_ct_match_body bool
inside_unsafe bool
inside_sum_type bool // to prevent parsing inline sum type again
inside_asm_template bool
inside_asm bool
inside_defer bool
defer_mode ast.DeferMode
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
array_dim int // array dim parsing level
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()
last_enum_name string // saves the last enum name on an array initialization
last_enum_mod string // saves the last enum mod name on an array initialization
imports map[string]string // alias => mod_name
ast_imports []ast.Import // mod_names
used_imports []string
auto_imports []string // imports, the user does not need to specify
implied_imports []string // imports that the user's code uses but omitted to import explicitly, used by `vfmt`
imported_symbols map[string]string
imported_symbols_used map[string]bool
imported_symbols_trie token.KeywordsMatcherTrie
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
expecting_value bool = true // true where a node value will be used
cur_fn_name string
cur_fn_scope &ast.Scope = unsafe { nil }
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
init_generic_types []ast.Type
if_cond_comments []ast.Comment
left_comments []ast.Comment
script_mode bool
script_mode_start_token token.Token
generic_type_level int // to avoid infinite recursion segfaults due to compiler bugs in ensure_type_exists
main_already_defined bool // TODO move to checker
is_vls bool
is_vls_skip_file bool // in `vls` mode, skip parse and check for unrelated files, such as `vlib`
inside_import_section bool
cur_comments []ast.Comment // comments between other stmts
pub mut:
scanner &scanner.Scanner = unsafe { nil }
table &ast.Table = unsafe { nil }
scope &ast.Scope = unsafe { nil }
opened_scopes int
max_opened_scopes int = 100 // values above 300 risk stack overflow
errors []errors.Error
warnings []errors.Warning
notices []errors.Notice
template_paths []string // record all compiled $tmpl files; needed for `v watch run webserver.v`
content ParseContentKind
}
enum ParseContentKind {
file
text
stmt
comptime
}
// for tests
pub fn parse_stmt(text string, mut table ast.Table, mut scope ast.Scope) ast.Stmt {
$if trace_parse_stmt ? {
eprintln('> ${@MOD}.${@FN} text: ${text}')
}
mut p := Parser{
content: .stmt
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, mut table ast.Table, pref_ &pref.Preferences, mut scope ast.Scope) &ast.File {
$if trace_parse_comptime ? {
eprintln('> ${@MOD}.${@FN} text: ${text}')
}
mut p := Parser{
content: .comptime
file_path: tmpl_path
scanner: scanner.new_scanner(text, .skip_comments, pref_)
table: table
pref: pref_
scope: scope
errors: []errors.Error{}
warnings: []errors.Warning{}
}
mut res := p.parse()
unsafe { p.free_scanner() }
res.is_template_text = true
return res
}
pub fn parse_text(text string, path string, mut 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{
content: .text
scanner: scanner.new_scanner(text, comments_mode, pref_)
table: table
pref: pref_
is_vls: pref_.is_vls
is_vls_skip_file: pref_.is_vls && path != pref_.path
scope: &ast.Scope{
start_pos: 0
parent: table.global_scope
}
errors: []errors.Error{}
warnings: []errors.Warning{}
}
p.set_path(path)
mut res := p.parse()
unsafe { p.free_scanner() }
res.is_parse_text = true
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_path = path
p.file_base = os.base(path)
p.file_display_path = os.real_path(p.file_path).replace_once(normalised_working_folder,
'').replace('\\', '/')
p.inside_vlib_file = os.dir(path).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, mut 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 file_idx := i16(table.filelist.index(path))
if file_idx == -1 {
file_idx = i16(table.filelist.len)
table.filelist << path
}
mut p := Parser{
content: .file
scanner: scanner.new_scanner_file(path, file_idx, comments_mode, pref_) or { panic(err) }
table: table
pref: pref_
// Only set vls mode if it's the file the user requested via `v -vls-mode file.v`
// Otherwise we'd be parsing entire stdlib in vls mode
is_vls: pref_.is_vls && path == pref_.path
is_vls_skip_file: pref_.is_vls && path != pref_.path
scope: &ast.Scope{
start_pos: 0
parent: table.global_scope
}
errors: []errors.Error{}
warnings: []errors.Warning{}
file_idx: file_idx
}
p.set_path(path)
res := p.parse()
unsafe { p.free_scanner() }
return res
}
pub fn (mut p Parser) parse() &ast.File {
$if trace_parse ? {
eprintln('> ${@FILE}:${@LINE} | p.path: ${p.file_path} | content: ${p.content} | nr_tokens: ${p.scanner.all_tokens.len} | nr_lines: ${p.scanner.line_nr} | nr_bytes: ${p.scanner.text.len}')
}
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
}
p.inside_import_section = true
// 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 {
if !p.is_vls_skip_file {
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
}
if p.pref.is_check_overflow {
p.register_auto_import('builtin.overflow')
}
p.handle_codegen_for_file()
ast_file := &ast.File{
path: p.file_path
path_base: p.file_base
is_test: p.inside_test_file
is_generated: p.is_generated
is_translated: p.is_translated
language: p.file_backend_mode
nr_lines: p.scanner.line_nr
nr_bytes: p.scanner.text.len
nr_tokens: p.scanner.all_tokens.len
mod: module_decl
imports: p.ast_imports
imported_symbols: p.imported_symbols
imported_symbols_trie: token.new_keywords_matcher_from_array_trie(p.imported_symbols.keys())
imported_symbols_used: p.imported_symbols_used
auto_imports: p.auto_imports
used_imports: p.used_imports
implied_imports: p.implied_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
}
$if trace_parse_file_path_and_mod ? {
eprintln('>> ast.File, tokens: ${ast_file.nr_tokens:5}, mname: ${ast_file.mod.name:20}, sname: ${ast_file.mod.short_name:11}, path: ${p.file_display_path}')
}
return ast_file
}
pub fn parse_files(paths []string, mut 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
}
unsafe {
mut files := []&ast.File{cap: paths.len}
for path in paths {
timers.start('parse_file ${path}')
files << parse_file(path, mut table, .skip_comments, pref_)
timers.show('parse_file ${path}')
}
handle_codegen_for_multiple_files(mut files)
return files
}
}
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 tok.kind != .eof {
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
}
fn (mut p Parser) open_scope() {
if p.opened_scopes > p.max_opened_scopes {
p.should_abort = true
p.error('nested opened scopes limit reached: ${p.max_opened_scopes}')
return
}
p.scope = &ast.Scope{
parent: p.scope
start_pos: p.tok.pos
}
p.opened_scopes++
}
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
p.opened_scopes--
}
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) is_in_top_level_comptime(inside_assign_rhs bool) bool {
// TODO: find out a better way detect we are in top level.
return p.cur_fn_name.len == 0
&& (p.inside_ct_if_expr || p.inside_ct_match || p.inside_ct_match_body)
&& !inside_assign_rhs && !p.script_mode && p.tok.kind != .name
}
fn (mut p Parser) parse_block_no_scope(is_top_level bool) []ast.Stmt {
p.check(.lcbr)
mut stmts := []ast.Stmt{cap: 20}
old_assign_rhs := p.inside_assign_rhs
p.inside_assign_rhs = false
if p.tok.kind != .rcbr {
mut count := 0
for p.tok.kind !in [.eof, .rcbr] {
if p.is_in_top_level_comptime(old_assign_rhs) {
// top level `$if cond { println() }` should goto `p.stmt()`
stmts << p.top_stmt()
} else {
stmts << p.stmt(is_top_level)
}
count++
if count % 100000 == 0 {
if p.is_vls {
// Stuck in VLS mode, exit
return []
}
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 []
}
}
}
p.inside_assign_rhs = old_assign_rhs
if is_top_level {
p.top_level_statement_end()
}
p.check(.rcbr)
// on assignment the last callexpr must be marked as return used recursively
if p.inside_assign_rhs && stmts.len > 0 {
mut last_stmt := stmts.last()
p.mark_last_call_return_as_used(mut last_stmt)
}
return stmts
}
fn (mut p Parser) mark_last_call_return_as_used(mut last_stmt ast.Stmt) {
match mut last_stmt {
ast.ExprStmt {
match mut last_stmt.expr {
ast.CallExpr {
// last stmt on block is CallExpr
last_stmt.expr.is_return_used = true
if last_stmt.expr.or_block.stmts.len > 0 {
mut or_block_last_stmt := last_stmt.expr.or_block.stmts.last()
p.mark_last_call_return_as_used(mut or_block_last_stmt)
}
}
ast.ConcatExpr {
// last stmt on block is: a, b, c := ret1(), ret2(), ret3()
for mut expr in last_stmt.expr.vals {
if mut expr is ast.CallExpr {
expr.is_return_used = true
}
}
}
ast.IfExpr {
// last stmt on block is: if .. { foo() } else { bar() }
for mut branch in last_stmt.expr.branches {
if branch.stmts.len > 0 {
mut last_if_stmt := branch.stmts.last()
p.mark_last_call_return_as_used(mut last_if_stmt)
}
}
}
ast.InfixExpr {
if last_stmt.expr.or_block.stmts.len > 0 {
mut or_block_last_stmt := last_stmt.expr.or_block.stmts.last()
p.mark_last_call_return_as_used(mut or_block_last_stmt)
}
// last stmt has infix expr with CallExpr: foo()? + 'a'
mut left_expr := last_stmt.expr.left
for {
if mut left_expr is ast.InfixExpr {
if left_expr.or_block.stmts.len > 0 {
mut or_block_last_stmt := left_expr.or_block.stmts.last()
p.mark_last_call_return_as_used(mut or_block_last_stmt)
}
left_expr = left_expr.left
continue
}
if mut left_expr is ast.CallExpr {
left_expr.is_return_used = true
if left_expr.or_block.stmts.len > 0 {
mut or_block_last_stmt := left_expr.or_block.stmts.last()
p.mark_last_call_return_as_used(mut or_block_last_stmt)
}
}
break
}
}
ast.ComptimeCall, ast.ComptimeSelector, ast.PrefixExpr, ast.SelectorExpr {
if last_stmt.expr.or_block.stmts.len > 0 {
mut or_block_last_stmt := last_stmt.expr.or_block.stmts.last()
p.mark_last_call_return_as_used(mut or_block_last_stmt)
}
}
else {}
}
}
else {}
}
}
@[inline]
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)
}
}
// 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
}
@[direct_array_access]
fn is_ident_name(name string) bool {
if name.len == 0 {
return false
}
if !util.name_char_table[name[0]] {
return false
}
for i in 1 .. name.len {
if !util.func_char_table[name[i]] {
return false
}
}
return true
}
fn (mut p Parser) check_name() string {
pos := p.tok.pos()
name := p.tok.lit
if p.tok.kind != .name && p.peek_tok.kind == .dot && name in p.imports {
p.register_used_import(name)
} else if p.tok.kind == .name && p.is_imported_symbol(name) && !p.imported_symbols_used[name] {
// symbols like Enum.field_name
p.register_used_import_for_symbol_name(p.imported_symbols[name])
}
if !is_ident_name(name) {
p.check(.name)
} else {
p.next()
}
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_path:-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 {
mut keep_cur_comments := false
defer {
// clear `cur_comments` after each statement, except a comment stmt
if !keep_cur_comments && p.pref.is_vls {
p.cur_comments.clear()
}
}
if p.tok.kind !in [.key_import, .comment, .dollar] {
// import section should only prepend by `import`, `comment` or `$if`.
p.inside_import_section = false
}
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_interface {
return p.interface_decl()
}
.key_import {
if !p.inside_import_section {
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 {
match p.peek_tok.kind {
.eof {
return p.unexpected(got: 'eof')
}
.key_for {
comptime_for_stmt := p.comptime_for()
return p.other_stmts(comptime_for_stmt)
}
.key_if {
if_expr := p.if_expr(true, false)
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)
}
}
.key_match {
mut pos := p.tok.pos()
expr := p.match_expr(true)
pos.update_last_line(p.prev_tok.line_nr)
return ast.ExprStmt{
expr: expr
pos: pos
}
}
.name {
// handles $dbg directly without registering token
if p.peek_tok.lit == 'dbg' {
return p.dbg_stmt()
} else {
mut pos := p.tok.pos()
expr := p.expr(0)
pos.update_last_line(p.prev_tok.line_nr)
return ast.ExprStmt{
expr: expr
pos: pos
}
}
}
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 {
keep_cur_comments = true
return p.comment_stmt()
}
.semicolon {
return p.semicolon_stmt()
}
.key_asm {
return p.asm_stmt(true)
}
else {
return p.other_stmts(ast.empty_stmt)
}
}
// clear `cur_comments` after each statement, except a comment stmt
if !keep_cur_comments && p.pref.is_vls {
p.cur_comments.clear()
}
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.main_already_defined {
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_path
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()
return ast.Comment{
text: text
is_multi: is_multi
pos: pos
}
}
fn (mut p Parser) comment_stmt() ast.ExprStmt {
comment := p.comment()
if p.pref.is_vls {
p.cur_comments << comment
}
return ast.ExprStmt{
expr: comment
pos: comment.pos
}
}
@[params]
struct EatCommentsConfig {
pub:
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 + p.prev_tok.lit.count('\n')
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) {
break
}
comments << p.comment()
if cfg.follow_up {
line = p.prev_tok.line_nr + p.prev_tok.lit.count('\n')
}
}
return comments
}
fn (mut p Parser) goto_eof() {
for p.tok.kind != .eof {
p.next()
}
}
fn (mut p Parser) stmt(is_top_level bool) ast.Stmt {
// ensure that possible parser aborts, are handled as early as possible (on the *next* processed statement):
if p.should_abort {
abort_pos := p.tok.pos()
p.goto_eof()
return ast.NodeError{
idx: 0
pos: abort_pos
}
}
mut keep_cur_comments := false
defer {
if !keep_cur_comments && p.pref.is_vls {
p.cur_comments.clear()
}
}
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()
if p.peek_token(2).kind == .colon {
expr := p.expr(0)