-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathstruct.v
More file actions
450 lines (431 loc) · 14.6 KB
/
Copy pathstruct.v
File metadata and controls
450 lines (431 loc) · 14.6 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
module main
import strings
// resolve_type_alias resolves type alias chains to the underlying type.
// V doesn't allow type A = B where B is also a type alias.
fn (mut c C2V) resolve_type_alias(type_name string) string {
if type_name.starts_with('&') {
return '&' + c.resolve_type_alias(type_name[1..])
}
if type_name.starts_with('[]') {
return '[]' + c.resolve_type_alias(type_name[2..])
}
if type_name.starts_with('[') {
idx := type_name.index(']') or { -1 }
if idx >= 0 && idx + 1 < type_name.len {
return type_name[..idx + 1] + c.resolve_type_alias(type_name[idx + 1..])
}
}
// If this type is a known alias, resolve to its underlying type
if underlying := c.type_aliases[type_name] {
// Recursively resolve in case of chains
return c.resolve_type_alias(underlying)
}
return type_name
}
// |-RecordDecl 0x7fd7c302c560 <a.c:3:1, line:5:1> line:3:8 struct User definition
fn (mut c C2V) record_decl(node &Node) {
vprintln('record_decl("${node.name}")')
// Skip empty structs (extern or forward decls)
if node.kindof(.record_decl) && node.inner.len == 0 {
return
}
mut c_name := node.name
// Dont generate struct header if it was already generated by typedef
// Confusing, but typedefs in C AST are really messy.
// ...
// If the struct has no name, then it's `typedef struct { ... } name`
// AST: 1) RecordDecl struct definition 2) TypedefDecl struct 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 {
if c.is_verbose {
c.genln('// typedef struct')
}
c_name = next_node.name
if c_name.contains('apthing_t') {
vprintln(node.str())
}
}
}
if c_name in builtin_type_names {
return
}
if c.is_verbose {
c.genln('// struct decl name="${c_name}"')
}
if c_name in c.types {
if node.previous_declaration == '' {
return
}
}
// Anonymous struct, most likely the next node is a vardecl with this anon struct type, so remember it
if c_name == '' {
c_name = 'AnonStruct_${node.location.line}'
c.last_declared_type_name = c_name
}
// First pass: scan for anonymous enums and generate named enum types BEFORE the struct.
// V doesn't support inline `enum {}` in struct fields like it does for struct/union.
// We need to generate the enum as a separate named type.
mut anon_enum_names := map[int]string{} // maps field index to generated enum name
mut struct_v_name := c.add_struct_name(mut c.types, c_name)
mut pending_enum := &Node(unsafe { nil })
for i, field in node.inner {
if field.kind == .enum_decl {
pending_enum = unsafe { &node.inner[i] }
continue
}
if field.kind == .field_decl && pending_enum != unsafe { nil } {
// Check the raw type string (not converted) for anonymous enum detection
if field.ast_type.qualified.contains('unnamed enum')
|| field.ast_type.qualified.contains('anonymous enum') {
// Generate a named enum for this anonymous enum
field_name := filter_name(field.name, false)
enum_name := c.generate_named_enum_for_anon(pending_enum, struct_v_name, field_name)
anon_enum_names[i] = enum_name
}
pending_enum = unsafe { nil }
}
}
if c_name !in ['struct', 'union'] {
// prevent duplicate generations:
if struct_v_name in c.generated_declarations {
return
}
c.generated_declarations[struct_v_name] = true
if node.tags.contains('union') {
c.genln('union ${struct_v_name} { ')
} else {
c.genln('struct ${struct_v_name} { ')
}
}
mut new_struct := Struct{}
// in V it's `field struct {...}`, but in C we get struct definition first, so save it and use it in the
// next child
mut anon_struct_definition := ''
mut anon_enum_definition := ''
for i, field in node.inner {
c.gen_comment(field)
// Handle anon structs and unions (unions appear as RecordDecl with tagUsed='union')
if field.kind == .record_decl {
is_union := field.tags.contains('union')
anon_struct_definition = c.anon_struct_field_type(field, is_union)
continue
}
if field.kind == .union_decl {
anon_struct_definition = c.anon_struct_field_type(field, true)
continue
}
// Handle anon enums - skip, already processed in first pass
if field.kind == .enum_decl {
continue
}
// There may be comments, skip them
if field.kind != .field_decl {
continue
}
field_type := convert_type(field.ast_type.qualified)
filtered := filter_name(field.name, false)
// Don't uncapitalize if it's a C. prefixed name (builtin function)
field_name := if filtered.starts_with('C.') {
filtered[2..] + '_'
} else {
filtered.uncapitalize()
}
mut field_type_name := field_type.name
// Handle anon structs/unions, the anonymous type has just been defined above, use its definition
// Check raw type string since convert_type may not preserve "unnamed" markers
raw_type := field.ast_type.qualified
if (raw_type.contains('unnamed struct') || raw_type.contains('unnamed union')
|| raw_type.contains('(unnamed at')
|| raw_type.contains('anonymous struct')
|| raw_type.contains('anonymous union')) && !raw_type.contains('unnamed enum')
&& !raw_type.contains('anonymous enum') {
field_type_name = anon_struct_definition
}
// Handle anon enums - use the pre-generated named enum type
// Check raw type (field.ast_type.qualified) since convert_type converts unnamed enums to 'int'
if field.ast_type.qualified.contains('unnamed enum')
|| field.ast_type.qualified.contains('anonymous enum') {
if i in anon_enum_names {
field_type_name = anon_enum_names[i]
} else {
field_type_name = anon_enum_definition
}
}
if field_type_name.contains('anonymous at') {
continue
}
/*
if field_type.name.contains('union') {
continue // TODO
}
*/
new_struct.fields << field_name
if field_type.name.ends_with('_s') { // TODO doom _t _s hack, remove
n := field_type.name[..field_type.name.len - 2] + '_t'
c.genln('\t${field_name} ${c.prefix_external_type(n)}')
} else {
c.genln('\t${field_name} ${c.prefix_external_type(field_type_name)}')
}
}
c.structs[c_name] = new_struct
c.genln('}')
}
fn (mut c C2V) anon_struct_field_type(node &Node, is_union bool) string {
mut sb := strings.new_builder(50)
if is_union {
sb.write_string('union {\n')
} else {
sb.write_string('struct {\n')
}
mut nested_anon_def := ''
for field in node.inner {
// Handle nested anonymous struct/union definitions
if field.kind == .record_decl {
nested_is_union := field.tags.contains('union')
nested_anon_def = c.anon_struct_field_type(field, nested_is_union)
continue
}
if field.kind != .field_decl {
continue
}
field_type := convert_type(field.ast_type.qualified)
field_name := filter_name(field.name, false)
mut field_type_name := field_type.name
// Use nested anonymous definition if this field references one
// Check raw type string since convert_type may convert unnamed types to voidptr
raw_type := field.ast_type.qualified
if raw_type.contains('unnamed struct') || raw_type.contains('unnamed union')
|| raw_type.contains('(unnamed at') || raw_type.contains('anonymous struct')
|| raw_type.contains('anonymous union') {
field_type_name = nested_anon_def
}
// Apply external type prefix for types from headers
field_type_name = c.prefix_external_type(field_type_name)
sb.write_string('${field_name} ${field_type_name}\n')
}
sb.write_string('}')
return sb.str()
}
fn (mut c C2V) anon_enum_field_type(node &Node) string {
mut sb := strings.new_builder(50)
sb.write_string('enum {\n')
for i, child in node.inner {
if child.kind != .enum_constant_decl {
continue
}
c_name := filter_name(child.name, false)
v_name := c_identifier_to_v_name(c_name)
sb.write_string('${v_name}')
// handle custom enum vals, e.g. `MF_SHOOTABLE = 4`
if child.inner.len > 0 {
mut const_expr := child.inner[0]
if const_expr.kind == .constant_expr && const_expr.inner.len > 0 {
// Try to get the literal value
literal := const_expr.inner[0]
if literal.kind == .integer_literal {
sb.write_string(' = ${literal.value.to_str()}')
}
}
}
sb.write_string('\n')
_ = i
}
sb.write_string('}')
return sb.str()
}
// Generate a named enum type for an anonymous enum field in a struct.
// V doesn't support inline `enum {}` syntax in struct fields (unlike struct/union),
// so we generate a separate named enum type before the struct.
// Returns the generated enum type name.
fn (mut c C2V) generate_named_enum_for_anon(node &Node, struct_name string, field_name string) string {
// Create enum name from struct name + field name, e.g. "With_anon_enum_Status"
enum_name := '${struct_name}_${field_name.capitalize()}'
// Generate the enum definition
c.genln('enum ${enum_name} {')
for child in node.inner {
if child.kind != .enum_constant_decl {
continue
}
c_name := filter_name(child.name, false)
v_name := c_identifier_to_v_name(c_name)
mut line := '\t${v_name}'
// handle custom enum vals, e.g. `MF_SHOOTABLE = 4`
if child.inner.len > 0 {
mut const_expr := child.inner[0]
if const_expr.kind == .constant_expr && const_expr.inner.len > 0 {
// Try to get the literal value
literal := const_expr.inner[0]
if literal.kind == .integer_literal {
line += ' = ${literal.value.to_str()}'
}
}
}
c.genln(line)
}
c.genln('}')
c.genln('')
// Register the generated enum so prefix_external_type recognizes it
c.enums[enum_name] = enum_name
return enum_name
}
// Typedef node goes after struct enum, but we need to parse it first, so that "type name { " is
// generated first
fn (mut c C2V) typedef_decl(node &Node) {
mut typ := node.ast_type.qualified
// just a single line typedef: (alias)
// typedef sha1_context_t sha1_context_s ;
// typedef after enum decl, just generate "enum NAME {" header
mut c_alias_name := node.name // get_val(-2)
if c_alias_name.contains('et_context_t') {
// TODO remove this
return
}
if c_alias_name in builtin_type_names {
return
}
if c_alias_name in c.enums {
// Enum typedefs are handled by enum_decl.
return
}
alias_has_concrete_decl := c_alias_name.capitalize() in c.generated_declarations
v_alias_name := c.add_struct_name(mut c.types, c_alias_name)
typedef_key := 'typedef:${v_alias_name}'
if typedef_key in c.generated_declarations {
return
}
if typ.starts_with('struct ') && typ.ends_with(' *') {
// Opaque pointer, for example: typedef struct TSTexture_t *TSTexture;
c.generated_declarations[typedef_key] = true
c.genln('type ${v_alias_name} = voidptr')
return
}
if !typ.contains(c_alias_name) {
if typ.contains('struct ') || typ.contains('class ') || typ.contains('union ') {
if alias_has_concrete_decl {
c.generated_declarations[typedef_key] = true
return
}
}
// Function pointer: int (*)(args)
if typ.contains('(*)') {
tt := convert_type(typ)
typ = c.prefix_external_type(tt.name)
}
// Function type without pointer: int (args) - e.g., typedef int fn_name(args)
// Note: don't require comma - single-argument functions like "void (void *)" have no comma
// Skip types with nested function pointers (too complex to parse)
else if typ.count('(') > 2 {
c.genln('// TODO: complex function pointer typedef: ${c_alias_name}')
return
} else if typ.contains('(') && typ.contains(')') && !typ.starts_with('(') {
// Parse function type: "int (arg1, arg2, ...)" -> "fn (arg1, arg2) int"
ret_typ := convert_type(typ.all_before('(').trim_space())
mut s := 'fn ('
sargs := typ.find_between('(', ')')
args := sargs.split(',')
for i, arg in args {
t := convert_type(arg.trim_space())
s += c.prefix_external_type(t.name)
if i < args.len - 1 {
s += ', '
}
}
if ret_typ.name == 'void' {
typ = s + ')'
} else {
typ = '${s}) ${c.prefix_external_type(ret_typ.name)}'
}
typ = typ.replace('(void)', '()')
}
// Struct types have junk before spaces
else {
c_alias_name = c_alias_name.all_after(' ')
tt := convert_type(typ)
typ = c.prefix_external_type(tt.name)
}
if c_alias_name.starts_with('__') {
// Skip internal stuff like __builtin_ms_va_list
return
}
if typ in c.enums {
return
}
mut cgen_alias := typ
if cgen_alias.starts_with('_') {
cgen_alias = trim_underscores(typ)
}
if typ !in ['int', 'i8', 'i16', 'i64', 'u8', 'u16', 'u32', 'u64', 'f32', 'f64', 'usize', 'isize', 'bool', 'void', 'voidptr']
&& !typ.starts_with('fn (') {
// TODO handle this better
cgen_alias = cgen_alias.capitalize()
}
// Resolve type alias chains - V doesn't allow type A = B where B is an alias
resolved_alias := c.resolve_type_alias(cgen_alias)
prefixed_alias := c.prefix_external_type(resolved_alias)
// Store this alias mapping for future resolution
c.type_aliases[c_alias_name.capitalize()] = prefixed_alias
c.file_declared_aliases[c_alias_name.capitalize()] = true
c.generated_declarations[typedef_key] = true
c.genln('type ${c_alias_name.capitalize()} = ${prefixed_alias}') // typedef alias (SINGLE LINE)')
return
}
if typ.contains('enum ') {
// enums were alredy handled in enum_decl
return
} else if typ.contains('struct ') || typ.contains('class ') || typ.contains('union ') {
alias_name := c_alias_name.capitalize()
underlying := c.prefix_external_type(convert_type(typ).name)
if alias_has_concrete_decl {
// Concrete declaration with the same name already exists.
// Skip conflicting typedef aliases like:
// struct Foo { ... }
// typedef struct Bar Foo;
c.generated_declarations[typedef_key] = true
return
}
if underlying != alias_name {
// Alias to a distinct tag type: keep it as a type alias.
resolved_alias := c.resolve_type_alias(underlying)
c.type_aliases[alias_name] = resolved_alias
c.file_declared_aliases[alias_name] = true
c.generated_declarations[typedef_key] = true
c.genln('type ${alias_name} = ${resolved_alias}')
return
}
// Self-typedef without an emitted concrete declaration in this TU.
// Example: typedef struct foo foo; with no matching record emitted by c2v.
// Skip when a real definition is known for this translation unit.
if alias_name in c.known_types {
return
}
decl_key := 'typedef_stub:${alias_name}'
if decl_key in c.generated_declarations {
return
}
c.generated_declarations[decl_key] = true
if typ.contains('union ') {
c.genln('union ${alias_name} {')
c.genln('}')
} else {
c.genln('struct ${alias_name} {')
c.genln('}')
}
c.generated_declarations[typedef_key] = true
return
}
}
// this calls typedef_decl() above
fn (mut c C2V) parse_next_typedef() bool {
// Hack: typedef with the actual enum name is next, parse it and generate "enum NAME {" first
/*
XTODO
next_line := c.lines[c.line_i + 1]
if next_line.contains('TypedefDecl') {
c.line_i++
c.parse_next_node()
return true
}
*/
return false
}