-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.go
More file actions
596 lines (510 loc) · 16.6 KB
/
Copy pathparse.go
File metadata and controls
596 lines (510 loc) · 16.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
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
package main
import (
"errors"
"fmt"
"strconv"
"strings"
"modernc.org/cc/v4"
)
// FieldKind represents the kind of field in an aggregate
type FieldKind uint
const (
ValueKind FieldKind = iota
PointerKind
ArrayKind
FunctionPointerKind
EnumEntryKind
)
// AggregateKind represents the kind of aggregate
type AggregateKind uint
const (
StructKind AggregateKind = iota
UnionKind
EnumKind
)
// An Aggregate represents a C aggregate type (struct, union, enum).
type Aggregate struct {
Name string
Typedef string
Kind AggregateKind
Fields []Field
}
// A Field is an entry that can be found within an aggregate, be it a struct
// or a union. It defines the Type method, useful to get its type description
// as a string.
type Field interface {
Type() string
Declaration() string
UnqualifiedType() string
}
// A Basic field is a field of either a primitive type, or an aggregate type.
// It describes a C value type.
type Basic struct {
Qualifiers []string
TypeName string
Name string
}
var (
keyQualifiers = map[string]struct{}{
"signed": {},
"unsigned": {},
"long": {},
}
)
// Type returns the type of the Basic field.
func (b Basic) Type() string {
var builder strings.Builder
for _, qualifier := range b.Qualifiers {
builder.WriteString(qualifier)
builder.WriteRune(' ')
}
builder.WriteString(b.TypeName)
return builder.String()
}
// Declaration returns the fully qualified name for the field. For a basic
// field, that's just its name.
func (b Basic) Declaration() string {
return b.Name
}
// UnqualifiedType returns the underlying type of the field without qualifiers
// that only affect access/storage. Signedness and `longness` are kept.
func (b Basic) UnqualifiedType() string {
var unqualType []string
for _, qual := range b.Qualifiers {
if _, isKey := keyQualifiers[qual]; isKey {
unqualType = append(unqualType, qual)
}
}
unqualType = append(unqualType, b.TypeName)
return strings.Join(unqualType, " ")
}
// A Pointer is an aggregate field which is a pointer to any Basic type. It
// describes a C pointer type.
type Pointer struct {
Basic
PointerQualifiers []string
}
// Type returns the type of the Pointer field.
func (p Pointer) Type() string {
var builder strings.Builder
for _, qualifier := range p.Qualifiers {
builder.WriteString(qualifier)
builder.WriteRune(' ')
}
builder.WriteString(p.TypeName)
builder.WriteString(" * ")
for _, pQualifier := range p.PointerQualifiers {
builder.WriteString(pQualifier)
builder.WriteRune(' ')
}
return builder.String()
}
// UnqualifiedType returns the underlying type of the field without qualifiers
// that only affect access/storage. Signedness and `longness` are kept.
func (p Pointer) UnqualifiedType() string {
return p.Basic.UnqualifiedType()
}
// Declaration returns the fully qualified name for the field. For a Pointer
// field, that's just its name.
func (p Pointer) Declaration() string {
return p.Name
}
// An Array is an aggregate field which is an array to any Basic type. It
// describes a C array type.
type Array struct {
Basic
Elements int
}
// Type returns the type of the Array field.
func (a Array) Type() string {
var builder strings.Builder
for _, qualifier := range a.Qualifiers {
builder.WriteString(qualifier)
builder.WriteRune(' ')
}
builder.WriteString(a.TypeName)
return builder.String()
}
// UnqualifiedType returns the underlying type of the field without qualifiers
// that only affect access/storage. Signedness and `longness` are kept.
func (a Array) UnqualifiedType() string {
return a.Basic.UnqualifiedType()
}
// Declaration returns the fully qualified name for the field. For an Array
// field, that's its name and size.
func (a Array) Declaration() string {
return fmt.Sprintf("%s[%d]", a.Name, a.Elements)
}
// An FuncPointer is an aggregate field which describes a C function pointer.
type FuncPointer struct {
ReturnType string
Name string
Args []string
}
// Type returns the type of the FuncPointer field.
func (fp FuncPointer) Type() string {
var builder strings.Builder
builder.WriteString(fp.ReturnType)
builder.WriteString(" (*) ")
for idx, arg := range fp.Args {
builder.WriteString(arg)
if idx != len(fp.Args)-1 {
builder.WriteString(", ")
}
}
return builder.String()
}
// UnqualifiedType returns the underlying type of the field without qualifiers
// that only affect access/storage. Signedness and `longness` are kept.
func (fp FuncPointer) UnqualifiedType() string {
return fp.Type()
}
// Declaration returns the fully qualified name for the field. For a
// FuncPointer field, that's its name and argument list.
func (f FuncPointer) Declaration() string {
var builder strings.Builder
builder.WriteString(f.Name)
builder.WriteRune('(')
for idx, arg := range f.Args {
builder.WriteString(arg)
if idx != len(f.Args)-1 {
builder.WriteString(", ")
}
}
builder.WriteRune(')')
return builder.String()
}
// An EnumEntry is a representation of one of the symbols defined as part of
// an enum.
type EnumEntry string
// Type returns the type of the FuncPointer field.
func (ee EnumEntry) Type() string {
return "enum"
}
// UnqualifiedType returns the underlying type of the field without qualifiers
// that only affect access/storage. Signedness and `longness` are kept.
func (ee EnumEntry) UnqualifiedType() string {
return string(ee)
}
// Declaration returns the fully qualified name for the field. For an Enum
// field, that's just its name.
func (e EnumEntry) Declaration() string {
return string(e)
}
var (
ErrNotAnAggregate = errors.New("not an aggregate")
)
// ParseAggregate parses a declaration tree in search for an Aggregate.
// If it does find one, it returns a pointer to it, otherwise fails reporting
// an error and returning a nil aggregate.
func ParseAggregate(decl *cc.Declaration) (*Aggregate, error) {
var ret Aggregate
specs := decl.DeclarationSpecifiers
// if the type was typedef'd, we retrieve the typedef name
if decl.InitDeclaratorList != nil {
token := getTypedefToken(decl)
ret.Typedef = token.SrcStr()
}
// check the specifiers list, the type section contains the aggregate one
if specs.Case == cc.DeclarationSpecifiersStorage {
specs = specs.DeclarationSpecifiers
}
// at this point, a type specifier must be present...
if specs.TypeSpecifier == nil {
return nil, ErrNotAnAggregate
}
// ...as it will lead us to the struct/union/enum specifier
aggrSpec := specs.TypeSpecifier.StructOrUnionSpecifier
enumSpec := specs.TypeSpecifier.EnumSpecifier
if aggrSpec == nil {
if enumSpec != nil {
err := parseEnum(enumSpec, &ret)
if err != nil {
return nil, err
}
return &ret, nil
}
return nil, ErrNotAnAggregate
}
// check which kind of aggregate this is, and its name
var (
aggregateId = aggrSpec.Token.SrcStr()
aggregateKind = aggrSpec.StructOrUnion.Token.SrcStr()
)
switch aggregateKind {
case "struct":
ret.Kind = StructKind
case "union":
ret.Kind = UnionKind
}
// if this is not a anonymous typedef'd struct, we get the name from here
if aggregateId != "" {
ret.Name = fmt.Sprintf("%s %s", aggregateKind, aggregateId)
}
// let us extract the fields and fully qualify them
declList := aggrSpec.StructDeclarationList
for ; declList != nil; declList = declList.StructDeclarationList {
ret.Fields = append(ret.Fields, parseField(declList.StructDeclaration))
}
return &ret, nil
}
// GetAggregateNames returns the identifier with which a user can refer to the
// passed aggregate.
// If the aggregate is not anonymous, then this function returns both the
// fully qualified name e.g. `struct foo`, and just the unqualified aggregate
// name, e.g. `foo`. If this is a typedef'd type, it returns the typedef name
// for the aggregate. Any combination of the two is possible, but not having
// any name should not be possible.
func GetAggregateNames(aggregate *Aggregate) []string {
const (
maxNames = 3
structTag = "struct "
)
names := make([]string, 0, maxNames)
if aggregate.Typedef != "" {
names = append(names, aggregate.Typedef)
}
if aggregate.Name != "" {
structIndex := strings.Index(aggregate.Name, structTag)
noStructName := aggregate.Name[structIndex+len(structTag):]
names = append(names, aggregate.Name)
names = append(names, noStructName)
}
return names
}
// parseEnum parses the whole enum in one go, since it's the simplest
// aggregate kind, and no special checks must be performed.
func parseEnum(spec *cc.EnumSpecifier, enum *Aggregate) error {
// if this is nil, we just know this cannot be any other kind of aggregate
if spec == nil {
return ErrNotAnAggregate
}
// extract kind and name: typedef should already be here from earlier
enum.Kind = EnumKind
// Token is always `enum`, Token2 contains the non-anonymous enum name
name := spec.Token2.SrcStr()
if name != "" {
enum.Name = fmt.Sprintf("enum %s", spec.Token2.SrcStr())
}
// add the enum entries one by one, the parsing is quite simple in this case
for list := spec.EnumeratorList; list != nil; list = list.EnumeratorList {
entry := list.Enumerator.Token.SrcStr()
enum.Fields = append(enum.Fields, EnumEntry(entry))
}
return nil
}
// parseField is a builder for the Field type. It constructs and returns a
// Field type described by the passed declaration.
func parseField(fieldDecl *cc.StructDeclaration) Field {
qualifiers, typeName := parseQualifiers(fieldDecl)
name, meta, kind := parseName(fieldDecl.StructDeclaratorList)
switch kind {
case ValueKind:
return Basic{qualifiers, typeName, name}
case PointerKind:
return Pointer{Basic{qualifiers, typeName, name}, meta.ptrQualifiers}
case ArrayKind:
return Array{Basic{qualifiers, typeName, name}, meta.arraySize}
case FunctionPointerKind:
return FuncPointer{typeName, name, meta.argsTypes}
case EnumEntryKind:
return EnumEntry(name)
default:
return nil
}
}
// parseQualifiers checks for qualifiers on the passed declaration and returns
// them, alongside with the type of the declaration, which is contained as the
// last qualifier in the declaration.
func parseQualifiers(fieldDecl *cc.StructDeclaration) ([]string, string) {
var (
qualifierId string
qualifiers []string
)
list := fieldDecl.SpecifierQualifierList
for ; list != nil; list = list.SpecifierQualifierList {
switch list.Case {
case cc.SpecifierQualifierListTypeQual: // case 1: TypeQualifier present
qual := list.TypeQualifier
qualifierId = qual.Token.SrcStr()
case cc.SpecifierQualifierListTypeSpec: // case 2: TypeSpecifier present
qual := list.TypeSpecifier
switch qual.Case {
case cc.TypeSpecifierStructOrUnion:
qualifierId = parseStructOrUnionQualifier(qual.StructOrUnionSpecifier)
case cc.TypeSpecifierEnum:
qualifierId = parseEnumQualifier(qual.EnumSpecifier)
default:
qualifierId = qual.Token.SrcStr()
}
}
qualifiers = append(qualifiers, qualifierId)
}
// this is the index of the type of the declaration
lastIdx := len(qualifiers) - 1
if len(qualifiers) > 1 {
return qualifiers[0:lastIdx], qualifiers[lastIdx]
}
return nil, qualifiers[lastIdx]
}
// parseStructOrUnionQualifier parses the aggregate qualifier in case the
// type is a fully qualified aggregate type.
func parseStructOrUnionQualifier(spec *cc.StructOrUnionSpecifier) string {
qualifierKind := spec.StructOrUnion.Token.SrcStr()
qualifierName := spec.Token.SrcStr()
return fmt.Sprintf("%s %s", qualifierKind, qualifierName)
}
// parseEnumQualifier parses the enum qualifier in case it is a fully
// qualified enum type.
func parseEnumQualifier(spec *cc.EnumSpecifier) string {
qualifierKind := spec.Token.SrcStr()
qualifierName := spec.Token2.SrcStr()
return fmt.Sprintf("%s %s", qualifierKind, qualifierName)
}
// A FieldMeta struct contains information related to the parsed field. It is
// populated differently based on which kind of field is encountered.
type FieldMeta struct {
ptrQualifiers []string
argsTypes []string
arraySize int
}
// parseName parses a declaratoer list in search of the field name. At this
// point in the parsing, it also extracts the kind for the Field which is
// being parsed, and any other metadata that may be available within the
// declarator list. This is a list of the pointer qualifiers, the argument
// types for function pointers, and array sizes.
func parseName(list *cc.StructDeclaratorList) (string, FieldMeta, FieldKind) {
var (
structDecl = list.StructDeclarator
decl = structDecl.Declarator
direct = decl.DirectDeclarator
fieldName = direct.Token.SrcStr() // this holds the name of the field...
)
// ...except in the array field case
if direct.AssignmentExpression != nil {
name, size := parseArrayName(direct)
return name, FieldMeta{arraySize: size}, ArrayKind
}
// ...and in the function pointer case
if direct.ParameterTypeList != nil {
name, args := parseFunctionPointerName(direct)
return name, FieldMeta{argsTypes: args}, FunctionPointerKind
}
// let us check if this is a pointer field
if decl.Pointer != nil {
qualifiers := parsePointerQualifiers(decl.Pointer)
return fieldName, FieldMeta{ptrQualifiers: qualifiers}, PointerKind
}
return fieldName, FieldMeta{}, ValueKind
}
// parsePointerQualifiers extracts the pointer qualifiers from the pointer
// description.
func parsePointerQualifiers(ptr *cc.Pointer) []string {
var qualifiers []string
for q := ptr.TypeQualifiers; q != nil; q = q.TypeQualifiers {
qualifierId := q.TypeQualifier.Token.SrcStr()
qualifiers = append(qualifiers, qualifierId)
}
return qualifiers
}
// parseArrayName parses the direct declarator for the array type and returns
// its name, alongside with its size.
func parseArrayName(direct *cc.DirectDeclarator) (string, int) {
// AssignmentExpression not nil if this is being called
var (
primaryExpr = direct.AssignmentExpression
name = direct.DirectDeclarator.Token.SrcStr()
size = resolveExpression(primaryExpr)
)
return name, size
}
// resolveExpression solves an integer expression and returns its result as
// a number. Used a lot to solve array constant expressions.
func resolveExpression(expr cc.ExpressionNode) int {
switch sizeExpr := expr.(type) {
case *cc.PrimaryExpression:
// handle list case (e.g. an expression in a parentheses)
if sizeExpr.ExpressionList != nil {
return resolveExpression(sizeExpr.ExpressionList)
}
size, _ := strconv.Atoi(sizeExpr.Token.SrcStr())
return size
case *cc.UnaryExpression:
switch sizeExpr.Case {
case cc.UnaryExpressionSizeofType:
var (
typeName = sizeExpr.TypeName
typeSpec = typeName.SpecifierQualifierList.TypeSpecifier
token = typeSpec.Token.SrcStr()
)
// TODO make it work for non primitive types too
typ := TypeMap[token]
return typ.Size
}
case *cc.AdditiveExpression:
var (
op = sizeExpr.Token.SrcStr()
lOperand = resolveExpression(sizeExpr.AdditiveExpression)
rOperand = resolveExpression(sizeExpr.MultiplicativeExpression)
)
switch op {
case "+":
return lOperand + rOperand
case "-":
return lOperand - rOperand
}
case *cc.MultiplicativeExpression:
var (
op = sizeExpr.Token.SrcStr()
lOperand = resolveExpression(sizeExpr.MultiplicativeExpression)
rOperand = resolveExpression(sizeExpr.CastExpression)
)
switch op {
case "*":
return lOperand * rOperand
case "/":
return lOperand / rOperand
case "%":
return lOperand % rOperand
}
}
return -1
}
// parseFunctionPointerName extracts the function pointer name and argument
// types from the passed direct declarator.
func parseFunctionPointerName(direct *cc.DirectDeclarator) (string, []string) {
var (
evenMoreDirect = direct.DirectDeclarator
superDeclarator = evenMoreDirect.Declarator
yoIHeardYouLikeDeclarators = superDeclarator.DirectDeclarator
)
fptrName := yoIHeardYouLikeDeclarators.Token.SrcStr()
args := parseParameterList(direct.ParameterTypeList)
return fptrName, args
}
// parseParameterList parses the parameter list for a function pointer field.
func parseParameterList(typeList *cc.ParameterTypeList) []string {
var args []string
for list := typeList.ParameterList; list != nil; list = list.ParameterList {
var (
paramDecl = list.ParameterDeclaration
declSpec = paramDecl.DeclarationSpecifiers
argType = declSpec.TypeSpecifier.Token.SrcStr()
)
args = append(args, argType)
}
return args
}
// getTypedefToken extracts the typedef token from the passed declaration.
func getTypedefToken(decl *cc.Declaration) *cc.Token {
if decl.DeclarationSpecifiers.Case == cc.DeclarationSpecifiersStorage {
// anonymous typedef'd enum case: this is found somewhere else
var (
declList = decl.InitDeclaratorList
initDecl = declList.InitDeclarator
directDecl = initDecl.Declarator.DirectDeclarator
)
return &directDecl.Token
}
return &decl.InitDeclaratorList.Token
}