-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathstruct.v
More file actions
711 lines (688 loc) · 17.5 KB
/
struct.v
File metadata and controls
711 lines (688 loc) · 17.5 KB
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
// Copyright (c) 2024 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by a GPL license that can be found in the LICENSE file.
fn (mut app App) gen_decl(decl GenDecl) {
app.comments(decl.doc)
// Reset iota value at the start of a const block
if decl.tok == 'const' {
app.current_iota_value = 0
app.in_const_block = true
app.last_const_expr = InvalidExpr{}
}
for spec in decl.specs {
match spec {
ImportSpec {
app.import_spec(spec)
}
TypeSpec {
match spec.typ {
InterfaceType {
app.interface_decl(spec.name.name, spec.typ)
}
StructType {
// Add both original and capitalized names to struct_or_alias
// so go2v_ident can recognize them and capitalize properly
app.struct_or_alias << spec.name.name
if !spec.name.name[0].is_capital() {
app.struct_or_alias << spec.name.name.capitalize()
}
app.struct_decl(spec.name.name, spec.typ)
}
else {
app.type_decl(spec)
}
}
}
ValueSpec {
// Note: spec.typ is Type sumtype now
match decl.tok {
'var' {
// app.genln('// ValueSpec global')
app.global_decl(spec)
}
else {
// app.genln('// VA const')
app.const_decl(spec)
// Increment iota for next const in block
app.current_iota_value++
}
}
}
}
}
app.in_const_block = false
// if needs_closer {
if app.is_enum_decl {
app.genln('}')
}
app.is_enum_decl = false
}
fn (mut app App) type_decl(spec TypeSpec) {
// Remember the type name for the upcoming const (enum) handler if it's an enum
name := spec.name.name
// V requires type aliases to start with a capital letter
mut v_name := name.capitalize()
// If only 1 char in name, double it
if v_name.len == 1 {
v_name += v_name
}
// Store alias info
app.struct_or_alias << name
app.struct_or_alias << v_name
// Track if this is an array type alias
if spec.typ is ArrayType {
app.array_type_aliases[name] = true
app.array_type_aliases[v_name] = true
}
// If this type will become an enum (detected by pre-scan), skip the type alias
if name in app.enum_types {
app.type_decl_name = name
return
}
// Generate actual type alias
app.gen('type ${v_name} = ')
app.typ(spec.typ)
app.genln('')
}
fn (mut app App) global_decl(spec ValueSpec) {
for name in spec.names {
// V globals must be snake_case (no uppercase letters allowed)
v_name := name.name.camel_to_snake()
// Handle anonymous struct types - generate struct definition first
if spec.typ is StructType {
struct_name := '${v_name.capitalize()}_Type'
// Generate the struct definition
app.genln('pub struct ${struct_name} {')
app.genln('pub mut:')
st := spec.typ as StructType
for field in st.fields.list {
for n in field.names {
app.gen('\t')
app.gen(app.go2v_ident(n.name.camel_to_snake()))
app.gen(' ')
app.typ(field.typ)
app.genln('')
}
}
app.genln('}')
// Now generate the global with the struct type
app.genln('__global ${v_name} ${struct_name}')
continue
}
app.gen('__global ${v_name}')
match spec.typ {
Ident {
app.gen(' ')
ident := spec.typ as Ident
app.genln(go2v_type(ident.name))
}
SelectorExpr {
app.gen(' ')
app.force_upper = true
app.selector_expr(spec.typ)
app.genln('')
}
StarExpr {
app.gen(' ')
app.typ(spec.typ)
app.genln('')
}
ArrayType {
app.gen(' ')
app.typ(spec.typ)
app.genln('')
}
MapType {
app.gen(' ')
app.typ(spec.typ)
app.genln('')
}
FuncType {
app.gen(' ')
app.typ(spec.typ)
app.genln('')
}
InvalidExpr {
app.gen(' = ')
if spec.values.len > 0 {
app.expr(spec.values[0])
}
app.genln('')
}
else {
// For other type nodes, try to use value or leave blank
if spec.values.len > 0 {
app.gen(' = ')
app.expr(spec.values[0])
app.genln('')
} else {
app.genln(' voidptr // TODO: unknown type')
}
}
}
}
}
fn (mut app App) const_decl(spec ValueSpec) {
// Handle iota (V enum) - check if this const block uses iota
// Only start a new enum if we're not already in one
// Don't generate enum for bitflag patterns (1 << iota)
if !app.is_enum_decl && spec.values.len > 0 {
first_val := spec.values[0]
if app.contains_iota(first_val) && !app.is_bitflag_pattern(first_val) {
app.is_enum_decl = true
// Use the type from the spec if available (for cases like `const X SomeType = iota`)
// Otherwise fall back to type_decl_name or generate from first const name
mut enum_name := if spec.typ is Ident {
ident := spec.typ as Ident
if ident.name != '' {
ident.name
} else {
''
}
} else {
''
}
if enum_name == '' {
enum_name = if app.type_decl_name != '' {
app.type_decl_name
} else if spec.names.len > 0 {
// Generate synthetic enum name from first const name
spec.names[0].name.capitalize() + 'Enum'
} else {
'UnnamedEnum'
}
}
// Single letter names need to be doubled (V requires > 1 char)
if enum_name.len == 1 {
enum_name = enum_name.capitalize() + enum_name.capitalize()
}
app.genln('enum ${enum_name} {')
}
}
for i, name in spec.names {
if !app.is_enum_decl && name.name.starts_with_capital() {
app.gen('pub ')
}
n := app.go2v_ident(name.name)
if app.is_enum_decl {
// Track this enum value for later use in match expressions
app.enum_values[n] = true
// Handle enum values - check if there's an explicit value
if i < spec.values.len {
val := spec.values[i]
if val is BasicLit {
// Explicit value like `= 5`
app.gen(n)
app.gen(' = ')
app.basic_lit(val)
app.genln('')
continue
} else if val is Ident && val.name == 'iota' {
// Just iota, output the name
app.genln(n)
continue
}
}
// No explicit value, just output the name
app.genln(n)
} else {
app.gen('const ${n} = ')
// Check if there's an explicit type that needs casting (e.g., uint64)
mut needs_cast := false
mut cast_type := ''
if spec.typ is Ident {
ident := spec.typ as Ident
// Types that need explicit casting to avoid overflow
if ident.name in ['uint64', 'int64', 'uint32', 'int32', 'uint16', 'int16', 'uint8',
'int8'] {
needs_cast = true
cast_type = go2v_type(ident.name)
}
}
if needs_cast {
app.gen('${cast_type}(')
}
if i < spec.values.len {
app.last_const_expr = spec.values[i]
app.expr(spec.values[i])
} else if app.last_const_expr !is InvalidExpr {
// Reuse last expression for iota patterns without explicit value
app.expr(app.last_const_expr)
}
if needs_cast {
app.gen(')')
}
app.genln('')
}
}
}
// TODO hardcoded esbuild paths
const master_module_paths = ['github.com.evanw.esbuild']
fn (mut app App) import_spec(spec ImportSpec) {
mut name := spec.path.value.replace('"', '').replace('/', '.')
// Skip modules that don't exist in V (fmt, strings etc)
if name in nonexistent_modules {
return
}
// Skip modules with V keywords in their names
if name.contains('.sql') || name == 'database.sql' {
return
}
// Skip modules that don't have V equivalents
// Note: 'bytes' and 'strings' are translated to V string methods, no import needed
if name in ['bufio', 'mime.multipart', 'sync.atomic', 'runtime.debug', 'runtime.pprof',
'runtime.trace', 'sort', 'runtime', 'syscall', 'errors', 'archive.zip', 'unicode', 'bytes',
'strings'] {
return
}
// Go's os/user package maps to V's os module
if name == 'os.user' {
name = 'os'
}
// Go to V module mappings
match name {
'compress.flate' {
name = 'compress.deflate'
}
'container.list' {
name = 'datatypes'
}
'io.ioutil' {
name = 'io.util'
}
'math.rand' {
name = 'rand'
}
'mime' {
name = 'net.http.mime'
}
'net.url' {
// Use alias to maintain 'url' usage in code
if 'net.urllib' in app.imported_modules {
return
}
app.imported_modules['net.urllib'] = true
app.genln('import net.urllib as url')
return
}
'unicode.utf8' {
name = 'encoding.utf8'
}
'net.http.cookiejar' {
name = 'net.http'
}
'regexp' {
// V's regex module is called 'regex', use alias to maintain 'regexp' usage
if 'regex' in app.imported_modules {
return
}
app.imported_modules['regex'] = true
app.genln('import regex as regexp')
return
}
else {}
}
// Check if it's a local module (internal or pkg)
for master_module_path in master_module_paths {
if name.starts_with(master_module_path) {
mut n := name.replace(master_module_path, '')[1..] // Remove leading dot
// Flatten the module structure - remove internal/ and pkg/ prefixes
// This avoids V module resolution issues with nested directories
n = n.replace('internal.', '').replace('pkg.', '')
if n in app.imported_modules {
return
}
app.imported_modules[n] = true
app.gen('import ${n}')
if spec.name.name != '' {
app.gen(' as ${spec.name.name}')
}
app.genln(' // local module')
return
}
}
// Handle golang.org/x/ imports by stripping the prefix
if name.starts_with('golang.org.x.') {
n := name.replace('golang.org.x.', '')
// Skip golang.org/x/ modules that don't exist in V
if n.starts_with('sys') {
return
}
if n in app.imported_modules {
return
}
app.imported_modules[n] = true
app.gen('import ${n}')
if spec.name.name != '' {
app.gen(' as ${spec.name.name}')
}
app.genln('')
return
}
// TODO a temp hack
if name.starts_with('github') {
return
}
// Skip if already imported (avoid duplicates like os and os.user both importing os)
if name in app.imported_modules {
return
}
app.imported_modules[name] = true
app.gen('import ${name}')
if spec.name.name != '' {
app.gen(' as ${spec.name.name}')
}
app.genln('')
}
fn (mut app App) struct_decl(struct_name string, spec StructType) {
// Convert struct name - V requires struct names to start with capital letter
// and single letter names need to be doubled (V requires > 1 char)
mut v_struct_name := struct_name.capitalize()
if struct_name.len == 1 {
v_struct_name = struct_name.capitalize() + struct_name.capitalize()
}
// Check for type name conflicts with V's standard library
if renamed := conflicting_type_names[v_struct_name] {
v_struct_name = renamed
}
// Check for name collision with existing global names
if v_struct_name in app.global_names {
mut i := 1
for {
new_name := '${v_struct_name}_${i}'
if new_name !in app.global_names {
v_struct_name = new_name
break
}
i++
}
}
// Track struct name globally
app.global_names[v_struct_name] = true
// In Go, exported types start with uppercase. Add 'pub' for exported structs.
pub_prefix := if struct_name.len > 0 && struct_name[0].is_capital() { 'pub ' } else { '' }
app.genln('${pub_prefix}struct ${v_struct_name} {')
// First output embedded structs (fields without names)
mut has_pub_mut := false
for field in spec.fields.list {
if field.names.len == 0 {
// Embedded struct - skip if it's a pointer type (V doesn't support embedded pointers)
if field.typ is StarExpr {
continue
}
// Skip primitive type embeddings (V only allows struct embeddings)
// Generate a named field instead for primitive types
if field.typ is Ident {
ident := field.typ as Ident
conversion := go2v_type_checked(ident.name)
if conversion.is_basic {
// Primitive type - generate as a named field
if !has_pub_mut {
app.genln('pub mut:')
has_pub_mut = true
}
app.genln('\t${ident.name.camel_to_snake()} ${conversion.v_type}')
continue
}
}
app.gen('\t')
app.force_upper = true
app.typ(field.typ)
app.force_upper = false
app.genln('')
}
}
// Then output named fields
mut has_named_fields := false
for field in spec.fields.list {
if field.names.len > 0 {
has_named_fields = true
break
}
}
if has_named_fields && !has_pub_mut {
app.genln('pub mut:')
}
for field in spec.fields.list {
app.comments(field.doc)
for n in field.names {
app.gen('\t')
// Field names must be snake_case and keywords must be escaped
app.gen(app.go2v_ident(n.name.camel_to_snake()))
app.gen(' ')
app.typ(field.typ)
if field.typ in [StarExpr, FuncType] {
app.gen(' = unsafe { nil }')
}
app.genln('')
}
}
app.genln('}\n')
}
fn (mut app App) struct_type(spec StructType) {
// Inline/anonymous struct type (e.g., struct { x int })
app.gen('struct {')
for field in spec.fields.list {
for n in field.names {
app.gen(' ')
app.gen(app.go2v_ident(n.name))
app.gen(' ')
app.typ(field.typ)
}
}
app.gen(' }')
}
fn (mut app App) interface_decl(interface_name string, spec InterfaceType) {
// Convert interface name - single letter names need to be doubled (V requires > 1 char)
mut v_interface_name := interface_name
if interface_name.len == 1 {
v_interface_name = interface_name.capitalize() + interface_name.capitalize()
}
// In Go, exported types start with uppercase. Add 'pub' for exported interfaces.
pub_prefix := if interface_name.len > 0 && interface_name[0].is_capital() { 'pub ' } else { '' }
app.genln('${pub_prefix}interface ${v_interface_name} {')
app.in_interface_decl = true
for field in spec.methods.list {
app.comments(field.doc)
for n in field.names {
app.gen('\t')
app.gen(app.go2v_ident(n.name))
app.force_upper = true
app.typ(field.typ)
app.genln('')
}
}
app.in_interface_decl = false
app.genln('}\n')
}
fn (mut app App) composite_lit(c CompositeLit) {
match c.typ {
ArrayType {
app.array_init(c)
}
BasicLit {
app.expr(c)
}
CompositeLit {
app.composite_lit(c)
}
Ident {
// Check if this is an array type alias
if c.typ.name in app.array_type_aliases {
// Generate array literal: [elem1, elem2, ...]
app.gen('[')
for i, elt in c.elts {
if i > 0 {
app.gen(', ')
}
app.expr(elt)
}
app.gen(']')
} else {
app.struct_init(c)
}
}
InvalidExpr {
if c.elts.len > 0 {
app.genln('')
}
for elt in c.elts {
app.expr(elt)
app.genln('')
}
}
MapType {
app.map_init(c)
}
SelectorExpr {
// Handle special Go types that need translation to V equivalents
sel := c.typ as SelectorExpr
if sel.x is Ident {
mod_name := (sel.x as Ident).name
type_name := sel.sel.name
// strings.Builder{} -> strings.new_builder(0)
if mod_name == 'strings' && type_name == 'Builder' {
app.require_import('strings')
app.gen('strings.new_builder(0)')
return
}
// bytes.Buffer{} -> strings.new_builder(0) (V uses strings.Builder for both)
if mod_name == 'bytes' && type_name == 'Buffer' {
app.require_import('strings')
app.gen('strings.new_builder(0)')
return
}
}
// Default handling for other SelectorExpr composite literals
force_upper := app.force_upper // save force upper for `mod.ForceUpper`
app.force_upper = true
app.selector_expr(c.typ)
app.force_upper = force_upper
// No space before { for module-qualified types in V
app.gen('{')
if c.elts.len > 0 {
app.genln('')
}
for elt in c.elts {
app.expr(elt)
app.genln('')
}
app.gen('}')
}
StructType {
// Anonymous struct initialization, e.g., struct{}{}
app.struct_type(c.typ)
app.gen('{')
for elt in c.elts {
app.expr(elt)
app.genln('')
}
app.gen('}')
}
else {
app.genln('// UNHANDLED CompositeLit type ${c.typ.type_name()} strtyp="${c.typ}"')
}
}
}
fn (mut app App) struct_init(c CompositeLit) {
typ := c.typ
match typ {
Ident {
app.force_upper = true
n := app.go2v_ident(typ.name)
app.force_upper = false // Reset after type name
app.gen('${n}{')
if c.elts.len > 0 {
app.genln('')
}
for elt in c.elts {
app.expr(elt)
app.genln('')
}
app.gen('}')
}
else {}
}
}
// Helper function to check if an expression contains iota
fn (app App) contains_iota(expr Expr) bool {
match expr {
Ident {
return expr.name == 'iota'
}
BinaryExpr {
return app.contains_iota(expr.x) || app.contains_iota(expr.y)
}
ParenExpr {
return app.contains_iota(expr.x)
}
CallExpr {
// Check if any arg contains iota
for arg in expr.args {
if app.contains_iota(arg) {
return true
}
}
return false
}
else {
return false
}
}
}
// Check if an expression is a bitflag pattern like `1 << iota`
// These should not be converted to enums because V enums don't support bitwise operations
fn (app App) is_bitflag_pattern(expr Expr) bool {
match expr {
BinaryExpr {
// Check for x << iota pattern
if expr.op == '<<' {
return app.contains_iota(expr.y)
}
return false
}
ParenExpr {
return app.is_bitflag_pattern(expr.x)
}
else {
return false
}
}
}
// Generate a synthetic struct for inline/anonymous struct types
// Returns the generated struct name
fn (mut app App) generate_inline_struct(expr Expr) string {
st := expr as StructType
// Generate unique struct name
mut struct_name := 'Go2VInlineStruct'
if app.inline_struct_count > 0 {
struct_name = 'Go2VInlineStruct_${app.inline_struct_count}'
}
app.inline_struct_count++
// Build struct definition
mut result := '\npub struct ${struct_name} {\nmut:\n'
for field in st.fields.list {
for n in field.names {
result += '\t${app.go2v_ident(n.name)} '
// Get type string
match field.typ {
Ident {
result += go2v_type(field.typ.name)
}
ArrayType {
result += '[]'
if field.typ.elt is Ident {
elt := field.typ.elt as Ident
result += go2v_type(elt.name)
}
}
else {
result += 'voidptr'
}
}
result += '\n'
}
}
result += '}\n'
app.pending_structs << result
return struct_name
}