-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
scanner.v
1827 lines (1752 loc) · 51.4 KB
/
scanner.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 scanner
import os
import strconv
import v.token
import v.pref
import v.util
import v.vet
import v.errors
import v.ast
import v.mathutil
const single_quote = `'`
const double_quote = `"`
// char used as number separator
const num_sep = `_`
const b_lf = 10
const b_cr = 13
const backslash = `\\`
@[minify]
pub struct Scanner {
pub mut:
file_path string // '/path/to/file.v'
file_base string // 'file.v'
text string // the whole text of the file
pos int // current position in the file, first character is s.text[0]
line_nr int // current line number
last_nl_pos int = -1 // for calculating column
is_crlf bool // special check when computing columns
is_inside_string bool // set to true in a string, *at the start* of an $var or ${expr}
is_nested_string bool // '${'abc':-12s}'
is_inter_start bool // for hacky string interpolation TODO simplify
is_inter_end bool
is_enclosed_inter bool
is_nested_enclosed_inter bool
line_comment string
last_lt int = -1 // position of latest <
is_started bool
is_print_line_on_error bool
is_print_colored_error bool
is_print_rel_paths_on_error bool
quote u8 // which quote is used to denote current string: ' or "
inter_quote u8
just_closed_inter bool // if is_enclosed_inter was set to false on the previous character: `}`
nr_lines int // total number of lines in the source file that were scanned
is_vh bool // Keep newlines
is_fmt bool // Used for v fmt.
comments_mode CommentsMode
is_inside_toplvl_statement bool // *only* used in comments_mode: .toplevel_comments, toggled by parser
all_tokens []token.Token // *only* used in comments_mode: .toplevel_comments, contains all tokens
tidx int
eofs int
inter_cbr_count int
pref &pref.Preferences
error_details []string
errors []errors.Error
warnings []errors.Warning
notices []errors.Notice
vet_errors []vet.Error
should_abort bool // when too many errors/warnings/notices are accumulated, should_abort becomes true, and the scanner should stop
}
/*
How the .toplevel_comments mode works:
In this mode, the scanner scans *everything* at once, before parsing starts,
including all the comments, and stores the results in an buffer s.all_tokens.
Then .scan() just returns s.all_tokens[ s.tidx++ ] *ignoring* the
comment tokens. In other words, by default in this mode, the parser
*will not see any comments* inside top level statements, so it has
no reason to complain about them.
When the parser determines, that it is outside of a top level statement,
it tells the scanner to backtrack s.tidx to the current p.tok index,
then it changes .is_inside_toplvl_statement to false , and refills its
lookahead buffer (i.e. p.peek_tok), from the scanner.
In effect, from the parser's point of view, the next tokens, that it will
receive with p.next(), will be the same, as if comments are not ignored
anymore, *between* top level statements.
When the parser determines, that it is going again inside a top level
statement, it does the same, this time setting .is_inside_toplvl_statement
to true, again refilling the lookahead buffer => calling .next() in this
mode, will again ignore all the comment tokens, till the top level statement
is finished.
*/
// The different kinds of scanner modes:
//
// .skip_comments - simplest/fastest, just ignores all comments early.
// This mode is used by the compiler itself.
//
// .parse_comments is used by vfmt. Ideally it should handle inline /* */
// comments too, i.e. it returns every kind of comment as a new token.
//
// .toplevel_comments is used by vdoc, parses *only* top level ones
// that are *outside* structs/enums/fns.
pub enum CommentsMode {
skip_comments
parse_comments
toplevel_comments
}
// new scanner from file.
pub fn new_scanner_file(file_path string, comments_mode CommentsMode, pref_ &pref.Preferences) !&Scanner {
if !os.is_file(file_path) {
return error('${file_path} is not a .v file')
}
mut raw_text := util.read_file(file_path) or { return err }
if pref_.line_info != '' {
// Add line info expr to the scanner text
abs_path := os.join_path(os.getwd(), file_path)
if pref_.linfo.path in [file_path, abs_path] {
raw_text = pref.add_line_info_expr_to_program_text(raw_text, pref_.linfo)
}
}
mut s := &Scanner{
pref: pref_
text: raw_text
all_tokens: []token.Token{cap: raw_text.len / 3}
is_print_line_on_error: true
is_print_colored_error: true
is_print_rel_paths_on_error: true
is_fmt: pref_.is_fmt
comments_mode: comments_mode
file_path: file_path
file_base: os.base(file_path)
}
s.scan_all_tokens_in_buffer()
return s
}
const internally_generated_v_code = 'internally_generated_v_code'
// new scanner from string.
pub fn new_scanner(text string, comments_mode CommentsMode, pref_ &pref.Preferences) &Scanner {
mut s := &Scanner{
pref: pref_
text: text
all_tokens: []token.Token{cap: text.len / 3}
is_print_line_on_error: true
is_print_colored_error: true
is_print_rel_paths_on_error: true
is_fmt: pref_.is_fmt
comments_mode: comments_mode
file_path: scanner.internally_generated_v_code
file_base: scanner.internally_generated_v_code
}
s.scan_all_tokens_in_buffer()
return s
}
@[unsafe]
pub fn (mut s Scanner) free() {
unsafe {
// Note: s.text is not freed here, because it is shared with all other util.read_file instances,
// and strings are not reference counted yet:
// s.text.free()
// .all_tokens however are not shared with anything, and can be freed:
s.all_tokens.free()
}
}
@[inline]
fn (s &Scanner) should_parse_comment() bool {
return s.comments_mode == .parse_comments
|| (s.comments_mode == .toplevel_comments && !s.is_inside_toplvl_statement)
}
// Note: this is called by v's parser
pub fn (mut s Scanner) set_is_inside_toplevel_statement(newstate bool) {
s.is_inside_toplvl_statement = newstate
}
pub fn (mut s Scanner) set_current_tidx(cidx int) {
mut tidx := if cidx < 0 { 0 } else { cidx }
tidx = if tidx > s.all_tokens.len { s.all_tokens.len } else { tidx }
s.tidx = tidx
}
@[inline]
fn (mut s Scanner) new_token(tok_kind token.Kind, lit string, len int) token.Token {
cidx := s.tidx
s.tidx++
line_offset := if tok_kind == .hash { 0 } else { 1 }
mut max_column := s.current_column() - len + 1
if max_column < 1 {
max_column = 1
}
return token.Token{
kind: tok_kind
lit: lit
line_nr: s.line_nr + line_offset
col: max_column
pos: s.pos - len + 1
len: len
tidx: cidx
}
}
@[inline]
fn (s &Scanner) new_eof_token() token.Token {
return token.Token{
kind: .eof
lit: ''
line_nr: s.line_nr + 1
col: s.current_column()
pos: s.pos
len: 1
tidx: s.tidx
}
}
@[inline]
fn (mut s Scanner) new_multiline_token(tok_kind token.Kind, lit string, len int, start_line int) token.Token {
cidx := s.tidx
s.tidx++
mut max_column := s.current_column() - len + 1
if max_column < 1 {
max_column = 1
}
return token.Token{
kind: tok_kind
lit: lit
line_nr: start_line + 1
col: max_column
pos: s.pos - len + 1
len: len
tidx: cidx
}
}
@[direct_array_access; inline]
fn (mut s Scanner) ident_name() string {
start := s.pos
s.pos++
for s.pos < s.text.len {
c := s.text[s.pos]
if (c >= `a` && c <= `z`) || (c >= `A` && c <= `Z`) || (c >= `0` && c <= `9`) || c == `_` {
s.pos++
continue
}
break
}
name := s.text[start..s.pos]
s.pos--
return name
}
fn (s Scanner) num_lit(start int, end int) string {
if s.is_fmt {
return s.text[start..end]
}
unsafe {
txt := s.text.str
mut b := malloc_noscan(end - start + 1) // add a byte for the endstring 0
mut i_no_sep := 0
for i in start .. end {
if txt[i] != scanner.num_sep {
b[i_no_sep] = txt[i]
i_no_sep++
}
}
b[i_no_sep] = 0 // C string compatibility
return b.vstring_with_len(i_no_sep)
}
}
fn (mut s Scanner) ident_bin_number() string {
mut has_wrong_digit := false
mut first_wrong_digit_pos := 0
mut first_wrong_digit := `\0`
start_pos := s.pos
s.pos += 2 // skip '0b'
if s.pos < s.text.len && s.text[s.pos] == scanner.num_sep {
s.error('separator `_` is only valid between digits in a numeric literal')
}
for s.pos < s.text.len {
c := s.text[s.pos]
if c == scanner.num_sep && s.text[s.pos - 1] == scanner.num_sep {
s.error('cannot use `_` consecutively')
}
if !c.is_bin_digit() && c != scanner.num_sep {
if (!c.is_digit() && !c.is_letter()) || s.is_inside_string || s.is_nested_string {
break
} else if !has_wrong_digit {
has_wrong_digit = true
first_wrong_digit_pos = s.pos
first_wrong_digit = c
}
}
s.pos++
}
if s.text[s.pos - 1] == scanner.num_sep {
s.pos--
s.error('cannot use `_` at the end of a numeric literal')
} else if start_pos + 2 == s.pos {
s.pos-- // adjust error position
s.error('number part of this binary is not provided')
} else if has_wrong_digit {
s.pos = first_wrong_digit_pos // adjust error position
s.error('this binary number has unsuitable digit `${first_wrong_digit.str()}`')
}
number := s.num_lit(start_pos, s.pos)
s.pos--
return number
}
@[direct_array_access]
fn (mut s Scanner) ident_hex_number() string {
mut has_wrong_digit := false
mut first_wrong_digit_pos := 0
mut first_wrong_digit := `\0`
start_pos := s.pos
if s.pos + 2 >= s.text.len {
return '0x'
}
s.pos += 2 // skip '0x'
if s.pos < s.text.len && s.text[s.pos] == scanner.num_sep {
s.error('separator `_` is only valid between digits in a numeric literal')
}
for s.pos < s.text.len {
c := s.text[s.pos]
if c == scanner.num_sep && s.text[s.pos - 1] == scanner.num_sep {
s.error('cannot use `_` consecutively')
}
if !c.is_hex_digit() && c != scanner.num_sep {
if !c.is_letter() || s.is_inside_string || s.is_nested_string {
break
} else if !has_wrong_digit {
has_wrong_digit = true
first_wrong_digit_pos = s.pos
first_wrong_digit = c
}
}
s.pos++
}
if s.text[s.pos - 1] == scanner.num_sep {
s.pos--
s.error('cannot use `_` at the end of a numeric literal')
} else if start_pos + 2 == s.pos {
s.pos-- // adjust error position
s.error('number part of this hexadecimal is not provided')
} else if has_wrong_digit {
s.pos = first_wrong_digit_pos // adjust error position
s.error('this hexadecimal number has unsuitable digit `${first_wrong_digit.str()}`')
}
number := s.num_lit(start_pos, s.pos)
s.pos--
return number
}
fn (mut s Scanner) ident_oct_number() string {
mut has_wrong_digit := false
mut first_wrong_digit_pos := 0
mut first_wrong_digit := `\0`
start_pos := s.pos
s.pos += 2 // skip '0o'
if s.pos < s.text.len && s.text[s.pos] == scanner.num_sep {
s.error('separator `_` is only valid between digits in a numeric literal')
}
for s.pos < s.text.len {
c := s.text[s.pos]
if c == scanner.num_sep && s.text[s.pos - 1] == scanner.num_sep {
s.error('cannot use `_` consecutively')
}
if !c.is_oct_digit() && c != scanner.num_sep {
if (!c.is_digit() && !c.is_letter()) || s.is_inside_string || s.is_nested_string {
break
} else if !has_wrong_digit {
has_wrong_digit = true
first_wrong_digit_pos = s.pos
first_wrong_digit = c
}
}
s.pos++
}
if s.text[s.pos - 1] == scanner.num_sep {
s.pos--
s.error('cannot use `_` at the end of a numeric literal')
} else if start_pos + 2 == s.pos {
s.pos-- // adjust error position
s.error('number part of this octal is not provided')
} else if has_wrong_digit {
s.pos = first_wrong_digit_pos // adjust error position
s.error('this octal number has unsuitable digit `${first_wrong_digit.str()}`')
}
number := s.num_lit(start_pos, s.pos)
s.pos--
return number
}
@[direct_array_access]
fn (mut s Scanner) ident_dec_number() string {
mut has_wrong_digit := false
mut first_wrong_digit_pos := 0
mut first_wrong_digit := `\0`
start_pos := s.pos
// scan integer part
for s.pos < s.text.len {
c := s.text[s.pos]
if c == scanner.num_sep && s.text[s.pos - 1] == scanner.num_sep {
s.error('cannot use `_` consecutively')
}
if !c.is_digit() && c != scanner.num_sep {
if !c.is_letter() || c in [`e`, `E`] || s.is_inside_string || s.is_nested_string {
break
} else if !has_wrong_digit {
has_wrong_digit = true
first_wrong_digit_pos = s.pos
first_wrong_digit = c
}
}
s.pos++
}
if s.text[s.pos - 1] == scanner.num_sep {
s.pos--
s.error('cannot use `_` at the end of a numeric literal')
}
mut call_method := false // true for, e.g., 5.str(), 5.5.str(), 5e5.str()
mut is_range := false // true for, e.g., 5..10
// scan fractional part
if s.pos < s.text.len && s.text[s.pos] == `.` {
s.pos++
if s.pos < s.text.len {
// 5.5, 5.5.str()
if s.text[s.pos].is_digit() {
for s.pos < s.text.len {
c := s.text[s.pos]
if !c.is_digit() {
if !c.is_letter() || c in [`e`, `E`] || s.is_inside_string
|| s.is_nested_string {
// 5.5.str()
if c == `.` && s.pos + 1 < s.text.len && s.text[s.pos + 1].is_letter() {
call_method = true
}
break
} else if !has_wrong_digit {
has_wrong_digit = true
first_wrong_digit_pos = s.pos
first_wrong_digit = c
}
}
s.pos++
}
} else if s.text[s.pos] == `.` {
// 5.. (a range)
is_range = true
s.pos--
} else if s.text[s.pos] in [`e`, `E`] {
// 5.e5
} else if s.text[s.pos].is_letter() {
// 5.str()
call_method = true
s.pos--
} else {
// 5.
mut symbol_length := 0
for i := s.pos - 2; i > 0 && s.text[i - 1].is_digit(); i-- {
symbol_length++
}
float_symbol := s.text[s.pos - 2 - symbol_length..s.pos - 1]
s.warn('float literals should have a digit after the decimal point, e.g. `${float_symbol}.0`')
}
}
}
// scan exponential part
mut has_exp := false
if s.pos < s.text.len && s.text[s.pos] in [`e`, `E`] {
has_exp = true
s.pos++
if s.pos < s.text.len && s.text[s.pos] in [`-`, `+`] {
s.pos++
}
for s.pos < s.text.len {
c := s.text[s.pos]
if !c.is_digit() {
if !c.is_letter() || s.is_inside_string || s.is_nested_string {
// 5e5.str()
if c == `.` && s.pos + 1 < s.text.len && s.text[s.pos + 1].is_letter() {
call_method = true
}
break
} else if !has_wrong_digit {
has_wrong_digit = true
first_wrong_digit_pos = s.pos
first_wrong_digit = c
}
}
s.pos++
}
}
if has_wrong_digit {
// error check: wrong digit
s.pos = first_wrong_digit_pos // adjust error position
if !s.pref.translated {
s.error('this number has unsuitable digit `${first_wrong_digit.str()}`')
}
} else if s.text[s.pos - 1] in [`e`, `E`] {
// error check: 5e
s.pos-- // adjust error position
s.error('exponent has no digits')
} else if s.pos < s.text.len && s.text[s.pos] == `.` && !is_range && !call_method {
// error check: 1.23.4, 123.e+3.4
if has_exp {
s.error('exponential part should be integer')
} else {
s.error('too many decimal points in number')
}
}
number := s.num_lit(start_pos, s.pos)
s.pos--
return number
}
fn (mut s Scanner) ident_number() string {
if s.expect('0b', s.pos) {
return s.ident_bin_number()
} else if s.expect('0x', s.pos) {
return s.ident_hex_number()
} else if s.expect('0o', s.pos) {
return s.ident_oct_number()
} else {
return s.ident_dec_number()
}
}
@[direct_array_access; inline]
fn (mut s Scanner) skip_whitespace() {
for s.pos < s.text.len {
c := s.text[s.pos]
if c == 9 {
// tabs are most common
s.pos++
continue
}
if !(c == 32 || (c > 8 && c < 14) || c == 0x85 || c == 0xa0) {
return
}
c_is_nl := c == scanner.b_cr || c == scanner.b_lf
if c_is_nl && s.is_vh {
return
}
if s.pos + 1 < s.text.len && c == scanner.b_cr && s.text[s.pos + 1] == scanner.b_lf {
s.is_crlf = true
}
// Count \r\n as one line
if c_is_nl && !(s.pos > 0 && s.text[s.pos - 1] == scanner.b_cr && c == scanner.b_lf) {
s.inc_line_number()
}
s.pos++
}
}
fn (mut s Scanner) end_of_file() token.Token {
s.eofs++
if s.eofs > 50 {
s.line_nr--
if s.file_path == scanner.internally_generated_v_code {
// show a bit more context for that case, since the source may not be easily visible by just inspecting a source file on the filesystem
dump(s.text#[0..50])
dump(s.text#[-50..])
dump(s.text.len)
}
panic(
'the end of file `${s.file_path}` has been reached 50 times already, the v parser is probably stuck.\n' +
'This should not happen. Please report the bug here, and include the last 2-3 lines of your source code:\n' +
'https://github.com/vlang/v/issues/new?labels=Bug&template=bug_report.md')
}
if s.pos != s.text.len && s.eofs == 1 {
s.inc_line_number()
}
s.pos = s.text.len
return s.new_eof_token()
}
fn (mut s Scanner) scan_all_tokens_in_buffer() {
mut timers := util.get_timers()
timers.measure_pause('PARSE')
util.timing_start('SCAN')
defer {
util.timing_measure_cumulative('SCAN')
timers.measure_resume('PARSE')
}
s.scan_remaining_text()
s.tidx = 0
$if trace_scanner ? {
for t in s.all_tokens {
eprintln('> tidx:${t.tidx:-5} | kind: ${t.kind:-10} | lit.len: ${t.lit.len:-5} | lit: `${t.lit}`')
}
}
}
fn (mut s Scanner) scan_remaining_text() {
for {
t := s.text_scan()
if s.comments_mode == .skip_comments && t.kind == .comment {
continue
}
s.all_tokens << t
if t.kind == .eof || s.should_abort {
break
}
}
}
@[direct_array_access]
pub fn (mut s Scanner) scan() token.Token {
for {
cidx := s.tidx
s.tidx++
if cidx >= s.all_tokens.len || s.should_abort {
return s.end_of_file()
}
if s.all_tokens[cidx].kind == .comment {
if !s.should_parse_comment() {
continue
}
}
return s.all_tokens[cidx]
}
return s.new_eof_token()
}
@[direct_array_access; inline]
pub fn (s &Scanner) peek_token(n int) token.Token {
idx := s.tidx + n
if idx >= s.all_tokens.len || idx < 0 {
return s.new_eof_token()
}
t := s.all_tokens[idx]
return t
}
@[direct_array_access; inline]
fn (s &Scanner) look_ahead(n int) u8 {
if s.pos + n < s.text.len {
return s.text[s.pos + n]
} else {
return `\0`
}
}
// text_scan returns a single token from the text, and updates the scanner state,
// so that it will be ready to get the next token right after that.
// See also Scanner.prepare_for_new_text and new_silent_scanner()
@[direct_array_access]
pub fn (mut s Scanner) text_scan() token.Token {
// The for loop here is so that instead of doing
// `return s.scan()` (which will use a new call stack frame),
// text_scan can just do continue, keeping
// memory & stack usage low.
// That optimization mostly matters for long sections
// of comments and string literals.
for {
if s.is_started {
s.pos++
} else {
s.is_started = true
}
if !s.is_inside_string {
s.skip_whitespace()
}
if s.pos >= s.text.len || s.should_abort {
return s.end_of_file()
}
// End of $var, start next string
if s.is_inter_end {
if s.text[s.pos] == s.quote || (s.text[s.pos] == s.inter_quote && s.is_enclosed_inter) {
s.is_inter_end = false
return s.new_token(.string, '', 1)
}
s.is_inter_end = false
ident_string := s.ident_string()
return s.new_token(.string, ident_string, ident_string.len + 2) // + two quotes
}
s.skip_whitespace()
// end of file
if s.pos >= s.text.len {
return s.end_of_file()
}
// handle each char
c := s.text[s.pos]
nextc := s.look_ahead(1)
// name or keyword
if util.is_name_char(c) {
name := s.ident_name()
// tmp hack to detect . in ${}
// Check if not .eof to prevent panic
next_char := s.look_ahead(1)
kind := token.scanner_matcher.find(name)
// '$type' '$struct'... will be recognized as ident (not keyword token)
if kind != -1 && !(s.is_inter_start && next_char == s.quote) {
return s.new_token(unsafe { token.Kind(kind) }, name, name.len)
}
// 'asdf $b' => "b" is the last name in the string, dont start parsing string
// at the next ', skip it
if s.is_inside_string {
if next_char == s.quote {
s.is_inter_end = true
s.is_inter_start = false
s.is_inside_string = false
}
}
// end of `$expr`
// allow `'$a.b'` and `'$a.c()'`
if s.is_inter_start && next_char == `\\`
&& s.look_ahead(2) !in [`x`, `n`, `r`, `\\`, `t`, `e`, `"`, `'`] {
s.warn('unknown escape sequence \\${s.look_ahead(2)}')
}
if s.is_inter_start && next_char == `(` {
if s.look_ahead(2) != `)` {
s.warn('use `\${f(expr)}` instead of `\$f(expr)`')
}
} else if s.is_inter_start && next_char != `.` {
s.is_inter_end = true
s.is_inter_start = false
}
return s.new_token(.name, name, name.len)
} else if c.is_digit() || (c == `.` && nextc.is_digit()) {
// `123`, `.123`
if !s.is_inside_string {
// In C ints with `0` prefix are octal (in V they're decimal), so discarding heading zeros is needed.
mut start_pos := s.pos
for start_pos < s.text.len && s.text[start_pos] == `0` {
start_pos++
}
mut prefix_zero_num := start_pos - s.pos // how many prefix zeros should be jumped
// for 0b, 0o, 0x the heading zero shouldn't be jumped
if start_pos == s.text.len || (c == `0` && !s.text[start_pos].is_digit()) {
prefix_zero_num--
}
s.pos += prefix_zero_num // jump these zeros
}
num := s.ident_number()
return s.new_token(.number, num, num.len)
}
// Handle `'$fn()'`
if c == `)` && s.is_inter_start {
next_char := s.look_ahead(1)
if next_char != `.` {
s.is_inter_end = true
s.is_inter_start = false
if next_char == s.quote {
s.is_inside_string = false
}
return s.new_token(.rpar, '', 1)
}
}
// all other tokens
match c {
`+` {
if nextc == `+` {
s.pos++
return s.new_token(.inc, '', 2)
} else if nextc == `=` {
s.pos++
return s.new_token(.plus_assign, '', 2)
}
return s.new_token(.plus, '', 1)
}
`-` {
if nextc == `-` {
s.pos++
return s.new_token(.dec, '', 2)
} else if nextc == `=` {
s.pos++
return s.new_token(.minus_assign, '', 2)
}
return s.new_token(.minus, '', 1)
}
`*` {
if nextc == `=` {
s.pos++
return s.new_token(.mult_assign, '', 2)
}
return s.new_token(.mul, '', 1)
}
`^` {
if nextc == `=` {
s.pos++
return s.new_token(.xor_assign, '', 2)
}
return s.new_token(.xor, '', 1)
}
`%` {
if nextc == `=` {
s.pos++
return s.new_token(.mod_assign, '', 2)
}
return s.new_token(.mod, '', 1)
}
`?` {
return s.new_token(.question, '?', 1)
}
scanner.single_quote, scanner.double_quote {
start_line := s.line_nr
ident_string := s.ident_string()
return s.new_multiline_token(.string, ident_string, ident_string.len + 2,
start_line) // + two quotes
}
`\`` {
// ` // apostrophe balance comment. do not remove
ident_char := s.ident_char()
return s.new_token(.chartoken, ident_char, ident_char.len + 2) // + two quotes
}
`(` {
// TODO `$if vet {` for performance
if s.pref.is_vet && s.text[s.pos + 1] == ` ` {
s.vet_error('Looks like you are adding a space after `(`', .vfmt)
}
return s.new_token(.lpar, '', 1)
}
`)` {
// TODO `$if vet {` for performance
if s.pref.is_vet && s.text[s.pos - 1] == ` ` {
s.vet_error('Looks like you are adding a space before `)`', .vfmt)
}
return s.new_token(.rpar, '', 1)
}
`[` {
return s.new_token(.lsbr, '', 1)
}
`]` {
return s.new_token(.rsbr, '', 1)
}
`{` {
// Skip { in `${` in strings
if s.is_inside_string || s.is_enclosed_inter {
if s.text[s.pos - 1] == `$` {
continue
} else {
s.inter_cbr_count++
}
}
return s.new_token(.lcbr, '', 1)
}
`$` {
if s.is_inside_string || s.is_enclosed_inter {
return s.new_token(.str_dollar, '', 1)
} else {
return s.new_token(.dollar, '', 1)
}
}
`}` {
// s = `hello $name !`
// s = `hello ${name} !`
if (s.is_enclosed_inter || s.is_nested_enclosed_inter) && s.inter_cbr_count == 0 {
if s.pos < s.text.len - 1 {
s.pos++
} else {
s.error('unfinished string literal')
}
if s.text[s.pos] == s.quote
|| (s.text[s.pos] == s.inter_quote && s.is_nested_enclosed_inter) {
s.is_inside_string = false
if s.is_nested_enclosed_inter {
s.is_nested_enclosed_inter = false
} else {
s.is_enclosed_inter = false
}
return s.new_token(.string, '', 1)
}
if s.is_nested_enclosed_inter {
s.is_nested_enclosed_inter = false
} else {
s.is_enclosed_inter = false
}
s.just_closed_inter = true
ident_string := s.ident_string()
return s.new_token(.string, ident_string, ident_string.len + 2) // + two quotes
} else {
if s.inter_cbr_count > 0 {
s.inter_cbr_count--
}
return s.new_token(.rcbr, '', 1)
}
}
`&` {
if nextc == `=` {
s.pos++
return s.new_token(.and_assign, '', 2)
}
afternextc := s.look_ahead(2)
if nextc == `&` && (afternextc.is_space() || afternextc == `!`) {
s.pos++
return s.new_token(.and, '', 2)
}
return s.new_token(.amp, '', 1)
}
`|` {
if nextc == `|` {
s.pos++
return s.new_token(.logical_or, '', 2)
}
if nextc == `=` {
s.pos++
return s.new_token(.or_assign, '', 2)
}
return s.new_token(.pipe, '', 1)
}
`,` {
return s.new_token(.comma, '', 1)
}
`@` {
// @[attr]
if s.text[s.pos + 1] == `[` {
return s.new_token(.at, '', 1)
}
mut name := ''
if nextc != `\0` {
s.pos++
name = s.ident_name()
}
if s.is_fmt {
return s.new_token(.name, '@' + name, name.len + 1)
}
// @FN, @STRUCT, @MOD etc. See full list in token.valid_at_tokens
if '@' + name in token.valid_at_tokens || name.starts_with('cc') { // `=@cccond` in inline assembly
return s.new_token(.at, '@' + name, name.len + 1)
}
if !token.is_key(name) {
mut at_error_msg := '@ must be used before keywords or compile time variables (e.g. `@type string` or `@FN`)'
// If name is all uppercase, the user is probably looking for a compile time variable ("at-token")
if name.is_upper() {
at_error_msg += '\nAvailable compile time variables:\n${token.valid_at_tokens}'
}
s.error(at_error_msg)
} else {
// s.note('@keyword is being deprecated and then removed from V. Use `keyword_` or a different name (e.g. `typ` instead of `type`)')
}
return s.new_token(.name, name, name.len)
}
`.` {
if nextc == `.` {
s.pos++
if s.pos + 1 < s.text.len && s.text[s.pos + 1] == `.` {
s.pos++
return s.new_token(.ellipsis, '', 3)
}
return s.new_token(.dotdot, '', 2)
}
return s.new_token(.dot, '', 1)
}
`#` {
// manage gated arrays/strings
if nextc == `[` {
s.pos++
return s.new_token(.nilsbr, '', 2)
}
start := s.pos + 1
s.ignore_line()
if nextc == `!` {
// treat shebang line (#!) as a comment
comment := s.text[start - 1..s.pos].trim_space()
// s.fgenln('// shebang line "$s.line_comment"')
return s.new_token(.comment, comment, comment.len + 2)
}
hash := s.text[start..s.pos].trim_space()
return s.new_token(.hash, hash, hash.len + 2)
}
`>` {
if nextc == `=` {
s.pos++
return s.new_token(.ge, '', 2)
} else if nextc == `>` {
if s.pos + 2 < s.text.len {
// an algorithm to decide it's generic or non-generic
// such as `foo<Baz, Bar<int>>(a)` vs `a, b := Foo{}<Foo{}, bar>>(baz)`
// @SleepyRoy if you have smarter algorithm :-)
// almost correct heuristics: last <T> of generic cannot be extremely long
// here we set the limit 100 which should be nice for real cases
// e.g. ...Bar<int, []Foo<int>, Baz_, [20]f64, map[string][]bool>> =>
// <int, Baz_, [20]f64, map[string][]bool => int, Baz_, f64, bool
is_generic := if s.last_lt >= 0 && s.pos - s.last_lt < 100 {
typs := s.text[s.last_lt + 1..s.pos].split(',').map(it.trim_space().trim_right('>').after(']'))
// if any typ is neither Type nor builtin, then the case is non-generic
typs.all(it.len > 0
&& ((it[0].is_capital() && it[1..].bytes().all(it.is_alnum()
|| it == `_`))
|| ast.builtin_type_names_matcher.matches(it)))
} else {
false
}
if is_generic {
return s.new_token(.gt, '', 1)
} else if s.text[s.pos + 2] == `=` {
s.pos += 2
return s.new_token(.right_shift_assign, '', 3)
} else if s.text[s.pos + 2] == `>` {
if s.pos + 3 < s.text.len && s.text[s.pos + 3] == `=` {
s.pos += 3
return s.new_token(.unsigned_right_shift_assign, '', 4)
}