/
fmt.v
2935 lines (2800 loc) · 67.7 KB
/
fmt.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 fmt
import strings
import v.ast
import v.util
import v.pref
const (
bs = '\\'
// when to break a line depending on the penalty
max_len = [0, 35, 60, 85, 93, 100]
)
[minify]
pub struct Fmt {
pub mut:
file ast.File
table &ast.Table = unsafe { nil }
pref &pref.Preferences = unsafe { nil }
is_debug bool
out strings.Builder
out_imports strings.Builder
indent int
empty_line bool
line_len int // the current line length, Note: it counts \t as 4 spaces, and starts at 0 after f.writeln
buffering bool // disables line wrapping for exprs that will be analyzed later
par_level int // how many parentheses are put around the current expression
array_init_break []bool // line breaks after elements in hierarchy level of multi dimensional array
array_init_depth int // current level of hierarchy in array init
single_line_if bool
cur_mod string
did_imports bool
is_assign bool
is_struct_init bool
auto_imports []string // automatically inserted imports that the user forgot to specify
import_pos int // position of the imports in the resulting string for later autoimports insertion
used_imports []string // to remove unused imports
import_syms_used map[string]bool // to remove unused import symbols.
mod2alias map[string]string // for `import time as t`, will contain: 'time'=>'t'
mod2syms map[string]string // import time { now } 'time.now'=>'now'
use_short_fn_args bool
single_line_fields bool // should struct fields be on a single line
it_name string // the name to replace `it` with
in_lambda_depth int
inside_const bool
inside_unsafe bool
inside_comptime_if bool
is_mbranch_expr bool // match a { x...y { } }
fn_scope &ast.Scope = unsafe { nil }
wsinfix_depth int
format_state FormatState
source_text string // can be set by `echo "println('hi')" | v fmt`, i.e. when processing source not from a file, but from stdin. In this case, it will contain the entire input text. You can use f.file.path otherwise, and read from that file.
}
[params]
pub struct FmtOptions {
source_text string
}
pub fn fmt(file ast.File, table &ast.Table, pref_ &pref.Preferences, is_debug bool, options FmtOptions) string {
mut f := Fmt{
file: file
table: table
pref: pref_
is_debug: is_debug
out: strings.new_builder(1000)
out_imports: strings.new_builder(200)
}
f.source_text = options.source_text
f.process_file_imports(file)
f.set_current_module_name('main')
// As these are toplevel stmts, the indent increase done in f.stmts() has to be compensated
f.indent--
f.stmts(file.stmts)
f.indent++
f.imports(f.file.imports) // now that we have all autoimports, handle them
res := f.out.str().trim_space() + '\n'
if res.len == 1 {
return f.out_imports.str().trim_space() + '\n'
}
if res.len <= f.import_pos {
imp_str := f.out_imports.str().trim_space()
if imp_str.len > 0 {
return res + '\n' + imp_str + '\n'
} else {
return res
}
} else {
return res[..f.import_pos] + f.out_imports.str() + res[f.import_pos..]
}
}
pub fn (mut f Fmt) process_file_imports(file &ast.File) {
for imp in file.imports {
f.mod2alias[imp.mod] = imp.alias
for sym in imp.syms {
f.mod2alias['${imp.mod}.${sym.name}'] = sym.name
f.mod2alias['${imp.mod.all_after_last('.')}.${sym.name}'] = sym.name
f.mod2alias[sym.name] = sym.name
f.mod2syms['${imp.mod}.${sym.name}'] = sym.name
f.mod2syms['${imp.mod.all_after_last('.')}.${sym.name}'] = sym.name
f.mod2syms[sym.name] = sym.name
f.import_syms_used[sym.name] = false
}
}
f.auto_imports = file.auto_imports
}
//=== Basic buffer write operations ===//
pub fn (mut f Fmt) write(s string) {
if f.indent > 0 && f.empty_line {
f.write_indent()
}
f.out.write_string(s)
f.line_len += s.len
f.empty_line = false
}
pub fn (mut f Fmt) writeln(s string) {
if f.indent > 0 && f.empty_line && s.len > 0 {
f.write_indent()
}
f.out.writeln(s)
f.empty_line = true
f.line_len = 0
}
fn (mut f Fmt) write_indent() {
f.out.write_string(util.tabs(f.indent))
f.line_len += f.indent * 4
}
pub fn (mut f Fmt) wrap_long_line(penalty_idx int, add_indent bool) bool {
if f.buffering {
return false
}
if penalty_idx > 0 && f.line_len <= fmt.max_len[penalty_idx] {
return false
}
if f.out.last() == ` ` {
f.out.go_back(1)
}
f.write('\n')
f.line_len = 0
if add_indent {
f.indent++
}
f.write_indent()
if add_indent {
f.indent--
}
return true
}
[params]
pub struct RemoveNewLineConfig {
imports_buffer bool // Work on f.out_imports instead of f.out
}
// When the removal action actually occurs, the string of the last line after the removal is returned
pub fn (mut f Fmt) remove_new_line(cfg RemoveNewLineConfig) string {
mut buffer := if cfg.imports_buffer { unsafe { &f.out_imports } } else { unsafe { &f.out } }
mut i := 0
for i = buffer.len - 1; i >= 0; i-- {
if !buffer.byte_at(i).is_space() { // != `\n` {
break
}
}
if i == buffer.len - 1 {
return ''
}
buffer.go_back(buffer.len - i - 1)
f.empty_line = false
mut line_len := 0
mut last_line_str := []u8{}
for i = buffer.len - 1; i >= 0; i-- {
ch := buffer.byte_at(i)
if ch == `\n` {
break
}
line_len += if ch == `\t` { 4 } else { 1 }
last_line_str << ch
}
f.line_len = line_len
return last_line_str.reverse().bytestr()
}
//=== Specialized write methods ===//
fn (mut f Fmt) write_language_prefix(lang ast.Language) {
match lang {
.c { f.write('C.') }
.js { f.write('JS.') }
.wasm { f.write('WASM.') }
else {}
}
}
fn (mut f Fmt) write_generic_types(gtypes []ast.Type) {
if gtypes.len > 0 {
f.write('[')
gtypes_string := gtypes.map(f.table.type_to_str(it)).join(', ')
f.write(gtypes_string)
f.write(']')
}
}
//=== Module handling helper methods ===//
pub fn (mut f Fmt) set_current_module_name(cmodname string) {
f.cur_mod = cmodname
f.table.cmod_prefix = cmodname + '.'
}
fn (f Fmt) get_modname_prefix(mname string) (string, string) {
// ./tests/proto_module_importing_vproto_keep.vv to know, why here is checked for ']' and '&'
if !mname.contains(']') && !mname.contains('&') {
return mname, ''
}
after_rbc := mname.all_after_last(']')
after_ref := mname.all_after_last('&')
modname := if after_rbc.len < after_ref.len { after_rbc } else { after_ref }
return modname, mname.trim_string_right(modname)
}
fn (mut f Fmt) is_external_name(name string) bool {
if name.len > 2 && name[0] == `C` && name[1] == `.` {
return true
}
if name.len > 3 && name[0] == `J` && name[1] == `S` && name[2] == `.` {
return true
}
return false
}
pub fn (mut f Fmt) no_cur_mod(typename string) string {
return util.no_cur_mod(typename, f.cur_mod)
}
// foo.bar.fn() => bar.fn()
pub fn (mut f Fmt) short_module(name string) string {
if !name.contains('.') || name.starts_with('JS.') {
return name
}
if name in f.mod2syms {
return f.mod2syms[name]
}
if name.ends_with(']') {
generic_levels := name.trim_string_right(']').split('[')
mut res := '${f.short_module(generic_levels[0])}'
for i in 1 .. generic_levels.len {
genshorts := generic_levels[i].split(', ').map(f.short_module(it)).join(', ')
res += '[${genshorts}'
}
res += ']'
return res
}
vals := name.split('.')
if vals.len < 2 {
return name
}
idx := vals.len - 1
mname, tprefix := f.get_modname_prefix(vals[..idx].join('.'))
symname := vals.last()
mut aname := f.mod2alias[mname]
if aname == '' {
for _, v in f.mod2alias {
if v == mname {
aname = mname
break
}
}
}
if aname == '' {
return '${tprefix}${symname}'
}
return '${tprefix}${aname}.${symname}'
}
//=== Import-related methods ===//
pub fn (mut f Fmt) mark_types_import_as_used(typ ast.Type) {
sym := f.table.sym(typ)
match sym.info {
ast.Map {
map_info := sym.map_info()
f.mark_types_import_as_used(map_info.key_type)
f.mark_types_import_as_used(map_info.value_type)
return
}
ast.Array, ast.ArrayFixed {
f.mark_types_import_as_used(sym.info.elem_type)
return
}
ast.GenericInst {
for concrete_typ in sym.info.concrete_types {
f.mark_types_import_as_used(concrete_typ)
}
}
else {}
}
name := sym.name.split('[')[0] // take `Type` from `Type[T]`
f.mark_import_as_used(name)
}
// `name` is a function (`foo.bar()`) or type (`foo.Bar{}`)
pub fn (mut f Fmt) mark_import_as_used(name string) {
parts := name.split('.')
last := parts.last()
if last in f.import_syms_used {
f.import_syms_used[last] = true
}
if parts.len == 1 {
return
}
mod := parts[0..parts.len - 1].join('.')
if mod in f.used_imports {
return
}
f.used_imports << mod
}
pub fn (mut f Fmt) imports(imports []ast.Import) {
if f.did_imports || imports.len == 0 {
return
}
f.did_imports = true
mut num_imports := 0
mut already_imported := map[string]bool{}
for imp in imports {
if imp.mod !in f.used_imports {
// TODO bring back once only unused imports are removed
// continue
}
if imp.mod in f.auto_imports && imp.mod !in f.used_imports {
continue
}
import_text := 'import ${f.imp_stmt_str(imp)}'
if already_imported[import_text] {
continue
}
already_imported[import_text] = true
if !f.format_state.is_vfmt_on {
import_original_source_lines := f.get_source_lines()#[imp.pos.line_nr..
imp.pos.last_line + 1].join('\n')
f.out_imports.writeln(import_original_source_lines)
// NOTE: imp.comments are on the *same line*, so they are already included in import_original_source_lines
f.import_comments(imp.next_comments)
} else {
f.out_imports.writeln(import_text)
f.import_comments(imp.comments, inline: true)
f.import_comments(imp.next_comments)
}
num_imports++
}
if num_imports > 0 {
f.out_imports.writeln('')
}
}
pub fn (f Fmt) imp_stmt_str(imp ast.Import) string {
mod := if imp.mod.len == 0 { imp.alias } else { imp.mod }
normalized_mod := mod.all_after('src.') // Ignore the 'src.' folder prefix since src/ folder is root of code
is_diff := imp.alias != normalized_mod && !normalized_mod.ends_with('.' + imp.alias)
mut imp_alias_suffix := if is_diff { ' as ${imp.alias}' } else { '' }
mut syms := imp.syms.map(it.name).filter(f.import_syms_used[it])
syms.sort()
if syms.len > 0 {
imp_alias_suffix += if imp.syms[0].pos.line_nr == imp.pos.line_nr {
' { ' + syms.join(', ') + ' }'
} else {
' {\n\t' + syms.join(',\n\t') + ',\n}'
}
}
return '${normalized_mod}${imp_alias_suffix}'
}
//=== Node helpers ===//
fn (f Fmt) should_insert_newline_before_node(node ast.Node, prev_node ast.Node) bool {
// No need to insert a newline if there is already one
if f.out.last_n(2) == '\n\n' {
return false
}
prev_line_nr := prev_node.pos().last_line
// The nodes are Stmts
if node is ast.Stmt && prev_node is ast.Stmt {
match prev_node {
// Force a newline after a block of HashStmts
ast.HashStmt {
if node !in [ast.HashStmt, ast.ExprStmt] {
return true
}
}
// Force a newline after function declarations
// The only exception is inside a block of no_body functions
ast.FnDecl {
if node !is ast.FnDecl || !prev_node.no_body {
return true
}
}
// Force a newline after struct declarations
ast.StructDecl {
return true
}
// Empty line after a block of type declarations
ast.TypeDecl {
if node !is ast.TypeDecl {
return true
}
}
// Imports are handled special hence they are ignored here
ast.Import {
return false
}
else {}
}
match node {
// Attributes are not respected in the stmts position, so this requires manual checking
ast.StructDecl, ast.EnumDecl, ast.FnDecl {
if node.attrs.len > 0 && node.attrs[0].pos.line_nr - prev_line_nr <= 1 {
return false
}
}
ast.Import {
return false
}
else {}
}
}
// The node shouldn't have a newline before
if node.pos().line_nr - prev_line_nr <= 1 {
return false
}
return true
}
pub fn (mut f Fmt) node_str(node ast.Node) string {
was_empty_line := f.empty_line
prev_line_len := f.line_len
pos := f.out.len
match node {
ast.Stmt { f.stmt(node) }
ast.Expr { f.expr(node) }
else { panic('´f.node_str()´ is not implemented for ${node}.') }
}
str := f.out.after(pos)
f.out.go_back_to(pos)
f.empty_line = was_empty_line
f.line_len = prev_line_len
return str
}
//=== General Stmt-related methods and helpers ===//
pub fn (mut f Fmt) stmts(stmts []ast.Stmt) {
mut prev_stmt := if stmts.len > 0 { stmts[0] } else { ast.empty_stmt }
f.indent++
for stmt in stmts {
if !f.pref.building_v && f.should_insert_newline_before_node(stmt, prev_stmt) {
f.out.writeln('')
}
f.stmt(stmt)
prev_stmt = stmt
}
f.indent--
}
pub fn (mut f Fmt) stmt(node ast.Stmt) {
if f.is_debug {
eprintln('stmt ${node.type_name():-20} | pos: ${node.pos.line_str()}')
}
match node {
ast.EmptyStmt, ast.NodeError {}
ast.AsmStmt {
f.asm_stmt(node)
}
ast.AssertStmt {
f.assert_stmt(node)
}
ast.AssignStmt {
f.assign_stmt(node)
}
ast.Block {
if node.is_unsafe {
f.inside_unsafe = true
f.block(node)
f.inside_unsafe = false
} else {
f.block(node)
}
}
ast.BranchStmt {
f.branch_stmt(node)
}
ast.ComptimeFor {
f.comptime_for(node)
}
ast.ConstDecl {
f.const_decl(node)
}
ast.DeferStmt {
f.defer_stmt(node)
}
ast.EnumDecl {
f.enum_decl(node)
}
ast.ExprStmt {
f.expr_stmt(node)
}
ast.FnDecl {
f.fn_decl(node)
}
ast.ForCStmt {
f.for_c_stmt(node)
}
ast.ForInStmt {
f.for_in_stmt(node)
}
ast.ForStmt {
f.for_stmt(node)
}
ast.GlobalDecl {
f.global_decl(node)
}
ast.GotoLabel {
f.goto_label(node)
}
ast.GotoStmt {
f.goto_stmt(node)
}
ast.HashStmt {
f.hash_stmt(node)
}
ast.Import {
// Imports are handled after the file is formatted, to automatically add necessary modules
// Just remember the position of the imports for now
f.import_pos = f.out.len
}
ast.InterfaceDecl {
f.interface_decl(node)
}
ast.Module {
f.module_stmt(node)
}
ast.Return {
f.return_stmt(node)
}
ast.SqlStmt {
f.sql_stmt(node)
}
ast.StructDecl {
f.struct_decl(node, false)
}
ast.TypeDecl {
f.type_decl(node)
}
}
}
fn stmt_is_single_line(stmt ast.Stmt) bool {
return match stmt {
ast.ExprStmt, ast.AssertStmt { expr_is_single_line(stmt.expr) }
ast.Return, ast.AssignStmt, ast.BranchStmt { true }
else { false }
}
}
//=== General Expr-related methods and helpers ===//
pub fn (mut f Fmt) expr(node_ ast.Expr) {
mut node := unsafe { node_ }
if f.is_debug {
eprintln('expr ${node.type_name():-20} | pos: ${node.pos().line_str()} | ${node.str()}')
}
match mut node {
ast.NodeError {}
ast.EmptyExpr {}
ast.AnonFn {
f.anon_fn(node)
}
ast.ArrayDecompose {
f.array_decompose(node)
}
ast.ArrayInit {
f.array_init(node)
}
ast.AsCast {
f.as_cast(node)
}
ast.Assoc {
f.assoc(node)
}
ast.AtExpr {
f.at_expr(node)
}
ast.BoolLiteral {
f.write(node.val.str())
}
ast.CallExpr {
f.call_expr(node)
}
ast.CastExpr {
f.cast_expr(node)
}
ast.ChanInit {
f.chan_init(mut node)
}
ast.CharLiteral {
f.char_literal(node)
}
ast.Comment {
f.comment(node, inline: true)
}
ast.ComptimeCall {
f.comptime_call(node)
}
ast.ComptimeSelector {
f.comptime_selector(node)
}
ast.ConcatExpr {
f.concat_expr(node)
}
ast.CTempVar {
eprintln('ast.CTempVar of ${node.orig.str()} should be generated/used only in cgen')
}
ast.DumpExpr {
f.dump_expr(node)
}
ast.EnumVal {
f.enum_val(node)
}
ast.FloatLiteral {
f.write(node.val)
if node.val.ends_with('.') {
f.write('0')
}
}
ast.GoExpr {
f.go_expr(node)
}
ast.SpawnExpr {
f.spawn_expr(node)
}
ast.Ident {
f.ident(node)
}
ast.IfExpr {
f.if_expr(node)
}
ast.IfGuardExpr {
f.if_guard_expr(node)
}
ast.IndexExpr {
f.index_expr(node)
}
ast.InfixExpr {
f.infix_expr(node)
}
ast.IntegerLiteral {
f.write(node.val)
}
ast.Likely {
f.likely(node)
}
ast.LockExpr {
f.lock_expr(node)
}
ast.MapInit {
f.map_init(node)
}
ast.MatchExpr {
f.match_expr(node)
}
ast.None {
f.write('none')
}
ast.Nil {
f.write('nil')
}
ast.OffsetOf {
f.offset_of(node)
}
ast.OrExpr {
// shouldn't happen, an or expression is always linked to a call expr or index expr
panic('fmt: OrExpr should be linked to ast.CallExpr or ast.IndexExpr')
}
ast.ParExpr {
f.par_expr(node)
}
ast.PostfixExpr {
f.postfix_expr(node)
}
ast.PrefixExpr {
f.prefix_expr(node)
}
ast.RangeExpr {
f.range_expr(node)
}
ast.SelectExpr {
f.select_expr(node)
}
ast.SelectorExpr {
f.selector_expr(node)
}
ast.SizeOf {
f.size_of(node)
}
ast.IsRefType {
f.is_ref_type(node)
}
ast.SqlExpr {
f.sql_expr(node)
}
ast.StringLiteral {
f.string_literal(node)
}
ast.StringInterLiteral {
f.string_inter_literal(node)
}
ast.StructInit {
f.struct_init(node)
}
ast.TypeNode {
f.type_expr(node)
}
ast.TypeOf {
f.type_of(node)
}
ast.UnsafeExpr {
f.inside_unsafe = true
f.unsafe_expr(node)
f.inside_unsafe = false
}
ast.ComptimeType {
match node.kind {
.array { f.write('\$array') }
.struct_ { f.write('\$struct') }
.iface { f.write('\$interface') }
.map_ { f.write('\$map') }
.int { f.write('\$int') }
.float { f.write('\$float') }
.sum_type { f.write('\$sumtype') }
.enum_ { f.write('\$enum') }
.alias { f.write('\$alias') }
.function { f.write('\$function') }
.option { f.write('\$option') }
}
}
}
}
fn expr_is_single_line(expr ast.Expr) bool {
match expr {
ast.Comment, ast.IfExpr, ast.MapInit, ast.MatchExpr {
return false
}
ast.AnonFn {
if !expr.decl.no_body {
return false
}
}
ast.StructInit {
if !expr.no_keys && (expr.init_fields.len > 0 || expr.pre_comments.len > 0) {
return false
}
}
ast.CallExpr {
if expr.or_block.stmts.len > 1 {
return false
}
}
ast.ArrayInit {
if expr.exprs.len > 0 {
return expr_is_single_line(expr.exprs[0])
}
}
ast.ConcatExpr {
for e in expr.vals {
if !expr_is_single_line(e) {
return false
}
}
}
ast.StringLiteral {
return expr.pos.line_nr == expr.pos.last_line
}
else {}
}
return true
}
//=== Specific Stmt methods ===//
pub fn (mut f Fmt) assert_stmt(node ast.AssertStmt) {
f.write('assert ')
mut expr := node.expr
for mut expr is ast.ParExpr {
expr = expr.expr
}
f.expr(expr)
if node.extra !is ast.EmptyExpr {
f.write(', ')
f.expr(node.extra)
}
f.writeln('')
}
pub fn (mut f Fmt) assign_stmt(node ast.AssignStmt) {
f.comments(node.comments)
for i, left in node.left {
f.expr(left)
if i < node.left.len - 1 {
f.write(', ')
}
}
f.is_assign = true
f.write(' ${node.op.str()} ')
for i, val in node.right {
f.expr(val)
if i < node.right.len - 1 {
f.write(', ')
}
}
f.comments(node.end_comments, has_nl: false, inline: true, level: .keep)
if !f.single_line_if {
f.writeln('')
}
f.is_assign = false
}
pub fn (mut f Fmt) block(node ast.Block) {
if node.is_unsafe {
f.write('unsafe ')
}
f.write('{')
if node.stmts.len > 0 || node.pos.line_nr < node.pos.last_line {
f.writeln('')
f.stmts(node.stmts)
}
f.writeln('}')
}
pub fn (mut f Fmt) branch_stmt(node ast.BranchStmt) {
f.writeln(node.str())
}
pub fn (mut f Fmt) comptime_for(node ast.ComptimeFor) {
typ := f.no_cur_mod(f.table.type_to_str_using_aliases(node.typ, f.mod2alias))
f.write('\$for ${node.val_var} in ${typ}.${node.kind.str()} {')
f.mark_types_import_as_used(node.typ)
if node.stmts.len > 0 || node.pos.line_nr < node.pos.last_line {
f.writeln('')
f.stmts(node.stmts)
}
f.writeln('}')
}
struct ConstAlignInfo {
mut:
max int
last_idx int
}
pub fn (mut f Fmt) const_decl(node ast.ConstDecl) {
f.attrs(node.attrs)
if node.is_pub {
f.write('pub ')
}
if node.fields.len == 0 && node.pos.line_nr == node.pos.last_line {
f.writeln('const ()\n')
return
}
f.inside_const = true
defer {
f.inside_const = false
}
f.write('const ')
mut align_infos := []ConstAlignInfo{}
if node.is_block {
f.writeln('(')
mut info := ConstAlignInfo{}
for i, field in node.fields {
if field.name.len > info.max {
info.max = field.name.len
}
if !expr_is_single_line(field.expr) {
info.last_idx = i
align_infos << info
info = ConstAlignInfo{}
}
}
info.last_idx = node.fields.len
align_infos << info
f.indent++
} else {
align_infos << ConstAlignInfo{0, 1}
}
mut prev_field := if node.fields.len > 0 {
ast.Node(node.fields[0])
} else {
ast.Node(ast.NodeError{})
}
mut align_idx := 0
for i, field in node.fields {
if i > align_infos[align_idx].last_idx {
align_idx++
}
if field.comments.len > 0 {
if f.should_insert_newline_before_node(ast.Expr(field.comments[0]), prev_field) {
f.writeln('')
}
f.comments(field.comments, inline: true)
prev_field = ast.Expr(field.comments.last())
}
if node.is_block && f.should_insert_newline_before_node(field, prev_field) {
f.writeln('')
}
name := field.name.after('.')
f.write('${name} ')
f.write(strings.repeat(` `, align_infos[align_idx].max - field.name.len))
f.write('= ')
f.expr(field.expr)
f.comments(field.end_comments, inline: true)
if node.is_block && field.end_comments.len == 0 {
f.writeln('')
} else {
// Write out single line comments after const expr if present
// E.g.: `const x = 1 // <comment>`
if node.end_comments.len > 0 && node.end_comments[0].text.contains('\n') {
f.writeln('\n')
}
f.comments(node.end_comments, inline: true)
}
prev_field = field
}
if node.is_block {
f.comments_after_last_field(node.end_comments)
} else if node.end_comments.len == 0 {
// If no single line comments after the const expr is present
f.writeln('')
}
if node.is_block {
f.indent--
f.writeln(')\n')
} else {
f.writeln('')
}
}
pub fn (mut f Fmt) defer_stmt(node ast.DeferStmt) {
f.write('defer {')
if node.stmts.len > 0 || node.pos.line_nr < node.pos.last_line {
f.writeln('')
f.stmts(node.stmts)
}
f.writeln('}')
}
pub fn (mut f Fmt) expr_stmt(node ast.ExprStmt) {
f.comments(node.comments)
f.expr(node.expr)
if !f.single_line_if {
f.writeln('')
}
}
pub fn (mut f Fmt) enum_decl(node ast.EnumDecl) {
f.attrs(node.attrs)
if node.is_pub {
f.write('pub ')
}
mut name := node.name.after('.')
if node.typ != ast.int_type {
senum_type := f.table.type_to_str_using_aliases(node.typ, f.mod2alias)
name += ' as ${senum_type}'
}
if node.fields.len == 0 && node.pos.line_nr == node.pos.last_line {
f.writeln('enum ${name} {}\n')
return
}
f.writeln('enum ${name} {')
f.comments(node.comments, inline: true, level: .indent)
for field in node.fields {
f.write('\t${field.name}')
if field.has_expr {
f.write(' = ')
f.expr(field.expr)
}
if field.attrs.len > 0 {
f.write(' ')
f.single_line_attrs(field.attrs, inline: true)
}