/
fn.v
2643 lines (2572 loc) · 81.5 KB
/
fn.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-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 c
import strings
import v.ast
import v.util
const c_fn_name_escape_seq = ['[', '_T_', ']', '']
fn (mut g Gen) is_used_by_main(node ast.FnDecl) bool {
mut is_used_by_main := true
if g.pref.skip_unused {
fkey := node.fkey()
is_used_by_main = g.table.used_fns[fkey]
$if trace_skip_unused_fns ? {
println('> is_used_by_main: ${is_used_by_main} | node.name: ${node.name} | fkey: ${fkey} | node.is_method: ${node.is_method}')
}
if !is_used_by_main {
$if trace_skip_unused_fns_in_c_code ? {
g.writeln('// trace_skip_unused_fns_in_c_code, ${node.name}, fkey: ${fkey}')
}
}
} else {
$if trace_skip_unused_fns_in_c_code ? {
g.writeln('// trace_skip_unused_fns_in_c_code, ${node.name}, fkey: ${node.fkey()}')
}
}
return is_used_by_main
}
fn (mut g Gen) fn_decl(node ast.FnDecl) {
if node.should_be_skipped {
return
}
if node.is_test {
g.test_function_names << node.name
}
if node.ninstances == 0 && node.generic_names.len > 0 {
$if trace_generics ? {
eprintln('skipping generic fn with no concrete instances: ${node.mod} ${node.name}')
}
return
}
if !g.is_used_by_main(node) {
return
}
if g.is_builtin_mod && g.pref.gc_mode == .boehm_leak && node.name == 'malloc' {
g.definitions.write_string('#define _v_malloc GC_MALLOC\n')
return
}
if g.pref.parallel_cc {
if node.is_anon {
g.write('static ')
g.definitions.write_string('static ')
}
if !node.is_anon {
g.out_fn_start_pos << g.out.len
}
}
prev_is_direct_array_access := g.is_direct_array_access
g.is_direct_array_access = node.is_direct_arr || g.pref.no_bounds_checking
defer {
g.is_direct_array_access = prev_is_direct_array_access
}
g.gen_attrs(node.attrs)
mut skip := false
pos := g.out.len
should_bundle_module := util.should_bundle_module(node.mod)
if g.pref.build_mode == .build_module {
// TODO true for not just "builtin"
// TODO: clean this up
mod := if g.is_builtin_mod { 'builtin' } else { node.name.all_before_last('.') }
// for now dont skip generic functions as they are being marked as static
// when -usecache is enabled, until a better solution is implemented.
if ((mod != g.module_built && node.mod != g.module_built.after('/'))
|| should_bundle_module) && node.generic_names.len == 0 {
// Skip functions that don't have to be generated for this module.
// println('skip bm $node.name mod=$node.mod module_built=$g.module_built')
skip = true
}
if g.is_builtin_mod && g.module_built == 'builtin' && node.mod == 'builtin' {
skip = false
}
if !skip && g.pref.is_verbose {
println('build module `${g.module_built}` fn `${node.name}`')
}
}
if g.pref.use_cache {
// We are using prebuilt modules, we do not need to generate
// their functions in main.c.
if node.mod != 'main' && node.mod != 'help' && !should_bundle_module && !g.pref.is_test
&& node.generic_names.len == 0 {
skip = true
}
}
keep_fn_decl := g.fn_decl
unsafe {
g.fn_decl = &node
}
if node.is_main {
g.has_main = true
}
// TODO PERF remove this from here
is_backtrace := node.name.starts_with('backtrace')
&& node.name in ['backtrace_symbols', 'backtrace', 'backtrace_symbols_fd']
if is_backtrace {
g.write('\n#ifndef __cplusplus\n')
}
g.gen_fn_decl(node, skip)
if is_backtrace {
g.write('\n#endif\n')
}
g.fn_decl = keep_fn_decl
if skip {
g.go_back_to(pos)
}
if !g.pref.skip_unused {
if node.language != .c {
g.writeln('')
}
}
// Write the next function into another parallel C file
// g.out_idx++
// if g.out_idx >= g.out_parallel.len {
// g.out_idx = 0
//}
}
fn (mut g Gen) gen_fn_decl(node &ast.FnDecl, skip bool) {
// TODO For some reason, build fails with autofree with this line
// as it's only informative, comment it for now
// g.gen_attrs(it.attrs)
if node.language == .c {
return
}
old_is_vlines_enabled := g.is_vlines_enabled
g.is_vlines_enabled = true
defer {
g.is_vlines_enabled = old_is_vlines_enabled
}
tmp_defer_vars := g.defer_vars // must be here because of workflow
if !g.anon_fn {
g.defer_vars = []string{}
} else {
if node.defer_stmts.len > 0 {
g.defer_vars = []string{}
defer {
g.defer_vars = tmp_defer_vars
}
}
}
// Skip [if xxx] if xxx is not defined
/*
for attr in node.attrs {
if !attr.is_comptime_define {
continue
}
if attr.name !in g.pref.compile_defines_all {
// println('skipping [if]')
return
}
}
*/
g.returned_var_name = ''
old_g_autofree := g.is_autofree
if node.is_manualfree {
g.is_autofree = false
}
defer {
g.is_autofree = old_g_autofree
}
if node.generic_names.len > 0 && g.cur_concrete_types.len == 0 {
// need the cur_concrete_type check to avoid inf. recursion
// loop thru each generic type and generate a function
nkey := node.fkey()
generic_types_by_fn := g.table.fn_generic_types[nkey]
$if trace_post_process_generic_fns ? {
eprintln('>> gen_fn_decl, nkey: ${nkey} | generic_types_by_fn: ${generic_types_by_fn}')
}
for concrete_types in generic_types_by_fn {
if g.pref.is_verbose {
syms := concrete_types.map(g.table.sym(it))
the_type := syms.map(it.name).join(', ')
println('gen fn `${node.name}` for type `${the_type}`')
}
g.cur_concrete_types = concrete_types
g.gen_fn_decl(node, skip)
}
g.cur_concrete_types = []
return
}
cur_fn_save := g.cur_fn
defer {
g.cur_fn = cur_fn_save
}
unsafe {
// TODO remove unsafe
g.cur_fn = node
}
fn_start_pos := g.out.len
is_closure := node.scope.has_inherited_vars()
mut cur_closure_ctx := ''
if is_closure {
cur_closure_ctx = g.closure_ctx(node)
// declare the struct before its implementation
g.definitions.write_string(cur_closure_ctx)
g.definitions.writeln(';')
}
g.write_v_source_line_info(node.pos)
fn_attrs := g.write_fn_attrs(node.attrs)
// Live
is_livefn := node.attrs.contains('live')
is_livemain := g.pref.is_livemain && is_livefn
is_liveshared := g.pref.is_liveshared && is_livefn
is_livemode := g.pref.is_livemain || g.pref.is_liveshared
is_live_wrap := is_livefn && is_livemode
if is_livefn && !is_livemode {
eprintln('INFO: compile with `v -live ${g.pref.path} `, if you want to use the [live] function ${node.name} .')
}
mut name := g.c_fn_name(node)
mut type_name := g.typ(g.unwrap_generic(node.return_type))
ret_sym := g.table.sym(g.unwrap_generic(node.return_type))
if node.return_type.has_flag(.generic) && !node.return_type.has_option_or_result()
&& ret_sym.kind == .array_fixed {
type_name = '_v_${type_name}'
} else if ret_sym.kind == .alias && !node.return_type.has_option_or_result() {
unalias_typ := g.table.unaliased_type(node.return_type)
unalias_sym := g.table.sym(unalias_typ)
if unalias_sym.kind == .array_fixed {
type_name = if !(unalias_sym.info as ast.ArrayFixed).is_fn_ret { '_v_' } else { '' } +
g.typ(unalias_typ)
}
}
if g.pref.obfuscate && g.cur_mod.name == 'main' && name.starts_with('main__') && !node.is_main
&& node.name != 'str' {
mut key := node.name
if node.is_method {
sym := g.table.sym(node.receiver.typ)
key = sym.name + '.' + node.name
}
g.writeln('/* obf: ${key} */')
name = g.obf_table[key] or {
panic('cgen: fn_decl: obf name "${key}" not found, this should never happen')
}
}
// Live functions are protected by a mutex, because otherwise they
// can be changed by the live reload thread, *while* they are
// running, with unpredictable results (usually just crashing).
// For this purpose, the actual body of the live function,
// is put under a non publicly accessible function, that is prefixed
// with 'impl_live_' .
if is_livemode {
if is_livefn {
g.hotcode_fn_names << name
}
g.hotcode_fpaths << g.file.path
}
mut impl_fn_name := name
if is_live_wrap {
impl_fn_name = 'impl_live_${name}'
}
last_fn_c_name_save := g.last_fn_c_name
defer {
g.last_fn_c_name = last_fn_c_name_save
}
g.last_fn_c_name = impl_fn_name
if node.trace_fns.len > 0 {
for trace_fn, call_fn in node.trace_fns {
if trace_fn in g.trace_fn_definitions {
continue
}
trace_fn_ret_type := g.typ(call_fn.return_type)
g.write('VV_LOCAL_SYMBOL ${trace_fn_ret_type} ${c_name(trace_fn)}(')
g.definitions.write_string('VV_LOCAL_SYMBOL ${trace_fn_ret_type} ${c_name(trace_fn)}(')
if call_fn.is_fn_var {
sig := g.fn_var_signature(call_fn.func.return_type, call_fn.func.params.map(it.typ),
call_fn.name)
g.write(sig)
g.definitions.write_string(sig)
} else {
g.fn_decl_params(call_fn.func.params, unsafe { nil }, call_fn.func.is_variadic)
}
g.writeln(') {')
g.definitions.write_string(');\n')
orig_fn_args := call_fn.func.params.map(it.name).join(', ')
if g.cur_fn.is_method || g.cur_fn.is_static_type_method {
g.writeln('\tarray_push((array*)&g_callstack, _MOV((v__debug__FnTrace[]){ ((v__debug__FnTrace){.name = _SLIT("${g.table.type_to_str(g.cur_fn.receiver.typ)}.${g.cur_fn.name.all_after_last('__static__')}"),.file = _SLIT("${call_fn.file}"),.line = ${call_fn.line},}) }));')
} else {
g.writeln('\tarray_push((array*)&g_callstack, _MOV((v__debug__FnTrace[]){ ((v__debug__FnTrace){.name = _SLIT("${g.cur_fn.name}"),.file = _SLIT("${call_fn.file}"),.line = ${call_fn.line},}) }));')
}
if call_fn.return_type == 0 || call_fn.return_type == ast.void_type {
g.writeln('\t${c_name(call_fn.name)}(${orig_fn_args});')
g.writeln('\tarray_pop((array*)&g_callstack);')
} else {
g.writeln('\t${g.typ(call_fn.return_type)} ret = ${c_name(call_fn.name)}(${orig_fn_args});')
g.writeln('\tarray_pop((array*)&g_callstack);')
g.writeln('\treturn ret;')
}
g.writeln('}')
g.writeln('')
g.trace_fn_definitions << trace_fn
}
}
//
if is_live_wrap {
if is_livemain {
g.definitions.write_string('${type_name} (* ${impl_fn_name})(')
g.write('${type_name} no_impl_${name}(')
}
if is_liveshared {
g.definitions.write_string('${type_name} ${impl_fn_name}(')
g.write('${type_name} ${impl_fn_name}(')
}
} else {
if !(node.is_pub || g.pref.is_debug) {
// Private functions need to marked as static so that they are not exportable in the
// binaries
if g.pref.build_mode != .build_module && !g.pref.use_cache {
// If we are building vlib/builtin, we need all private functions like array_get
// to be public, so that all V programs can access them.
g.write('VV_LOCAL_SYMBOL ')
g.definitions.write_string('VV_LOCAL_SYMBOL ')
}
}
// as a temp solution generic functions are marked static
// when -usecache is enabled to fix duplicate symbols with clang
// TODO: implement a better sulution
visibility_kw := if g.cur_concrete_types.len > 0
&& (g.pref.build_mode == .build_module || g.pref.use_cache) {
'static '
} else {
''
}
fn_header := '${visibility_kw}${type_name} ${fn_attrs}${name}('
g.definitions.write_string(fn_header)
g.write(fn_header)
}
arg_start_pos := g.out.len
fargs, fargtypes, heap_promoted := g.fn_decl_params(node.params, node.scope, node.is_variadic)
if is_closure {
g.nr_closures++
}
arg_str := g.out.after(arg_start_pos)
if node.no_body || ((g.pref.use_cache && g.pref.build_mode != .build_module) && node.is_builtin
&& !g.pref.is_test) || skip {
// Just a function header. Builtin function bodies are defined in builtin.o
g.definitions.writeln(');') // NO BODY')
g.writeln(');')
return
}
if node.params.len == 0 {
g.definitions.write_string('void')
}
if attr := node.attrs.find_first('_linker_section') {
g.definitions.writeln(') __attribute__ ((section ("${attr.arg}")));')
} else {
g.definitions.writeln(');')
}
g.writeln(') {')
if is_closure {
g.writeln('${cur_closure_ctx}* ${c.closure_ctx} = __CLOSURE_GET_DATA();')
}
for i, is_promoted in heap_promoted {
if is_promoted {
g.writeln('${fargtypes[i]}* ${fargs[i]} = HEAP(${fargtypes[i]}, _v_toheap_${fargs[i]});')
}
}
g.indent++
for defer_stmt in node.defer_stmts {
g.writeln('bool ${g.defer_flag_var(defer_stmt)} = false;')
for var in defer_stmt.defer_vars {
if var.name in fargs || var.kind == .constant {
continue
}
if var.kind == .variable {
if var.name !in g.defer_vars {
g.defer_vars << var.name
mut deref := ''
if v := var.scope.find_var(var.name) {
if v.is_auto_heap {
deref = '*'
}
}
info := var.obj as ast.Var
if g.table.sym(info.typ).kind != .function {
g.writeln('${g.typ(info.typ)}${deref} ${c_name(var.name)};')
}
}
}
}
}
g.indent--
if is_live_wrap {
// The live function just calls its implementation dual, while ensuring
// that the call is wrapped by the mutex lock & unlock calls.
// Adding the mutex lock/unlock inside the body of the implementation
// function is not reliable, because the implementation function can do
// an early exit, which will leave the mutex locked.
mut fn_args_list := []string{}
for ia, fa in fargs {
fn_args_list << '${fargtypes[ia]} ${fa}'
}
mut live_fncall := '${impl_fn_name}(' + fargs.join(', ') + ');'
mut live_fnreturn := ''
if type_name != 'void' {
live_fncall = '${type_name} res = ${live_fncall}'
live_fnreturn = 'return res;'
}
g.definitions.writeln('${type_name} ${name}(' + fn_args_list.join(', ') + ');')
g.hotcode_definitions.writeln('${type_name} ${name}(' + fn_args_list.join(', ') + '){')
g.hotcode_definitions.writeln(' pthread_mutex_lock(&live_fn_mutex);')
g.hotcode_definitions.writeln(' ${live_fncall}')
g.hotcode_definitions.writeln(' pthread_mutex_unlock(&live_fn_mutex);')
g.hotcode_definitions.writeln(' ${live_fnreturn}')
g.hotcode_definitions.writeln('}')
}
// Profiling mode? Start counting at the beginning of the function (save current time).
if g.pref.is_prof && g.pref.build_mode != .build_module {
g.profile_fn(node)
}
// we could be in an anon fn so save outer fn defer stmts
prev_defer_stmts := g.defer_stmts
g.defer_stmts = []
ctmp := g.tmp_count
g.tmp_count = 0
defer {
g.tmp_count = ctmp
}
prev_inside_ternary := g.inside_ternary
g.inside_ternary = 0
prev_indent := g.indent
g.indent = 0
defer {
g.indent = prev_indent
}
g.stmts(node.stmts)
g.inside_ternary = prev_inside_ternary
if node.is_noreturn {
g.writeln('\twhile(1);')
}
// clear g.fn_mut_arg_names
if !node.has_return {
g.write_defer_stmts_when_needed()
}
if node.is_anon {
g.defer_stmts = prev_defer_stmts
} else {
g.defer_stmts = []
}
if node.return_type != ast.void_type && node.stmts.len > 0 && node.stmts.last() !is ast.Return
&& !node.attrs.contains('_naked') {
default_expr := g.type_default(node.return_type)
// TODO: perf?
if default_expr == '{0}' {
g.writeln('\treturn (${type_name})${default_expr};')
} else {
g.writeln('\treturn ${default_expr};')
}
}
g.writeln('}')
if g.pref.printfn_list.len > 0 && g.last_fn_c_name in g.pref.printfn_list {
println(g.out.after(fn_start_pos))
}
for attr in node.attrs {
if attr.name == 'export' {
weak := if node.attrs.any(it.name == 'weak') { 'VWEAK ' } else { '' }
g.writeln('// export alias: ${attr.arg} -> ${name}')
export_alias := '${weak}${type_name} ${fn_attrs}${attr.arg}(${arg_str})'
g.definitions.writeln('VV_EXPORTED_SYMBOL ${export_alias}; // exported fn ${node.name}')
g.writeln('${export_alias} {')
g.write('\treturn ${name}(')
g.write(fargs.join(', '))
g.writeln(');')
g.writeln('}')
}
}
}
fn (mut g Gen) c_fn_name(node &ast.FnDecl) string {
mut name := node.name
if name in ['+', '-', '*', '/', '%', '<', '=='] {
name = util.replace_op(name)
}
if node.is_method {
unwrapped_rec_typ := g.unwrap_generic(node.receiver.typ)
name = g.cc_type(unwrapped_rec_typ, false) + '_' + name
if g.table.sym(unwrapped_rec_typ).kind == .placeholder {
name = name.replace_each(c.c_fn_name_escape_seq)
}
}
if node.language == .c {
name = util.no_dots(name)
} else {
name = c_fn_name(name)
}
if node.generic_names.len > 0 {
name = g.generic_fn_name(g.cur_concrete_types, name)
}
if g.pref.translated || g.file.is_translated || node.is_file_translated {
if cattr := node.attrs.find_first('c') {
// This fixes unknown symbols errors when building separate .c => .v files into .o files
// example:
// [c: 'P_TryMove'] fn p_trymove(thing &Mobj_t, x int, y int) bool
// translates to:
// bool P_TryMove(main__Mobj_t* thing, int x, int y);
// In fn_call every time `p_trymove` is called, `P_TryMove` will be generated instead.
name = cattr.arg
}
}
return name
}
const closure_ctx = '_V_closure_ctx'
fn (mut g Gen) closure_ctx(node ast.FnDecl) string {
mut fn_name := node.name
if node.generic_names.len > 0 {
fn_name = g.generic_fn_name(g.cur_concrete_types, fn_name)
}
return 'struct _V_${fn_name}_Ctx'
}
fn (mut g Gen) gen_anon_fn(mut node ast.AnonFn) {
g.gen_anon_fn_decl(mut node)
mut fn_name := node.decl.name
if node.decl.generic_names.len > 0 {
fn_name = g.generic_fn_name(g.cur_concrete_types, fn_name)
}
if !node.decl.scope.has_inherited_vars() {
g.write(fn_name)
return
}
ctx_struct := g.closure_ctx(node.decl)
// it may be possible to optimize `memdup` out if the closure never leaves current scope
// TODO in case of an assignment, this should only call "__closure_set_data" and "__closure_set_function" (and free the former data)
g.write('__closure_create(${fn_name}, (${ctx_struct}*) memdup_uncollectable(&(${ctx_struct}){')
g.indent++
for var in node.inherited_vars {
mut has_inherited := false
mut is_ptr := false
if obj := node.decl.scope.find(var.name) {
if obj is ast.Var {
is_ptr = obj.typ.is_ptr()
if obj.has_inherited {
has_inherited = true
var_sym := g.table.sym(var.typ)
if var_sym.info is ast.ArrayFixed {
g.write('.${var.name} = {')
for i in 0 .. var_sym.info.size {
g.write('${c.closure_ctx}->${var.name}[${i}],')
}
g.writeln('},')
} else {
g.writeln('.${var.name} = ${c.closure_ctx}->${var.name},')
}
}
}
}
if !has_inherited {
var_sym := g.table.sym(var.typ)
if var_sym.info is ast.ArrayFixed {
g.write('.${var.name} = {')
for i in 0 .. var_sym.info.size {
g.write('${var.name}[${i}],')
}
g.writeln('},')
} else if g.is_autofree && !var.is_mut && var_sym.info is ast.Array {
g.writeln('.${var.name} = array_clone(&${var.name}),')
} else if g.is_autofree && !var.is_mut && var_sym.kind == .string {
g.writeln('.${var.name} = string_clone(${var.name}),')
} else {
mut is_auto_heap := false
if obj := node.decl.scope.parent.find(var.name) {
if obj is ast.Var {
is_auto_heap = !obj.is_stack_obj && obj.is_auto_heap
}
}
if is_auto_heap && !is_ptr {
g.writeln('.${var.name} = *${var.name},')
} else {
g.writeln('.${var.name} = ${var.name},')
}
}
}
}
g.indent--
g.write('}, sizeof(${ctx_struct})))')
g.empty_line = false
}
fn (mut g Gen) gen_anon_fn_decl(mut node ast.AnonFn) {
mut fn_name := node.decl.name
if node.decl.generic_names.len > 0 {
fn_name = g.generic_fn_name(g.cur_concrete_types, fn_name)
}
if node.has_gen[fn_name] {
return
}
node.has_gen[fn_name] = true
mut builder := strings.new_builder(256)
builder.writeln('/*F*/')
if node.inherited_vars.len > 0 {
ctx_struct := g.closure_ctx(node.decl)
builder.writeln('${ctx_struct} {')
for var in node.inherited_vars {
var_sym := g.table.sym(var.typ)
if var_sym.info is ast.FnType {
sig := g.fn_var_signature(var_sym.info.func.return_type, var_sym.info.func.params.map(it.typ),
var.name)
builder.writeln('\t' + sig + ';')
} else {
styp := g.typ(var.typ)
builder.writeln('\t${styp} ${var.name};')
}
}
builder.writeln('};\n')
}
pos := g.out.len
was_anon_fn := g.anon_fn
g.anon_fn = true
g.fn_decl(node.decl)
g.anon_fn = was_anon_fn
builder.write_string(g.out.cut_to(pos))
g.anon_fn_definitions << builder.str()
}
fn (g &Gen) defer_flag_var(stmt &ast.DeferStmt) string {
return '${g.last_fn_c_name}_defer_${stmt.idx_in_fn}'
}
fn (mut g Gen) write_defer_stmts_when_needed() {
// unlock all mutexes, in case we are in a lock statement. defers are not allowed in lock statements
g.unlock_locks()
if g.defer_stmts.len > 0 {
g.write_defer_stmts()
}
if g.defer_profile_code.len > 0 {
g.writeln('')
g.writeln('\t// defer_profile_code')
g.writeln(g.defer_profile_code)
g.writeln('')
}
}
fn (mut g Gen) fn_decl_params(params []ast.Param, scope &ast.Scope, is_variadic bool) ([]string, []string, []bool) {
mut fparams := []string{}
mut fparamtypes := []string{}
mut heap_promoted := []bool{}
if params.len == 0 {
// in C, `()` is untyped, unlike `(void)`
g.write('void')
}
for i, param in params {
mut caname := if param.name == '_' {
g.new_tmp_declaration_name()
} else {
c_name(param.name)
}
mut typ := g.unwrap_generic(param.typ)
if g.pref.translated && g.file.is_translated && param.typ.has_flag(.variadic) {
typ = g.table.sym(typ).array_info().elem_type.set_flag(.variadic)
}
param_type_sym := g.table.sym(typ)
mut param_type_name := g.typ(typ).replace_each(c.c_fn_name_escape_seq)
if param_type_sym.kind == .function && !typ.has_flag(.option) {
info := param_type_sym.info as ast.FnType
func := info.func
g.write('${g.typ(func.return_type)} (*${caname})(')
g.definitions.write_string('${g.typ(func.return_type)} (*${caname})(')
g.fn_decl_params(func.params, unsafe { nil }, func.is_variadic)
g.write(')')
g.definitions.write_string(')')
fparams << caname
fparamtypes << param_type_name
heap_promoted << false
} else {
mut heap_prom := false
if scope != unsafe { nil } {
if param.name != '_' {
if v := scope.find_var(param.name) {
if !v.is_stack_obj && v.is_auto_heap {
heap_prom = true
}
}
}
}
var_name_prefix := if heap_prom { '_v_toheap_' } else { '' }
const_prefix := if param.typ.is_any_kind_of_pointer() && !param.is_mut
&& param.name.starts_with('const_') {
'const '
} else {
''
}
s := '${const_prefix}${param_type_name} ${var_name_prefix}${caname}'
g.write(s)
g.definitions.write_string(s)
fparams << caname
fparamtypes << param_type_name
heap_promoted << heap_prom
}
if i < params.len - 1 {
g.write(', ')
g.definitions.write_string(', ')
}
}
if g.pref.translated && is_variadic {
g.write(', ... ')
g.definitions.write_string(', ... ')
}
return fparams, fparamtypes, heap_promoted
}
fn (mut g Gen) get_anon_fn_type_name(mut node ast.AnonFn, var_name string) string {
mut builder := strings.new_builder(64)
return_styp := g.typ(node.decl.return_type)
builder.write_string('${return_styp} (*${var_name}) (')
if node.decl.params.len == 0 {
builder.write_string('void)')
} else {
for i, param in node.decl.params {
param_styp := g.typ(param.typ)
builder.write_string('${param_styp} ${param.name}')
if i != node.decl.params.len - 1 {
builder.write_string(', ')
}
}
builder.write_string(')')
}
return builder.str()
}
fn (mut g Gen) call_expr(node ast.CallExpr) {
if node.should_be_skipped {
return
}
// NOTE: everything could be done this way
// see my comment in parser near anon_fn
if node.left is ast.AnonFn {
if node.left.inherited_vars.len > 0 {
tmp_var := g.new_tmp_var()
fn_type := g.fn_var_signature(node.left.decl.return_type, node.left.decl.params.map(it.typ),
tmp_var)
line := g.go_before_last_stmt().trim_space()
g.empty_line = true
g.write('${fn_type} = ')
g.expr(node.left)
g.writeln(';')
g.write(line)
if g.out.last_n(1) != '\n' {
g.writeln('')
}
g.write(tmp_var)
} else if node.or_block.kind == .absent {
g.expr(node.left)
}
} else if node.left is ast.IndexExpr && node.name == '' {
g.is_fn_index_call = true
g.expr(node.left)
g.is_fn_index_call = false
} else if !g.inside_curry_call && node.left is ast.CallExpr && node.name == '' {
if node.or_block.kind == .absent {
g.expr(node.left)
} else {
old_inside_curry_call := g.inside_curry_call
g.inside_curry_call = true
ret_typ := node.return_type
line := g.go_before_last_stmt()
g.empty_line = true
tmp_res := g.new_tmp_var()
g.write('${g.typ(ret_typ)} ${tmp_res} = ')
g.last_tmp_call_var << tmp_res
g.expr(node.left)
g.expr(node)
g.inside_curry_call = old_inside_curry_call
g.write(line)
g.write('*(${g.base_type(ret_typ)}*)${tmp_res}.data')
return
}
}
old_inside_call := g.inside_call
g.inside_call = true
defer {
g.inside_call = old_inside_call
}
gen_keep_alive := node.is_keep_alive && node.return_type != ast.void_type
&& g.pref.gc_mode in [.boehm_full, .boehm_incr, .boehm_full_opt, .boehm_incr_opt]
gen_or := node.or_block.kind != .absent // && !g.is_autofree
is_gen_or_and_assign_rhs := gen_or && !g.discard_or_result
mut cur_line := if !g.inside_curry_call && (is_gen_or_and_assign_rhs || gen_keep_alive) { // && !g.is_autofree {
// `x := foo() or { ...}`
// cut everything that has been generated to prepend option variable creation
line := g.go_before_last_stmt()
g.out.write_string(util.tabs(g.indent))
line
} else {
''
}
// g.write('/*EE line="$cur_line"*/')
tmp_opt := if gen_or || gen_keep_alive {
if g.inside_curry_call && g.last_tmp_call_var.len > 0 {
g.last_tmp_call_var.pop()
} else {
g.new_tmp_var()
}
} else {
''
}
if gen_or || gen_keep_alive {
mut ret_typ := node.return_type
if g.table.sym(ret_typ).kind == .alias {
unaliased_type := g.table.unaliased_type(ret_typ)
if unaliased_type.has_option_or_result() {
ret_typ = unaliased_type
}
}
mut styp := g.typ(ret_typ)
if gen_or && !is_gen_or_and_assign_rhs {
cur_line = g.go_before_last_stmt()
}
if gen_or && g.infix_left_var_name.len > 0 {
g.writeln('${styp} ${tmp_opt};')
g.writeln('if (${g.infix_left_var_name}) {')
g.indent++
g.write('${tmp_opt} = ')
} else if !g.inside_curry_call {
if g.assign_ct_type != 0 && node.or_block.kind in [.propagate_option, .propagate_result] {
styp = g.typ(g.assign_ct_type.derive(ret_typ))
}
g.write('${styp} ${tmp_opt} = ')
if node.left is ast.AnonFn {
g.expr(node.left)
}
}
}
if node.is_method && !node.is_field {
if node.name == 'writeln' && g.pref.experimental && node.args.len > 0
&& node.args[0].expr is ast.StringInterLiteral
&& g.table.sym(node.receiver_type).name == 'strings.Builder' {
g.string_inter_literal_sb_optimized(node)
} else {
g.method_call(node)
}
} else {
g.fn_call(node)
}
if gen_or {
g.or_block(tmp_opt, node.or_block, node.return_type)
mut unwrapped_typ := node.return_type.clear_option_and_result()
if g.table.sym(unwrapped_typ).kind == .alias {
unaliased_type := g.table.unaliased_type(unwrapped_typ)
if unaliased_type.has_option_or_result() {
unwrapped_typ = unaliased_type.clear_option_and_result()
}
}
mut unwrapped_styp := g.typ(unwrapped_typ)
if g.infix_left_var_name.len > 0 {
g.indent--
g.writeln('}')
g.set_current_pos_as_last_stmt_pos()
}
if unwrapped_typ == ast.void_type {
g.write('\n ${cur_line}')
} else if !g.inside_curry_call {
if !g.inside_const_opt_or_res {
if g.assign_ct_type != 0
&& node.or_block.kind in [.propagate_option, .propagate_result] {
unwrapped_styp = g.typ(g.assign_ct_type.derive(node.return_type).clear_option_and_result())
}
if g.table.sym(node.return_type).kind == .array_fixed
&& unwrapped_styp.starts_with('_v_') {
unwrapped_styp = unwrapped_styp[3..]
}
g.write('\n ${cur_line} (*(${unwrapped_styp}*)${tmp_opt}.data)')
} else {
g.write('\n ${cur_line} ${tmp_opt}')
}
}
} else if gen_keep_alive {
if node.return_type == ast.void_type {
g.write('\n ${cur_line}')
} else {
g.write('\n ${cur_line} ${tmp_opt}')
}
}
if node.is_noreturn {
if g.inside_ternary == 0 {
g.writeln(';')
g.write('VUNREACHABLE()')
} else {
$if msvc {
// MSVC has no support for the statement expressions used below
} $else {
g.write(', ({VUNREACHABLE();})')
}
}
}
}
fn (mut g Gen) conversion_function_call(prefix string, postfix string, node ast.CallExpr) {
g.write('${prefix}( (')
g.expr(node.left)
dot := if node.left_type.is_ptr() { '->' } else { '.' }
g.write(')${dot}_typ )${postfix}')
}
@[inline]
fn (mut g Gen) gen_arg_from_type(node_type ast.Type, node ast.Expr) {
if node_type.has_flag(.shared_f) {
if node_type.is_ptr() {
g.write('&')
}
g.expr(node)
g.write('->val')
} else {
if node_type.is_ptr() {
g.expr(node)
} else {
g.write('&')
g.expr(node)
}
}
}
fn (mut g Gen) gen_map_method_call(node ast.CallExpr, left_type ast.Type, left_sym ast.TypeSymbol) bool {
match node.name {
'clear' {
g.write('map_clear(')
g.gen_arg_from_type(left_type, node.left)
g.write(')')
return true
}
'delete' {
left_info := left_sym.info as ast.Map
elem_type_str := g.typ(left_info.key_type)
g.write('map_delete(')
g.gen_arg_from_type(left_type, node.left)
g.write(', &(${elem_type_str}[]){')
g.expr(node.args[0].expr)
g.write('})')
return true
}
else {}
}
return false
}
fn (mut g Gen) gen_array_method_call(node ast.CallExpr, left_type ast.Type) bool {
match node.name {
'filter' {
g.gen_array_filter(node)
return true
}
'sort' {
g.gen_array_sort(node)
return true
}
'sorted' {
g.gen_array_sorted(node)
return true
}
'insert' {
g.gen_array_insert(node)
return true
}
'map' {
g.gen_array_map(node)
return true
}
'prepend' {
g.gen_array_prepend(node)
return true
}
'contains' {
g.gen_array_contains(left_type, node.left, node.args[0].typ, node.args[0].expr)
return true