modernc.org/cc@v1.0.1/etc.go (about) 1 // Copyright 2016 The CC Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package cc // import "modernc.org/cc" 6 7 import ( 8 "bytes" 9 "fmt" 10 "go/token" 11 "path/filepath" 12 "strings" 13 14 "modernc.org/golex/lex" 15 "modernc.org/mathutil" 16 "modernc.org/strutil" 17 "modernc.org/xc" 18 ) 19 20 var ( 21 _ Specifier = (*DeclarationSpecifiers)(nil) 22 _ Specifier = (*SpecifierQualifierList)(nil) 23 _ Specifier = (*spec)(nil) 24 25 _ Type = (*ctype)(nil) 26 ) 27 28 var ( 29 noTypedefNameAfter = map[rune]bool{ 30 '*': true, 31 '.': true, 32 ARROW: true, 33 BOOL: true, 34 CHAR: true, 35 COMPLEX: true, 36 DOUBLE: true, 37 ENUM: true, 38 FLOAT: true, 39 GOTO: true, 40 INT: true, 41 LONG: true, 42 SHORT: true, 43 SIGNED: true, 44 STRUCT: true, 45 TYPEDEFNAME: true, 46 UNION: true, 47 UNSIGNED: true, 48 VOID: true, 49 } 50 51 undefined = &ctype{} 52 debugTypeStrings bool 53 ) 54 55 // EnumConstant represents the name/value pair defined by an Enumerator. 56 type EnumConstant struct { 57 DefTok xc.Token // Enumeration constant name definition token. 58 Value interface{} // Value represented by name. Type of Value is C int. 59 Tokens []xc.Token // The tokens the constant expression consists of. 60 } 61 62 // Specifier describes a combination of {Function,StorageClass,Type}Specifiers 63 // and TypeQualifiers. 64 type Specifier interface { 65 IsAuto() bool // StorageClassSpecifier "auto" present. 66 IsConst() bool // TypeQualifier "const" present. 67 IsExtern() bool // StorageClassSpecifier "extern" present. 68 IsInline() bool // FunctionSpecifier "inline" present. 69 IsRegister() bool // StorageClassSpecifier "register" present. 70 IsRestrict() bool // TypeQualifier "restrict" present. 71 IsStatic() bool // StorageClassSpecifier "static" present. 72 IsTypedef() bool // StorageClassSpecifier "typedef" present. 73 IsVolatile() bool // TypeQualifier "volatile" present. 74 TypedefName() int // TypedefName returns the typedef name ID used, if any, zero otherwise. 75 attrs() int // Encoded attributes. 76 firstTypeSpecifier() *TypeSpecifier // 77 kind() Kind // 78 member(int) (*Member, error) // 79 str() string // 80 typeSpecifiers() int // Encoded TypeSpecifier combination. 81 } 82 83 // Type decribes properties of a C type. 84 type Type interface { 85 // AlignOf returns the alignment in bytes of a value of this type when 86 // allocated in memory not as a struct field. Incomplete struct types 87 // have no alignment and the value returned will be < 0. 88 AlignOf() int 89 90 // Bits returns the bit width of the type's value. For non integral 91 // types the returned value will < 0. 92 Bits() int 93 94 // SetBits returns a type instance with the value Bits() will return 95 // equal to n. SetBits panics for n < 0. 96 SetBits(n int) Type 97 98 // CanAssignTo returns whether this type can be assigned to dst. 99 CanAssignTo(dst Type) bool 100 101 // Declarator returns the full Declarator which defined an entity of 102 // this type. The returned declarator is possibly artificial. 103 Declarator() *Declarator 104 105 // RawDeclarator returns the typedef declarator associated with a type 106 // if this type is a typedef name. Otherwise the normal declarator is 107 // returned. 108 RawDeclarator() *Declarator 109 110 // Element returns the type this Ptr type points to or the element type 111 // of an Array type. 112 Element() Type 113 114 // Elements returns the number of elements an Array type has. The 115 // returned value is < 0 if this type is not an Array or if the array 116 // is not of a constant size. 117 Elements() int 118 119 // EnumeratorList returns the enumeration constants defined by an Enum 120 // type, if any. 121 EnumeratorList() []EnumConstant 122 123 // Kind returns one of Ptr, Void, Int, ... 124 Kind() Kind 125 126 // Member returns the type of a member of this Struct or Union type, 127 // having numeric name identifier nm. 128 Member(nm int) (*Member, error) 129 130 // Members returns the members of a Struct or Union type in declaration 131 // order. Returned members are valid iff non nil. 132 // 133 // Note: Non nil members of length 0 means the struct/union has no 134 // members or the type is incomplete, which is indicated by the 135 // isIncomplete return value. 136 // 137 // Note 2: C99 standard does not allow empty structs/unions, but GCC 138 // supports that as an extension. 139 Members() (members []Member, isIncomplete bool) 140 141 // Parameters returns the parameters of a Function type in declaration 142 // order. Result is valid iff params is not nil. 143 // 144 // Note: len(params) == 0 is fine and just means the function has no 145 // parameters. 146 Parameters() (params []Parameter, isVariadic bool) 147 148 // Pointer returns a type that points to this type. 149 Pointer() Type 150 151 // Result returns the result type of a Function type. 152 Result() Type 153 154 // Sizeof returns the number of bytes needed to store a value of this 155 // type. Incomplete struct types have no size and the value returned 156 // will be < 0. 157 SizeOf() int 158 159 // Specifier returns the Specifier of this type. 160 Specifier() Specifier 161 162 // String returns a C-like type specifier of this type. 163 String() string 164 165 // StructAlignOf returns the alignment in bytes of a value of this type 166 // when allocated in memory as a struct field. Incomplete struct types 167 // have no alignment and the value returned will be < 0. 168 StructAlignOf() int 169 170 // Tag returns the ID of a tag of a Struct, Union or Enum type, if any. 171 // Otherwise the returned value is zero. 172 Tag() int 173 174 sizeOf(*lexer) int 175 structAlignOf(*lexer) int 176 } 177 178 // Member describes a member of a struct or union. 179 // 180 // BitFieldGroup represents the ordinal number of the packed bit fields: 181 // 182 // struct foo { 183 // int i; 184 // int j:1; // BitFieldGroup: 0 185 // int k:2; // BitFieldGroup: 0 186 // double l; 187 // int m:1; // BitFieldGroup: 1 188 // int n:2; // BitFieldGroup: 1 189 // } 190 type Member struct { 191 BitFieldType Type 192 BitFieldGroup int // Ordinal number of the packed bits field. 193 BitOffsetOf int // Bit field starting bit. 194 Bits int // Size in bits for bit fields, 0 otherwise. 195 Declarator *Declarator // Possibly nil for bit fields. 196 Name int 197 OffsetOf int 198 Padding int // Number of unused bytes added to the end of the field to force proper alignment requirements. 199 Type Type 200 } 201 202 // Parameter describes a function argument. 203 type Parameter struct { 204 Declarator *Declarator 205 Name int 206 Type Type 207 } 208 209 // PrettyString pretty prints things produced by this package. 210 func PrettyString(v interface{}) string { 211 return strutil.PrettyString(v, "", "", printHooks) 212 } 213 214 func position(pos token.Pos) token.Position { return fset.Position(pos) } 215 216 // Binding records the declaration Node of a declared name. 217 // 218 // In the NSIdentifiers namespace the dynamic type of Node for declared names 219 // is always *DirectDeclarator. The *Declarator associated with the direct 220 // declarator is available via (*DirectDeclarator).TopDeclarator(). 221 // 222 // int* p; 223 // 224 // In the NSTags namespace the dynamic type of Node is xc.Token when a tag is 225 // declared: 226 // 227 // struct foo; 228 // enum bar; 229 // 230 // When a tag is defined, the dynamic type of Node is *EnumSpecifier or 231 // *StructOrUnionSpecifier: 232 // 233 // struct foo { int i; }; 234 // enum bar { a = 1 }; 235 // 236 type Binding struct { 237 Node Node 238 enum bool 239 } 240 241 // Bindings record names declared in a scope. 242 type Bindings struct { 243 Identifiers map[int]Binding // NSIdentifiers name space bindings. 244 Tags map[int]Binding // NSTags name space bindings. 245 kind Scope // ScopeFile, ... 246 Parent *Bindings // Parent scope or nil for ScopeFile. 247 248 // Scoped helpers. 249 250 mergeScope *Bindings // Fn params. 251 specifier Specifier // To store in full declarators. 252 253 // Struct/union field handling. 254 bitFieldGroup int // Group ordinal number. 255 bitFieldTypes []Type // 256 bitOffset int // 257 isUnion bool // 258 maxAlign int // 259 maxSize int // 260 offset int // 261 prevStructDeclarator *Declarator // 262 } 263 264 func newBindings(parent *Bindings, kind Scope) *Bindings { 265 return &Bindings{ 266 kind: kind, 267 Parent: parent, 268 } 269 } 270 271 // Scope retuns the kind of b. 272 func (b *Bindings) Scope() Scope { return b.kind } 273 274 func (b *Bindings) merge(c *Bindings) { 275 if b.kind != ScopeBlock || len(b.Identifiers) != 0 || c.kind != ScopeParams { 276 panic("internal error") 277 } 278 279 b.boot(NSIdentifiers) 280 for k, v := range c.Identifiers { 281 b.Identifiers[k] = v 282 } 283 } 284 285 func (b *Bindings) boot(ns Namespace) map[int]Binding { 286 var m *map[int]Binding 287 switch ns { 288 case NSIdentifiers: 289 m = &b.Identifiers 290 case NSTags: 291 m = &b.Tags 292 default: 293 panic(fmt.Errorf("internal error %v", ns)) 294 } 295 296 mp := *m 297 if mp == nil { 298 mp = make(map[int]Binding) 299 *m = mp 300 } 301 return mp 302 } 303 304 func (b *Bindings) root() *Bindings { 305 for b.Parent != nil { 306 b = b.Parent 307 } 308 return b 309 } 310 311 // Lookup returns the Binding of id in ns or any of its parents. If id is 312 // undeclared, the returned Binding has its Node field set to nil. 313 func (b *Bindings) Lookup(ns Namespace, id int) Binding { 314 r, _ := b.Lookup2(ns, id) 315 return r 316 } 317 318 // Lookup2 is like Lookup but addionally it returns also the scope in which id 319 // was found. 320 func (b *Bindings) Lookup2(ns Namespace, id int) (Binding, *Bindings) { 321 if ns == NSTags { 322 b = b.root() 323 } 324 for b != nil { 325 m := b.boot(ns) 326 if x, ok := m[id]; ok { 327 return x, b 328 } 329 330 b = b.Parent 331 } 332 333 return Binding{}, nil 334 } 335 336 func (b *Bindings) declareIdentifier(tok xc.Token, d *DirectDeclarator, report *xc.Report) { 337 m := b.boot(NSIdentifiers) 338 var p *Binding 339 if ex, ok := m[tok.Val]; ok { 340 p = &ex 341 } 342 343 d.prev = p 344 m[tok.Val] = Binding{d, false} 345 } 346 347 func (b *Bindings) declareEnumTag(tok xc.Token, report *xc.Report) { 348 b = b.root() 349 m := b.boot(NSTags) 350 if ex, ok := m[tok.Val]; ok { 351 if !ex.enum { 352 report.ErrTok(tok, "struct tag redeclared as enum tag, previous declaration/definition: %s", position(ex.Node.Pos())) 353 } 354 return 355 } 356 357 m[tok.Val] = Binding{tok, true} 358 } 359 360 func (b *Bindings) defineEnumTag(tok xc.Token, n Node, report *xc.Report) { 361 b = b.root() 362 m := b.boot(NSTags) 363 if ex, ok := m[tok.Val]; ok { 364 if !ex.enum { 365 report.ErrTok(tok, "struct tag redefined as enum tag, previous declaration/definition: %s", position(ex.Node.Pos())) 366 return 367 } 368 369 if _, ok := ex.Node.(xc.Token); !ok { 370 report.ErrTok(tok, "enum tag redefined, previous definition: %s", position(ex.Node.Pos())) 371 return 372 } 373 } 374 375 m[tok.Val] = Binding{n, true} 376 } 377 378 func (b *Bindings) defineEnumConst(lx *lexer, tok xc.Token, v interface{}) *Declarator { 379 b = b.root() 380 d := lx.model.makeDeclarator(0, tsInt) 381 dd := d.DirectDeclarator 382 dd.Token = tok 383 dd.EnumVal = v 384 d.setFull(lx) 385 b.declareIdentifier(tok, dd, lx.report) 386 switch x := v.(type) { 387 case int16: 388 lx.iota = int64(x) + 1 389 case int32: 390 lx.iota = int64(x) + 1 391 case int64: 392 lx.iota = x + 1 393 default: 394 panic(fmt.Errorf("%T", x)) 395 } 396 return d 397 } 398 399 func (b *Bindings) declareStructTag(tok xc.Token, report *xc.Report) { 400 b = b.root() 401 m := b.boot(NSTags) 402 if ex, ok := m[tok.Val]; ok { 403 if ex.enum { 404 report.ErrTok(tok, "enum tag redeclared as struct tag, previous declaration/definition: %s", position(ex.Node.Pos())) 405 } 406 return 407 } 408 409 m[tok.Val] = Binding{tok, false} 410 } 411 412 func (b *Bindings) defineStructTag(tok xc.Token, n Node, report *xc.Report) { 413 b = b.root() 414 m := b.boot(NSTags) 415 if ex, ok := m[tok.Val]; ok { 416 if ex.enum { 417 report.ErrTok(tok, "enum tag redefined as struct tag, previous declaration/definition: %s", position(ex.Node.Pos())) 418 return 419 } 420 421 if _, ok := ex.Node.(xc.Token); !ok { 422 if !n.(*StructOrUnionSpecifier).isCompatible(ex.Node.(*StructOrUnionSpecifier)) { 423 report.ErrTok(tok, "incompatible struct tag redefinition, previous definition at %s", position(ex.Node.Pos())) 424 } 425 return 426 } 427 } 428 429 m[tok.Val] = Binding{n, false} 430 } 431 432 func (b *Bindings) isTypedefName(id int) bool { 433 x := b.Lookup(NSIdentifiers, id) 434 if dd, ok := x.Node.(*DirectDeclarator); ok { 435 return dd.specifier.IsTypedef() 436 } 437 438 return false 439 } 440 441 func (b *Bindings) lexerHack(tok, prev xc.Token) xc.Token { // https://en.wikipedia.org/wiki/The_lexer_hack 442 if noTypedefNameAfter[prev.Rune] { 443 return tok 444 } 445 446 if tok.Rune == IDENTIFIER && b.isTypedefName(tok.Val) { 447 tok.Char = lex.NewChar(tok.Pos(), TYPEDEFNAME) 448 } 449 return tok 450 } 451 452 func errPos(a ...token.Pos) token.Pos { 453 for _, v := range a { 454 if v.IsValid() { 455 return v 456 } 457 } 458 459 return token.Pos(0) 460 } 461 462 func isZero(v interface{}) bool { return !isNonZero(v) } 463 464 func isNonZero(v interface{}) bool { 465 switch x := v.(type) { 466 case int32: 467 return x != 0 468 case int: 469 return x != 0 470 case uint32: 471 return x != 0 472 case int64: 473 return x != 0 474 case uint64: 475 return x != 0 476 case float32: 477 return x != 0 478 case float64: 479 return x != 0 480 case StringLitID, LongStringLitID: 481 return true 482 default: 483 panic(fmt.Errorf("internal error: %T", x)) 484 } 485 } 486 487 func fromSlashes(a []string) []string { 488 for i, v := range a { 489 a[i] = filepath.FromSlash(v) 490 } 491 return a 492 } 493 494 type ctype struct { 495 bits int 496 dds []*DirectDeclarator // Expanded. 497 dds0 []*DirectDeclarator // Unexpanded, only for typedefs 498 model *Model 499 resultAttr int 500 resultSpecifier Specifier 501 resultStars int 502 stars int 503 } 504 505 func (n *ctype) SetBits(b int) Type { 506 if b < 0 { 507 panic("internal error") 508 } 509 510 if b == n.bits { 511 return n 512 } 513 514 o := *n 515 o.bits = b 516 return &o 517 } 518 519 func (n *ctype) Bits() int { 520 if n.bits > 0 { 521 return n.bits 522 } 523 524 if !IsIntType(n) { 525 return -1 526 } 527 528 n.bits = n.model.Items[n.Kind()].Size * 8 529 return n.bits 530 } 531 532 func (n *ctype) arrayDecay() *ctype { 533 return n.setElements(-1) 534 } 535 536 func (n *ctype) setElements(elems int) *ctype { 537 m := *n 538 m.dds = append([]*DirectDeclarator(nil), n.dds...) 539 for i, dd := range m.dds { 540 switch dd.Case { 541 case 0: // IDENTIFIER 542 // nop 543 case 2: // DirectDeclarator '[' TypeQualifierListOpt ExpressionOpt ']' 544 dd := dd.clone() 545 dd.elements = elems 546 m.dds[i] = dd 547 return &m 548 default: 549 //dbg("", position(dd.Pos()), n.str(), elems) 550 panic(dd.Case) 551 } 552 } 553 return n 554 } 555 556 func (n *ctype) eq(m *ctype) (r bool) { 557 const ignore = saInline | saTypedef | saExtern | saStatic | saAuto | saRegister | saConst | saRestrict | saVolatile | saNoreturn 558 559 if n == m { 560 return true 561 } 562 563 if len(n.dds) != len(m.dds) || n.resultAttr&^ignore != m.resultAttr&^ignore || 564 n.resultStars != m.resultStars || n.stars != m.stars { 565 return false 566 } 567 568 for i, n := range n.dds { 569 if !n.isCompatible(m.dds[i]) { 570 return false 571 } 572 } 573 574 return n.resultSpecifier.str() == m.resultSpecifier.str() 575 } 576 577 func (n *ctype) isCompatible(m *ctype) (r bool) { 578 const ignore = saInline | saTypedef | saExtern | saStatic | saAuto | saRegister | saConst | saRestrict | saVolatile | saNoreturn 579 580 if n == m { 581 return true 582 } 583 584 if n.Kind() == Array { 585 n = n.arrayDecay() 586 } 587 588 if m.Kind() == Array { 589 m = m.arrayDecay() 590 } 591 592 if len(n.dds) != len(m.dds) || n.resultAttr&^ignore != m.resultAttr&^ignore || 593 n.resultStars != m.resultStars || n.stars != m.stars { 594 return false 595 } 596 597 if n.Kind() == Function && m.Kind() == Function { 598 a, va := n.Parameters() 599 b, vb := m.Parameters() 600 return isCompatibleParameters(a, b, va, vb) 601 } 602 603 for i, n := range n.dds { 604 if !n.isCompatible(m.dds[i]) { 605 return false 606 } 607 } 608 609 ns := n.resultSpecifier 610 ms := m.resultSpecifier 611 if ns == ms { 612 return true 613 } 614 615 if n.Kind() != m.Kind() { 616 return false 617 } 618 619 switch ns.kind() { 620 case Array: 621 panic("internal error") 622 case Struct, Union: 623 return n.structOrUnionSpecifier().isCompatible(m.structOrUnionSpecifier()) 624 case Enum: 625 /*TODO 626 6.2.7 Compatible type and composite type 627 628 1 Two types have compatible type if their types are the same. 629 Additional rules for determining whether two types are 630 compatible are described in 6.7.2 for type specifiers, in 6.7.3 631 for type qualifiers, and in 6.7.5 for declarators.46) Moreover, 632 two structure, union, or enumerated types declared in separate 633 translation units are compatible if their tags and members 634 satisfy the following requirements: If one is declared with a 635 tag, the other shall be declared with the same tag. If both are 636 complete types, then the following additional requirements 637 apply: there shall be a one-to-one correspondence between their 638 members such that each pair of corresponding members are 639 declared with compatible types, and such that if one member of 640 a corresponding pair is declared with a name, the other member 641 is declared with the same name. For two structures, 642 corresponding members shall be declared in the same order. For 643 two structures or unions, corresponding bit-fields shall have 644 the same widths. For two enumerations, corresponding members 645 shall have the same values. 646 647 */ 648 return ms.kind() == Enum 649 case TypedefName: 650 panic("internal error") 651 default: 652 return true 653 } 654 } 655 656 func (n *ctype) index(d int) int { return len(n.dds) - 1 + d } 657 658 func (n *ctype) top(d int) *DirectDeclarator { 659 return n.dds[n.index(d)] 660 } 661 662 // AlignOf implements Type. 663 func (n *ctype) AlignOf() int { 664 if n == undefined { 665 return 1 666 } 667 668 if n.Kind() == Array { 669 return n.Element().AlignOf() 670 } 671 672 switch k := n.Kind(); k { 673 case 674 Void, 675 Ptr, 676 Char, 677 SChar, 678 UChar, 679 Short, 680 UShort, 681 Int, 682 UInt, 683 Long, 684 ULong, 685 LongLong, 686 ULongLong, 687 Float, 688 Double, 689 LongDouble, 690 Bool, 691 FloatComplex, 692 DoubleComplex, 693 LongDoubleComplex: 694 return n.model.Items[k].Align 695 case Enum: 696 return n.model.Items[Int].Align 697 case Struct, Union: 698 switch sus := n.structOrUnionSpecifier(); sus.Case { 699 case 1: // StructOrUnion IDENTIFIER 700 return -1 // Incomplete type 701 case 0: // StructOrUnion IdentifierOpt '{' StructDeclarationList '}' 702 return sus.alignOf 703 default: 704 panic(sus.Case) 705 } 706 default: 707 panic(k.String()) 708 } 709 } 710 711 func (n *ctype) unionCanAssignTo(dst Type) bool { 712 m, isIncomplete := n.Members() 713 if isIncomplete { 714 return false 715 } 716 717 for _, v := range m { 718 if v.Type.CanAssignTo(dst) { 719 return true 720 } 721 } 722 723 return false 724 } 725 726 // CanAssignTo implements Type. 727 func (n *ctype) CanAssignTo(dst Type) bool { 728 if n == undefined || dst.Kind() == Undefined { 729 return false 730 } 731 732 if n.Kind() == Bool && IsIntType(dst) { 733 return true 734 } 735 736 if dst.Kind() == Bool && IsIntType(n) { 737 return true 738 } 739 740 if n.Kind() == Union && n.unionCanAssignTo(dst) { 741 return true 742 } 743 744 if dst.Kind() == Union && dst.(*ctype).unionCanAssignTo(n) { 745 return true 746 } 747 748 if n.Kind() == Function { 749 n = n.Pointer().(*ctype) 750 } 751 752 if dst.Kind() == Function { 753 dst = dst.Pointer().(*ctype) 754 } 755 756 if n.Kind() == Array && dst.Kind() == Ptr { 757 n = n.arrayDecay() 758 } 759 760 if dst.Kind() == Array && n.Kind() == Ptr { 761 dst = dst.(*ctype).arrayDecay() 762 } 763 764 if IsArithmeticType(n) && IsArithmeticType(dst) { 765 return true 766 } 767 768 if IsIntType(n) && dst.Kind() == Enum { 769 return true 770 } 771 772 if n.Kind() == Enum && IsIntType(dst) { 773 return true 774 } 775 776 if n.Kind() == Ptr && dst.Kind() == Ptr && dst.Element().Kind() == Void { 777 return true 778 } 779 780 if n.Kind() == Ptr && n.Element().Kind() == Void && dst.Kind() == Ptr { 781 return true 782 } 783 784 if n.isCompatible(dst.(*ctype)) { 785 return true 786 } 787 788 if n.Kind() == Ptr && dst.Kind() == Ptr { 789 t := Type(n) 790 u := dst 791 for t.Kind() == Ptr && u.Kind() == Ptr { 792 t = t.Element() 793 u = u.Element() 794 } 795 if t.Kind() == Array && unsigned(t.Element().Kind()) == unsigned(u.Kind()) { 796 return true 797 } 798 799 if t.Kind() == Ptr || u.Kind() == Ptr { 800 return false 801 } 802 803 if IsIntType(t) && IsIntType(u) && unsigned(t.Kind()) == unsigned(u.Kind()) { 804 return true 805 } 806 807 if t.Kind() == Function && u.Kind() == Function { 808 a, _ := t.Parameters() 809 b, _ := u.Parameters() 810 if (len(a) == 0) != (len(b) == 0) { 811 a := t.Result() 812 b := u.Result() 813 return a.Kind() == Void && b.Kind() == Void || t.Result().CanAssignTo(u.Result()) 814 } 815 } 816 817 return t.(*ctype).isCompatible(u.(*ctype)) 818 } 819 820 if n.Kind() == Function && dst.Kind() == Ptr && dst.Element().Kind() == Function { 821 return n.isCompatible(dst.Element().(*ctype)) 822 } 823 824 if dst.Kind() == Ptr { 825 if IsIntType(n) { 826 return true 827 } 828 } 829 830 return false 831 } 832 833 // RawDeclarator implements Type. 834 func (n *ctype) RawDeclarator() *Declarator { 835 if len(n.dds0) == 0 { 836 return n.dds[0].TopDeclarator() 837 } 838 839 return n.dds0[0].TopDeclarator() 840 } 841 842 // Declarator implements Type. 843 func (n *ctype) Declarator() *Declarator { 844 if len(n.dds) == 0 { 845 panic("internal error") 846 } 847 848 return n.dds[0].TopDeclarator() 849 } 850 851 // Element implements Type. 852 func (n *ctype) Element() Type { 853 if n == undefined { 854 return n 855 } 856 857 if n.Kind() != Ptr && n.Kind() != Array { 858 return undefined 859 } 860 861 if len(n.dds) == 1 { 862 m := *n 863 m.stars-- 864 return &m 865 } 866 867 switch dd := n.dds[1]; dd.Case { 868 case 1: // '(' Declarator ')' 869 if n.stars == 1 { 870 m := *n 871 m.dds = append([]*DirectDeclarator{n.dds[0]}, n.dds[2:]...) 872 m.dds0 = n.dds0 873 switch len(m.dds0) { 874 case 0: 875 // nop 876 case 1: 877 nm := m.Declarator().RawSpecifier().TypedefName() 878 typedef := m.Declarator().DirectDeclarator.idScope.Lookup(NSIdentifiers, nm) 879 if typedef.Node == nil { 880 break // undefined 881 } 882 883 m.dds0 = typedef.Node.(*DirectDeclarator).TopDeclarator().Type.(*ctype).dds0 884 if len(m.dds0) < 3 { 885 break 886 } 887 888 fallthrough 889 default: 890 m.dds0 = append([]*DirectDeclarator{m.dds0[0]}, m.dds0[2:]...) 891 } 892 m.stars-- 893 return &m 894 } 895 896 m := *n 897 m.stars-- 898 return &m 899 case 2: // DirectDeclarator '[' TypeQualifierListOpt ExpressionOpt ']' 900 m := *n 901 m.dds = append([]*DirectDeclarator{n.dds[0]}, n.dds[2:]...) 902 switch { 903 case len(m.dds) == 1: 904 m.stars += m.resultStars 905 m.resultStars = 0 906 default: 907 if dd := m.dds[1]; dd.Case == 1 { // '(' Declarator ')' 908 m.stars = dd.Declarator.stars() 909 if dd.Declarator.stars() == 0 { 910 m.dds = append([]*DirectDeclarator{m.dds[0]}, m.dds[2:]...) 911 } 912 } 913 } 914 return &m 915 default: 916 //dbg("", position(n.dds[0].Pos()), n, n.Kind()) 917 //dbg("", n.str()) 918 panic(dd.Case) 919 } 920 } 921 922 // Kind implements Type. 923 func (n *ctype) Kind() Kind { 924 if n == undefined { 925 return Undefined 926 } 927 928 if n.stars > 0 { 929 return Ptr 930 } 931 932 if len(n.dds) == 1 { 933 return n.resultSpecifier.kind() 934 } 935 936 i := 1 937 for { 938 switch dd := n.dds[i]; dd.Case { 939 //TODO case 1: // '(' Declarator ')' 940 case 2: // DirectDeclarator '[' TypeQualifierListOpt ExpressionOpt ']' 941 if dd.elements < 0 { 942 return Ptr 943 } 944 945 return Array 946 case 947 6, // DirectDeclarator '(' ParameterTypeList ')' 948 7: // DirectDeclarator '(' IdentifierListOpt ')' 949 return Function 950 default: 951 //dbg("", position(n.Declarator().Pos())) 952 //dbg("", n) 953 //dbg("", n.str()) 954 panic(dd.Case) 955 } 956 } 957 } 958 959 // Member implements Type. 960 func (n *ctype) Member(nm int) (*Member, error) { 961 if n == undefined { 962 return nil, fmt.Errorf("not a struct/union (have '%s')", n) 963 } 964 965 if n.Kind() == Array { 966 panic("TODO") 967 } 968 969 if k := n.Kind(); k != Struct && k != Union { 970 return nil, fmt.Errorf("request for member %s in something not a structure or union (have '%s')", xc.Dict.S(nm), n) 971 } 972 973 a, _ := n.Members() 974 for i := range a { 975 if a[i].Name == nm { 976 return &a[i], nil 977 } 978 } 979 980 return nil, fmt.Errorf("%s has no member named %s", Type(n), xc.Dict.S(nm)) 981 } 982 983 // Returns nil if type kind != Enum 984 func (n *ctype) enumSpecifier() *EnumSpecifier { 985 return n.resultSpecifier.firstTypeSpecifier().EnumSpecifier 986 } 987 988 func (n *ctype) structOrUnionSpecifier() *StructOrUnionSpecifier { 989 if k := n.Kind(); k != Struct && k != Union { 990 return nil 991 } 992 993 ts := n.resultSpecifier.firstTypeSpecifier() 994 if ts.Case != 11 { // StructOrUnionSpecifier 995 panic("internal error") 996 } 997 998 switch sus := ts.StructOrUnionSpecifier; sus.Case { 999 case 0: // StructOrUnion IdentifierOpt '{' StructDeclarationList '}' 1000 return sus 1001 case 1: // StructOrUnion IDENTIFIER 1002 b := sus.scope.Lookup(NSTags, sus.Token.Val) 1003 switch x := b.Node.(type) { 1004 case nil: 1005 return sus 1006 case *StructOrUnionSpecifier: 1007 return x 1008 case xc.Token: 1009 return sus 1010 default: 1011 panic("internal error") 1012 } 1013 case 2: // StructOrUnion IdentifierOpt '{' '}' // Case 2 1014 return sus 1015 default: 1016 panic(sus.Case) 1017 } 1018 } 1019 1020 func (n *ctype) members(p *[]Member, l *StructDeclarationList) { 1021 r := *p 1022 defer func() { *p = r }() 1023 1024 for ; l != nil; l = l.StructDeclarationList { 1025 switch sdn := l.StructDeclaration; sdn.Case { 1026 case 0: // SpecifierQualifierList StructDeclaratorList ';' 1027 for l := sdn.StructDeclaratorList; l != nil; l = l.StructDeclaratorList { 1028 var d *Declarator 1029 var bits int 1030 switch sd := l.StructDeclarator; sd.Case { 1031 case 0: // Declarator 1032 d = sd.Declarator 1033 case 1: // DeclaratorOpt ':' ConstantExpression 1034 if o := sd.DeclaratorOpt; o != nil { 1035 d = o.Declarator 1036 } 1037 switch x := sd.ConstantExpression.Value.(type) { 1038 case int32: 1039 bits = int(x) 1040 case int64: 1041 if x <= int64(n.model.Items[Int].Size*8) { 1042 bits = int(x) 1043 break 1044 } 1045 1046 panic("internal error") 1047 case uint64: 1048 if x <= uint64(n.model.Items[Int].Size*8) { 1049 bits = int(x) 1050 break 1051 } 1052 1053 panic("internal error") 1054 default: 1055 panic("internal error") 1056 } 1057 default: 1058 panic(sd.Case) 1059 } 1060 var id, off, pad, bitoff, group int 1061 t := n.model.IntType 1062 var bt Type 1063 if d != nil { 1064 id, _ = d.Identifier() 1065 t = d.Type 1066 off = d.offsetOf 1067 pad = d.padding 1068 bitoff = d.bitOffset 1069 bt = d.bitFieldType 1070 group = d.bitFieldGroup 1071 } 1072 r = append(r, Member{ 1073 BitFieldGroup: group, 1074 BitFieldType: bt, 1075 BitOffsetOf: bitoff, 1076 Bits: bits, 1077 Declarator: d, 1078 Name: id, 1079 OffsetOf: off, 1080 Padding: pad, 1081 Type: t, 1082 }) 1083 } 1084 case 1: // SpecifierQualifierList ';' // Case 1 1085 d := sdn.SpecifierQualifierList.TypeSpecifier.StructOrUnionSpecifier.declarator 1086 t := d.Type 1087 r = append(r, Member{ 1088 Declarator: d, 1089 OffsetOf: d.offsetOf, 1090 Padding: d.padding, 1091 Type: t, 1092 }) 1093 case 2: // StaticAssertDeclaration // Case 2 1094 //nop 1095 default: 1096 panic("internal error") 1097 } 1098 } 1099 } 1100 1101 // Members implements Type. 1102 func (n *ctype) Members() (r []Member, isIncomplete bool) { 1103 if k := n.Kind(); k != Struct && k != Union { 1104 return nil, false 1105 } 1106 1107 switch sus := n.structOrUnionSpecifier(); sus.Case { 1108 case 0: // StructOrUnion IdentifierOpt '{' StructDeclarationList '}' 1109 n.members(&r, sus.StructDeclarationList) 1110 return r, false 1111 case 1: // StructOrUnion IDENTIFIER 1112 return []Member{}, true 1113 case 2: // StructOrUnion IdentifierOpt '{' '}' // Case 2 1114 return []Member{}, false 1115 default: 1116 panic(sus.Case) 1117 } 1118 } 1119 1120 // Parameters implements Type. 1121 func (n *ctype) Parameters() ([]Parameter, bool) { 1122 if n == undefined || n.Kind() != Function { 1123 return nil, false 1124 } 1125 1126 switch dd := n.dds[1]; dd.Case { 1127 case 6: // DirectDeclarator '(' ParameterTypeList ')' 1128 l := dd.ParameterTypeList 1129 return l.params, l.Case == 1 // ParameterList ',' "..." 1130 case 7: // DirectDeclarator '(' IdentifierListOpt ')' 1131 o := dd.IdentifierListOpt 1132 if o == nil { 1133 return make([]Parameter, 0), false 1134 } 1135 1136 return o.params, false 1137 default: 1138 //dbg("", dd.Case) 1139 panic("internal error") 1140 } 1141 } 1142 1143 // Pointer implements Type. 1144 func (n *ctype) Pointer() Type { 1145 if n == undefined { 1146 return n 1147 } 1148 1149 if len(n.dds) == 1 { 1150 m := *n 1151 m.stars++ 1152 return &m 1153 } 1154 1155 switch dd := n.dds[1]; dd.Case { 1156 case 1157 2, // DirectDeclarator '[' TypeQualifierListOpt ExpressionOpt ']' // Case 2 1158 3, // DirectDeclarator '[' "static" TypeQualifierListOpt Expression ']' // Case 3 1159 4, // DirectDeclarator '[' TypeQualifierList "static" Expression ']' // Case 4 1160 5, // DirectDeclarator '[' TypeQualifierListOpt '*' ']' // Case 5 1161 6, // DirectDeclarator '(' ParameterTypeList ')' 1162 7: // DirectDeclarator '(' IdentifierListOpt ')' 1163 dd := &DirectDeclarator{ 1164 Case: 1, // '(' Declarator ')' 1165 Declarator: &Declarator{ 1166 DirectDeclarator: &DirectDeclarator{}, 1167 PointerOpt: &PointerOpt{ 1168 Pointer: &Pointer{}, 1169 }, 1170 }, 1171 } 1172 m := *n 1173 m.dds = append(append([]*DirectDeclarator{n.dds[0]}, dd), n.dds[1:]...) 1174 m.stars++ 1175 return &m 1176 default: 1177 m := *n 1178 m.stars++ 1179 return &m 1180 } 1181 } 1182 1183 // Result implements Type. 1184 func (n *ctype) Result() Type { 1185 if n == undefined { 1186 return n 1187 } 1188 1189 if n.Kind() != Function { 1190 //dbg("", n, n.Kind()) 1191 //dbg("", n.str()) 1192 panic("TODO") 1193 } 1194 1195 i := 1 1196 for { 1197 switch dd := n.dds[i]; dd.Case { 1198 case 1199 6, // DirectDeclarator '(' ParameterTypeList ')' 1200 7: // DirectDeclarator '(' IdentifierListOpt ')' 1201 if i == len(n.dds)-1 { // Outermost function. 1202 if i == 1 { 1203 m := *n 1204 m.dds = m.dds[:1:1] 1205 m.stars += m.resultStars 1206 m.resultStars = 0 1207 return &m 1208 } 1209 1210 //dbg("", n) 1211 //dbg("", n.str()) 1212 panic("TODO") 1213 } 1214 1215 m := *n 1216 m.dds = append([]*DirectDeclarator{n.dds[0]}, n.dds[i+1:]...) 1217 if dd := m.dds[1]; dd.Case == 1 { // '(' Declarator ')' 1218 m.stars = dd.Declarator.stars() 1219 } 1220 return &m 1221 default: 1222 //dbg("", position(n.dds[0].Pos()), n) 1223 //dbg("", n.str()) 1224 panic(dd.Case) 1225 } 1226 1227 } 1228 } 1229 1230 // Elements implements Type. 1231 func (n *ctype) Elements() int { 1232 done := false 1233 loop: 1234 for _, dd := range n.dds { 1235 more: 1236 switch dd.Case { 1237 case 0: // IDENTIFIER 1238 case 1: // '(' Declarator ')' 1239 dd = dd.Declarator.DirectDeclarator 1240 done = true 1241 goto more 1242 case 1243 2, // DirectDeclarator '[' TypeQualifierListOpt ExpressionOpt ']' 1244 3, // DirectDeclarator '[' "static" TypeQualifierListOpt Expression ']' 1245 4, // DirectDeclarator '[' TypeQualifierList "static" Expression ']' 1246 5: // DirectDeclarator '[' TypeQualifierListOpt '*' ']' 1247 return dd.elements 1248 case 6: // DirectDeclarator '(' ParameterTypeList ')' // Case 6 1249 break loop 1250 default: 1251 //dbg("", position(n.dds[0].Pos()), n) 1252 //dbg("", n.str()) 1253 panic(dd.Case) 1254 } 1255 if done { 1256 break 1257 } 1258 } 1259 return -1 1260 } 1261 1262 // EnumeratorList implements Type 1263 func (n *ctype) EnumeratorList() (r []EnumConstant) { 1264 if n.Kind() != Enum { 1265 return nil 1266 } 1267 1268 switch es := n.enumSpecifier(); es.Case { 1269 case 0: // "enum" IdentifierOpt '{' EnumeratorList CommaOpt '}' 1270 for l := es.EnumeratorList; l != nil; l = l.EnumeratorList { 1271 e := l.Enumerator 1272 if e.ConstantExpression != nil { 1273 r = append(r, EnumConstant{ 1274 DefTok: e.EnumerationConstant.Token, 1275 Value: e.Value, 1276 Tokens: e.ConstantExpression.toks}) 1277 continue 1278 } 1279 r = append(r, EnumConstant{ 1280 DefTok: e.EnumerationConstant.Token, 1281 Value: e.Value, 1282 }) 1283 } 1284 return r 1285 case 1: // "enum" IDENTIFIER 1286 return nil 1287 default: 1288 panic(es.Case) 1289 } 1290 } 1291 1292 // SizeOf implements Type. 1293 func (n *ctype) SizeOf() int { 1294 if n == undefined { 1295 return 1 1296 } 1297 1298 if n.Kind() == Array { 1299 switch nelem := n.Elements(); { 1300 case nelem < 0: 1301 return n.model.Items[Ptr].Size 1302 default: 1303 return nelem * n.Element().SizeOf() 1304 } 1305 } 1306 1307 switch k := n.Kind(); k { 1308 case 1309 Void, 1310 Ptr, 1311 Char, 1312 SChar, 1313 UChar, 1314 Short, 1315 UShort, 1316 Int, 1317 UInt, 1318 Long, 1319 ULong, 1320 LongLong, 1321 ULongLong, 1322 Float, 1323 Double, 1324 LongDouble, 1325 Bool, 1326 FloatComplex, 1327 DoubleComplex, 1328 LongDoubleComplex: 1329 return n.model.Items[k].Size 1330 case Enum: 1331 return n.model.Items[Int].Size 1332 case Struct, Union: 1333 switch sus := n.structOrUnionSpecifier(); sus.Case { 1334 case 0: // StructOrUnion IdentifierOpt '{' StructDeclarationList '}' 1335 return sus.sizeOf 1336 case 1: // StructOrUnion IDENTIFIER 1337 return -1 // Incomplete type 1338 case 2: // StructOrUnion IdentifierOpt '{' '}' // Case 2 1339 return 0 1340 default: 1341 panic(sus.Case) 1342 } 1343 case Function: 1344 return n.model.Items[Ptr].Size 1345 default: 1346 return -1 1347 } 1348 } 1349 1350 func (n *ctype) sizeOf(lx *lexer) int { 1351 r := n.SizeOf() 1352 if r < 0 { 1353 lx.report.Err(n.Declarator().Pos(), "cannot determine size of %v", n) 1354 r = 1 1355 } 1356 return r 1357 } 1358 1359 // Specifier implements Type. 1360 func (n *ctype) Specifier() Specifier { return &spec{n.resultAttr, n.resultSpecifier.typeSpecifiers()} } 1361 1362 // String implements Type. 1363 func (n *ctype) String() string { 1364 if n == undefined { 1365 return "<undefined>" 1366 } 1367 1368 var buf bytes.Buffer 1369 s := attrString(n.resultAttr) 1370 buf.WriteString(s) 1371 if s != "" { 1372 buf.WriteString(" ") 1373 } 1374 s = specifierString(n.resultSpecifier) 1375 buf.WriteString(s) 1376 buf.WriteString(strings.Repeat("*", n.resultStars)) 1377 1378 params := func(p []Parameter) { 1379 for i, v := range p { 1380 fmt.Fprintf(&buf, "%s", v.Type) 1381 if i != len(p)-1 { 1382 buf.WriteByte(',') 1383 } 1384 } 1385 } 1386 1387 var f func(int) 1388 starsWritten := false 1389 f = func(x int) { 1390 switch dd := n.top(x); dd.Case { 1391 case 0: // IDENTIFIER 1392 if debugTypeStrings { 1393 id := dd.Token.Val 1394 if id == 0 { 1395 id = idID 1396 } 1397 fmt.Fprintf(&buf, "<%s>", xc.Dict.S(id)) 1398 } 1399 if !starsWritten { 1400 buf.WriteString(strings.Repeat("*", n.stars)) 1401 } 1402 case 1: // '(' Declarator ')' 1403 buf.WriteString("(") 1404 s := 0 1405 switch dd2 := n.top(x - 1); dd2.Case { 1406 case 0: // IDENTIFIER 1407 s = n.stars 1408 starsWritten = true 1409 default: 1410 s = dd.Declarator.stars() 1411 } 1412 buf.WriteString(strings.Repeat("*", s)) 1413 f(x - 1) 1414 buf.WriteString(")") 1415 case 2: // DirectDeclarator '[' TypeQualifierListOpt ExpressionOpt ']' 1416 f(x - 1) 1417 buf.WriteString("[") 1418 sep := "" 1419 if o := dd.TypeQualifierListOpt; o != nil { 1420 buf.WriteString(attrString(o.TypeQualifierList.attr)) 1421 sep = " " 1422 } 1423 if e := dd.elements; e > 0 { 1424 buf.WriteString(sep) 1425 fmt.Fprint(&buf, e) 1426 } 1427 buf.WriteString("]") 1428 case 6: // DirectDeclarator '(' ParameterTypeList ')' 1429 f(x - 1) 1430 buf.WriteString("(") 1431 params(dd.ParameterTypeList.params) 1432 buf.WriteString(")") 1433 case 7: // DirectDeclarator '(' IdentifierListOpt ')' 1434 f(x - 1) 1435 buf.WriteString("(") 1436 if o := dd.IdentifierListOpt; o != nil { 1437 params(o.params) 1438 } 1439 buf.WriteString(")") 1440 default: 1441 panic(dd.Case) 1442 } 1443 } 1444 f(0) 1445 return buf.String() 1446 } 1447 1448 // StructAlignOf implements Type. 1449 func (n *ctype) StructAlignOf() int { 1450 if n == undefined { 1451 return 1 1452 } 1453 1454 if n.Kind() == Array { 1455 return n.Element().StructAlignOf() 1456 } 1457 1458 switch k := n.Kind(); k { 1459 case 1460 Void, 1461 Ptr, 1462 Char, 1463 SChar, 1464 UChar, 1465 Short, 1466 UShort, 1467 Int, 1468 UInt, 1469 Long, 1470 ULong, 1471 LongLong, 1472 ULongLong, 1473 Float, 1474 Double, 1475 LongDouble, 1476 Bool, 1477 FloatComplex, 1478 DoubleComplex, 1479 LongDoubleComplex: 1480 return n.model.Items[k].StructAlign 1481 case Enum: 1482 return n.model.Items[Int].StructAlign 1483 case Struct, Union: 1484 switch sus := n.structOrUnionSpecifier(); sus.Case { 1485 case 0: // StructOrUnion IdentifierOpt '{' StructDeclarationList '}' 1486 return sus.alignOf 1487 case 1: // StructOrUnion IDENTIFIER 1488 return -1 // Incomplete type 1489 case 2: // StructOrUnion IdentifierOpt '{' '}' // Case 2 1490 return 1 1491 default: 1492 panic(sus.Case) 1493 } 1494 default: 1495 return -1 1496 } 1497 } 1498 1499 func (n *ctype) structAlignOf(lx *lexer) int { 1500 r := n.StructAlignOf() 1501 if r < 0 { 1502 lx.report.Err(n.Declarator().Pos(), "cannot determine struct align of %v", n) 1503 r = 1 1504 } 1505 return r 1506 } 1507 1508 // Tag implements Type. 1509 func (n *ctype) Tag() int { 1510 switch k := n.Kind(); k { 1511 case Struct, Union: 1512 switch sus := n.structOrUnionSpecifier(); sus.Case { 1513 case 0: // StructOrUnion IdentifierOpt '{' StructDeclarationList '}' 1514 if o := sus.IdentifierOpt; o != nil { 1515 return o.Token.Val 1516 } 1517 1518 return 0 1519 case 1: // StructOrUnion IDENTIFIER 1520 return sus.Token.Val 1521 default: 1522 panic(sus.Case) 1523 } 1524 case Enum: 1525 es := n.enumSpecifier() 1526 if es == nil { 1527 return 0 1528 } 1529 1530 switch es.Case { 1531 case 0: // "enum" IdentifierOpt '{' EnumeratorList CommaOpt '}' 1532 if o := es.IdentifierOpt; o != nil { 1533 return o.Token.Val 1534 } 1535 1536 return 0 1537 case 1: // "enum" IDENTIFIER 1538 return es.Token2.Val 1539 default: 1540 panic(es.Case) 1541 } 1542 default: 1543 return 0 1544 } 1545 } 1546 1547 type spec struct { 1548 attr int 1549 ts int 1550 } 1551 1552 func (s *spec) IsAuto() bool { return s.attr&saAuto != 0 } 1553 func (s *spec) IsConst() bool { return s.attr&saConst != 0 } 1554 func (s *spec) IsExtern() bool { return s.attr&saExtern != 0 } 1555 func (s *spec) IsInline() bool { return s.attr&saInline != 0 } 1556 func (s *spec) IsRegister() bool { return s.attr&saRegister != 0 } 1557 func (s *spec) IsRestrict() bool { return s.attr&saRestrict != 0 } 1558 func (s *spec) IsStatic() bool { return s.attr&saStatic != 0 } 1559 func (s *spec) IsTypedef() bool { return s.attr&saTypedef != 0 } 1560 func (s *spec) IsVolatile() bool { return s.attr&saVolatile != 0 } 1561 func (s *spec) TypedefName() int { return 0 } 1562 func (s *spec) attrs() int { return s.attr } 1563 func (s *spec) firstTypeSpecifier() *TypeSpecifier { panic("TODO") } 1564 func (s *spec) kind() Kind { return tsValid[s.ts] } 1565 func (s *spec) member(int) (*Member, error) { panic("TODO") } 1566 func (s *spec) str() string { return specifierString(s) } 1567 func (s *spec) typeSpecifiers() int { return s.ts } 1568 1569 func specifierString(sp Specifier) string { 1570 if sp == nil { 1571 return "" 1572 } 1573 1574 var buf bytes.Buffer 1575 switch k := sp.kind(); k { 1576 case Enum: 1577 switch ts := sp.firstTypeSpecifier(); ts.Case { 1578 case 12: // EnumSpecifier 1579 es := ts.EnumSpecifier 1580 switch es.Case { 1581 case 0: // "enum" IdentifierOpt '{' EnumeratorList CommaOpt '}' 1582 buf.WriteString("enum") 1583 if o := es.IdentifierOpt; o != nil { 1584 buf.WriteString(" " + string(xc.Dict.S(o.Token.Val))) 1585 } 1586 buf.WriteString(" { ... }") 1587 case 1: // "enum" IDENTIFIER 1588 fmt.Fprintf(&buf, "enum %s", xc.Dict.S(es.Token2.Val)) 1589 default: 1590 panic(es.Case) 1591 } 1592 default: 1593 panic(ts.Case) 1594 } 1595 case Function: 1596 panic("TODO Function") 1597 case Struct, Union: 1598 switch ts := sp.firstTypeSpecifier(); ts.Case { 1599 case 11: // StructOrUnionSpecifier 1600 sus := ts.StructOrUnionSpecifier 1601 buf.WriteString(sus.StructOrUnion.str()) 1602 switch sus.Case { 1603 case 0: // StructOrUnion IdentifierOpt '{' StructDeclarationList '}' 1604 if o := sus.IdentifierOpt; o != nil { 1605 buf.WriteString(" ") 1606 buf.Write(o.Token.S()) 1607 break 1608 } 1609 1610 buf.WriteString("{") 1611 outerFirst := true 1612 for l := sus.StructDeclarationList; l != nil; l = l.StructDeclarationList { 1613 if !outerFirst { 1614 buf.WriteString("; ") 1615 } 1616 outerFirst = false 1617 first := true 1618 for l := l.StructDeclaration.StructDeclaratorList; l != nil; l = l.StructDeclaratorList { 1619 if !first { 1620 buf.WriteString(", ") 1621 } 1622 first = false 1623 switch sd := l.StructDeclarator; sd.Case { 1624 case 0: // Declarator 1625 buf.WriteString(sd.Declarator.Type.String()) 1626 case 1: // DeclaratorOpt ':' ConstantExpression 1627 if o := sd.DeclaratorOpt; o != nil { 1628 buf.WriteString(o.Declarator.Type.String()) 1629 } 1630 buf.WriteByte(':') 1631 fmt.Fprintf(&buf, "%v", sd.ConstantExpression.Value) 1632 default: 1633 fmt.Fprintf(&buf, "specifierString_TODO%v", sd.Case) 1634 } 1635 } 1636 } 1637 buf.WriteString(";}") 1638 case 1: // StructOrUnion IDENTIFIER 1639 buf.WriteString(" ") 1640 buf.Write(sus.Token.S()) 1641 case 2: // StructOrUnion IdentifierOpt '{' '}' // Case 2 1642 if o := sus.IdentifierOpt; o != nil { 1643 buf.WriteString(" ") 1644 buf.Write(o.Token.S()) 1645 } 1646 buf.WriteString("{}") 1647 default: 1648 panic(sus.Case) 1649 } 1650 default: 1651 panic(ts.Case) 1652 } 1653 default: 1654 buf.WriteString(k.CString()) 1655 } 1656 return buf.String() 1657 } 1658 1659 func align(off, algn int) int { 1660 r := off % algn 1661 if r != 0 { 1662 off += algn - r 1663 } 1664 return off 1665 } 1666 1667 func finishBitField(n Node, lx *lexer) { 1668 sc := lx.scope 1669 maxLLBits := lx.model.LongLongType.SizeOf() * 8 1670 bits := sc.bitOffset 1671 if bits > maxLLBits || bits == 0 { 1672 panic(fmt.Errorf("%s: internal error %v", position(n.Pos()), bits)) //TODO split group. 1673 } 1674 1675 var bytes, al int 1676 for _, k := range []Kind{Char, Short, Int, Long, LongLong} { 1677 bytes = lx.model.Items[k].Size 1678 al = lx.model.Items[k].StructAlign 1679 if bytes*8 >= bits { 1680 var t Type 1681 switch k { 1682 case Char: 1683 t = lx.model.CharType 1684 case Short: 1685 t = lx.model.ShortType 1686 case Int: 1687 t = lx.model.IntType 1688 case Long: 1689 t = lx.model.LongType 1690 case LongLong: 1691 t = lx.model.LongLongType 1692 default: 1693 panic("internal error") 1694 } 1695 sc.bitFieldTypes = append(sc.bitFieldTypes, t) 1696 break 1697 } 1698 } 1699 switch { 1700 case sc.isUnion: 1701 off := 0 1702 sc.offset = align(sc.offset, al) 1703 if pd := sc.prevStructDeclarator; pd != nil { 1704 pd.padding = sc.offset - off 1705 pd.offsetOf = sc.offset 1706 } 1707 sc.bitOffset = 0 1708 sc.bitFieldGroup++ 1709 default: 1710 off := sc.offset 1711 sc.offset = align(sc.offset, al) 1712 if pd := sc.prevStructDeclarator; pd != nil { 1713 pd.padding = sc.offset - off 1714 pd.offsetOf = sc.offset 1715 } 1716 sc.offset += bytes 1717 sc.bitOffset = 0 1718 sc.bitFieldGroup++ 1719 } 1720 sc.maxAlign = mathutil.Max(sc.maxAlign, al) 1721 } 1722 1723 // IsArithmeticType reports wheter t.Kind() is one of UintPtr, Char, SChar, 1724 // UChar, Short, UShort, Int, UInt, Long, ULong, LongLong, ULongLong, Float, 1725 // Double, LongDouble, FloatComplex, DoubleComplex, LongDoubleComplex, Bool or 1726 // Enum. 1727 func IsArithmeticType(t Type) bool { 1728 switch t.Kind() { 1729 case 1730 UintPtr, 1731 Char, 1732 SChar, 1733 UChar, 1734 Short, 1735 UShort, 1736 Int, 1737 UInt, 1738 Long, 1739 ULong, 1740 LongLong, 1741 ULongLong, 1742 Float, 1743 Double, 1744 LongDouble, 1745 FloatComplex, 1746 DoubleComplex, 1747 LongDoubleComplex, 1748 Bool, 1749 Enum: 1750 return true 1751 default: 1752 return false 1753 } 1754 } 1755 1756 // IsIntType reports t.Kind() is one of Char, SChar, UChar, Short, UShort, Int, 1757 // UInt, Long, ULong, LongLong, ULongLong, Bool or Enum. 1758 func IsIntType(t Type) bool { 1759 switch t.Kind() { 1760 case 1761 Char, 1762 SChar, 1763 UChar, 1764 Short, 1765 UShort, 1766 Int, 1767 UInt, 1768 Long, 1769 ULong, 1770 LongLong, 1771 ULongLong, 1772 // [0], 6.2.5/6: The type _Bool and the unsigned integer types 1773 // that correspond to the standard signed integer types are the 1774 // standard unsigned integer types. 1775 Bool, 1776 Enum: 1777 return true 1778 default: 1779 return false 1780 } 1781 } 1782 1783 func elements(v interface{}, t Type) (int, error) { 1784 if !IsIntType(t) { 1785 return -1, fmt.Errorf("expression shall have integer type") 1786 } 1787 1788 if v == nil { 1789 return -1, nil 1790 } 1791 1792 r, err := toInt(v) 1793 if err != nil { 1794 return -1, err 1795 } 1796 1797 if r < 0 { 1798 return -1, fmt.Errorf("array size must be positive: %v", v) 1799 } 1800 1801 return r, nil 1802 } 1803 1804 func toInt(v interface{}) (int, error) { 1805 switch x := v.(type) { 1806 case int8: 1807 return int(x), nil 1808 case byte: 1809 return int(x), nil 1810 case int16: 1811 return int(x), nil 1812 case uint16: 1813 return int(x), nil 1814 case int32: 1815 return int(x), nil 1816 case uint32: 1817 return int(x), nil 1818 case int64: 1819 if x < mathutil.MinInt || x > mathutil.MaxInt { 1820 return 0, fmt.Errorf("value out of bounds: %v", x) 1821 } 1822 1823 return int(x), nil 1824 case uint64: 1825 if x > mathutil.MaxInt { 1826 return 0, fmt.Errorf("value out of bounds: %v", x) 1827 } 1828 1829 return int(x), nil 1830 case int: 1831 return x, nil 1832 default: 1833 return -1, fmt.Errorf("not a constant integer expression: %v", x) 1834 } 1835 } 1836 1837 func dedupAbsPaths(a []string) (r []string, _ error) { 1838 m := map[string]struct{}{} 1839 for _, v := range a { 1840 av, err := filepath.Abs(v) 1841 if err != nil { 1842 return nil, err 1843 } 1844 1845 if _, ok := m[av]; ok { 1846 continue 1847 } 1848 1849 r = append(r, v) 1850 m[v] = struct{}{} 1851 } 1852 return r, nil 1853 } 1854 1855 func isCompatibleParameters(a, b []Parameter, va, vb bool) bool { 1856 if len(a) != len(b) || va != vb { 1857 return false 1858 } 1859 1860 for i, v := range a { 1861 if !v.Type.CanAssignTo(b[i].Type) { 1862 return false 1863 } 1864 } 1865 1866 return true 1867 } 1868 1869 // [0], 6.2.7-3 1870 // 1871 // A composite type can be constructed from two types that are compatible; it 1872 // is a type that is compatible with both of the two types and satisfies the 1873 // following conditions: 1874 // 1875 // — If one type is an array of known constant size, the composite type is an 1876 // array of that size; otherwise, if one type is a variable length array, the 1877 // composite type is that type. 1878 // 1879 // — If only one type is a function type with a parameter type list (a function 1880 // prototype), the composite type is a function prototype with the parameter 1881 // type list. 1882 // 1883 // — If both types are function types with parameter type lists, the type of 1884 // each parameter in the composite parameter type list is the composite type of 1885 // the corresponding parameters. 1886 // 1887 // These rules apply recursively to the types from which the two types are 1888 // derived. 1889 func compositeType(a, b Type) (c Type, isA bool) { 1890 t, u := a, b 1891 for t.Kind() == Ptr && u.Kind() == Ptr { 1892 t = t.Element() 1893 u = u.Element() 1894 } 1895 1896 if t.Kind() == Function && u.Kind() == Function { 1897 if !t.Result().CanAssignTo(u.Result()) { 1898 return nil, false 1899 } 1900 1901 p, va := t.Parameters() 1902 q, vb := u.Parameters() 1903 if va != vb { 1904 return nil, false 1905 } 1906 1907 if len(p) == 0 && len(q) != 0 { 1908 return b, false 1909 } 1910 1911 if len(p) != 0 && len(q) == 0 { 1912 return a, true 1913 } 1914 1915 if len(p) != len(q) { 1916 return nil, false 1917 } 1918 1919 for i, v := range p { 1920 w := q[i] 1921 if v.Type != undefined && w.Type == undefined || v.Type.CanAssignTo(w.Type) { 1922 continue 1923 } 1924 1925 return nil, false 1926 } 1927 1928 return a, true 1929 } 1930 1931 return nil, false 1932 } 1933 1934 func eqTypes(a, b Type) bool { return a.(*ctype).eq(b.(*ctype)) } 1935 1936 func isStrLitID(v interface{}) bool { 1937 switch v.(type) { 1938 case StringLitID, LongStringLitID: 1939 return true 1940 } 1941 1942 return false 1943 } 1944 1945 func nElem(t Type) int { 1946 p := -1 1947 for { 1948 n := t.Elements() 1949 if n < 0 { 1950 return p 1951 } 1952 1953 if p < 0 { 1954 p = 1 1955 } 1956 p *= n 1957 t = t.Element() 1958 } 1959 } 1960 1961 func unsigned(k Kind) Kind { 1962 switch k { 1963 case Char, SChar: 1964 return UChar 1965 case Short: 1966 return UShort 1967 case Int: 1968 return UInt 1969 case Long: 1970 return ULong 1971 case LongLong: 1972 return ULongLong 1973 default: 1974 return k 1975 } 1976 } 1977 1978 func isEnum(tn ...*TypeName) bool { 1979 for _, tn := range tn { 1980 t := tn.Type 1981 if t.Kind() == Enum { 1982 return true 1983 } 1984 1985 ts := tn.SpecifierQualifierList.TypeSpecifier 1986 if ts == nil { 1987 continue 1988 } 1989 1990 switch ts.Case { 1991 case 15: // "typeof" '(' TypeName ')' // Case 15 1992 nm := ts.TypeName.SpecifierQualifierList.TypedefName() 1993 if nm == 0 { 1994 break 1995 } 1996 1997 n := ts.TypeName.scope.Lookup(NSIdentifiers, nm) 1998 switch x := n.Node.(type) { 1999 case *DirectDeclarator: 2000 if x.specifier.kind() == Enum { 2001 return true 2002 } 2003 } 2004 } 2005 } 2006 return false 2007 } 2008 2009 func memberOffsetRecursive(t Type, name int) (offset int, ty *Type, err error) { 2010 members, incomplete := t.Members() 2011 if incomplete { 2012 return 0, nil, fmt.Errorf("memberOffsetRecursive: incomplete") 2013 } 2014 matches := 0 2015 for _, member := range members { 2016 if member.Name == name { 2017 matches++ 2018 offset = member.OffsetOf 2019 ty = &member.Type 2020 } 2021 if member.Name == 0 { 2022 moffset, mty, err := memberOffsetRecursive(member.Type, name) 2023 if err == nil { 2024 matches++ 2025 offset += member.OffsetOf + moffset 2026 ty = mty 2027 } 2028 } 2029 } 2030 if matches > 1 { 2031 return 0, nil, fmt.Errorf("memberOffsetRecursive: ambigous member %s", string(dict.S(name))) 2032 } 2033 if matches == 0 { 2034 return 0, nil, fmt.Errorf("memberOffsetRecursive: non-existent member %s", string(dict.S(name))) 2035 } 2036 return offset, ty, err 2037 } 2038 2039 func comment(tw *tweaks, p ...Node) int { 2040 for _, v := range p { 2041 v := v.Pos() 2042 if n := tw.comments[v]; n != 0 { 2043 return n 2044 } 2045 2046 v -= token.Pos(xc.FileSet.Position(v).Column - 1) 2047 if n := tw.comments[v]; n != 0 { 2048 return n 2049 } 2050 } 2051 return 0 2052 2053 } 2054 2055 func fixParams(in []Parameter) { 2056 for i, v := range in { 2057 if t := v.Type; t.Kind() == Function { 2058 in[i].Type = t.Pointer() 2059 } 2060 } 2061 } 2062 2063 func clean(paths []string) (r []string) { 2064 for _, v := range paths { 2065 a, err := filepath.Abs(v) 2066 if err != nil { 2067 a = v 2068 } 2069 r = append(r, a) 2070 } 2071 return r 2072 }