-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc2v.v
2293 lines (2164 loc) · 56.6 KB
/
c2v.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) 2022 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by a GPL license that can
// be found in the LICENSE file.
module main
import os
import strings
import json
import time
import toml
const version = '0.4.0'
// V keywords, that are not keywords in C:
const v_keywords = ['go', 'type', 'true', 'false', 'module', 'byte', 'in', 'none', 'map', 'string',
'spawn', 'shared', 'select', 'as']
// libc fn definitions that have to be skipped (V already knows about them):
const builtin_fn_names = ['fopen', 'puts', 'fflush', 'printf', 'memset', 'atoi', 'memcpy', 'remove',
'strlen', 'rename', 'stdout', 'stderr', 'stdin', 'ftell', 'fclose', 'fread', 'read', 'perror',
'ftruncate', 'FILE', 'strcmp', 'toupper', 'strchr', 'strdup', 'strncasecmp', 'strcasecmp',
'isspace', 'strncmp', 'malloc', 'close', 'open', 'lseek', 'fseek', 'fgets', 'rewind', 'write',
'calloc', 'setenv', 'gets', 'abs', 'sqrt', 'erfl', 'fprintf', 'snprintf', 'exit', '__stderrp',
'fwrite', 'scanf', 'sscanf', 'strrchr', 'strchr', 'div', 'free', 'memcmp', 'memmove', 'vsnprintf',
'rintf', 'rint', 'bsearch', 'qsort']
const builtin_type_names = ['ldiv_t', '__float2', '__double2', 'exception', 'double_t']
const builtin_global_names = ['sys_nerr', 'sys_errlist', 'suboptarg']
const tabs = ['', '\t', '\t\t', '\t\t\t', '\t\t\t\t', '\t\t\t\t\t', '\t\t\t\t\t\t', '\t\t\t\t\t\t\t',
'\t\t\t\t\t\t\t\t', '\t\t\t\t\t\t\t\t\t', '\t\t\t\t\t\t\t\t\t\t', '\t\t\t\t\t\t\t\t\t\t\t',
'\t\t\t\t\t\t\t\t\t\t\t\t', '\t\t\t\t\t\t\t\t\t\t\t\t\t']
const cur_dir = os.getwd()
const clang = find_clang_in_path()
struct Type {
mut:
name string
is_const bool
is_static bool
}
fn find_clang_in_path() string {
clangs := ['clang-17', 'clang-14', 'clang-13', 'clang-12', 'clang-11', 'clang-10', 'clang']
for clang in clangs {
os.find_abs_path_of_executable(clang) or { continue }
return clang
}
panic('cannot find clang in PATH')
}
struct LabelStmt {
name string
}
struct Struct {
mut:
fields []string
}
struct C2V {
mut:
tree Node
is_dir bool // when translating a directory (multiple C=>V files)
c_file_contents string
line_i int
node_i int // when parsing nodes
unhandled_nodes []string // when coming across an unknown Clang AST node
// out stuff
out strings.Builder // os.File
globals_out map[string]string // `globals_out["myglobal"] == "extern int myglobal = 0;"` // strings.Builder
out_file os.File
out_line_empty bool
types []string // to avoid dups
enums []string // to avoid dups
enum_vals map[string][]string // enum_vals['Color'] = ['green', 'blue'], for converting C globals to enum values
structs map[string]Struct // for correct `Foo{field:..., field2:...}` (implicit value init expr is 0, so un-initied fields are just skipped with 0s)
fns []string // to avoid dups
outv string
cur_file string
consts []string
globals map[string]Global
inside_switch int // used to be a bool, a counter to handle switches inside switches
inside_switch_enum bool
inside_for bool // to handle `;;++i`
inside_array_index bool // for enums used as int array index: `if player.weaponowned[.wp_chaingun]`
global_struct_init string
cur_out_line string
inside_main bool
indent int
empty_line bool // for indents
is_wrapper bool
wrapper_module_name string // name of the wrapper module
nm_lines []string
is_verbose bool
skip_parens bool // for skipping unnecessary params like in `enum Foo { bar = (1+2) }`
labels map[string]string // for goto stmts: `label_stmts[label_id] == 'labelname'`
//
project_folder string // the final folder passed on the CLI, or the folder of the last file, passed on the CLI. Will be used for searching for a c2v.toml file, containing project configuration overrides, when the C2V_CONFIG env variable is not set explicitly.
conf toml.Doc = empty_toml_doc() // conf will be set by parsing the TOML configuration file
//
project_output_dirname string // by default, 'c2v_out.dir'; override with `[project] output_dirname = "another"`
project_additional_flags string // what to pass to clang, so that it could parse all the input files; mainly -I directives to find additional headers; override with `[project] additional_flags = "-I/some/folder"`
project_uses_sdl bool // if a project uses sdl, then the additional flags will include the result of `sdl2-config --cflags` too; override with `[project] uses_sdl = true`
file_additional_flags string // can be added per file, appended to project_additional_flags ; override with `['info.c'] additional_flags = -I/xyz`
//
project_globals_path string // where to store the _globals.v file, that will contain all the globals/consts for the project folder; calculated using project_output_dirname and project_folder
//
translations int // how many translations were done so far
translation_start_ticks i64 // initialised before the loop calling .translate_file()
has_cfile bool
returning_bool bool
keep_ast bool // do not delete ast.json after running
already_declared_types map[string]bool // to avoid duplicate type declarations
last_declared_type_name string
}
fn empty_toml_doc() toml.Doc {
return toml.parse_text('') or { panic(err) }
}
struct Global {
name string
typ string
is_extern bool
}
struct NameType {
name string
typ Type
}
fn filter_line(s string) string {
return s.replace('false_', 'false').replace('true_', 'true')
}
pub fn replace_file_extension(file_path string, old_extension string, new_extension string) string {
// NOTE: It can't be just `file_path.replace(old_extenstion, new_extension)`, because it will replace all occurencies of old_extenstion string.
// Path '/dir/dir/dir.c.c.c.c.c.c/kalle.c' will become '/dir/dir/dir.json.json.json.json.json.json/kalle.json'.
return file_path.trim_string_right(old_extension) + new_extension
}
fn add_place_data_to_error(err IError) string {
return '${@MOD}.${@FILE_LINE} - ${err}'
}
fn (mut c C2V) genln(s string) {
if s.starts_with('type ') {
if s in c.already_declared_types {
return
}
c.already_declared_types[s] = true
}
if c.indent > 0 && c.out_line_empty {
c.out.write_string(tabs[c.indent])
}
if c.cur_out_line != '' {
c.out.write_string(filter_line(c.cur_out_line))
c.cur_out_line = ''
}
c.out.writeln(filter_line(s))
c.out_line_empty = true
}
fn (mut c C2V) gen(s string) {
if c.indent > 0 && c.out_line_empty {
c.out.write_string(tabs[c.indent])
}
c.cur_out_line += s
c.out_line_empty = false
}
fn (mut c C2V) save() {
vprintln('\n\n')
mut s := c.out.str()
vprintln('VVVV len=${c.labels.len}')
vprintln(c.labels.str())
// If there are goto statements, replace all placeholders with actual `goto label_name;`
// Because JSON AST doesn't have label names for some reason, just IDs.
if c.labels.len > 0 {
for label_name, label_id in c.labels {
vprintln('"${label_id}" => "${label_name}"')
s = s.replace('_GOTO_PLACEHOLDER_' + label_id, label_name)
}
}
c.out_file.write_string(s) or { panic('failed to write to the .v file: ${err}') }
c.out_file.close()
if s.contains('FILE') {
c.has_cfile = true
}
if !c.is_wrapper && !c.outv.contains('st_lib.v') {
os.system('v fmt -translated -w ${c.outv} > /dev/null')
}
}
// recursive
fn set_kind_enum(mut n Node) {
for mut child in n.inner {
child.kind = convert_str_into_node_kind(child.kind_str)
// unsafe {
// child.parent_node = n
//}
if child.ref_declaration.kind_str != '' {
child.ref_declaration.kind = convert_str_into_node_kind(child.ref_declaration.kind_str)
}
if child.inner.len > 0 {
set_kind_enum(mut child)
}
}
}
fn new_c2v(args []string) &C2V {
mut c2v := &C2V{
is_wrapper: args.len > 1 && args[1] == 'wrapper'
}
c2v.handle_configuration(args)
return c2v
}
fn (mut c2v C2V) add_file(ast_path string, outv string, c_file string) {
vprintln('new tree(outv=${outv} c_file=${c_file})')
c_file_contents := if c_file == '' {
''
} else {
os.read_file(c_file) or { '' }
}
ast_txt := os.read_file(ast_path) or {
vprintln('failed to read ast file "${ast_path}": ${err}')
panic(err)
}
c2v.tree = json.decode(Node, ast_txt) or {
vprintln('failed to decode ast file "${ast_path}": ${err}')
panic(err)
}
c2v.outv = outv
c2v.c_file_contents = c_file_contents
c2v.cur_file = c_file
if c2v.is_wrapper {
// Generate v_wrapper.v in user's current directory
c2v.wrapper_module_name = os.dir(outv).all_after_last('/')
wrapper_path := c2v.outv
c2v.out_file = os.create(wrapper_path) or { panic('cant create file "${wrapper_path}" ') }
} else {
c2v.out_file = os.create(c2v.outv) or {
vprintln('cant create')
panic(err)
}
}
c2v.genln('@[translated]')
// Predeclared identifiers
if !c2v.is_wrapper {
c2v.genln('module main\n')
} else if c2v.is_wrapper {
c2v.genln('module ${c2v.wrapper_module_name}\n')
}
// Convert Clang JSON AST nodes to C2V's nodes with extra info. Skip nodes from libc.
set_kind_enum(mut c2v.tree)
for i, mut node in c2v.tree.inner {
vprintln('\nQQQQ ${i} ${node.name}')
// Builtin types have completely empty "loc" objects:
// `"loc": {}`
// Mark them with `is_std`
if node.is_builtin() {
vprintln('${c2v.line_i} is_std name=${node.name}')
node.is_builtin_type = true
continue
} else if line_is_source(node.location.file) {
vprintln('${c2v.line_i} is_source')
}
// if node.name.contains('mobj_t') {
//}
vprintln('ADDED TOP NODE line_i=${c2v.line_i}')
}
if c2v.unhandled_nodes.len > 0 {
vprintln('GOT SOME UNHANDLED NODES:')
for s in c2v.unhandled_nodes {
vprintln(s)
}
exit(1)
}
}
fn line_is_builtin_header(val string) bool {
return val.contains_any_substr(['usr/include', '/opt/', 'usr/lib', 'usr/local', '/Library/',
'lib/clang'])
}
fn line_is_source(val string) bool {
return val.ends_with('.c')
}
fn (mut c C2V) fn_call(mut node Node) {
expr := node.try_get_next_child() or {
println(add_place_data_to_error(err))
bad_node
}
// vprintln('FN CALL')
c.expr(expr) // this is `fn_name(`
// vprintln(expr.str())
// Clean up macos builtin fn names
// $if macos
is_memcpy := c.cur_out_line.contains('__builtin___memcpy_chk')
is_memmove := c.cur_out_line.contains('__builtin___memmove_chk')
is_memset := c.cur_out_line.contains('__builtin___memset_chk')
if is_memcpy {
c.cur_out_line = c.cur_out_line.replace('__builtin___memcpy_chk', 'C.memcpy')
}
if is_memmove {
c.cur_out_line = c.cur_out_line.replace('__builtin___memmove_chk', 'C.memmove')
}
if is_memset {
c.cur_out_line = c.cur_out_line.replace('__builtin___memset_chk', 'C.memset')
}
if c.cur_out_line.contains('memset') {
vprintln('!! ${c.cur_out_line}')
c.cur_out_line = c.cur_out_line.replace('memset(', 'C.memset(')
}
// Drop last argument if we have memcpy_chk
is_m := is_memcpy || is_memmove || is_memset
len := if is_m { 3 } else { node.inner.len - 1 }
c.gen('(')
for i, arg in node.inner {
if is_m && i > len {
break
}
if i > 0 {
c.expr(arg)
if i < len {
c.gen(', ')
}
}
}
c.gen(')')
}
fn (mut c C2V) fn_decl(mut node Node, gen_types string) {
vprintln('1FN DECL name="${node.name}" cur_file="${c.cur_file}"')
c.inside_main = false
if node.location.file.contains('usr/include') {
vprintln('\nskipping fn:')
vprintln('')
return
}
if c.is_dir && c.cur_file.ends_with('/info.c') {
// TODO tmp doom hack
return
}
// No statements - it's a function declration, skip it
no_stmts := if !node.has_child_of_kind(.compound_stmt) { true } else { false }
vprintln('no_stmts: ${no_stmts}')
for child in node.inner {
vprintln('INNER: ${child.kind} ${child.kind_str}')
}
// Skip C++ tmpl args
if node.has_child_of_kind(.template_argument) {
cnt := node.count_children_of_kind(.template_argument)
for i := 0; i < cnt; i++ {
node.try_get_next_child_of_kind(.template_argument) or {
println(add_place_data_to_error(err))
continue
}
}
}
mut name := node.name
if name in ['invalid', 'referenced'] {
return
}
if !c.contains_word(name) {
vprintln('RRRR ${name} not here, skipping')
// This fn is not found in current .c file, means that it was only
// in the include file, so it's declared and used in some other .c file,
// no need to genenerate it here.
// TODO perf right now this searches an entire .c file for each global.
return
}
if node.ast_type.qualified.contains('...)') {
// TODO handle this better (`...any` ?)
c.genln('@[c2v_variadic]')
}
if name.contains('blkcpy') {
vprintln('GOT FINISH')
}
if c.is_wrapper {
if name in c.fns {
return
}
if name.starts_with('_') {
return
}
if node.class_modifier == 'static' {
// Static functions are limited to their obejct files.
// Cant include them into wrappers. Skip.
vprintln('SKIPPING STATIC')
return
}
}
c.fns << name
mut typ := node.ast_type.qualified.before('(').trim_space()
if typ == 'void' {
typ = ''
} else {
typ = convert_type(typ).name
}
if typ.contains('...') {
c.gen('F')
}
if name == 'main' {
c.inside_main = true
typ = ''
}
if true || name.contains('Vile') {
vprintln('\nFN DECL name="${name}" typ="${typ}"')
}
// Build fn params
params := c.fn_params(mut node)
str_args := if name == 'main' { '' } else { params.join(', ') }
if !no_stmts || c.is_wrapper {
c_name := name + gen_types
if c.is_wrapper {
c.genln('fn C.${c_name}(${str_args}) ${typ}\n')
}
v_name := name.to_lower()
if v_name != c_name && !c.is_wrapper {
c.genln("[c:'${c_name}']")
}
if c.is_wrapper {
// strip the "modulename__" from the start of the function
stripped_name := v_name.replace(c.wrapper_module_name + '_', '')
c.genln('pub fn ${stripped_name}(${str_args}) ${typ} {')
} else {
c.genln('fn ${v_name}(${str_args}) ${typ} {')
}
if !c.is_wrapper {
// For wrapper generation just generate function definitions without bodies
mut stmts := node.try_get_next_child_of_kind(.compound_stmt) or {
println(add_place_data_to_error(err))
bad_node
}
c.statements(mut stmts)
} else if c.is_wrapper {
if typ != '' {
c.gen('\treturn ')
} else {
c.gen('\t')
}
c.gen('C.${c_name}(')
mut i := 0
for param in params {
x := param.trim_space().split(' ')[0]
if x == '' {
continue
}
c.gen(x)
if i < params.len - 1 {
c.gen(', ')
}
i++
}
c.genln(')\n}')
}
} else {
lower := name.to_lower()
if lower != name {
// 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
//
// Now every time `p_trymove` is called, `P_TryMove` will be generated instead.
c.genln("[c:'${name}']")
}
name = lower
c.genln('fn ${name}(${str_args}) ${typ}')
}
c.genln('')
vprintln('END OF FN DECL ast line=${c.line_i}')
}
fn (c &C2V) fn_params(mut node Node) []string {
mut str_args := []string{cap: 5}
nr_params := node.count_children_of_kind(.parm_var_decl)
for i := 0; i < nr_params; i++ {
param := node.try_get_next_child_of_kind(.parm_var_decl) or {
println(add_place_data_to_error(err))
continue
}
arg_typ := convert_type(param.ast_type.qualified)
if arg_typ.name.contains('...') {
vprintln('vararg: ' + arg_typ.name)
}
mut param_name := filter_name(param.name).to_lower().all_after_last('c.')
if param_name == '' {
param_name = 'arg${i}'
}
str_args << '${param_name} ${arg_typ.name}'
}
return str_args
}
// converts a C type to a V type
fn convert_type(typ_ string) Type {
mut typ := typ_
if true || typ.contains('type_t') {
vprintln('\nconvert_type("${typ}")')
}
if typ.contains('__va_list_tag *') {
return Type{
name: 'va_list'
}
}
// TODO DOOM hack
typ = typ.replace('fixed_t', 'int')
is_const := typ.contains('const ')
if is_const {
}
typ = typ.replace('const ', '')
typ = typ.replace('volatile ', '')
typ = typ.replace('std::', '')
if typ == 'char **' {
return Type{
name: '&&u8'
}
}
if typ == 'void *' {
return Type{
name: 'voidptr'
}
} else if typ == 'void **' {
return Type{
name: '&voidptr'
}
} else if typ.starts_with('void *[') {
return Type{
name: '[' + typ.substr('void *['.len, typ.len - 1) + ']voidptr'
}
}
// enum
if typ.starts_with('enum ') {
return Type{
name: typ.substr('enum '.len, typ.len).capitalize()
is_const: is_const
}
}
// int[3]
mut idx := ''
if typ.contains('[') && typ.contains(']') {
if true {
pos := typ.index('[') or { panic('no [ in conver_type(${typ})') }
idx = typ[pos..]
typ = typ[..pos]
} else {
idx = typ.after('[')
idx = '[' + idx
typ = typ.before('[')
}
}
// leveldb::DB
if typ.contains('::') {
typ = typ.after('::')
}
// boolean:boolean
else if typ.contains(':') {
typ = typ.all_before(':')
}
typ = typ.replace(' void *', 'voidptr')
// char*** => ***char
mut base := typ.trim_space().replace_each(['struct ', '']) //, 'signed ', ''])
if base.starts_with('signed ') {
// "signed char" == "char", so just ignore "signed "
base = base['signed '.len..]
}
if base.ends_with('*') {
base = base.before(' *')
}
base = match base {
'long long' {
'i64'
}
'long double' {
'f64'
}
'long' {
'int'
}
'unsigned int' {
'u32'
}
'unsigned long long' {
'i64'
}
'unsigned long' {
'u32'
}
'unsigned char' {
'u8'
}
'*unsigned char' {
'&u8'
}
'unsigned short' {
'u16'
}
'uint32_t' {
'u32'
}
'int32_t' {
'int'
}
'uint64_t' {
'u64'
}
'int64_t' {
'i64'
}
'int16_t' {
'i16'
}
'uint16_t' {
'u16'
}
'uint8_t' {
'u8'
}
'__int64_t' {
'i64'
}
'__int32_t' {
'int'
}
'__uint32_t' {
'u32'
}
'__uint64_t' {
'u64'
}
'short' {
'i16'
}
'char' {
'i8'
}
'float' {
'f32'
}
'double' {
'f64'
}
'byte' {
'u8'
}
// just to avoid capitalizing these:
'int' {
'int'
}
'voidptr' {
'voidptr'
}
'intptr_t' {
'C.intptr_t'
}
'void' {
'void'
}
'u32' {
'u32'
}
'size_t' {
'usize'
}
'ptrdiff_t' {
'isize'
}
'boolean', '_Bool', 'Bool', 'bool (int)', 'bool' {
'bool'
}
'FILE' {
'C.FILE'
}
else {
trim_underscores(base.capitalize())
}
}
mut amps := ''
if typ.ends_with('*') {
star_pos := typ.index('*') or { -1 }
nr_stars := typ[star_pos..].len
amps = strings.repeat(`&`, nr_stars)
typ = amps + base
}
// fn type
// int (*)(void *, int, char **, char **)
// fn (voidptr, int, *byteptr, *byteptr) int
else if typ.contains('(*)') {
ret_typ := convert_type(typ.all_before('('))
mut s := 'fn ('
// move fn to the right place
typ = typ.replace('(*)', ' ')
// handle each arg
sargs := typ.find_between('(', ')')
args := sargs.split(',')
for i, arg in args {
t := convert_type(arg)
s += t.name
if i < args.len - 1 {
s += ', '
}
}
// Function doesn't return anything
if ret_typ.name == 'void' {
typ = s + ')'
} else {
typ = '${s}) ${ret_typ.name}'
}
// C allows having fn(void) instead of fn()
typ = typ.replace('(void)', '()')
} else {
typ = base
}
// User & => &User
if typ.ends_with(' &') {
typ = typ[..typ.len - 2]
base = typ
typ = '&' + typ
}
typ = typ.trim_space()
if typ.contains('&& ') {
typ = typ.replace(' ', '')
}
if typ.contains(' ') {
}
vprintln('"${typ_}" => "${typ}" base="${base}"')
name := idx + typ
return Type{
name: name
is_const: is_const
}
}
fn (mut c C2V) enum_decl(mut node Node) {
// Hack: typedef with the actual enum name is next, parse it and generate "enum NAME {" first
mut enum_name := node.name //''
if c.tree.inner.len > c.node_i + 1 {
next_node := c.tree.inner[c.node_i + 1]
if next_node.kind == .typedef_decl {
enum_name = next_node.name
}
}
if enum_name == 'boolean' {
return
}
if enum_name == '' {
// empty enum means it's just a list of #define'ed consts
c.genln('\nconst ( // empty enum')
} else {
enum_name = enum_name.capitalize().replace('Enum ', '')
if enum_name in c.enums {
return
}
c.genln('enum ${enum_name} {')
}
mut vals := c.enum_vals[enum_name]
for i, mut child in node.inner {
name := filter_name(child.name.to_lower())
vals << name
mut has_anon_generated := false
// empty enum means it's just a list of #define'ed consts
if enum_name == '' {
if !name.starts_with('_') && name !in c.consts {
c.consts << name
c.gen('\t${name}')
has_anon_generated = true
}
} else {
c.gen('\t' + name)
}
// handle custom enum vals, e.g. `MF_SHOOTABLE = 4`
if child.inner.len > 0 {
mut const_expr := child.try_get_next_child() or {
println(add_place_data_to_error(err))
bad_node
}
if const_expr.kind == .constant_expr {
c.gen(' = ')
c.skip_parens = true
c.expr(const_expr.try_get_next_child() or {
println(add_place_data_to_error(err))
bad_node
})
c.skip_parens = false
}
} else if has_anon_generated {
c.gen(' = ${i}')
}
c.genln('')
}
if enum_name != '' {
vprintln('decl enum "${enum_name}" with ${vals.len} vals')
c.enum_vals[enum_name] = vals
c.genln('}\n')
} else {
c.genln(')\n')
}
if enum_name != '' {
c.enums << enum_name
}
}
fn (mut c C2V) statements(mut compound_stmt Node) {
c.indent++
// Each CompoundStmt's child is a statement
for i, _ in compound_stmt.inner {
c.statement(mut compound_stmt.inner[i])
}
c.indent--
c.genln('}')
}
fn (mut c C2V) statements_no_rcbr(mut compound_stmt Node) {
for i, _ in compound_stmt.inner {
c.statement(mut compound_stmt.inner[i])
}
}
fn (mut c C2V) statement(mut child Node) {
if child.kindof(.decl_stmt) {
c.var_decl(mut child)
c.genln('')
} else if child.kindof(.return_stmt) {
c.return_st(mut child)
c.genln('')
} else if child.kindof(.if_stmt) {
c.if_statement(mut child)
} else if child.kindof(.while_stmt) {
c.while_st(mut child)
} else if child.kindof(.for_stmt) {
c.for_st(mut child)
} else if child.kindof(.do_stmt) {
c.do_st(mut child)
} else if child.kindof(.switch_stmt) {
c.switch_st(mut child)
}
// Just { }
else if child.kindof(.compound_stmt) {
c.genln('{')
c.statements(mut child)
} else if child.kindof(.gcc_asm_stmt) {
c.genln('__asm__') // TODO
} else if child.kindof(.goto_stmt) {
c.goto_stmt(child)
} else if child.kindof(.label_stmt) {
label := child.name // child.get_val(-1)
c.labels[child.name] = child.declaration_id
c.genln('// RRRREG ${child.name} id=${child.declaration_id}')
c.genln('${label}: ')
c.statements_no_rcbr(mut child)
}
// C++
else if child.kindof(.cxx_for_range_stmt) {
c.for_range(child)
} else {
c.expr(child)
c.genln('')
}
}
fn (mut c C2V) goto_stmt(node &Node) {
mut label := c.labels[node.label_id]
if label == '' {
label = '_GOTO_PLACEHOLDER_' + node.label_id
}
c.genln('goto ${label} // id: ${node.label_id}')
}
fn (mut c C2V) return_st(mut node Node) {
c.gen('return ')
// returning expression?
if node.inner.len > 0 && !c.inside_main {
expr := node.try_get_next_child() or {
println(add_place_data_to_error(err))
bad_node
}
if expr.kindof(.implicit_cast_expr) {
if expr.ast_type.qualified == 'bool' {
// Handle `return 1` which is actually `return true`
c.returning_bool = true
}
}
c.expr(expr)
c.returning_bool = false
}
}
fn (mut c C2V) if_statement(mut node Node) {
expr := node.try_get_next_child() or {
println(add_place_data_to_error(err))
bad_node
}
c.gen('if ')
c.gen_bool(expr)
// Main if block
mut child := node.try_get_next_child() or {
println(add_place_data_to_error(err))
bad_node
}
if child.kindof(.null_stmt) {
// The if branch body can be empty (`if (foo) ;`)
c.genln(' {}')
} else {
c.st_block(mut child)
}
// Optional else block
mut else_st := node.try_get_next_child() or {
// dont print here not an error optional else
// println(add_place_data_to_error(err))
bad_node
}
if else_st.kindof(.compound_stmt) || else_st.kindof(.return_stmt) {
c.genln('else {')
c.st_block_no_start(mut else_st)
}
// else if
else if else_st.kindof(.if_stmt) {
c.gen('else ')
c.if_statement(mut else_st)
}
// `else expr() ;` else statement in one line without {}
else if !else_st.kindof(.bad) && !else_st.kindof(.null) {
c.genln('else { // 3')
if else_st.kind in [.return_stmt, .do_stmt] {
c.statement(mut else_st)
} else {
c.expr(else_st)
}
c.genln('\n}')
}
}
fn (mut c C2V) while_st(mut node Node) {
c.gen('for ')
expr := node.try_get_next_child() or {
println(add_place_data_to_error(err))
bad_node
}
c.gen_bool(expr)
c.genln(' {')
mut stmts := node.try_get_next_child() or {
println(add_place_data_to_error(err))
bad_node
}
c.st_block_no_start(mut stmts)
}
fn (mut c C2V) for_st(mut node Node) {
c.inside_for = true
c.gen('for ')
// Can be "for (int i = ...)"
if node.has_child_of_kind(.decl_stmt) {
mut decl_stmt := node.try_get_next_child_of_kind(.decl_stmt) or {
println(add_place_data_to_error(err))
bad_node
}
c.var_decl(mut decl_stmt)
}
// Or "for (i = ....)"
else {
expr := node.try_get_next_child() or {
println(add_place_data_to_error(err))
bad_node
}
c.expr(expr)
}