-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
cgen.v
6283 lines (6148 loc) · 180 KB
/
cgen.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-2021 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 os
import strings
import v.ast
import v.table
import v.pref
import v.token
import v.util
import v.depgraph
const (
// NB: some of the words in c_reserved, are not reserved in C,
// but are in C++, or have special meaning in V, thus need escaping too.
c_reserved = ['auto', 'break', 'calloc', 'case', 'char', 'class', 'const', 'continue', 'default',
'delete', 'do', 'double', 'else', 'enum', 'error', 'exit', 'export', 'extern', 'float',
'for', 'free', 'goto', 'if', 'inline', 'int', 'link', 'long', 'malloc', 'namespace', 'new',
'panic', 'register', 'restrict', 'return', 'short', 'signed', 'sizeof', 'static', 'struct',
'switch', 'typedef', 'typename', 'union', 'unix', 'unsigned', 'void', 'volatile', 'while',
'template',
]
// same order as in token.Kind
cmp_str = ['eq', 'ne', 'gt', 'lt', 'ge', 'le']
// when operands are switched
cmp_rev = ['eq', 'ne', 'lt', 'gt', 'le', 'ge']
)
struct Gen {
pref &pref.Preferences
module_built string
mut:
table &table.Table
out strings.Builder
cheaders strings.Builder
includes strings.Builder // all C #includes required by V modules
typedefs strings.Builder
typedefs2 strings.Builder
type_definitions strings.Builder // typedefs, defines etc (everything that goes to the top of the file)
definitions strings.Builder // typedefs, defines etc (everything that goes to the top of the file)
inits map[string]strings.Builder // contents of `void _vinit/2{}`
cleanups map[string]strings.Builder // contents of `void _vcleanup(){}`
gowrappers strings.Builder // all go callsite wrappers
stringliterals strings.Builder // all string literals (they depend on tos3() beeing defined
auto_str_funcs strings.Builder // function bodies of all auto generated _str funcs
comptime_defines strings.Builder // custom defines, given by -d/-define flags on the CLI
pcs_declarations strings.Builder // -prof profile counter declarations for each function
hotcode_definitions strings.Builder // -live declarations & functions
embedded_data strings.Builder // data to embed in the executable/binary
shared_types strings.Builder // shared/lock types
shared_functions strings.Builder // shared constructors
channel_definitions strings.Builder // channel related code
options_typedefs strings.Builder // Option typedefs
options strings.Builder // `Option_xxxx` types
json_forward_decls strings.Builder // json type forward decls
enum_typedefs strings.Builder // enum types
sql_buf strings.Builder // for writing exprs to args via `sqlite3_bind_int()` etc
file ast.File
fn_decl &ast.FnDecl // pointer to the FnDecl we are currently inside otherwise 0
last_fn_c_name string
tmp_count int // counter for unique tmp vars (_tmp1, tmp2 etc)
tmp_count2 int // a separate tmp var counter for autofree fn calls
is_c_call bool // e.g. `C.printf("v")`
is_assign_lhs bool // inside left part of assign expr (for array_set(), etc)
discard_or_result bool // do not safe last ExprStmt of `or` block in tmp variable to defer ongoing expr usage
is_void_expr_stmt bool // ExprStmt whos result is discarded
is_arraymap_set bool // map or array set value state
is_amp bool // for `&Foo{}` to merge PrefixExpr `&` and StructInit `Foo{}`; also for `&byte(0)` etc
is_sql bool // Inside `sql db{}` statement, generating sql instead of C (e.g. `and` instead of `&&` etc)
is_shared bool // for initialization of hidden mutex in `[rw]shared` literals
is_vlines_enabled bool // is it safe to generate #line directives when -g is passed
arraymap_set_pos int // map or array set value position
vlines_path string // set to the proper path for generating #line directives
optionals []string // to avoid duplicates TODO perf, use map
chan_pop_optionals []string // types for `x := <-ch or {...}`
chan_push_optionals []string // types for `ch <- x or {...}`
shareds []int // types with hidden mutex for which decl has been emitted
inside_ternary int // ?: comma separated statements on a single line
inside_map_postfix bool // inside map++/-- postfix expr
inside_map_infix bool // inside map<</+=/-= infix expr
inside_map_index bool
inside_opt_data bool
inside_if_optional bool
ternary_names map[string]string
ternary_level_names map[string][]string
stmt_path_pos []int // positions of each statement start, for inserting C statements before the current statement
skip_stmt_pos bool // for handling if expressions + autofree (since both prepend C statements)
right_is_opt bool
is_autofree bool // false, inside the bodies of fns marked with [manualfree], otherwise === g.pref.autofree
indent int
empty_line bool
is_test bool
assign_op token.Kind // *=, =, etc (for array_set)
defer_stmts []ast.DeferStmt
defer_ifdef string
defer_profile_code string
str_types []string // types that need automatic str() generation
threaded_fns []string // for generating unique wrapper types and fns for `go xxx()`
waiter_fns []string // functions that wait for `go xxx()` to finish
array_fn_definitions []string // array equality functions that have been defined
map_fn_definitions []string // map equality functions that have been defined
struct_fn_definitions []string // struct equality functions that have been defined
sumtype_fn_definitions []string // sumtype equality functions that have been defined
alias_fn_definitions []string // alias equality functions that have been defined
auto_fn_definitions []string // auto generated functions defination list
anon_fn_definitions []string // anon generated functions defination list
sumtype_definitions map[int]bool // `_TypeA_to_sumtype_TypeB()` fns that have been generated
is_json_fn bool // inside json.encode()
json_types []string // to avoid json gen duplicates
pcs []ProfileCounterMeta // -prof profile counter fn_names => fn counter name
is_builtin_mod bool
hotcode_fn_names []string
embedded_files []ast.EmbeddedFile
cur_fn ast.FnDecl
cur_generic_types []table.Type // `int`, `string`, etc in `foo<T>()`
sql_i int
sql_stmt_name string
sql_side SqlExprSide // left or right, to distinguish idents in `name == name`
inside_vweb_tmpl bool
inside_return bool
inside_or_block bool
strs_to_free0 []string // strings.Builder
// strs_to_free []string // strings.Builder
inside_call bool
has_main bool
inside_const bool
comp_for_method string // $for method in T.methods {}
comp_for_field_var string // $for field in T.fields {}; the variable name
comp_for_field_value table.Field // value of the field variable
comp_for_field_type table.Type // type of the field variable inferred from `$if field.typ is T {}`
comptime_var_type_map map[string]table.Type
// tmp_arg_vars_to_free []string
// autofree_pregen map[string]string
// autofree_pregen_buf strings.Builder
// autofree_tmp_vars []string // to avoid redefining the same tmp vars in a single function
called_fn_name string
cur_mod ast.Module
is_js_call bool // for handling a special type arg #1 `json.decode(User, ...)`
is_fn_index_call bool
// nr_vars_to_free int
// doing_autofree_tmp bool
inside_lambda bool
prevent_sum_type_unwrapping_once bool // needed for assign new values to sum type
// used in match multi branch
// TypeOne, TypeTwo {}
// where an aggregate (at least two types) is generated
// sum type deref needs to know which index to deref because unions take care of the correct field
aggregate_type_idx int
returned_var_name string // to detect that a var doesn't need to be freed since it's being returned
branch_parent_pos int // used in BranchStmt (continue/break) for autofree stop position
timers &util.Timers = util.new_timers(false)
force_main_console bool // true when [console] used on fn main()
as_cast_type_names map[string]string // table for type name lookup in runtime (for __as_cast)
obf_table map[string]string
// main_fn_decl_node ast.FnDecl
}
pub fn gen(files []ast.File, table &table.Table, pref &pref.Preferences) string {
// println('start cgen2')
mut module_built := ''
if pref.build_mode == .build_module {
for file in files {
if file.path.contains(pref.path)
&& file.mod.short_name == pref.path.all_after_last(os.path_separator).trim_right(os.path_separator) {
module_built = file.mod.name
break
}
}
}
mut timers_should_print := false
$if time_cgening ? {
timers_should_print = true
}
mut g := Gen{
out: strings.new_builder(512000)
cheaders: strings.new_builder(15000)
includes: strings.new_builder(100)
typedefs: strings.new_builder(100)
typedefs2: strings.new_builder(100)
type_definitions: strings.new_builder(100)
definitions: strings.new_builder(100)
gowrappers: strings.new_builder(100)
stringliterals: strings.new_builder(100)
auto_str_funcs: strings.new_builder(100)
comptime_defines: strings.new_builder(100)
pcs_declarations: strings.new_builder(100)
hotcode_definitions: strings.new_builder(100)
embedded_data: strings.new_builder(1000)
options_typedefs: strings.new_builder(100)
options: strings.new_builder(100)
shared_types: strings.new_builder(100)
shared_functions: strings.new_builder(100)
channel_definitions: strings.new_builder(100)
json_forward_decls: strings.new_builder(100)
enum_typedefs: strings.new_builder(100)
sql_buf: strings.new_builder(100)
table: table
pref: pref
fn_decl: 0
is_autofree: true
indent: -1
module_built: module_built
timers: util.new_timers(timers_should_print)
}
g.timers.start('cgen init')
for mod in g.table.modules {
g.inits[mod] = strings.new_builder(100)
g.cleanups[mod] = strings.new_builder(100)
}
g.init()
g.timers.show('cgen init')
mut tests_inited := false
mut autofree_used := false
for file in files {
g.timers.start('cgen_file $file.path')
g.file = file
if g.pref.is_vlines {
g.vlines_path = util.vlines_escape_path(file.path, g.pref.ccompiler)
}
// println('\ncgen "$g.file.path" nr_stmts=$file.stmts.len')
// building_v := true && (g.file.path.contains('/vlib/') || g.file.path.contains('cmd/v'))
g.is_test = g.pref.is_test
if g.file.path == '' || !g.pref.autofree {
// cgen test or building V
// println('autofree=false')
g.is_autofree = false
} else {
g.is_autofree = true
autofree_used = true
}
// anon fn may include assert and thus this needs
// to be included before any test contents are written
if g.is_test && !tests_inited {
g.write_tests_definitions()
tests_inited = true
}
g.stmts(file.stmts)
// Transfer embedded files
if file.embedded_files.len > 0 {
for path in file.embedded_files {
if path !in g.embedded_files {
g.embedded_files << path
}
}
}
g.timers.show('cgen_file $file.path')
}
g.timers.start('cgen common')
if autofree_used {
g.is_autofree = true // so that void _vcleanup is generated
}
// to make sure type idx's are the same in cached mods
if g.pref.build_mode == .build_module {
for idx, typ in g.table.type_symbols {
if idx == 0 {
continue
}
g.definitions.writeln('int _v_type_idx_${typ.cname}();')
}
} else if g.pref.use_cache {
for idx, typ in g.table.type_symbols {
if idx == 0 {
continue
}
g.definitions.writeln('int _v_type_idx_${typ.cname}() { return $idx; };')
}
}
//
g.dump_expr_definitions()
// v files are finished, what remains is pure C code
g.gen_vlines_reset()
if g.pref.build_mode != .build_module {
// no init in builtin.o
g.write_init_function()
}
g.finish()
mut b := strings.new_builder(640000)
b.write_string(g.hashes())
b.writeln('\n// V comptime_defines:')
b.write_string(g.comptime_defines.str())
b.writeln('\n// V typedefs:')
b.write_string(g.typedefs.str())
b.writeln('\n// V typedefs2:')
b.write_string(g.typedefs2.str())
b.writeln('\n// V cheaders:')
b.write_string(g.cheaders.str())
if g.pcs_declarations.len > 0 {
b.writeln('\n// V profile counters:')
b.write_string(g.pcs_declarations.str())
}
b.writeln('\n// V includes:')
b.write_string(g.includes.str())
b.writeln('\n// Enum definitions:')
b.write_string(g.enum_typedefs.str())
b.writeln('\n// V type definitions:')
b.write_string(g.type_definitions.str())
b.writeln('\n// V shared types:')
b.write_string(g.shared_types.str())
b.writeln('\n// V Option_xxx definitions:')
b.write_string(g.options.str())
b.writeln('\n// V json forward decls:')
b.write_string(g.json_forward_decls.str())
b.writeln('\n// V definitions:')
b.write_string(g.definitions.str())
interface_table := g.interface_table()
if interface_table.len > 0 {
b.writeln('\n// V interface table:')
b.write_string(interface_table)
}
if g.gowrappers.len > 0 {
b.writeln('\n// V gowrappers:')
b.write_string(g.gowrappers.str())
}
if g.hotcode_definitions.len > 0 {
b.writeln('\n// V hotcode definitions:')
b.write_string(g.hotcode_definitions.str())
}
if g.embedded_data.len > 0 {
b.writeln('\n// V embedded data:')
b.write_string(g.embedded_data.str())
}
if g.options_typedefs.len > 0 {
b.writeln('\n// V option typedefs:')
b.write_string(g.options_typedefs.str())
}
if g.shared_functions.len > 0 {
b.writeln('\n// V shared type functions:')
b.write_string(g.shared_functions.str())
b.write_string(c_concurrency_helpers)
}
if g.channel_definitions.len > 0 {
b.writeln('\n// V channel code:')
b.write_string(g.channel_definitions.str())
}
if g.stringliterals.len > 0 {
b.writeln('\n// V stringliterals:')
b.write_string(g.stringliterals.str())
}
if g.auto_str_funcs.len > 0 {
// if g.pref.build_mode != .build_module {
b.writeln('\n// V auto str functions:')
b.write_string(g.auto_str_funcs.str())
// }
}
if g.auto_fn_definitions.len > 0 {
for fn_def in g.auto_fn_definitions {
b.writeln(fn_def)
}
}
if g.anon_fn_definitions.len > 0 {
for fn_def in g.anon_fn_definitions {
b.writeln(fn_def)
}
}
b.writeln('\n// V out')
b.write_string(g.out.str())
b.writeln('\n// THE END.')
g.timers.show('cgen common')
return b.str()
}
pub fn (g &Gen) hashes() string {
mut res := c_commit_hash_default.replace('@@@', util.vhash())
res += c_current_commit_hash_default.replace('@@@', util.githash(g.pref.building_v))
return res
}
pub fn (mut g Gen) init() {
if g.pref.custom_prelude != '' {
g.cheaders.writeln(g.pref.custom_prelude)
} else if !g.pref.no_preludes {
g.cheaders.writeln('// Generated by the V compiler')
tcc_undef_has_include := '
#if defined(__TINYC__) && defined(__has_include)
// tcc does not support has_include properly yet, turn it off completely
#undef __has_include
#endif'
g.cheaders.writeln(tcc_undef_has_include)
g.includes.writeln(tcc_undef_has_include)
g.cheaders.writeln(get_guarded_include_text('<inttypes.h>', 'The C compiler can not find <inttypes.h> . Please install build-essentials')) // int64_t etc
g.cheaders.writeln(c_builtin_types)
if g.pref.is_bare {
g.cheaders.writeln(bare_c_headers)
} else {
g.cheaders.writeln(c_headers)
}
g.definitions.writeln('void _STR_PRINT_ARG(const char*, char**, int*, int*, int, ...);')
g.definitions.writeln('string _STR(const char*, int, ...);')
g.definitions.writeln('string _STR_TMP(const char*, ...);')
}
if g.pref.os == .ios {
g.cheaders.writeln('#define __TARGET_IOS__ 1')
g.cheaders.writeln('#include <spawn.h>')
}
g.write_builtin_types()
g.write_typedef_types()
g.write_typeof_functions()
if g.pref.build_mode != .build_module {
// _STR functions should not be defined in builtin.o
g.write_str_fn_definitions()
}
g.write_sorted_types()
g.write_multi_return_types()
g.definitions.writeln('// end of definitions #endif')
//
g.stringliterals.writeln('')
g.stringliterals.writeln('// >> string literal consts')
if g.pref.build_mode != .build_module {
g.stringliterals.writeln('void vinit_string_literals(){')
}
if g.pref.compile_defines_all.len > 0 {
g.comptime_defines.writeln('// V compile time defines by -d or -define flags:')
g.comptime_defines.writeln('// All custom defines : ' +
g.pref.compile_defines_all.join(','))
g.comptime_defines.writeln('// Turned ON custom defines: ' +
g.pref.compile_defines.join(','))
for cdefine in g.pref.compile_defines {
g.comptime_defines.writeln('#define CUSTOM_DEFINE_$cdefine')
}
g.comptime_defines.writeln('')
}
if g.pref.gc_mode in [.boehm, .boehm_leak] {
g.comptime_defines.writeln('#define _VGCBOEHM (1)')
}
if g.pref.is_debug || 'debug' in g.pref.compile_defines {
g.comptime_defines.writeln('#define _VDEBUG (1)')
}
if g.pref.is_prod || 'prod' in g.pref.compile_defines {
g.comptime_defines.writeln('#define _VPROD (1)')
}
if g.pref.is_test || 'test' in g.pref.compile_defines {
g.comptime_defines.writeln('#define _VTEST (1)')
}
if g.pref.autofree {
g.comptime_defines.writeln('#define _VAUTOFREE (1)')
// g.comptime_defines.writeln('unsigned char* g_cur_str;')
}
if g.pref.prealloc {
g.comptime_defines.writeln('#define _VPREALLOC (1)')
}
if g.pref.is_livemain || g.pref.is_liveshared {
g.generate_hotcode_reloading_declarations()
}
// Obfuscate only functions in the main module for now.
// Generate the obf_table.
if g.pref.obfuscate {
mut i := 0
// fns
for key, f in g.table.fns {
if f.mod != 'main' && key != 'main' { // !key.starts_with('main.') {
continue
}
g.obf_table[key] = '_f$i'
i++
}
// methods
for type_sym in g.table.type_symbols {
if type_sym.mod != 'main' {
continue
}
for method in type_sym.methods {
g.obf_table[type_sym.name + '.' + method.name] = '_f$i'
i++
}
}
}
}
pub fn (mut g Gen) finish() {
if g.pref.build_mode != .build_module {
g.stringliterals.writeln('}')
}
g.stringliterals.writeln('// << string literal consts')
g.stringliterals.writeln('')
if g.pref.is_prof && g.pref.build_mode != .build_module {
g.gen_vprint_profile_stats()
}
if g.pref.is_livemain || g.pref.is_liveshared {
g.generate_hotcode_reloader_code()
}
if g.embed_file_is_prod_mode() && g.embedded_files.len > 0 {
g.gen_embedded_data()
}
if g.pref.is_test {
g.gen_c_main_for_tests()
} else {
g.gen_c_main()
}
}
pub fn (mut g Gen) write_typeof_functions() {
g.writeln('')
g.writeln('// >> typeof() support for sum types / interfaces')
for typ in g.table.type_symbols {
if typ.kind == .sum_type {
sum_info := typ.info as table.SumType
g.writeln('static char * v_typeof_sumtype_${typ.cname}(int sidx) { /* $typ.name */ ')
if g.pref.build_mode == .build_module {
g.writeln('\t\tif( sidx == _v_type_idx_${typ.cname}() ) return "${util.strip_main_name(typ.name)}";')
for v in sum_info.variants {
subtype := g.table.get_type_symbol(v)
g.writeln('\tif( sidx == _v_type_idx_${subtype.cname}() ) return "${util.strip_main_name(subtype.name)}";')
}
g.writeln('\treturn "unknown ${util.strip_main_name(typ.name)}";')
} else {
tidx := g.table.find_type_idx(typ.name)
g.writeln('\tswitch(sidx) {')
g.writeln('\t\tcase $tidx: return "${util.strip_main_name(typ.name)}";')
for v in sum_info.variants {
subtype := g.table.get_type_symbol(v)
g.writeln('\t\tcase $v: return "${util.strip_main_name(subtype.name)}";')
}
g.writeln('\t\tdefault: return "unknown ${util.strip_main_name(typ.name)}";')
g.writeln('\t}')
}
g.writeln('}')
} else if typ.kind == .interface_ {
inter_info := typ.info as table.Interface
g.writeln('static char * v_typeof_interface_${typ.cname}(int sidx) { /* $typ.name */ ')
for t in inter_info.types {
subtype := g.table.get_type_symbol(t)
g.writeln('\tif (sidx == _${typ.cname}_${subtype.cname}_index) return "${util.strip_main_name(subtype.name)}";')
}
g.writeln('\treturn "unknown ${util.strip_main_name(typ.name)}";')
g.writeln('}')
}
}
g.writeln('// << typeof() support for sum types')
g.writeln('')
}
// V type to C typecc
fn (mut g Gen) typ(t table.Type) string {
styp := g.base_type(t)
if t.has_flag(.optional) {
// Register an optional if it's not registered yet
return g.register_optional(t)
}
/*
if styp.starts_with('C__') {
return styp[3..]
}
*/
return styp
}
fn (mut g Gen) base_type(t table.Type) string {
share := t.share()
mut styp := if share == .atomic_t { t.atomic_typename() } else { g.cc_type(t, true) }
if t.has_flag(.shared_f) {
styp = g.find_or_register_shared(t, styp)
}
nr_muls := t.nr_muls()
if nr_muls > 0 {
styp += strings.repeat(`*`, nr_muls)
}
return styp
}
fn (mut g Gen) expr_string(expr ast.Expr) string {
pos := g.out.len
g.expr(expr)
expr_str := g.out.after(pos)
g.out.go_back(expr_str.len)
return expr_str.trim_space()
}
// TODO this really shouldnt be seperate from typ
// but I(emily) would rather have this generation
// all unified in one place so that it doesnt break
// if one location changes
fn (mut g Gen) optional_type_name(t table.Type) (string, string) {
base := g.base_type(t)
mut styp := 'Option_$base'
if t.is_ptr() {
styp = styp.replace('*', '_ptr')
}
return styp, base
}
fn (g &Gen) optional_type_text(styp string, base string) string {
// replace void with something else
size := if base == 'void' { 'byte' } else { base }
ret := 'struct $styp {
byte state;
IError err;
byte data[sizeof($size)];
}'
return ret
}
fn (mut g Gen) register_optional(t table.Type) string {
styp, base := g.optional_type_name(t)
if styp !in g.optionals {
g.typedefs2.writeln('typedef struct $styp $styp;')
g.options.write_string(g.optional_type_text(styp, base))
g.options.writeln(';\n')
g.optionals << styp.clone()
}
return styp
}
fn (mut g Gen) find_or_register_shared(t table.Type, base string) string {
sh_typ := '__shared__$base'
t_idx := t.idx()
if t_idx in g.shareds {
return sh_typ
}
mtx_typ := 'sync__RwMutex'
g.shared_types.writeln('struct $sh_typ { $base val; $mtx_typ mtx; };')
g.shared_functions.writeln('static inline voidptr __dup${sh_typ}(voidptr src, int sz) {')
g.shared_functions.writeln('\t$sh_typ* dest = memdup(src, sz);')
g.shared_functions.writeln('\tsync__RwMutex_init(&dest->mtx);')
g.shared_functions.writeln('\treturn dest;')
g.shared_functions.writeln('}')
g.typedefs2.writeln('typedef struct $sh_typ $sh_typ;')
// println('registered shared type $sh_typ')
g.shareds << t_idx
return sh_typ
}
fn (mut g Gen) register_thread_array_wait_call(eltyp string) string {
is_void := eltyp == 'void'
thread_typ := if is_void { '__v_thread' } else { '__v_thread_$eltyp' }
ret_typ := if is_void { 'void' } else { 'Array_$eltyp' }
thread_arr_typ := 'Array_$thread_typ'
fn_name := '${thread_arr_typ}_wait'
if fn_name !in g.waiter_fns {
g.waiter_fns << fn_name
if is_void {
g.gowrappers.writeln('
void ${fn_name}($thread_arr_typ a) {
for (int i = 0; i < a.len; ++i) {
$thread_typ t = (($thread_typ*)a.data)[i];
__v_thread_wait(t);
}
}')
} else {
g.gowrappers.writeln('
$ret_typ ${fn_name}($thread_arr_typ a) {
$ret_typ res = __new_array_with_default(a.len, a.len, sizeof($eltyp), 0);
for (int i = 0; i < a.len; ++i) {
$thread_typ t = (($thread_typ*)a.data)[i];
(($eltyp*)res.data)[i] = __v_thread_${eltyp}_wait(t);
}
return res;
}')
}
}
return fn_name
}
fn (mut g Gen) register_chan_pop_optional_call(opt_el_type string, styp string) {
if opt_el_type !in g.chan_pop_optionals {
g.chan_pop_optionals << opt_el_type
g.channel_definitions.writeln('
static inline $opt_el_type __Option_${styp}_popval($styp ch) {
$opt_el_type _tmp = {0};
if (sync__Channel_try_pop_priv(ch, _tmp.data, false)) {
return ($opt_el_type){ .state = 2, .err = v_error(_SLIT("channel closed")) };
}
return _tmp;
}')
}
}
fn (mut g Gen) register_chan_push_optional_call(el_type string, styp string) {
if styp !in g.chan_push_optionals {
g.chan_push_optionals << styp
g.channel_definitions.writeln('
static inline Option_void __Option_${styp}_pushval($styp ch, $el_type e) {
if (sync__Channel_try_push_priv(ch, &e, false)) {
return (Option_void){ .state = 2, .err = v_error(_SLIT("channel closed")) };
}
return (Option_void){0};
}')
}
}
// cc_type whether to prefix 'struct' or not (C__Foo -> struct Foo)
fn (g &Gen) cc_type(typ table.Type, is_prefix_struct bool) string {
sym := g.table.get_type_symbol(g.unwrap_generic(typ))
mut styp := sym.cname
// TODO: this needs to be removed; cgen shouldn't resolve generic types (job of checker)
if mut sym.info is table.Struct {
if sym.info.generic_types.len > 0 {
mut sgtyps := '_T'
for gt in sym.info.generic_types {
gts := g.table.get_type_symbol(if gt.has_flag(.generic) {
g.unwrap_generic(gt)
} else {
gt
})
sgtyps += '_$gts.cname'
}
styp += sgtyps
}
} else if mut sym.info is table.MultiReturn {
// TODO: this doesn't belong here, but makes it working for now
mut cname := 'multi_return'
for mr_typ in sym.info.types {
mr_type_sym := g.table.get_type_symbol(g.unwrap_generic(mr_typ))
cname += '_$mr_type_sym.cname'
}
return cname
}
if is_prefix_struct && styp.starts_with('C__') {
styp = styp[3..]
if sym.kind == .struct_ {
info := sym.info as table.Struct
if !info.is_typedef {
styp = 'struct $styp'
}
}
}
return styp
}
[inline]
fn (g &Gen) type_sidx(t table.Type) string {
if g.pref.build_mode == .build_module {
sym := g.table.get_type_symbol(t)
return '_v_type_idx_${sym.cname}()'
}
return '$t.idx()'
}
//
pub fn (mut g Gen) write_typedef_types() {
for typ in g.table.type_symbols {
if typ.name in c.builtins {
continue
}
match typ.kind {
.alias {
parent := unsafe { &g.table.type_symbols[typ.parent_idx] }
is_c_parent := parent.name.len > 2 && parent.name[0] == `C` && parent.name[1] == `.`
mut is_typedef := false
if parent.info is table.Struct {
is_typedef = parent.info.is_typedef
}
mut parent_styp := parent.cname
if is_c_parent {
if !is_typedef {
parent_styp = 'struct ' + parent.cname[3..]
} else {
parent_styp = parent.cname[3..]
}
} else {
if typ.info is table.Alias {
parent_styp = g.typ(typ.info.parent_type)
}
}
g.type_definitions.writeln('typedef $parent_styp $typ.cname;')
}
.array {
g.type_definitions.writeln('typedef array $typ.cname;')
}
.interface_ {
g.write_interface_typesymbol_declaration(typ)
}
.chan {
if typ.name != 'chan' {
g.type_definitions.writeln('typedef chan $typ.cname;')
chan_inf := typ.chan_info()
chan_elem_type := chan_inf.elem_type
if !chan_elem_type.has_flag(.generic) {
el_stype := g.typ(chan_elem_type)
g.channel_definitions.writeln('
static inline $el_stype __${typ.cname}_popval($typ.cname ch) {
$el_stype val;
sync__Channel_try_pop_priv(ch, &val, false);
return val;
}')
g.channel_definitions.writeln('
static inline void __${typ.cname}_pushval($typ.cname ch, $el_stype val) {
sync__Channel_try_push_priv(ch, &val, false);
}')
}
}
}
.map {
g.type_definitions.writeln('typedef map $typ.cname;')
}
.function {
g.write_fn_typesymbol_declaration(typ)
}
else {
continue
}
}
}
}
pub fn (mut g Gen) write_interface_typesymbol_declaration(sym table.TypeSymbol) {
info := sym.info as table.Interface
g.type_definitions.writeln('typedef struct {')
g.type_definitions.writeln('\tvoid* _object;')
g.type_definitions.writeln('\tint _interface_idx;')
for field in info.fields {
styp := g.typ(field.typ)
cname := c_name(field.name)
g.type_definitions.writeln('\t$styp* $cname;')
}
g.type_definitions.writeln('} ${c_name(sym.name)};\n')
}
pub fn (mut g Gen) write_fn_typesymbol_declaration(sym table.TypeSymbol) {
info := sym.info as table.FnType
func := info.func
is_fn_sig := func.name == ''
not_anon := !info.is_anon
if !info.has_decl && (not_anon || is_fn_sig) && !func.return_type.has_flag(.generic) {
fn_name := sym.cname
g.type_definitions.write_string('typedef ${g.typ(func.return_type)} (*$fn_name)(')
for i, param in func.params {
g.type_definitions.write_string(g.typ(param.typ))
if i < func.params.len - 1 {
g.type_definitions.write_string(',')
}
}
g.type_definitions.writeln(');')
}
}
pub fn (mut g Gen) write_multi_return_types() {
g.typedefs.writeln('\n// BEGIN_multi_return_typedefs')
g.type_definitions.writeln('\n// BEGIN_multi_return_structs')
for sym in g.table.type_symbols {
if sym.kind != .multi_return {
continue
}
info := sym.mr_info()
if info.types.filter(it.has_flag(.generic)).len > 0 {
continue
}
g.typedefs.writeln('typedef struct $sym.cname $sym.cname;')
g.type_definitions.writeln('struct $sym.cname {')
for i, mr_typ in info.types {
type_name := g.typ(mr_typ)
g.type_definitions.writeln('\t$type_name arg$i;')
}
g.type_definitions.writeln('};\n')
}
g.typedefs.writeln('// END_multi_return_typedefs\n')
g.type_definitions.writeln('// END_multi_return_structs\n')
}
pub fn (mut g Gen) write(s string) {
$if trace_gen ? {
eprintln('gen file: ${g.file.path:-30} | last_fn_c_name: ${g.last_fn_c_name:-45} | write: $s')
}
if g.indent > 0 && g.empty_line {
g.out.write_string(util.tabs(g.indent))
}
g.out.write_string(s)
g.empty_line = false
}
pub fn (mut g Gen) writeln(s string) {
$if trace_gen ? {
eprintln('gen file: ${g.file.path:-30} | last_fn_c_name: ${g.last_fn_c_name:-45} | writeln: $s')
}
if g.indent > 0 && g.empty_line {
g.out.write_string(util.tabs(g.indent))
}
g.out.writeln(s)
g.empty_line = true
}
pub fn (mut g Gen) new_tmp_var() string {
g.tmp_count++
return '_t$g.tmp_count'
}
pub fn (mut g Gen) current_tmp_var() string {
return '_t$g.tmp_count'
}
/*
pub fn (mut g Gen) new_tmp_var2() string {
g.tmp_count2++
return '_tt$g.tmp_count2'
}
*/
pub fn (mut g Gen) reset_tmp_count() {
g.tmp_count = 0
}
fn (mut g Gen) decrement_inside_ternary() {
key := g.inside_ternary.str()
for name in g.ternary_level_names[key] {
g.ternary_names.delete(name)
}
g.ternary_level_names.delete(key)
g.inside_ternary--
}
fn (mut g Gen) stmts(stmts []ast.Stmt) {
g.stmts_with_tmp_var(stmts, '')
}
// tmp_var is used in `if` expressions only
fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) {
g.indent++
if g.inside_ternary > 0 {
g.write('(')
}
for i, stmt in stmts {
if i == stmts.len - 1 && tmp_var != '' {
// Handle if expressions, set the value of the last expression to the temp var.
if g.inside_if_optional {
g.stmt_path_pos << g.out.len
g.skip_stmt_pos = true
if stmt is ast.ExprStmt {
if stmt.typ == table.error_type_idx || stmt.expr is ast.None {
g.writeln('${tmp_var}.state = 2;')
g.write('${tmp_var}.err = ')
g.expr(stmt.expr)
g.writeln(';')
} else {
mut styp := g.base_type(stmt.typ)
$if tinyc && x32 && windows {
if stmt.typ == table.int_literal_type {
styp = 'int'
} else if stmt.typ == table.float_literal_type {
styp = 'f64'
}
}
g.write('opt_ok(&($styp[]) { ')
g.stmt(stmt)
g.writeln(' }, (Option*)(&$tmp_var), sizeof($styp));')
}
}
} else {
g.stmt_path_pos << g.out.len
g.skip_stmt_pos = true
g.write('$tmp_var = ')
g.stmt(stmt)
}
} else {
g.stmt(stmt)
if g.inside_if_optional && stmt is ast.ExprStmt {
g.writeln(';')
}
}
g.skip_stmt_pos = false
if g.inside_ternary > 0 && i < stmts.len - 1 {
g.write(',')
}
}
g.indent--
if g.inside_ternary > 0 {
g.write('')
g.write(')')
}
if g.is_autofree && !g.inside_vweb_tmpl && stmts.len > 0 {
// use the first stmt to get the scope
stmt := stmts[0]
// stmt := stmts[stmts.len-1]
if stmt !is ast.FnDecl && g.inside_ternary == 0 {
// g.writeln('// autofree scope')
// g.writeln('// autofree_scope_vars($stmt.pos.pos) | ${typeof(stmt)}')
// go back 1 position is important so we dont get the
// internal scope of for loops and possibly other nodes
// g.autofree_scope_vars(stmt.pos.pos - 1)
mut stmt_pos := stmt.pos
if stmt_pos.pos == 0 {
// Do not autofree if the position is 0, since the correct scope won't be found.
// Report a bug, since position shouldn't be 0 for most nodes.
if stmt is ast.Module {
return
}
if stmt is ast.ExprStmt {
// For some reason ExprStmt.pos is 0 when ExprStmt.expr is comp if expr
// Extract the pos. TODO figure out why and fix.
stmt_pos = stmt.expr.position()
}
if stmt_pos.pos == 0 {
$if trace_autofree ? {
println('autofree: first stmt pos = 0. $stmt.type_name()')
}
return
}
}
g.autofree_scope_vars(stmt_pos.pos - 1, stmt_pos.line_nr, false)
}
}
}
[inline]
fn (mut g Gen) write_v_source_line_info(pos token.Position) {
if g.inside_ternary == 0 && g.pref.is_vlines && g.is_vlines_enabled {
nline := pos.line_nr + 1
lineinfo := '\n#line $nline "$g.vlines_path"'
g.writeln(lineinfo)