-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathtranspiler.v
More file actions
4666 lines (4352 loc) · 121 KB
/
transpiler.v
File metadata and controls
4666 lines (4352 loc) · 121 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
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
module main
const max_generated_line_len = 121
pub struct VTranspiler {
mut:
usings []string
tmp_gen TmpVarGen
// Maps and state tracked during transpilation
var_types map[string]string
escaped_identifiers map[string]bool
current_class_name string
global_vars map[string]bool
extra_mut_vars map[string]bool
mut_param_indices map[string][]int
func_defaults map[string][]string
func_param_count map[string]int
func_return_types map[string]string
generated_code_has_any_type bool
// Class metadata
class_attr_symbols map[string]map[string]string
class_direct_fields map[string][]string
class_base_names map[string][]string
known_classes map[string][]string
// Module name for emitted code
module_name string
}
fn emitted_class_name(name string) string {
if name.len == 1 {
c := name[0]
if c >= `A` && c <= `Z` {
return '${name}_struct'
}
}
return name
}
// new_transpiler creates a new VTranspiler instance
pub fn new_transpiler() VTranspiler {
return VTranspiler{
usings: []string{}
tmp_gen: new_tmp_var_gen()
var_types: map[string]string{}
escaped_identifiers: map[string]bool{}
current_class_name: ''
global_vars: map[string]bool{}
extra_mut_vars: map[string]bool{}
mut_param_indices: map[string][]int{}
func_defaults: map[string][]string{}
func_param_count: map[string]int{}
func_return_types: map[string]string{}
generated_code_has_any_type: false
class_attr_symbols: map[string]map[string]string{}
class_direct_fields: map[string][]string{}
class_base_names: map[string][]string{}
known_classes: map[string][]string{}
module_name: ''
}
}
// visit_module emits the top-level V module source for a Module node.
pub fn (mut t VTranspiler) visit_module(node Module) string {
mut module_name := t.module_name
if module_name.len == 0 {
module_name = 'main'
}
// Buckets — emitted in order: type_decls, struct_decls, func_decls, main_fn
mut type_decls := []string{} // `type X = ...`, `const ...`
mut struct_decls := []string{} // `pub struct ...` (from ClassDef)
mut func_decls := []string{} // `fn ...` (non-main functions)
mut main_fn_body := []string{} // body lines for fn main()
mut main_fn_override := '' // full `fn main() {...}` from guard rewrite
mut comment_lines := []string{} // top-level import comments etc.
mut first_stmt := true
for stmt in node.body {
// Skip module-level docstrings (first bare string constant)
if first_stmt {
first_stmt = false
if stmt is ExprStmt {
es := stmt as ExprStmt
if es.value is Constant {
c := es.value as Constant
if c.value is string {
continue
}
}
}
}
s := t.visit_stmt(stmt)
if s.len == 0 {
continue
}
match stmt {
ClassDef {
// Class emits struct def + methods; split on first fn boundary
struct_decls << s
}
FunctionDef {
if stmt.name == 'main' {
main_fn_override = s
} else {
func_decls << s
}
}
AsyncFunctionDef {
if stmt.name == 'main' {
main_fn_override = s
} else {
func_decls << s
}
}
else {
trimmed := s.trim_space()
if trimmed.starts_with('type ') || trimmed.starts_with('const ') {
type_decls << s
} else if stmt is TypeAlias {
type_decls << s
} else if trimmed.starts_with('//') {
// Import comments and similar go before fn main()
comment_lines << s
} else {
main_fn_body << s
}
}
}
}
// Any type alias must be first among type_decls
if t.generated_code_has_any_type {
type_decls.prepend('type Any = bool | int | i64 | f64 | string | []u8')
}
// Build final fn main(): merge guard-rewritten body with module-level inits
mut main_str := ''
mut all_main_lines := []string{}
all_main_lines << comment_lines
all_main_lines << main_fn_body
if main_fn_override.len > 0 {
if all_main_lines.len > 0 {
// Inject init lines at start of the guard-rewritten fn main() body
open_brace := main_fn_override.index('{') or { -1 }
if open_brace >= 0 {
head := main_fn_override[0..open_brace + 1]
tail := main_fn_override[open_brace + 1..]
mut indented := []string{}
for line in all_main_lines {
indented << indent(line, 1, '\t')
}
main_str = '${head}\n${indented.join('\n')}${tail}'
} else {
main_str = main_fn_override
}
} else {
main_str = main_fn_override
}
} else if all_main_lines.len > 0 {
mut indented := []string{}
for line in all_main_lines {
indented << indent(line, 1, '\t')
}
main_str = 'fn main() {\n${indented.join('\n')}\n}'
}
// Assemble output sections in order
mut parts := []string{}
parts << '@[translated]'
parts << 'module ${module_name}'
if t.usings.len > 0 {
mut import_lines := []string{}
for u in t.usings {
import_lines << 'import ${u}'
}
parts << import_lines.join('\n')
}
if type_decls.len > 0 {
parts << type_decls.join('\n\n')
}
if struct_decls.len > 0 {
parts << struct_decls.join('\n\n')
}
if func_decls.len > 0 {
parts << func_decls.join('\n\n')
}
if main_str != '' {
parts << main_str
}
return parts.join('\n\n') + '\n'
}
// add_using registers an import usage required by generated code.
pub fn (mut t VTranspiler) add_using(mod string) {
if mod == '' {
return
}
if mod in t.usings {
return
}
t.usings << mod
}
// new_tmp returns a fresh temporary variable name.
pub fn (mut t VTranspiler) new_tmp(prefix string) string {
return t.tmp_gen.next(prefix)
}
// indent_code indents `code` by `level` using a tab indent.
pub fn (mut t VTranspiler) indent_code(code string, level int) string {
// refer to t to avoid v vet "unused receiver" warnings
_ = t.module_name
return indent(code, level, '\t')
}
// visit_body_stmts visits a list of statements and returns an indented block string.
pub fn (mut t VTranspiler) visit_body_stmts(stmts []Stmt, level int) string {
mut parts := []string{}
for stmt in stmts {
s := t.visit_stmt(stmt)
if s.len == 0 {
continue
}
parts << indent(s, level, '\t')
}
return parts.join('\n')
}
// visit_return emits V code for a Return statement.
pub fn (mut t VTranspiler) visit_return(node Return) string {
if val := node.value {
return 'return ${t.visit_expr(val)}'
}
return 'return'
}
// visit_delete emits V delete operations where V has an equivalent.
pub fn (mut t VTranspiler) visit_delete(node Delete) string {
mut parts := []string{}
for target in node.targets {
parts << t.emit_delete_target(target)
}
return parts.join('\n')
}
// emit_delete_target lowers one Python del target into one or more V lines.
fn (mut t VTranspiler) emit_delete_target(target Expr) []string {
match target {
Subscript {
sub := target as Subscript
if sub.slice is Slice {
return [
'// del ${t.visit_expr(target)} // unsupported: slice deletion',
]
}
base := t.visit_expr(sub.value)
index := t.visit_expr(sub.slice)
coll_type := t.infer_expr_type(sub.value)
if coll_type.starts_with('map[') || sub.value is Dict {
return ['${base}.delete(${index})']
}
if coll_type.starts_with('[]') || coll_type == 'array' || sub.value is List {
return ['${base}.delete(${index})']
}
if coll_type.len > 0 {
return [
'// del ${t.visit_expr(target)} // unsupported: subscript delete on ${coll_type}',
]
}
return [
'// del ${t.visit_expr(target)} // unsupported: unknown subscript container',
]
}
Tuple {
mut lines := []string{}
for elt in (target as Tuple).elts {
lines << t.emit_delete_target(elt)
}
return lines
}
List {
mut lines := []string{}
for elt in (target as List).elts {
lines << t.emit_delete_target(elt)
}
return lines
}
Name {
return [
'// del ${t.visit_expr(target)} - V does not support deleting variables',
]
}
Attribute {
return [
'// del ${t.visit_expr(target)} // unsupported: attribute deletion',
]
}
else {
return ['// del ${t.visit_expr(target)} // unsupported del form']
}
}
}
// has_setter_decorator returns true if any decorator is a .setter attribute.
fn has_setter_decorator(decorators []main.Expr) bool {
for d in decorators {
if d is Attribute {
if (d as Attribute).attr == 'setter' {
return true
}
}
}
return false
}
// visit_stmt visits a statement and dispatches to the appropriate visitor.
pub fn (mut t VTranspiler) visit_stmt(stmt Stmt) string {
match stmt {
FunctionDef { return t.visit_function_def(stmt) }
AsyncFunctionDef { return t.visit_async_function_def(stmt) }
ClassDef { return t.visit_class_def(stmt) }
Return { return t.visit_return(stmt) }
Delete { return t.visit_delete(stmt) }
Assign { return t.visit_assign(stmt) }
AugAssign { return t.visit_aug_assign(stmt) }
AnnAssign { return t.visit_ann_assign(stmt) }
For { return t.visit_for(stmt) }
AsyncFor { return t.visit_async_for(stmt) }
While { return t.visit_while(stmt) }
If { return t.visit_if(stmt) }
With { return t.visit_with(stmt) }
AsyncWith { return t.visit_async_with(stmt) }
Raise { return t.visit_raise(stmt) }
Try { return t.visit_try(stmt) }
Assert { return t.visit_assert(stmt) }
Import { return t.visit_import(stmt) }
ImportFrom { return t.visit_import_from(stmt) }
Global { return t.visit_global(stmt) }
Nonlocal { return t.visit_nonlocal(stmt) }
ExprStmt { return t.visit_expr_stmt(stmt) }
Pass { return '// pass' }
Break { return 'break' }
Continue { return 'continue' }
TypeAlias { return t.visit_type_alias(stmt) }
Match { return t.visit_match(stmt) }
}
}
// visit_expr visits an expression and dispatches to expression visitors.
pub fn (mut t VTranspiler) visit_expr(expr Expr) string {
match expr {
Constant { return t.visit_constant(expr) }
Name { return t.visit_name(expr) }
BinOp { return t.visit_binop(expr) }
UnaryOp { return t.visit_unaryop(expr) }
BoolOp { return t.visit_boolop(expr) }
Compare { return t.visit_compare(expr) }
Call { return t.visit_call(expr) }
Attribute { return t.visit_attribute(expr) }
Subscript { return t.visit_subscript(expr) }
Slice { return t.visit_slice(expr) }
List { return t.visit_list(expr) }
Tuple { return t.visit_tuple(expr) }
Dict { return t.visit_dict(expr) }
Set { return t.visit_set(expr) }
IfExp { return t.visit_ifexp(expr) }
Lambda { return t.visit_lambda(expr) }
ListComp { return t.visit_list_comp(expr) }
SetComp { return t.visit_set_comp(expr) }
DictComp { return t.visit_dict_comp(expr) }
GeneratorExp { return t.visit_generator_exp(expr) }
Await { return t.visit_await(expr) }
Yield { return t.visit_yield(expr) }
YieldFrom { return t.visit_yield_from(expr) }
FormattedValue { return t.visit_formatted_value(expr) }
JoinedStr { return t.visit_joined_str(expr) }
NamedExpr { return t.visit_named_expr(expr) }
Starred { return t.visit_starred(expr) }
}
}
// visit_function_def emits V code for a Python FunctionDef node.
pub fn (mut t VTranspiler) visit_function_def(node FunctionDef) string {
// Save var_types and escaped_identifiers for function scope (keep globals, reset locals)
saved_var_types := t.var_types.clone()
saved_escaped_identifiers := t.escaped_identifiers.clone()
t.escaped_identifiers = map[string]bool{}
saved_current_class := t.current_class_name
if node.is_class_method {
t.current_class_name = node.class_name
}
// Keep global variable types, reset function-local ones
mut func_var_types := map[string]string{}
for k, v in t.var_types {
if t.global_vars[k] or { false } {
func_var_types[k] = v
}
}
t.var_types = func_var_types.clone()
mut signature := []string{}
signature << 'fn'
// Handle class method receiver
if node.is_class_method {
emitted_receiver := emitted_class_name(node.class_name)
if 'self' in node.mutable_vars || node.name == '__init__' {
signature << '(mut self ${emitted_receiver})'
} else {
signature << '(self ${emitted_receiver})'
}
}
// Process arguments
mut args_strs := []string{}
mut generics := []string{}
mut mut_indices := []int{} // Track which parameter indices are mutable
mut param_idx := 0
for arg in node.args.args {
if arg.arg == 'self' {
continue
}
mut typename := ''
if ann := arg.annotation {
typename = t.typename_from_annotation(ann)
}
mut arg_name := escape_identifier(arg.arg)
// Track identifiers escaped due to built-in type name conflicts
if arg.arg in v_builtin_types {
t.escaped_identifiers[arg.arg] = true
}
// Check if this argument is mutable
if arg.arg in node.mutable_vars {
arg_name = 'mut ${arg_name}'
mut_indices << param_idx
}
if typename == '' {
// V functions require explicit parameter types.
typename = 'Any'
t.generated_code_has_any_type = true
} else if typename.len == 1 && typename[0] >= `A` && typename[0] <= `Z` {
// Single uppercase letter is a generic
if typename !in generics {
generics << typename
}
}
args_strs << '${arg_name} ${typename}'
// Track parameter type for return type inference
if typename.len > 0 && typename != 'Any' && !(typename.len == 1 && typename[0] >= `A`
&& typename[0] <= `Z`) {
t.var_types[arg.arg] = typename
}
param_idx++
}
// Register function's mut parameter indices for call-site mut keyword generation
if mut_indices.len > 0 && !node.is_class_method {
t.mut_param_indices[node.name] = mut_indices
}
// Record default values for call-site default filling
if node.args.defaults.len > 0 && !node.is_class_method {
mut default_strs := []string{}
for def in node.args.defaults {
default_strs << t.visit_expr(def)
}
t.func_defaults[node.name] = default_strs
t.func_param_count[node.name] = param_idx
}
// Handle vararg (*args)
if vararg := node.args.vararg {
mut typename := ''
if ann := vararg.annotation {
typename = t.typename_from_annotation(ann)
}
if typename.starts_with('[]') {
typename = '...' + typename[2..]
} else if typename == '' {
typename = '...Any'
t.generated_code_has_any_type = true
} else {
typename = '...' + typename
}
args_strs << '${escape_identifier(vararg.arg)} ${typename}'
}
// Handle **kwargs — emit as map[string]Any with a comment
if kwarg := node.args.kwarg {
t.generated_code_has_any_type = true
args_strs << '${escape_identifier(kwarg.arg)} map[string]Any // **kwargs'
}
// Handle keyword-only args (after *)
for kwonly in node.args.kwonlyargs {
kwname := escape_identifier(kwonly.arg)
mut kwtype := 'Any'
t.generated_code_has_any_type = true
if ann := kwonly.annotation {
kwtype = t.typename_from_annotation(ann)
}
args_strs << '${kwname} ${kwtype}'
}
// For generator functions, add channel parameter
if node.is_generator {
yield_type := t.infer_generator_yield_type(node.body)
args_strs << 'ch chan ${yield_type}'
}
signature << '${node.name}(${args_strs.join(', ')})'
// Pre-scan body to populate var_types for return type inference
t.prescan_body_types(node.body)
// Return type
if !node.is_void && !node.is_generator && node.name != '__init__' {
if ret := node.returns {
ret_type := t.typename_from_annotation(ret)
signature << ret_type
t.func_return_types[node.name] = ret_type
} else {
// Infer return type from return statements
mut inferred := t.infer_return_type(node.body)
// Fall back to Any when function returns a value but type can't be inferred
if inferred.len == 0 {
inferred = 'Any'
t.generated_code_has_any_type = true
}
signature << inferred
t.func_return_types[node.name] = inferred
}
}
// Process body - separate nested function definitions
mut nested_fndefs := []string{}
mut body_stmts := []Stmt{}
mut first_stmt := true
for stmt in node.body {
// Skip docstrings (first statement that is a bare string constant)
if first_stmt {
first_stmt = false
if stmt is ExprStmt {
es := stmt as ExprStmt
if es.value is Constant {
c := es.value as Constant
if c.value is string {
continue
}
}
}
}
match stmt {
FunctionDef {
nested_fndefs << t.visit_function_def(stmt)
}
AsyncFunctionDef {
nested_fndefs << t.visit_async_function_def(stmt)
}
else {
body_stmts << stmt
}
}
}
// Pre-scan body for variables passed to mut-parameter functions
t.prescan_mut_call_args(body_stmts)
// Build body
mut body_lines := []string{}
if node.is_generator {
body_lines << t.indent_code('defer { ch.close() }', 1)
}
body_lines << t.visit_body_stmts(body_stmts, 1)
body := body_lines.join('\n')
func_code := '${signature.join(' ')} {\n${body}\n}'
// Restore var_types and escaped_identifiers from parent scope
t.var_types = saved_var_types.clone()
t.escaped_identifiers = saved_escaped_identifiers.clone()
if nested_fndefs.len > 0 {
t.current_class_name = saved_current_class
return nested_fndefs.join('\n') + '\n' + func_code
}
t.current_class_name = saved_current_class
return func_code
}
// visit_async_function_def emits V code for an AsyncFunctionDef node (converted to sync).
pub fn (mut t VTranspiler) visit_async_function_def(node AsyncFunctionDef) string {
// Convert to regular FunctionDef
fd := FunctionDef{
name: node.name
args: node.args
body: node.body
decorator_list: node.decorator_list
returns: node.returns
type_comment: node.type_comment
loc: node.loc
is_generator: node.is_generator
is_void: node.is_void
mutable_vars: node.mutable_vars
is_class_method: node.is_class_method
class_name: node.class_name
}
return t.visit_function_def(fd)
}
// visit_class_def emits V code for a ClassDef node.
pub fn (mut t VTranspiler) visit_class_def(node ClassDef) string {
emitted_name := emitted_class_name(node.name)
// Detect @dataclass decorator — changes field emission strategy
mut is_dataclass := false
for d in node.decorator_list {
if d is Name && (d as Name).id == 'dataclass' {
is_dataclass = true
break
}
if d is Attribute && (d as Attribute).attr == 'dataclass' {
is_dataclass = true
break
}
if d is Call {
fn_part := (d as Call).func
if fn_part is Name && (fn_part as Name).id == 'dataclass' {
is_dataclass = true
break
}
}
}
_ = is_dataclass // used below for field-default emission
mut fields := []string{}
mut field_names := []string{}
mut base_names := []string{}
mut class_attr_values := []string{}
mut class_attr_syms := map[string]string{}
mut init_field_names := map[string]bool{}
for stmt in node.body {
match stmt {
FunctionDef {
if stmt.name != '__init__' {
continue
}
for init_stmt in stmt.body {
match init_stmt {
Assign {
if init_stmt.targets.len == 1 && init_stmt.targets[0] is Attribute {
attr := init_stmt.targets[0] as Attribute
if attr.value is Name && (attr.value as Name).id == 'self' {
init_field_names[attr.attr] = true
}
}
}
AnnAssign {
if init_stmt.target is Attribute {
attr := init_stmt.target as Attribute
if attr.value is Name && (attr.value as Name).id == 'self' {
init_field_names[attr.attr] = true
}
}
}
else {}
}
}
}
Assign {
if stmt.targets.len == 1 && stmt.targets[0] is Name {
attr_name := (stmt.targets[0] as Name).id
if !is_v_field_ident(attr_name) {
class_attr_syms[attr_name] = class_attr_symbol_name(node.name, attr_name)
}
}
}
else {}
}
}
t.class_attr_symbols[node.name] = class_attr_syms.clone()
for stmt in node.body {
match stmt {
Assign {
if stmt.targets.len == 1 && stmt.targets[0] is Name {
attr_name := (stmt.targets[0] as Name).id
if sym := class_attr_syms[attr_name] {
class_attr_values << 'const ${sym} = ${t.visit_expr(stmt.value)}'
}
}
}
else {}
}
}
if node.declarations.len > 0 {
mut has_typed_fields := false
for decl, typename in node.declarations {
if decl in class_attr_syms && decl !in init_field_names {
continue
}
mut decl_type := typename
if decl_type == '' {
// Preserve untyped __init__ fields so method assignments compile.
decl_type = 'Any'
t.generated_code_has_any_type = true
}
if !has_typed_fields {
fields << 'pub mut:'
has_typed_fields = true
}
mut typ := map_type(decl_type)
if typ == 'auto' {
typ = 'Any'
t.generated_code_has_any_type = true
}
if should_emit_ref_field_type(typ) {
typ = '&${typ}'
}
if default_expr := node.class_defaults[decl] {
default_str := t.visit_expr(default_expr)
fields << t.indent_code('${decl} ${typ} = ${default_str}', 1)
} else {
fields << t.indent_code('${decl} ${typ}', 1)
}
field_names << decl
}
}
for base in node.bases {
if base is Name {
base_name := (base as Name).id
if base_name.len > 0 {
base_names << base_name
}
}
}
// Register class shape metadata for constructor generation
t.class_direct_fields[node.name] = field_names
t.class_base_names[node.name] = base_names
mut all_field_names := []string{}
for base_name in base_names {
base_fields := t.known_classes[base_name] or { []string{} }
all_field_names << base_fields
}
all_field_names << field_names
t.known_classes[node.name] = all_field_names
// Embed base classes (inheritance -> struct embedding)
mut embeds := []string{}
for base_name in base_names {
if base_name in t.known_classes {
embeds << t.indent_code(emitted_class_name(base_name), 1)
}
}
mut all_parts := []string{}
all_parts << embeds
all_parts << fields
mut struct_def := if all_parts.len > 0 {
'pub struct ${emitted_name} {\n${all_parts.join('\n')}\n}'
} else {
'pub struct ${emitted_name} {\n}'
}
// Add class docstring as struct comment (V convention: "// StructName ...")
if doc := node.docstring_comment {
lines := doc.split('\n')
mut comment_lines := []string{}
for i, raw_line in lines {
line := raw_line.trim_space()
if line.len == 0 {
if i > 0 && i < lines.len - 1 {
comment_lines << '//'
}
continue
}
if i == 0 && !line.starts_with(node.name) {
comment_lines << '// ${node.name} - ${line}'
} else {
comment_lines << '// ${line}'
}
}
if comment_lines.len > 0 {
struct_def = comment_lines.join('\n') + '\n' + struct_def
}
}
// Emit class-level attributes as module-level symbols.
if class_attr_values.len > 0 {
struct_def = class_attr_values.join('\n') + '\n\n' + struct_def
}
// Pre-pass: register return types of all methods that have explicit annotations
for stmt in node.body {
if stmt is FunctionDef {
if !stmt.is_void {
if ret := stmt.returns {
ret_type := t.typename_from_annotation(ret)
if ret_type.len > 0 {
t.func_return_types[stmt.name] = ret_type
}
}
}
}
}
// Process body (methods)
mut methods := []string{}
for stmt in node.body {
match stmt {
FunctionDef {
// Mark as class method
mut fd := stmt
fd.is_class_method = true
fd.class_name = node.name
// Rename @property.setter methods to set_<name> to avoid duplicate method names
if has_setter_decorator(fd.decorator_list) {
fd.name = 'set_${fd.name}'
}
methods << t.visit_function_def(fd)
}
else {}
}
}
if methods.len > 0 {
return struct_def + '\n\n' + methods.join('\n\n')
}
return struct_def
}
// visit_assign emits V code for an Assign statement.
pub fn (mut t VTranspiler) visit_assign(node Assign) string {
// Special-case __all__ exception exports into a V union alias.
if node.targets.len == 1 && node.targets[0] is Name {
target_name := (node.targets[0] as Name).id
if target_name == '__all__' && node.value is List {
mut members := []string{}
for elt in (node.value as List).elts {
if elt is Constant {
c := elt as Constant
if c.value is string {
name := c.value as string
if name.ends_with('Exception') {
members << name
}
}
}
}
if members.len > 0 {
return 'type WebDriverExceptions = ${members.join(' | ')}'
}
return ''
}
}
// Track variable types for print() optimization
for target in node.targets {
if target is Name {
n := target as Name
inferred := t.infer_expr_type(node.value)
if inferred.len > 0 {
t.var_types[n.id] = inferred
}
}
}
mut assigns := []string{}
use_temp := node.targets.len > 1 && node.value is Call
// Determine if RHS was an ellipsis so we can append a trailing
// comment at the end of the generated assignment line(s).
mut trailing_comment := ''
if node.value is Constant {
c := node.value as Constant
if c.value is EllipsisValue {
trailing_comment = ' // ...'
}
}
if use_temp {
assigns << 'mut tmp := ${t.visit_expr(node.value)}'
}
for target in node.targets {
mut is_redefined := false
if target is Name {
n := target as Name
is_redefined = n.id in node.redefined_targets || (t.global_vars[n.id] or { false })
}
value_str := if use_temp { 'tmp' } else { t.visit_expr(node.value) }
match target {
Tuple {
// Tuple unpacking
elts := target.elts
// Check for starred unpacking
has_starred := elts.any(fn (e Expr) bool {
return e is Starred
})
if has_starred {
assigns << t.handle_starred_unpack(elts, value_str)
} else {
// Check if value is a tuple/list literal with same length - can unpack directly
is_tuple_swap := node.value is Tuple
&& (node.value as Tuple).elts.len == elts.len
if is_tuple_swap {
// Direct tuple swap: x, y = y, x or a, b, c = 1, 2, 3
mut subtargets := []string{}
mut any_redefined := false
mut all_names_mutable := true
mut has_subscript_or_attr := false
// Check if all targets are mutable names (meaning they were defined earlier)
for st in elts {
if st is Name {
if st.id in node.redefined_targets {
any_redefined = true
}
if !st.is_mutable {
all_names_mutable = false
}
} else if st is Subscript || st is Attribute {
has_subscript_or_attr = true
} else {
all_names_mutable = false
}
}
// If all names are marked mutable, this is likely a reassignment (like swap)
// Use = without mut prefix
for st in elts {
mut subkw := ''
if st is Name {
if !any_redefined && !all_names_mutable && !has_subscript_or_attr {
if st.is_mutable && st.id !in node.redefined_targets {
subkw = 'mut '
}
}
}
subtargets << '${subkw}${t.visit_expr(st)}'
}
// Check if any target is _ (discard) - V uses = for those
has_discard := elts.any(fn (e Expr) bool {
if e is Name {
return (e as Name).id == '_'
}
return false
})
op := if is_redefined || any_redefined || all_names_mutable
|| has_subscript_or_attr || has_discard {
'='
} else {
':='
}
// Strip brackets from value
mut val := value_str
if val.starts_with('[') && val.ends_with(']') {
val = val[1..val.len - 1]
}
assigns << '${subtargets.join(', ')} ${op} ${val}'
} else {
// Unpacking from array/variable - V doesn't support this directly
// Generate individual assignments: a := arr[0]; b := arr[1]; c := arr[2]
tmp_var := t.new_tmp('unpack')
assigns << '${tmp_var} := ${value_str}'
for i, st in elts {
mut any_redefined := false
if st is Name {
if st.id in node.redefined_targets {
any_redefined = true
}
}
op := if any_redefined { '=' } else { ':=' }
// All unpack targets get mut (V needs this for array element operations)
subkw := if !any_redefined { 'mut ' } else { '' }
assigns << '${subkw}${t.visit_expr(st)} ${op} ${tmp_var}[${i}]'
}
}
}
}
List {
// List unpacking
elts := target.elts