compiler: relocate ID encoding utilities to gofrontend
[official-gcc.git] / gcc / go / gofrontend / types.cc
blob33d3460e49389d8d7fffcc31f58135fcf2ac69e1
1 // types.cc -- Go frontend types.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
7 #include "go-system.h"
9 #include <ostream>
11 #include "go-c.h"
12 #include "gogo.h"
13 #include "go-diagnostics.h"
14 #include "go-encode-id.h"
15 #include "operator.h"
16 #include "expressions.h"
17 #include "statements.h"
18 #include "export.h"
19 #include "import.h"
20 #include "backend.h"
21 #include "types.h"
23 // Forward declarations so that we don't have to make types.h #include
24 // backend.h.
26 static void
27 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
28 bool use_placeholder,
29 std::vector<Backend::Btyped_identifier>* bfields);
31 static void
32 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
33 std::vector<Backend::Btyped_identifier>* bfields);
35 static void
36 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
37 bool use_placeholder,
38 std::vector<Backend::Btyped_identifier>* bfields);
40 // Class Type.
42 Type::Type(Type_classification classification)
43 : classification_(classification), btype_(NULL), type_descriptor_var_(NULL),
44 gc_symbol_var_(NULL)
48 Type::~Type()
52 // Get the base type for a type--skip names and forward declarations.
54 Type*
55 Type::base()
57 switch (this->classification_)
59 case TYPE_NAMED:
60 return this->named_type()->named_base();
61 case TYPE_FORWARD:
62 return this->forward_declaration_type()->real_type()->base();
63 default:
64 return this;
68 const Type*
69 Type::base() const
71 switch (this->classification_)
73 case TYPE_NAMED:
74 return this->named_type()->named_base();
75 case TYPE_FORWARD:
76 return this->forward_declaration_type()->real_type()->base();
77 default:
78 return this;
82 // Skip defined forward declarations.
84 Type*
85 Type::forwarded()
87 Type* t = this;
88 Forward_declaration_type* ftype = t->forward_declaration_type();
89 while (ftype != NULL && ftype->is_defined())
91 t = ftype->real_type();
92 ftype = t->forward_declaration_type();
94 return t;
97 const Type*
98 Type::forwarded() const
100 const Type* t = this;
101 const Forward_declaration_type* ftype = t->forward_declaration_type();
102 while (ftype != NULL && ftype->is_defined())
104 t = ftype->real_type();
105 ftype = t->forward_declaration_type();
107 return t;
110 // If this is a named type, return it. Otherwise, return NULL.
112 Named_type*
113 Type::named_type()
115 return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
118 const Named_type*
119 Type::named_type() const
121 return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
124 // Return true if this type is not defined.
126 bool
127 Type::is_undefined() const
129 return this->forwarded()->forward_declaration_type() != NULL;
132 // Return true if this is a basic type: a type which is not composed
133 // of other types, and is not void.
135 bool
136 Type::is_basic_type() const
138 switch (this->classification_)
140 case TYPE_INTEGER:
141 case TYPE_FLOAT:
142 case TYPE_COMPLEX:
143 case TYPE_BOOLEAN:
144 case TYPE_STRING:
145 case TYPE_NIL:
146 return true;
148 case TYPE_ERROR:
149 case TYPE_VOID:
150 case TYPE_FUNCTION:
151 case TYPE_POINTER:
152 case TYPE_STRUCT:
153 case TYPE_ARRAY:
154 case TYPE_MAP:
155 case TYPE_CHANNEL:
156 case TYPE_INTERFACE:
157 return false;
159 case TYPE_NAMED:
160 case TYPE_FORWARD:
161 return this->base()->is_basic_type();
163 default:
164 go_unreachable();
168 // Return true if this is an abstract type.
170 bool
171 Type::is_abstract() const
173 switch (this->classification())
175 case TYPE_INTEGER:
176 return this->integer_type()->is_abstract();
177 case TYPE_FLOAT:
178 return this->float_type()->is_abstract();
179 case TYPE_COMPLEX:
180 return this->complex_type()->is_abstract();
181 case TYPE_STRING:
182 return this->is_abstract_string_type();
183 case TYPE_BOOLEAN:
184 return this->is_abstract_boolean_type();
185 default:
186 return false;
190 // Return a non-abstract version of an abstract type.
192 Type*
193 Type::make_non_abstract_type()
195 go_assert(this->is_abstract());
196 switch (this->classification())
198 case TYPE_INTEGER:
199 if (this->integer_type()->is_rune())
200 return Type::lookup_integer_type("int32");
201 else
202 return Type::lookup_integer_type("int");
203 case TYPE_FLOAT:
204 return Type::lookup_float_type("float64");
205 case TYPE_COMPLEX:
206 return Type::lookup_complex_type("complex128");
207 case TYPE_STRING:
208 return Type::lookup_string_type();
209 case TYPE_BOOLEAN:
210 return Type::lookup_bool_type();
211 default:
212 go_unreachable();
216 // Return true if this is an error type. Don't give an error if we
217 // try to dereference an undefined forwarding type, as this is called
218 // in the parser when the type may legitimately be undefined.
220 bool
221 Type::is_error_type() const
223 const Type* t = this->forwarded();
224 // Note that we return false for an undefined forward type.
225 switch (t->classification_)
227 case TYPE_ERROR:
228 return true;
229 case TYPE_NAMED:
230 return t->named_type()->is_named_error_type();
231 default:
232 return false;
236 // If this is a pointer type, return the type to which it points.
237 // Otherwise, return NULL.
239 Type*
240 Type::points_to() const
242 const Pointer_type* ptype = this->convert<const Pointer_type,
243 TYPE_POINTER>();
244 return ptype == NULL ? NULL : ptype->points_to();
247 // Return whether this is a slice type.
249 bool
250 Type::is_slice_type() const
252 return this->array_type() != NULL && this->array_type()->length() == NULL;
255 // Return whether this is the predeclared constant nil being used as a
256 // type.
258 bool
259 Type::is_nil_constant_as_type() const
261 const Type* t = this->forwarded();
262 if (t->forward_declaration_type() != NULL)
264 const Named_object* no = t->forward_declaration_type()->named_object();
265 if (no->is_unknown())
266 no = no->unknown_value()->real_named_object();
267 if (no != NULL
268 && no->is_const()
269 && no->const_value()->expr()->is_nil_expression())
270 return true;
272 return false;
275 // Traverse a type.
278 Type::traverse(Type* type, Traverse* traverse)
280 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
281 || (traverse->traverse_mask()
282 & Traverse::traverse_expressions) != 0);
283 if (traverse->remember_type(type))
285 // We have already traversed this type.
286 return TRAVERSE_CONTINUE;
288 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
290 int t = traverse->type(type);
291 if (t == TRAVERSE_EXIT)
292 return TRAVERSE_EXIT;
293 else if (t == TRAVERSE_SKIP_COMPONENTS)
294 return TRAVERSE_CONTINUE;
296 // An array type has an expression which we need to traverse if
297 // traverse_expressions is set.
298 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
299 return TRAVERSE_EXIT;
300 return TRAVERSE_CONTINUE;
303 // Default implementation for do_traverse for child class.
306 Type::do_traverse(Traverse*)
308 return TRAVERSE_CONTINUE;
311 // Return whether two types are identical. If ERRORS_ARE_IDENTICAL,
312 // then return true for all erroneous types; this is used to avoid
313 // cascading errors. If REASON is not NULL, optionally set *REASON to
314 // the reason the types are not identical.
316 bool
317 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
318 std::string* reason)
320 if (t1 == NULL || t2 == NULL)
322 // Something is wrong.
323 return errors_are_identical ? true : t1 == t2;
326 // Skip defined forward declarations.
327 t1 = t1->forwarded();
328 t2 = t2->forwarded();
330 // Ignore aliases for purposes of type identity.
331 if (t1->named_type() != NULL && t1->named_type()->is_alias())
332 t1 = t1->named_type()->real_type();
333 if (t2->named_type() != NULL && t2->named_type()->is_alias())
334 t2 = t2->named_type()->real_type();
336 if (t1 == t2)
337 return true;
339 // An undefined forward declaration is an error.
340 if (t1->forward_declaration_type() != NULL
341 || t2->forward_declaration_type() != NULL)
342 return errors_are_identical;
344 // Avoid cascading errors with error types.
345 if (t1->is_error_type() || t2->is_error_type())
347 if (errors_are_identical)
348 return true;
349 return t1->is_error_type() && t2->is_error_type();
352 // Get a good reason for the sink type. Note that the sink type on
353 // the left hand side of an assignment is handled in are_assignable.
354 if (t1->is_sink_type() || t2->is_sink_type())
356 if (reason != NULL)
357 *reason = "invalid use of _";
358 return false;
361 // A named type is only identical to itself.
362 if (t1->named_type() != NULL || t2->named_type() != NULL)
363 return false;
365 // Check type shapes.
366 if (t1->classification() != t2->classification())
367 return false;
369 switch (t1->classification())
371 case TYPE_VOID:
372 case TYPE_BOOLEAN:
373 case TYPE_STRING:
374 case TYPE_NIL:
375 // These types are always identical.
376 return true;
378 case TYPE_INTEGER:
379 return t1->integer_type()->is_identical(t2->integer_type());
381 case TYPE_FLOAT:
382 return t1->float_type()->is_identical(t2->float_type());
384 case TYPE_COMPLEX:
385 return t1->complex_type()->is_identical(t2->complex_type());
387 case TYPE_FUNCTION:
388 return t1->function_type()->is_identical(t2->function_type(),
389 false,
390 errors_are_identical,
391 reason);
393 case TYPE_POINTER:
394 return Type::are_identical(t1->points_to(), t2->points_to(),
395 errors_are_identical, reason);
397 case TYPE_STRUCT:
398 return t1->struct_type()->is_identical(t2->struct_type(),
399 errors_are_identical);
401 case TYPE_ARRAY:
402 return t1->array_type()->is_identical(t2->array_type(),
403 errors_are_identical);
405 case TYPE_MAP:
406 return t1->map_type()->is_identical(t2->map_type(),
407 errors_are_identical);
409 case TYPE_CHANNEL:
410 return t1->channel_type()->is_identical(t2->channel_type(),
411 errors_are_identical);
413 case TYPE_INTERFACE:
414 return t1->interface_type()->is_identical(t2->interface_type(),
415 errors_are_identical);
417 case TYPE_CALL_MULTIPLE_RESULT:
418 if (reason != NULL)
419 *reason = "invalid use of multiple-value function call";
420 return false;
422 default:
423 go_unreachable();
427 // Return true if it's OK to have a binary operation with types LHS
428 // and RHS. This is not used for shifts or comparisons.
430 bool
431 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
433 if (Type::are_identical(lhs, rhs, true, NULL))
434 return true;
436 // A constant of abstract bool type may be mixed with any bool type.
437 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
438 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
439 return true;
441 // A constant of abstract string type may be mixed with any string
442 // type.
443 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
444 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
445 return true;
447 lhs = lhs->base();
448 rhs = rhs->base();
450 // A constant of abstract integer, float, or complex type may be
451 // mixed with an integer, float, or complex type.
452 if ((rhs->is_abstract()
453 && (rhs->integer_type() != NULL
454 || rhs->float_type() != NULL
455 || rhs->complex_type() != NULL)
456 && (lhs->integer_type() != NULL
457 || lhs->float_type() != NULL
458 || lhs->complex_type() != NULL))
459 || (lhs->is_abstract()
460 && (lhs->integer_type() != NULL
461 || lhs->float_type() != NULL
462 || lhs->complex_type() != NULL)
463 && (rhs->integer_type() != NULL
464 || rhs->float_type() != NULL
465 || rhs->complex_type() != NULL)))
466 return true;
468 // The nil type may be compared to a pointer, an interface type, a
469 // slice type, a channel type, a map type, or a function type.
470 if (lhs->is_nil_type()
471 && (rhs->points_to() != NULL
472 || rhs->interface_type() != NULL
473 || rhs->is_slice_type()
474 || rhs->map_type() != NULL
475 || rhs->channel_type() != NULL
476 || rhs->function_type() != NULL))
477 return true;
478 if (rhs->is_nil_type()
479 && (lhs->points_to() != NULL
480 || lhs->interface_type() != NULL
481 || lhs->is_slice_type()
482 || lhs->map_type() != NULL
483 || lhs->channel_type() != NULL
484 || lhs->function_type() != NULL))
485 return true;
487 return false;
490 // Return true if a value with type T1 may be compared with a value of
491 // type T2. IS_EQUALITY_OP is true for == or !=, false for <, etc.
493 bool
494 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
495 const Type *t2, std::string *reason)
497 if (t1 != t2
498 && !Type::are_assignable(t1, t2, NULL)
499 && !Type::are_assignable(t2, t1, NULL))
501 if (reason != NULL)
502 *reason = "incompatible types in binary expression";
503 return false;
506 if (!is_equality_op)
508 if (t1->integer_type() == NULL
509 && t1->float_type() == NULL
510 && !t1->is_string_type())
512 if (reason != NULL)
513 *reason = _("invalid comparison of non-ordered type");
514 return false;
517 else if (t1->is_slice_type()
518 || t1->map_type() != NULL
519 || t1->function_type() != NULL
520 || t2->is_slice_type()
521 || t2->map_type() != NULL
522 || t2->function_type() != NULL)
524 if (!t1->is_nil_type() && !t2->is_nil_type())
526 if (reason != NULL)
528 if (t1->is_slice_type() || t2->is_slice_type())
529 *reason = _("slice can only be compared to nil");
530 else if (t1->map_type() != NULL || t2->map_type() != NULL)
531 *reason = _("map can only be compared to nil");
532 else
533 *reason = _("func can only be compared to nil");
535 // Match 6g error messages.
536 if (t1->interface_type() != NULL || t2->interface_type() != NULL)
538 char buf[200];
539 snprintf(buf, sizeof buf, _("invalid operation (%s)"),
540 reason->c_str());
541 *reason = buf;
544 return false;
547 else
549 if (!t1->is_boolean_type()
550 && t1->integer_type() == NULL
551 && t1->float_type() == NULL
552 && t1->complex_type() == NULL
553 && !t1->is_string_type()
554 && t1->points_to() == NULL
555 && t1->channel_type() == NULL
556 && t1->interface_type() == NULL
557 && t1->struct_type() == NULL
558 && t1->array_type() == NULL
559 && !t1->is_nil_type())
561 if (reason != NULL)
562 *reason = _("invalid comparison of non-comparable type");
563 return false;
566 if (t1->named_type() != NULL)
567 return t1->named_type()->named_type_is_comparable(reason);
568 else if (t2->named_type() != NULL)
569 return t2->named_type()->named_type_is_comparable(reason);
570 else if (t1->struct_type() != NULL)
572 if (t1->struct_type()->is_struct_incomparable())
574 if (reason != NULL)
575 *reason = _("invalid comparison of generated struct");
576 return false;
578 const Struct_field_list* fields = t1->struct_type()->fields();
579 for (Struct_field_list::const_iterator p = fields->begin();
580 p != fields->end();
581 ++p)
583 if (!p->type()->is_comparable())
585 if (reason != NULL)
586 *reason = _("invalid comparison of non-comparable struct");
587 return false;
591 else if (t1->array_type() != NULL)
593 if (t1->array_type()->is_array_incomparable())
595 if (reason != NULL)
596 *reason = _("invalid comparison of generated array");
597 return false;
599 if (t1->array_type()->length()->is_nil_expression()
600 || !t1->array_type()->element_type()->is_comparable())
602 if (reason != NULL)
603 *reason = _("invalid comparison of non-comparable array");
604 return false;
609 return true;
612 // Return true if a value with type RHS may be assigned to a variable
613 // with type LHS. If REASON is not NULL, set *REASON to the reason
614 // the types are not assignable.
616 bool
617 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
619 // Do some checks first. Make sure the types are defined.
620 if (rhs != NULL && !rhs->is_undefined())
622 if (rhs->is_void_type())
624 if (reason != NULL)
625 *reason = "non-value used as value";
626 return false;
628 if (rhs->is_call_multiple_result_type())
630 if (reason != NULL)
631 reason->assign(_("multiple-value function call in "
632 "single-value context"));
633 return false;
637 // Any value may be assigned to the blank identifier.
638 if (lhs != NULL
639 && !lhs->is_undefined()
640 && lhs->is_sink_type())
641 return true;
643 // Identical types are assignable.
644 if (Type::are_identical(lhs, rhs, true, reason))
645 return true;
647 // The types are assignable if they have identical underlying types
648 // and either LHS or RHS is not a named type.
649 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
650 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
651 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
652 return true;
654 // The types are assignable if LHS is an interface type and RHS
655 // implements the required methods.
656 const Interface_type* lhs_interface_type = lhs->interface_type();
657 if (lhs_interface_type != NULL)
659 if (lhs_interface_type->implements_interface(rhs, reason))
660 return true;
661 const Interface_type* rhs_interface_type = rhs->interface_type();
662 if (rhs_interface_type != NULL
663 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
664 reason))
665 return true;
668 // The type are assignable if RHS is a bidirectional channel type,
669 // LHS is a channel type, they have identical element types, and
670 // either LHS or RHS is not a named type.
671 if (lhs->channel_type() != NULL
672 && rhs->channel_type() != NULL
673 && rhs->channel_type()->may_send()
674 && rhs->channel_type()->may_receive()
675 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
676 && Type::are_identical(lhs->channel_type()->element_type(),
677 rhs->channel_type()->element_type(),
678 true,
679 reason))
680 return true;
682 // The nil type may be assigned to a pointer, function, slice, map,
683 // channel, or interface type.
684 if (rhs->is_nil_type()
685 && (lhs->points_to() != NULL
686 || lhs->function_type() != NULL
687 || lhs->is_slice_type()
688 || lhs->map_type() != NULL
689 || lhs->channel_type() != NULL
690 || lhs->interface_type() != NULL))
691 return true;
693 // An untyped numeric constant may be assigned to a numeric type if
694 // it is representable in that type.
695 if ((rhs->is_abstract()
696 && (rhs->integer_type() != NULL
697 || rhs->float_type() != NULL
698 || rhs->complex_type() != NULL))
699 && (lhs->integer_type() != NULL
700 || lhs->float_type() != NULL
701 || lhs->complex_type() != NULL))
702 return true;
704 // Give some better error messages.
705 if (reason != NULL && reason->empty())
707 if (rhs->interface_type() != NULL)
708 reason->assign(_("need explicit conversion"));
709 else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
711 size_t len = (lhs->named_type()->name().length()
712 + rhs->named_type()->name().length()
713 + 100);
714 char* buf = new char[len];
715 snprintf(buf, len, _("cannot use type %s as type %s"),
716 rhs->named_type()->message_name().c_str(),
717 lhs->named_type()->message_name().c_str());
718 reason->assign(buf);
719 delete[] buf;
723 return false;
726 // Return true if a value with type RHS may be converted to type LHS.
727 // If REASON is not NULL, set *REASON to the reason the types are not
728 // convertible.
730 bool
731 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
733 // The types are convertible if they are assignable.
734 if (Type::are_assignable(lhs, rhs, reason))
735 return true;
737 // The types are convertible if they have identical underlying
738 // types.
739 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
740 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
741 return true;
743 // The types are convertible if they are both unnamed pointer types
744 // and their pointer base types have identical underlying types.
745 if (lhs->named_type() == NULL
746 && rhs->named_type() == NULL
747 && lhs->points_to() != NULL
748 && rhs->points_to() != NULL
749 && (lhs->points_to()->named_type() != NULL
750 || rhs->points_to()->named_type() != NULL)
751 && Type::are_identical(lhs->points_to()->base(),
752 rhs->points_to()->base(),
753 true,
754 reason))
755 return true;
757 // Integer and floating point types are convertible to each other.
758 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
759 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
760 return true;
762 // Complex types are convertible to each other.
763 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
764 return true;
766 // An integer, or []byte, or []rune, may be converted to a string.
767 if (lhs->is_string_type())
769 if (rhs->integer_type() != NULL)
770 return true;
771 if (rhs->is_slice_type())
773 const Type* e = rhs->array_type()->element_type()->forwarded();
774 if (e->integer_type() != NULL
775 && (e->integer_type()->is_byte()
776 || e->integer_type()->is_rune()))
777 return true;
781 // A string may be converted to []byte or []rune.
782 if (rhs->is_string_type() && lhs->is_slice_type())
784 const Type* e = lhs->array_type()->element_type()->forwarded();
785 if (e->integer_type() != NULL
786 && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
787 return true;
790 // An unsafe.Pointer type may be converted to any pointer type or to
791 // a type whose underlying type is uintptr, and vice-versa.
792 if (lhs->is_unsafe_pointer_type()
793 && (rhs->points_to() != NULL
794 || (rhs->integer_type() != NULL
795 && rhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
796 return true;
797 if (rhs->is_unsafe_pointer_type()
798 && (lhs->points_to() != NULL
799 || (lhs->integer_type() != NULL
800 && lhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
801 return true;
803 // Give a better error message.
804 if (reason != NULL)
806 if (reason->empty())
807 *reason = "invalid type conversion";
808 else
810 std::string s = "invalid type conversion (";
811 s += *reason;
812 s += ')';
813 *reason = s;
817 return false;
820 // Return a hash code for the type to be used for method lookup.
822 unsigned int
823 Type::hash_for_method(Gogo* gogo) const
825 unsigned int ret = 0;
826 if (this->classification_ != TYPE_FORWARD)
827 ret += this->classification_;
828 return ret + this->do_hash_for_method(gogo);
831 // Default implementation of do_hash_for_method. This is appropriate
832 // for types with no subfields.
834 unsigned int
835 Type::do_hash_for_method(Gogo*) const
837 return 0;
840 // Return a hash code for a string, given a starting hash.
842 unsigned int
843 Type::hash_string(const std::string& s, unsigned int h)
845 const char* p = s.data();
846 size_t len = s.length();
847 for (; len > 0; --len)
849 h ^= *p++;
850 h*= 16777619;
852 return h;
855 // A hash table mapping unnamed types to the backend representation of
856 // those types.
858 Type::Type_btypes Type::type_btypes;
860 // Return the backend representation for this type.
862 Btype*
863 Type::get_backend(Gogo* gogo)
865 if (this->btype_ != NULL)
866 return this->btype_;
868 if (this->forward_declaration_type() != NULL
869 || this->named_type() != NULL)
870 return this->get_btype_without_hash(gogo);
872 if (this->is_error_type())
873 return gogo->backend()->error_type();
875 // To avoid confusing the backend, translate all identical Go types
876 // to the same backend representation. We use a hash table to do
877 // that. There is no need to use the hash table for named types, as
878 // named types are only identical to themselves.
880 std::pair<Type*, Type_btype_entry> val;
881 val.first = this;
882 val.second.btype = NULL;
883 val.second.is_placeholder = false;
884 std::pair<Type_btypes::iterator, bool> ins =
885 Type::type_btypes.insert(val);
886 if (!ins.second && ins.first->second.btype != NULL)
888 // Note that GOGO can be NULL here, but only when the GCC
889 // middle-end is asking for a frontend type. That will only
890 // happen for simple types, which should never require
891 // placeholders.
892 if (!ins.first->second.is_placeholder)
893 this->btype_ = ins.first->second.btype;
894 else if (gogo->named_types_are_converted())
896 this->finish_backend(gogo, ins.first->second.btype);
897 ins.first->second.is_placeholder = false;
900 return ins.first->second.btype;
903 Btype* bt = this->get_btype_without_hash(gogo);
905 if (ins.first->second.btype == NULL)
907 ins.first->second.btype = bt;
908 ins.first->second.is_placeholder = false;
910 else
912 // We have already created a backend representation for this
913 // type. This can happen when an unnamed type is defined using
914 // a named type which in turns uses an identical unnamed type.
915 // Use the representation we created earlier and ignore the one we just
916 // built.
917 if (this->btype_ == bt)
918 this->btype_ = ins.first->second.btype;
919 bt = ins.first->second.btype;
922 return bt;
925 // Return the backend representation for a type without looking in the
926 // hash table for identical types. This is used for named types,
927 // since a named type is never identical to any other type.
929 Btype*
930 Type::get_btype_without_hash(Gogo* gogo)
932 if (this->btype_ == NULL)
934 Btype* bt = this->do_get_backend(gogo);
936 // For a recursive function or pointer type, we will temporarily
937 // return a circular pointer type during the recursion. We
938 // don't want to record that for a forwarding type, as it may
939 // confuse us later.
940 if (this->forward_declaration_type() != NULL
941 && gogo->backend()->is_circular_pointer_type(bt))
942 return bt;
944 if (gogo == NULL || !gogo->named_types_are_converted())
945 return bt;
947 this->btype_ = bt;
949 return this->btype_;
952 // Get the backend representation of a type without forcing the
953 // creation of the backend representation of all supporting types.
954 // This will return a backend type that has the correct size but may
955 // be incomplete. E.g., a pointer will just be a placeholder pointer,
956 // and will not contain the final representation of the type to which
957 // it points. This is used while converting all named types to the
958 // backend representation, to avoid problems with indirect references
959 // to types which are not yet complete. When this is called, the
960 // sizes of all direct references (e.g., a struct field) should be
961 // known, but the sizes of indirect references (e.g., the type to
962 // which a pointer points) may not.
964 Btype*
965 Type::get_backend_placeholder(Gogo* gogo)
967 if (gogo->named_types_are_converted())
968 return this->get_backend(gogo);
969 if (this->btype_ != NULL)
970 return this->btype_;
972 Btype* bt;
973 switch (this->classification_)
975 case TYPE_ERROR:
976 case TYPE_VOID:
977 case TYPE_BOOLEAN:
978 case TYPE_INTEGER:
979 case TYPE_FLOAT:
980 case TYPE_COMPLEX:
981 case TYPE_STRING:
982 case TYPE_NIL:
983 // These are simple types that can just be created directly.
984 return this->get_backend(gogo);
986 case TYPE_MAP:
987 case TYPE_CHANNEL:
988 // All maps and channels have the same backend representation.
989 return this->get_backend(gogo);
991 case TYPE_NAMED:
992 case TYPE_FORWARD:
993 // Named types keep track of their own dependencies and manage
994 // their own placeholders.
995 return this->get_backend(gogo);
997 case TYPE_INTERFACE:
998 if (this->interface_type()->is_empty())
999 return Interface_type::get_backend_empty_interface_type(gogo);
1000 break;
1002 default:
1003 break;
1006 std::pair<Type*, Type_btype_entry> val;
1007 val.first = this;
1008 val.second.btype = NULL;
1009 val.second.is_placeholder = false;
1010 std::pair<Type_btypes::iterator, bool> ins =
1011 Type::type_btypes.insert(val);
1012 if (!ins.second && ins.first->second.btype != NULL)
1013 return ins.first->second.btype;
1015 switch (this->classification_)
1017 case TYPE_FUNCTION:
1019 // A Go function type is a pointer to a struct type.
1020 Location loc = this->function_type()->location();
1021 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1023 break;
1025 case TYPE_POINTER:
1027 Location loc = Linemap::unknown_location();
1028 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1030 break;
1032 case TYPE_STRUCT:
1033 // We don't have to make the struct itself be a placeholder. We
1034 // are promised that we know the sizes of the struct fields.
1035 // But we may have to use a placeholder for any particular
1036 // struct field.
1038 std::vector<Backend::Btyped_identifier> bfields;
1039 get_backend_struct_fields(gogo, this->struct_type()->fields(),
1040 true, &bfields);
1041 bt = gogo->backend()->struct_type(bfields);
1043 break;
1045 case TYPE_ARRAY:
1046 if (this->is_slice_type())
1048 std::vector<Backend::Btyped_identifier> bfields;
1049 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1050 bt = gogo->backend()->struct_type(bfields);
1052 else
1054 Btype* element = this->array_type()->get_backend_element(gogo, true);
1055 Bexpression* len = this->array_type()->get_backend_length(gogo);
1056 bt = gogo->backend()->array_type(element, len);
1058 break;
1060 case TYPE_INTERFACE:
1062 go_assert(!this->interface_type()->is_empty());
1063 std::vector<Backend::Btyped_identifier> bfields;
1064 get_backend_interface_fields(gogo, this->interface_type(), true,
1065 &bfields);
1066 bt = gogo->backend()->struct_type(bfields);
1068 break;
1070 case TYPE_SINK:
1071 case TYPE_CALL_MULTIPLE_RESULT:
1072 /* Note that various classifications were handled in the earlier
1073 switch. */
1074 default:
1075 go_unreachable();
1078 if (ins.first->second.btype == NULL)
1080 ins.first->second.btype = bt;
1081 ins.first->second.is_placeholder = true;
1083 else
1085 // A placeholder for this type got created along the way. Use
1086 // that one and ignore the one we just built.
1087 bt = ins.first->second.btype;
1090 return bt;
1093 // Complete the backend representation. This is called for a type
1094 // using a placeholder type.
1096 void
1097 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1099 switch (this->classification_)
1101 case TYPE_ERROR:
1102 case TYPE_VOID:
1103 case TYPE_BOOLEAN:
1104 case TYPE_INTEGER:
1105 case TYPE_FLOAT:
1106 case TYPE_COMPLEX:
1107 case TYPE_STRING:
1108 case TYPE_NIL:
1109 go_unreachable();
1111 case TYPE_FUNCTION:
1113 Btype* bt = this->do_get_backend(gogo);
1114 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1115 go_assert(saw_errors());
1117 break;
1119 case TYPE_POINTER:
1121 Btype* bt = this->do_get_backend(gogo);
1122 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1123 go_assert(saw_errors());
1125 break;
1127 case TYPE_STRUCT:
1128 // The struct type itself is done, but we have to make sure that
1129 // all the field types are converted.
1130 this->struct_type()->finish_backend_fields(gogo);
1131 break;
1133 case TYPE_ARRAY:
1134 // The array type itself is done, but make sure the element type
1135 // is converted.
1136 this->array_type()->finish_backend_element(gogo);
1137 break;
1139 case TYPE_MAP:
1140 case TYPE_CHANNEL:
1141 go_unreachable();
1143 case TYPE_INTERFACE:
1144 // The interface type itself is done, but make sure the method
1145 // types are converted.
1146 this->interface_type()->finish_backend_methods(gogo);
1147 break;
1149 case TYPE_NAMED:
1150 case TYPE_FORWARD:
1151 go_unreachable();
1153 case TYPE_SINK:
1154 case TYPE_CALL_MULTIPLE_RESULT:
1155 default:
1156 go_unreachable();
1159 this->btype_ = placeholder;
1162 // Return a pointer to the type descriptor for this type.
1164 Bexpression*
1165 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1167 Type* t = this->forwarded();
1168 if (t->named_type() != NULL && t->named_type()->is_alias())
1169 t = t->named_type()->real_type();
1170 if (t->type_descriptor_var_ == NULL)
1172 t->make_type_descriptor_var(gogo);
1173 go_assert(t->type_descriptor_var_ != NULL);
1175 Bexpression* var_expr =
1176 gogo->backend()->var_expression(t->type_descriptor_var_, location);
1177 return gogo->backend()->address_expression(var_expr, location);
1180 // A mapping from unnamed types to type descriptor variables.
1182 Type::Type_descriptor_vars Type::type_descriptor_vars;
1184 // Build the type descriptor for this type.
1186 void
1187 Type::make_type_descriptor_var(Gogo* gogo)
1189 go_assert(this->type_descriptor_var_ == NULL);
1191 Named_type* nt = this->named_type();
1193 // We can have multiple instances of unnamed types, but we only want
1194 // to emit the type descriptor once. We use a hash table. This is
1195 // not necessary for named types, as they are unique, and we store
1196 // the type descriptor in the type itself.
1197 Bvariable** phash = NULL;
1198 if (nt == NULL)
1200 Bvariable* bvnull = NULL;
1201 std::pair<Type_descriptor_vars::iterator, bool> ins =
1202 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1203 if (!ins.second)
1205 // We've already built a type descriptor for this type.
1206 this->type_descriptor_var_ = ins.first->second;
1207 return;
1209 phash = &ins.first->second;
1212 // The type descriptor symbol for the unsafe.Pointer type is defined in
1213 // libgo/go-unsafe-pointer.c, so we just return a reference to that
1214 // symbol if necessary.
1215 if (this->is_unsafe_pointer_type())
1217 Location bloc = Linemap::predeclared_location();
1219 Type* td_type = Type::make_type_descriptor_type();
1220 Btype* td_btype = td_type->get_backend(gogo);
1221 const char *name = "__go_tdn_unsafe.Pointer";
1222 std::string asm_name(go_selectively_encode_id(name));
1223 this->type_descriptor_var_ =
1224 gogo->backend()->immutable_struct_reference(name, asm_name,
1225 td_btype,
1226 bloc);
1228 if (phash != NULL)
1229 *phash = this->type_descriptor_var_;
1230 return;
1233 std::string var_name = this->type_descriptor_var_name(gogo, nt);
1235 // Build the contents of the type descriptor.
1236 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1238 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1240 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1242 const Package* dummy;
1243 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1245 std::string asm_name(go_selectively_encode_id(var_name));
1246 this->type_descriptor_var_ =
1247 gogo->backend()->immutable_struct_reference(var_name, asm_name,
1248 initializer_btype,
1249 loc);
1250 if (phash != NULL)
1251 *phash = this->type_descriptor_var_;
1252 return;
1255 // See if this type descriptor can appear in multiple packages.
1256 bool is_common = false;
1257 if (nt != NULL)
1259 // We create the descriptor for a builtin type whenever we need
1260 // it.
1261 is_common = nt->is_builtin();
1263 else
1265 // This is an unnamed type. The descriptor could be defined in
1266 // any package where it is needed, and the linker will pick one
1267 // descriptor to keep.
1268 is_common = true;
1271 // We are going to build the type descriptor in this package. We
1272 // must create the variable before we convert the initializer to the
1273 // backend representation, because the initializer may refer to the
1274 // type descriptor of this type. By setting type_descriptor_var_ we
1275 // ensure that type_descriptor_pointer will work if called while
1276 // converting INITIALIZER.
1278 std::string asm_name(go_selectively_encode_id(var_name));
1279 this->type_descriptor_var_ =
1280 gogo->backend()->immutable_struct(var_name, asm_name, false, is_common,
1281 initializer_btype, loc);
1282 if (phash != NULL)
1283 *phash = this->type_descriptor_var_;
1285 Translate_context context(gogo, NULL, NULL, NULL);
1286 context.set_is_const();
1287 Bexpression* binitializer = initializer->get_backend(&context);
1289 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1290 var_name, false, is_common,
1291 initializer_btype, loc,
1292 binitializer);
1295 // Return the name of the type descriptor variable. If NT is not
1296 // NULL, use it to get the name. Otherwise this is an unnamed type.
1298 std::string
1299 Type::type_descriptor_var_name(Gogo* gogo, Named_type* nt)
1301 if (nt == NULL)
1302 return "__go_td_" + this->mangled_name(gogo);
1304 Named_object* no = nt->named_object();
1305 unsigned int index;
1306 const Named_object* in_function = nt->in_function(&index);
1307 std::string ret = "__go_tdn_";
1308 if (nt->is_builtin())
1309 go_assert(in_function == NULL);
1310 else
1312 const std::string& pkgpath(no->package() == NULL
1313 ? gogo->pkgpath_symbol()
1314 : no->package()->pkgpath_symbol());
1315 ret.append(pkgpath);
1316 ret.append(1, '.');
1317 if (in_function != NULL)
1319 const Typed_identifier* rcvr =
1320 in_function->func_value()->type()->receiver();
1321 if (rcvr != NULL)
1323 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
1324 ret.append(Gogo::unpack_hidden_name(rcvr_type->name()));
1325 ret.append(1, '.');
1327 ret.append(Gogo::unpack_hidden_name(in_function->name()));
1328 ret.append(1, '.');
1329 if (index > 0)
1331 char buf[30];
1332 snprintf(buf, sizeof buf, "%u", index);
1333 ret.append(buf);
1334 ret.append(1, '.');
1339 // FIXME: This adds in pkgpath twice for hidden symbols, which is
1340 // pointless.
1341 const std::string& name(no->name());
1342 if (!Gogo::is_hidden_name(name))
1343 ret.append(name);
1344 else
1346 ret.append(1, '.');
1347 ret.append(Gogo::pkgpath_for_symbol(Gogo::hidden_name_pkgpath(name)));
1348 ret.append(1, '.');
1349 ret.append(Gogo::unpack_hidden_name(name));
1352 return ret;
1355 // Return true if this type descriptor is defined in a different
1356 // package. If this returns true it sets *PACKAGE to the package.
1358 bool
1359 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1360 const Package** package)
1362 if (nt != NULL)
1364 if (nt->named_object()->package() != NULL)
1366 // This is a named type defined in a different package. The
1367 // type descriptor should be defined in that package.
1368 *package = nt->named_object()->package();
1369 return true;
1372 else
1374 if (this->points_to() != NULL
1375 && this->points_to()->named_type() != NULL
1376 && this->points_to()->named_type()->named_object()->package() != NULL)
1378 // This is an unnamed pointer to a named type defined in a
1379 // different package. The descriptor should be defined in
1380 // that package.
1381 *package = this->points_to()->named_type()->named_object()->package();
1382 return true;
1385 return false;
1388 // Return a composite literal for a type descriptor.
1390 Expression*
1391 Type::type_descriptor(Gogo* gogo, Type* type)
1393 return type->do_type_descriptor(gogo, NULL);
1396 // Return a composite literal for a type descriptor with a name.
1398 Expression*
1399 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1401 go_assert(name != NULL && type->named_type() != name);
1402 return type->do_type_descriptor(gogo, name);
1405 // Generate the GC symbol for this TYPE. VALS is the data so far in this
1406 // symbol; extra values will be appended in do_gc_symbol. OFFSET is the
1407 // offset into the symbol where the GC data is located. STACK_SIZE is the
1408 // size of the GC stack when dealing with array types.
1410 void
1411 Type::gc_symbol(Gogo* gogo, Type* type, Expression_list** vals,
1412 Expression** offset, int stack_size)
1414 type->do_gc_symbol(gogo, vals, offset, stack_size);
1417 // Make a builtin struct type from a list of fields. The fields are
1418 // pairs of a name and a type.
1420 Struct_type*
1421 Type::make_builtin_struct_type(int nfields, ...)
1423 va_list ap;
1424 va_start(ap, nfields);
1426 Location bloc = Linemap::predeclared_location();
1427 Struct_field_list* sfl = new Struct_field_list();
1428 for (int i = 0; i < nfields; i++)
1430 const char* field_name = va_arg(ap, const char *);
1431 Type* type = va_arg(ap, Type*);
1432 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1435 va_end(ap);
1437 return Type::make_struct_type(sfl, bloc);
1440 // A list of builtin named types.
1442 std::vector<Named_type*> Type::named_builtin_types;
1444 // Make a builtin named type.
1446 Named_type*
1447 Type::make_builtin_named_type(const char* name, Type* type)
1449 Location bloc = Linemap::predeclared_location();
1450 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1451 Named_type* ret = no->type_value();
1452 Type::named_builtin_types.push_back(ret);
1453 return ret;
1456 // Convert the named builtin types.
1458 void
1459 Type::convert_builtin_named_types(Gogo* gogo)
1461 for (std::vector<Named_type*>::const_iterator p =
1462 Type::named_builtin_types.begin();
1463 p != Type::named_builtin_types.end();
1464 ++p)
1466 bool r = (*p)->verify();
1467 go_assert(r);
1468 (*p)->convert(gogo);
1472 // Return the type of a type descriptor. We should really tie this to
1473 // runtime.Type rather than copying it. This must match commonType in
1474 // libgo/go/runtime/type.go.
1476 Type*
1477 Type::make_type_descriptor_type()
1479 static Type* ret;
1480 if (ret == NULL)
1482 Location bloc = Linemap::predeclared_location();
1484 Type* uint8_type = Type::lookup_integer_type("uint8");
1485 Type* uint32_type = Type::lookup_integer_type("uint32");
1486 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1487 Type* string_type = Type::lookup_string_type();
1488 Type* pointer_string_type = Type::make_pointer_type(string_type);
1490 // This is an unnamed version of unsafe.Pointer. Perhaps we
1491 // should use the named version instead, although that would
1492 // require us to create the unsafe package if it has not been
1493 // imported. It probably doesn't matter.
1494 Type* void_type = Type::make_void_type();
1495 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1497 Typed_identifier_list *params = new Typed_identifier_list();
1498 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1499 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1500 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1502 Typed_identifier_list* results = new Typed_identifier_list();
1503 results->push_back(Typed_identifier("", uintptr_type, bloc));
1505 Type* hash_fntype = Type::make_function_type(NULL, params, results,
1506 bloc);
1508 params = new Typed_identifier_list();
1509 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1510 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1511 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1513 results = new Typed_identifier_list();
1514 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1516 Type* equal_fntype = Type::make_function_type(NULL, params, results,
1517 bloc);
1519 // Forward declaration for the type descriptor type.
1520 Named_object* named_type_descriptor_type =
1521 Named_object::make_type_declaration("commonType", NULL, bloc);
1522 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1523 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1525 // The type of a method on a concrete type.
1526 Struct_type* method_type =
1527 Type::make_builtin_struct_type(5,
1528 "name", pointer_string_type,
1529 "pkgPath", pointer_string_type,
1530 "mtyp", pointer_type_descriptor_type,
1531 "typ", pointer_type_descriptor_type,
1532 "tfn", unsafe_pointer_type);
1533 Named_type* named_method_type =
1534 Type::make_builtin_named_type("method", method_type);
1536 // Information for types with a name or methods.
1537 Type* slice_named_method_type =
1538 Type::make_array_type(named_method_type, NULL);
1539 Struct_type* uncommon_type =
1540 Type::make_builtin_struct_type(3,
1541 "name", pointer_string_type,
1542 "pkgPath", pointer_string_type,
1543 "methods", slice_named_method_type);
1544 Named_type* named_uncommon_type =
1545 Type::make_builtin_named_type("uncommonType", uncommon_type);
1547 Type* pointer_uncommon_type =
1548 Type::make_pointer_type(named_uncommon_type);
1550 // The type descriptor type.
1552 Struct_type* type_descriptor_type =
1553 Type::make_builtin_struct_type(11,
1554 "kind", uint8_type,
1555 "align", uint8_type,
1556 "fieldAlign", uint8_type,
1557 "size", uintptr_type,
1558 "hash", uint32_type,
1559 "hashfn", hash_fntype,
1560 "equalfn", equal_fntype,
1561 "gc", uintptr_type,
1562 "string", pointer_string_type,
1563 "", pointer_uncommon_type,
1564 "ptrToThis",
1565 pointer_type_descriptor_type);
1567 Named_type* named = Type::make_builtin_named_type("commonType",
1568 type_descriptor_type);
1570 named_type_descriptor_type->set_type_value(named);
1572 ret = named;
1575 return ret;
1578 // Make the type of a pointer to a type descriptor as represented in
1579 // Go.
1581 Type*
1582 Type::make_type_descriptor_ptr_type()
1584 static Type* ret;
1585 if (ret == NULL)
1586 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1587 return ret;
1590 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1591 // hash code for this type and which compare whether two values of
1592 // this type are equal. If NAME is not NULL it is the name of this
1593 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1594 // functions, for convenience; they may be NULL.
1596 void
1597 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1598 Function_type* equal_fntype, Named_object** hash_fn,
1599 Named_object** equal_fn)
1601 if (!this->is_comparable())
1603 *hash_fn = NULL;
1604 *equal_fn = NULL;
1605 return;
1608 if (hash_fntype == NULL || equal_fntype == NULL)
1610 Location bloc = Linemap::predeclared_location();
1612 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1613 Type* void_type = Type::make_void_type();
1614 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1616 if (hash_fntype == NULL)
1618 Typed_identifier_list* params = new Typed_identifier_list();
1619 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1620 bloc));
1621 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1622 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1624 Typed_identifier_list* results = new Typed_identifier_list();
1625 results->push_back(Typed_identifier("", uintptr_type, bloc));
1627 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1629 if (equal_fntype == NULL)
1631 Typed_identifier_list* params = new Typed_identifier_list();
1632 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1633 bloc));
1634 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1635 bloc));
1636 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1638 Typed_identifier_list* results = new Typed_identifier_list();
1639 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1640 bloc));
1642 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1646 const char* hash_fnname;
1647 const char* equal_fnname;
1648 if (this->compare_is_identity(gogo))
1650 hash_fnname = "__go_type_hash_identity";
1651 equal_fnname = "__go_type_equal_identity";
1653 else
1655 switch (this->base()->classification())
1657 case Type::TYPE_ERROR:
1658 case Type::TYPE_VOID:
1659 case Type::TYPE_NIL:
1660 case Type::TYPE_FUNCTION:
1661 case Type::TYPE_MAP:
1662 // For these types is_comparable should have returned false.
1663 go_unreachable();
1665 case Type::TYPE_BOOLEAN:
1666 case Type::TYPE_INTEGER:
1667 case Type::TYPE_POINTER:
1668 case Type::TYPE_CHANNEL:
1669 // For these types compare_is_identity should have returned true.
1670 go_unreachable();
1672 case Type::TYPE_FLOAT:
1673 hash_fnname = "__go_type_hash_float";
1674 equal_fnname = "__go_type_equal_float";
1675 break;
1677 case Type::TYPE_COMPLEX:
1678 hash_fnname = "__go_type_hash_complex";
1679 equal_fnname = "__go_type_equal_complex";
1680 break;
1682 case Type::TYPE_STRING:
1683 hash_fnname = "__go_type_hash_string";
1684 equal_fnname = "__go_type_equal_string";
1685 break;
1687 case Type::TYPE_STRUCT:
1689 // This is a struct which can not be compared using a
1690 // simple identity function. We need to build a function
1691 // for comparison.
1692 this->specific_type_functions(gogo, name, hash_fntype,
1693 equal_fntype, hash_fn, equal_fn);
1694 return;
1697 case Type::TYPE_ARRAY:
1698 if (this->is_slice_type())
1700 // Type::is_compatible_for_comparison should have
1701 // returned false.
1702 go_unreachable();
1704 else
1706 // This is an array which can not be compared using a
1707 // simple identity function. We need to build a
1708 // function for comparison.
1709 this->specific_type_functions(gogo, name, hash_fntype,
1710 equal_fntype, hash_fn, equal_fn);
1711 return;
1713 break;
1715 case Type::TYPE_INTERFACE:
1716 if (this->interface_type()->is_empty())
1718 hash_fnname = "runtime.nilinterhash";
1719 equal_fnname = "runtime.nilinterequal";
1721 else
1723 hash_fnname = "runtime.interhash";
1724 equal_fnname = "runtime.interequal";
1726 break;
1728 case Type::TYPE_NAMED:
1729 case Type::TYPE_FORWARD:
1730 go_unreachable();
1732 default:
1733 go_unreachable();
1738 Location bloc = Linemap::predeclared_location();
1739 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1740 hash_fntype, bloc);
1741 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1742 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1743 equal_fntype, bloc);
1744 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1747 // A hash table mapping types to the specific hash functions.
1749 Type::Type_functions Type::type_functions_table;
1751 // Handle a type function which is specific to a type: a struct or
1752 // array which can not use an identity comparison.
1754 void
1755 Type::specific_type_functions(Gogo* gogo, Named_type* name,
1756 Function_type* hash_fntype,
1757 Function_type* equal_fntype,
1758 Named_object** hash_fn,
1759 Named_object** equal_fn)
1761 Hash_equal_fn fnull(NULL, NULL);
1762 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1763 std::pair<Type_functions::iterator, bool> ins =
1764 Type::type_functions_table.insert(val);
1765 if (!ins.second)
1767 // We already have functions for this type
1768 *hash_fn = ins.first->second.first;
1769 *equal_fn = ins.first->second.second;
1770 return;
1773 std::string base_name;
1774 if (name == NULL)
1776 // Mangled names can have '.' if they happen to refer to named
1777 // types in some way. That's fine if this is simply a named
1778 // type, but otherwise it will confuse the code that builds
1779 // function identifiers. Remove '.' when necessary.
1780 base_name = this->mangled_name(gogo);
1781 size_t i;
1782 while ((i = base_name.find('.')) != std::string::npos)
1783 base_name[i] = '$';
1784 base_name = gogo->pack_hidden_name(base_name, false);
1786 else
1788 // This name is already hidden or not as appropriate.
1789 base_name = name->name();
1790 unsigned int index;
1791 const Named_object* in_function = name->in_function(&index);
1792 if (in_function != NULL)
1794 base_name.append(1, '$');
1795 const Typed_identifier* rcvr =
1796 in_function->func_value()->type()->receiver();
1797 if (rcvr != NULL)
1799 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
1800 base_name.append(Gogo::unpack_hidden_name(rcvr_type->name()));
1801 base_name.append(1, '$');
1803 base_name.append(Gogo::unpack_hidden_name(in_function->name()));
1804 if (index > 0)
1806 char buf[30];
1807 snprintf(buf, sizeof buf, "%u", index);
1808 base_name += '$';
1809 base_name += buf;
1813 std::string hash_name = base_name + "$hash";
1814 std::string equal_name = base_name + "$equal";
1816 Location bloc = Linemap::predeclared_location();
1818 const Package* package = NULL;
1819 bool is_defined_elsewhere =
1820 this->type_descriptor_defined_elsewhere(name, &package);
1821 if (is_defined_elsewhere)
1823 *hash_fn = Named_object::make_function_declaration(hash_name, package,
1824 hash_fntype, bloc);
1825 *equal_fn = Named_object::make_function_declaration(equal_name, package,
1826 equal_fntype, bloc);
1828 else
1830 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
1831 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
1832 bloc);
1835 ins.first->second.first = *hash_fn;
1836 ins.first->second.second = *equal_fn;
1838 if (!is_defined_elsewhere)
1840 if (gogo->in_global_scope())
1841 this->write_specific_type_functions(gogo, name, hash_name, hash_fntype,
1842 equal_name, equal_fntype);
1843 else
1844 gogo->queue_specific_type_function(this, name, hash_name, hash_fntype,
1845 equal_name, equal_fntype);
1849 // Write the hash and equality functions for a type which needs to be
1850 // written specially.
1852 void
1853 Type::write_specific_type_functions(Gogo* gogo, Named_type* name,
1854 const std::string& hash_name,
1855 Function_type* hash_fntype,
1856 const std::string& equal_name,
1857 Function_type* equal_fntype)
1859 Location bloc = Linemap::predeclared_location();
1861 if (gogo->specific_type_functions_are_written())
1863 go_assert(saw_errors());
1864 return;
1867 go_assert(this->is_comparable());
1869 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
1870 bloc);
1871 hash_fn->func_value()->set_is_type_specific_function();
1872 gogo->start_block(bloc);
1874 if (name != NULL && name->real_type()->named_type() != NULL)
1875 this->write_named_hash(gogo, name, hash_fntype, equal_fntype);
1876 else if (this->struct_type() != NULL)
1877 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
1878 equal_fntype);
1879 else if (this->array_type() != NULL)
1880 this->array_type()->write_hash_function(gogo, name, hash_fntype,
1881 equal_fntype);
1882 else
1883 go_unreachable();
1885 Block* b = gogo->finish_block(bloc);
1886 gogo->add_block(b, bloc);
1887 gogo->lower_block(hash_fn, b);
1888 gogo->finish_function(bloc);
1890 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
1891 false, bloc);
1892 equal_fn->func_value()->set_is_type_specific_function();
1893 gogo->start_block(bloc);
1895 if (name != NULL && name->real_type()->named_type() != NULL)
1896 this->write_named_equal(gogo, name);
1897 else if (this->struct_type() != NULL)
1898 this->struct_type()->write_equal_function(gogo, name);
1899 else if (this->array_type() != NULL)
1900 this->array_type()->write_equal_function(gogo, name);
1901 else
1902 go_unreachable();
1904 b = gogo->finish_block(bloc);
1905 gogo->add_block(b, bloc);
1906 gogo->lower_block(equal_fn, b);
1907 gogo->finish_function(bloc);
1909 // Build the function descriptors for the type descriptor to refer to.
1910 hash_fn->func_value()->descriptor(gogo, hash_fn);
1911 equal_fn->func_value()->descriptor(gogo, equal_fn);
1914 // Write a hash function that simply calls the hash function for a
1915 // named type. This is used when one named type is defined as
1916 // another. This ensures that this case works when the other named
1917 // type is defined in another package and relies on calling hash
1918 // functions defined only in that package.
1920 void
1921 Type::write_named_hash(Gogo* gogo, Named_type* name,
1922 Function_type* hash_fntype, Function_type* equal_fntype)
1924 Location bloc = Linemap::predeclared_location();
1926 Named_type* base_type = name->real_type()->named_type();
1927 go_assert(base_type != NULL);
1929 // The pointer to the type we are going to hash. This is an
1930 // unsafe.Pointer.
1931 Named_object* key_arg = gogo->lookup("key", NULL);
1932 go_assert(key_arg != NULL);
1934 // The seed argument to the hash function.
1935 Named_object* seed_arg = gogo->lookup("seed", NULL);
1936 go_assert(seed_arg != NULL);
1938 // The size of the type we are going to hash.
1939 Named_object* keysz_arg = gogo->lookup("key_size", NULL);
1940 go_assert(keysz_arg != NULL);
1942 Named_object* hash_fn;
1943 Named_object* equal_fn;
1944 name->real_type()->type_functions(gogo, base_type, hash_fntype, equal_fntype,
1945 &hash_fn, &equal_fn);
1947 // Call the hash function for the base type.
1948 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
1949 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
1950 Expression* keysz_ref = Expression::make_var_reference(keysz_arg, bloc);
1951 Expression_list* args = new Expression_list();
1952 args->push_back(key_ref);
1953 args->push_back(seed_ref);
1954 args->push_back(keysz_ref);
1955 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
1956 Expression* call = Expression::make_call(func, args, false, bloc);
1958 // Return the hash of the base type.
1959 Expression_list* vals = new Expression_list();
1960 vals->push_back(call);
1961 Statement* s = Statement::make_return_statement(vals, bloc);
1962 gogo->add_statement(s);
1965 // Write an equality function that simply calls the equality function
1966 // for a named type. This is used when one named type is defined as
1967 // another. This ensures that this case works when the other named
1968 // type is defined in another package and relies on calling equality
1969 // functions defined only in that package.
1971 void
1972 Type::write_named_equal(Gogo* gogo, Named_type* name)
1974 Location bloc = Linemap::predeclared_location();
1976 // The pointers to the types we are going to compare. These have
1977 // type unsafe.Pointer.
1978 Named_object* key1_arg = gogo->lookup("key1", NULL);
1979 Named_object* key2_arg = gogo->lookup("key2", NULL);
1980 go_assert(key1_arg != NULL && key2_arg != NULL);
1982 Named_type* base_type = name->real_type()->named_type();
1983 go_assert(base_type != NULL);
1985 // Build temporaries with the base type.
1986 Type* pt = Type::make_pointer_type(base_type);
1988 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
1989 ref = Expression::make_cast(pt, ref, bloc);
1990 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
1991 gogo->add_statement(p1);
1993 ref = Expression::make_var_reference(key2_arg, bloc);
1994 ref = Expression::make_cast(pt, ref, bloc);
1995 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
1996 gogo->add_statement(p2);
1998 // Compare the values for equality.
1999 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
2000 t1 = Expression::make_unary(OPERATOR_MULT, t1, bloc);
2002 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
2003 t2 = Expression::make_unary(OPERATOR_MULT, t2, bloc);
2005 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
2007 // Return the equality comparison.
2008 Expression_list* vals = new Expression_list();
2009 vals->push_back(cond);
2010 Statement* s = Statement::make_return_statement(vals, bloc);
2011 gogo->add_statement(s);
2014 // Return a composite literal for the type descriptor for a plain type
2015 // of kind RUNTIME_TYPE_KIND named NAME.
2017 Expression*
2018 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
2019 Named_type* name, const Methods* methods,
2020 bool only_value_methods)
2022 Location bloc = Linemap::predeclared_location();
2024 Type* td_type = Type::make_type_descriptor_type();
2025 const Struct_field_list* fields = td_type->struct_type()->fields();
2027 Expression_list* vals = new Expression_list();
2028 vals->reserve(9);
2030 if (!this->has_pointer())
2031 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
2032 if (this->points_to() != NULL)
2033 runtime_type_kind |= RUNTIME_TYPE_KIND_DIRECT_IFACE;
2034 Struct_field_list::const_iterator p = fields->begin();
2035 go_assert(p->is_field_name("kind"));
2036 vals->push_back(Expression::make_integer_ul(runtime_type_kind, p->type(),
2037 bloc));
2039 ++p;
2040 go_assert(p->is_field_name("align"));
2041 Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT;
2042 vals->push_back(Expression::make_type_info(this, type_info));
2044 ++p;
2045 go_assert(p->is_field_name("fieldAlign"));
2046 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2047 vals->push_back(Expression::make_type_info(this, type_info));
2049 ++p;
2050 go_assert(p->is_field_name("size"));
2051 type_info = Expression::TYPE_INFO_SIZE;
2052 vals->push_back(Expression::make_type_info(this, type_info));
2054 ++p;
2055 go_assert(p->is_field_name("hash"));
2056 unsigned int h;
2057 if (name != NULL)
2058 h = name->hash_for_method(gogo);
2059 else
2060 h = this->hash_for_method(gogo);
2061 vals->push_back(Expression::make_integer_ul(h, p->type(), bloc));
2063 ++p;
2064 go_assert(p->is_field_name("hashfn"));
2065 Function_type* hash_fntype = p->type()->function_type();
2067 ++p;
2068 go_assert(p->is_field_name("equalfn"));
2069 Function_type* equal_fntype = p->type()->function_type();
2071 Named_object* hash_fn;
2072 Named_object* equal_fn;
2073 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
2074 &equal_fn);
2075 if (hash_fn == NULL)
2076 vals->push_back(Expression::make_cast(hash_fntype,
2077 Expression::make_nil(bloc),
2078 bloc));
2079 else
2080 vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
2081 if (equal_fn == NULL)
2082 vals->push_back(Expression::make_cast(equal_fntype,
2083 Expression::make_nil(bloc),
2084 bloc));
2085 else
2086 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
2088 ++p;
2089 go_assert(p->is_field_name("gc"));
2090 vals->push_back(Expression::make_gc_symbol(this));
2092 ++p;
2093 go_assert(p->is_field_name("string"));
2094 Expression* s = Expression::make_string((name != NULL
2095 ? name->reflection(gogo)
2096 : this->reflection(gogo)),
2097 bloc);
2098 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2100 ++p;
2101 go_assert(p->is_field_name("uncommonType"));
2102 if (name == NULL && methods == NULL)
2103 vals->push_back(Expression::make_nil(bloc));
2104 else
2106 if (methods == NULL)
2107 methods = name->methods();
2108 vals->push_back(this->uncommon_type_constructor(gogo,
2109 p->type()->deref(),
2110 name, methods,
2111 only_value_methods));
2114 ++p;
2115 go_assert(p->is_field_name("ptrToThis"));
2116 if (name == NULL && methods == NULL)
2117 vals->push_back(Expression::make_nil(bloc));
2118 else
2120 Type* pt;
2121 if (name != NULL)
2122 pt = Type::make_pointer_type(name);
2123 else
2124 pt = Type::make_pointer_type(this);
2125 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2128 ++p;
2129 go_assert(p == fields->end());
2131 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2134 // Return a pointer to the Garbage Collection information for this type.
2136 Bexpression*
2137 Type::gc_symbol_pointer(Gogo* gogo)
2139 Type* t = this->forwarded();
2140 if (t->named_type() != NULL && t->named_type()->is_alias())
2141 t = t->named_type()->real_type();
2142 if (t->gc_symbol_var_ == NULL)
2144 t->make_gc_symbol_var(gogo);
2145 go_assert(t->gc_symbol_var_ != NULL);
2147 Location bloc = Linemap::predeclared_location();
2148 Bexpression* var_expr =
2149 gogo->backend()->var_expression(t->gc_symbol_var_, bloc);
2150 return gogo->backend()->address_expression(var_expr, bloc);
2153 // A mapping from unnamed types to GC symbol variables.
2155 Type::GC_symbol_vars Type::gc_symbol_vars;
2157 // Build the GC symbol for this type.
2159 void
2160 Type::make_gc_symbol_var(Gogo* gogo)
2162 go_assert(this->gc_symbol_var_ == NULL);
2164 Named_type* nt = this->named_type();
2166 // We can have multiple instances of unnamed types and similar to type
2167 // descriptors, we only want to the emit the GC data once, so we use a
2168 // hash table.
2169 Bvariable** phash = NULL;
2170 if (nt == NULL)
2172 Bvariable* bvnull = NULL;
2173 std::pair<GC_symbol_vars::iterator, bool> ins =
2174 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2175 if (!ins.second)
2177 // We've already built a gc symbol for this type.
2178 this->gc_symbol_var_ = ins.first->second;
2179 return;
2181 phash = &ins.first->second;
2184 std::string sym_name = this->type_descriptor_var_name(gogo, nt) + "$gc";
2186 // Build the contents of the gc symbol.
2187 Expression* sym_init = this->gc_symbol_constructor(gogo);
2188 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2190 // If the type descriptor for this type is defined somewhere else, so is the
2191 // GC symbol.
2192 const Package* dummy;
2193 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2195 std::string asm_name(go_selectively_encode_id(sym_name));
2196 this->gc_symbol_var_ =
2197 gogo->backend()->implicit_variable_reference(sym_name, asm_name,
2198 sym_btype);
2199 if (phash != NULL)
2200 *phash = this->gc_symbol_var_;
2201 return;
2204 // See if this gc symbol can appear in multiple packages.
2205 bool is_common = false;
2206 if (nt != NULL)
2208 // We create the symbol for a builtin type whenever we need
2209 // it.
2210 is_common = nt->is_builtin();
2212 else
2214 // This is an unnamed type. The descriptor could be defined in
2215 // any package where it is needed, and the linker will pick one
2216 // descriptor to keep.
2217 is_common = true;
2220 // Since we are building the GC symbol in this package, we must create the
2221 // variable before converting the initializer to its backend representation
2222 // because the initializer may refer to the GC symbol for this type.
2223 std::string asm_name(go_selectively_encode_id(sym_name));
2224 this->gc_symbol_var_ =
2225 gogo->backend()->implicit_variable(sym_name, asm_name,
2226 sym_btype, false, true, is_common, 0);
2227 if (phash != NULL)
2228 *phash = this->gc_symbol_var_;
2230 Translate_context context(gogo, NULL, NULL, NULL);
2231 context.set_is_const();
2232 Bexpression* sym_binit = sym_init->get_backend(&context);
2233 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2234 sym_btype, false, true, is_common,
2235 sym_binit);
2238 // Return an array literal for the Garbage Collection information for this type.
2240 Expression*
2241 Type::gc_symbol_constructor(Gogo* gogo)
2243 Location bloc = Linemap::predeclared_location();
2245 // The common GC Symbol data starts with the width of the type and ends
2246 // with the GC Opcode GC_END.
2247 // However, for certain types, the GC symbol may include extra information
2248 // before the ending opcode, so we pass the expression list into
2249 // Type::gc_symbol to allow it to add extra information as is necessary.
2250 Expression_list* vals = new Expression_list;
2252 Type* uintptr_t = Type::lookup_integer_type("uintptr");
2253 // width
2254 vals->push_back(Expression::make_type_info(this,
2255 Expression::TYPE_INFO_SIZE));
2257 Expression* offset = Expression::make_integer_ul(0, uintptr_t, bloc);
2259 this->do_gc_symbol(gogo, &vals, &offset, 0);
2261 vals->push_back(Expression::make_integer_ul(GC_END, uintptr_t, bloc));
2263 Expression* len = Expression::make_integer_ul(vals->size() + 1, NULL,
2264 bloc);
2265 Array_type* gc_symbol_type = Type::make_array_type(uintptr_t, len);
2266 return Expression::make_array_composite_literal(gc_symbol_type, vals, bloc);
2269 // Advance the OFFSET of the GC symbol by this type's width.
2271 void
2272 Type::advance_gc_offset(Expression** offset)
2274 if (this->is_error_type())
2275 return;
2277 Location bloc = Linemap::predeclared_location();
2278 Expression* width =
2279 Expression::make_type_info(this, Expression::TYPE_INFO_SIZE);
2280 *offset = Expression::make_binary(OPERATOR_PLUS, *offset, width, bloc);
2283 // Return a composite literal for the uncommon type information for
2284 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
2285 // struct. If name is not NULL, it is the name of the type. If
2286 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
2287 // is true if only value methods should be included. At least one of
2288 // NAME and METHODS must not be NULL.
2290 Expression*
2291 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
2292 Named_type* name, const Methods* methods,
2293 bool only_value_methods) const
2295 Location bloc = Linemap::predeclared_location();
2297 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
2299 Expression_list* vals = new Expression_list();
2300 vals->reserve(3);
2302 Struct_field_list::const_iterator p = fields->begin();
2303 go_assert(p->is_field_name("name"));
2305 ++p;
2306 go_assert(p->is_field_name("pkgPath"));
2308 if (name == NULL)
2310 vals->push_back(Expression::make_nil(bloc));
2311 vals->push_back(Expression::make_nil(bloc));
2313 else
2315 Named_object* no = name->named_object();
2316 std::string n = Gogo::unpack_hidden_name(no->name());
2317 Expression* s = Expression::make_string(n, bloc);
2318 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2320 if (name->is_builtin())
2321 vals->push_back(Expression::make_nil(bloc));
2322 else
2324 const Package* package = no->package();
2325 const std::string& pkgpath(package == NULL
2326 ? gogo->pkgpath()
2327 : package->pkgpath());
2328 s = Expression::make_string(pkgpath, bloc);
2329 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2333 ++p;
2334 go_assert(p->is_field_name("methods"));
2335 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
2336 only_value_methods));
2338 ++p;
2339 go_assert(p == fields->end());
2341 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
2342 vals, bloc);
2343 return Expression::make_unary(OPERATOR_AND, r, bloc);
2346 // Sort methods by name.
2348 class Sort_methods
2350 public:
2351 bool
2352 operator()(const std::pair<std::string, const Method*>& m1,
2353 const std::pair<std::string, const Method*>& m2) const
2355 return (Gogo::unpack_hidden_name(m1.first)
2356 < Gogo::unpack_hidden_name(m2.first));
2360 // Return a composite literal for the type method table for this type.
2361 // METHODS_TYPE is the type of the table, and is a slice type.
2362 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
2363 // then only value methods are used.
2365 Expression*
2366 Type::methods_constructor(Gogo* gogo, Type* methods_type,
2367 const Methods* methods,
2368 bool only_value_methods) const
2370 Location bloc = Linemap::predeclared_location();
2372 std::vector<std::pair<std::string, const Method*> > smethods;
2373 if (methods != NULL)
2375 smethods.reserve(methods->count());
2376 for (Methods::const_iterator p = methods->begin();
2377 p != methods->end();
2378 ++p)
2380 if (p->second->is_ambiguous())
2381 continue;
2382 if (only_value_methods && !p->second->is_value_method())
2383 continue;
2385 // This is where we implement the magic //go:nointerface
2386 // comment. If we saw that comment, we don't add this
2387 // method to the type descriptor.
2388 if (p->second->nointerface())
2389 continue;
2391 smethods.push_back(std::make_pair(p->first, p->second));
2395 if (smethods.empty())
2396 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
2398 std::sort(smethods.begin(), smethods.end(), Sort_methods());
2400 Type* method_type = methods_type->array_type()->element_type();
2402 Expression_list* vals = new Expression_list();
2403 vals->reserve(smethods.size());
2404 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
2405 = smethods.begin();
2406 p != smethods.end();
2407 ++p)
2408 vals->push_back(this->method_constructor(gogo, method_type, p->first,
2409 p->second, only_value_methods));
2411 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
2414 // Return a composite literal for a single method. METHOD_TYPE is the
2415 // type of the entry. METHOD_NAME is the name of the method and M is
2416 // the method information.
2418 Expression*
2419 Type::method_constructor(Gogo*, Type* method_type,
2420 const std::string& method_name,
2421 const Method* m,
2422 bool only_value_methods) const
2424 Location bloc = Linemap::predeclared_location();
2426 const Struct_field_list* fields = method_type->struct_type()->fields();
2428 Expression_list* vals = new Expression_list();
2429 vals->reserve(5);
2431 Struct_field_list::const_iterator p = fields->begin();
2432 go_assert(p->is_field_name("name"));
2433 const std::string n = Gogo::unpack_hidden_name(method_name);
2434 Expression* s = Expression::make_string(n, bloc);
2435 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2437 ++p;
2438 go_assert(p->is_field_name("pkgPath"));
2439 if (!Gogo::is_hidden_name(method_name))
2440 vals->push_back(Expression::make_nil(bloc));
2441 else
2443 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
2444 bloc);
2445 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2448 Named_object* no = (m->needs_stub_method()
2449 ? m->stub_object()
2450 : m->named_object());
2452 Function_type* mtype;
2453 if (no->is_function())
2454 mtype = no->func_value()->type();
2455 else
2456 mtype = no->func_declaration_value()->type();
2457 go_assert(mtype->is_method());
2458 Type* nonmethod_type = mtype->copy_without_receiver();
2460 ++p;
2461 go_assert(p->is_field_name("mtyp"));
2462 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
2464 ++p;
2465 go_assert(p->is_field_name("typ"));
2466 bool want_pointer_receiver = !only_value_methods && m->is_value_method();
2467 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
2468 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
2470 ++p;
2471 go_assert(p->is_field_name("tfn"));
2472 vals->push_back(Expression::make_func_code_reference(no, bloc));
2474 ++p;
2475 go_assert(p == fields->end());
2477 return Expression::make_struct_composite_literal(method_type, vals, bloc);
2480 // Return a composite literal for the type descriptor of a plain type.
2481 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
2482 // NULL, it is the name to use as well as the list of methods.
2484 Expression*
2485 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
2486 Named_type* name)
2488 return this->type_descriptor_constructor(gogo, runtime_type_kind,
2489 name, NULL, true);
2492 // Return the type reflection string for this type.
2494 std::string
2495 Type::reflection(Gogo* gogo) const
2497 std::string ret;
2499 // The do_reflection virtual function should set RET to the
2500 // reflection string.
2501 this->do_reflection(gogo, &ret);
2503 return ret;
2506 // Return a mangled name for the type.
2508 std::string
2509 Type::mangled_name(Gogo* gogo) const
2511 std::string ret;
2513 // The do_mangled_name virtual function should set RET to the
2514 // mangled name. For a composite type it should append a code for
2515 // the composition and then call do_mangled_name on the components.
2516 this->do_mangled_name(gogo, &ret);
2518 return ret;
2521 // Return whether the backend size of the type is known.
2523 bool
2524 Type::is_backend_type_size_known(Gogo* gogo)
2526 switch (this->classification_)
2528 case TYPE_ERROR:
2529 case TYPE_VOID:
2530 case TYPE_BOOLEAN:
2531 case TYPE_INTEGER:
2532 case TYPE_FLOAT:
2533 case TYPE_COMPLEX:
2534 case TYPE_STRING:
2535 case TYPE_FUNCTION:
2536 case TYPE_POINTER:
2537 case TYPE_NIL:
2538 case TYPE_MAP:
2539 case TYPE_CHANNEL:
2540 case TYPE_INTERFACE:
2541 return true;
2543 case TYPE_STRUCT:
2545 const Struct_field_list* fields = this->struct_type()->fields();
2546 for (Struct_field_list::const_iterator pf = fields->begin();
2547 pf != fields->end();
2548 ++pf)
2549 if (!pf->type()->is_backend_type_size_known(gogo))
2550 return false;
2551 return true;
2554 case TYPE_ARRAY:
2556 const Array_type* at = this->array_type();
2557 if (at->length() == NULL)
2558 return true;
2559 else
2561 Numeric_constant nc;
2562 if (!at->length()->numeric_constant_value(&nc))
2563 return false;
2564 mpz_t ival;
2565 if (!nc.to_int(&ival))
2566 return false;
2567 mpz_clear(ival);
2568 return at->element_type()->is_backend_type_size_known(gogo);
2572 case TYPE_NAMED:
2573 this->named_type()->convert(gogo);
2574 return this->named_type()->is_named_backend_type_size_known();
2576 case TYPE_FORWARD:
2578 Forward_declaration_type* fdt = this->forward_declaration_type();
2579 return fdt->real_type()->is_backend_type_size_known(gogo);
2582 case TYPE_SINK:
2583 case TYPE_CALL_MULTIPLE_RESULT:
2584 go_unreachable();
2586 default:
2587 go_unreachable();
2591 // If the size of the type can be determined, set *PSIZE to the size
2592 // in bytes and return true. Otherwise, return false. This queries
2593 // the backend.
2595 bool
2596 Type::backend_type_size(Gogo* gogo, int64_t *psize)
2598 if (!this->is_backend_type_size_known(gogo))
2599 return false;
2600 if (this->is_error_type())
2601 return false;
2602 Btype* bt = this->get_backend_placeholder(gogo);
2603 *psize = gogo->backend()->type_size(bt);
2604 if (*psize == -1)
2606 if (this->named_type() != NULL)
2607 go_error_at(this->named_type()->location(),
2608 "type %s larger than address space",
2609 Gogo::message_name(this->named_type()->name()).c_str());
2610 else
2611 go_error_at(Linemap::unknown_location(),
2612 "type %s larger than address space",
2613 this->reflection(gogo).c_str());
2615 // Make this an error type to avoid knock-on errors.
2616 this->classification_ = TYPE_ERROR;
2617 return false;
2619 return true;
2622 // If the alignment of the type can be determined, set *PALIGN to
2623 // the alignment in bytes and return true. Otherwise, return false.
2625 bool
2626 Type::backend_type_align(Gogo* gogo, int64_t *palign)
2628 if (!this->is_backend_type_size_known(gogo))
2629 return false;
2630 Btype* bt = this->get_backend_placeholder(gogo);
2631 *palign = gogo->backend()->type_alignment(bt);
2632 return true;
2635 // Like backend_type_align, but return the alignment when used as a
2636 // field.
2638 bool
2639 Type::backend_type_field_align(Gogo* gogo, int64_t *palign)
2641 if (!this->is_backend_type_size_known(gogo))
2642 return false;
2643 Btype* bt = this->get_backend_placeholder(gogo);
2644 *palign = gogo->backend()->type_field_alignment(bt);
2645 return true;
2648 // Default function to export a type.
2650 void
2651 Type::do_export(Export*) const
2653 go_unreachable();
2656 // Import a type.
2658 Type*
2659 Type::import_type(Import* imp)
2661 if (imp->match_c_string("("))
2662 return Function_type::do_import(imp);
2663 else if (imp->match_c_string("*"))
2664 return Pointer_type::do_import(imp);
2665 else if (imp->match_c_string("struct "))
2666 return Struct_type::do_import(imp);
2667 else if (imp->match_c_string("["))
2668 return Array_type::do_import(imp);
2669 else if (imp->match_c_string("map "))
2670 return Map_type::do_import(imp);
2671 else if (imp->match_c_string("chan "))
2672 return Channel_type::do_import(imp);
2673 else if (imp->match_c_string("interface"))
2674 return Interface_type::do_import(imp);
2675 else
2677 go_error_at(imp->location(), "import error: expected type");
2678 return Type::make_error_type();
2682 // A type used to indicate a parsing error. This exists to simplify
2683 // later error detection.
2685 class Error_type : public Type
2687 public:
2688 Error_type()
2689 : Type(TYPE_ERROR)
2692 protected:
2693 bool
2694 do_compare_is_identity(Gogo*)
2695 { return false; }
2697 Btype*
2698 do_get_backend(Gogo* gogo)
2699 { return gogo->backend()->error_type(); }
2701 Expression*
2702 do_type_descriptor(Gogo*, Named_type*)
2703 { return Expression::make_error(Linemap::predeclared_location()); }
2705 void
2706 do_reflection(Gogo*, std::string*) const
2707 { go_assert(saw_errors()); }
2709 void
2710 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
2711 { go_assert(saw_errors()); }
2713 void
2714 do_mangled_name(Gogo*, std::string* ret) const
2715 { ret->push_back('E'); }
2718 Type*
2719 Type::make_error_type()
2721 static Error_type singleton_error_type;
2722 return &singleton_error_type;
2725 // The void type.
2727 class Void_type : public Type
2729 public:
2730 Void_type()
2731 : Type(TYPE_VOID)
2734 protected:
2735 bool
2736 do_compare_is_identity(Gogo*)
2737 { return false; }
2739 Btype*
2740 do_get_backend(Gogo* gogo)
2741 { return gogo->backend()->void_type(); }
2743 Expression*
2744 do_type_descriptor(Gogo*, Named_type*)
2745 { go_unreachable(); }
2747 void
2748 do_reflection(Gogo*, std::string*) const
2751 void
2752 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
2755 void
2756 do_mangled_name(Gogo*, std::string* ret) const
2757 { ret->push_back('v'); }
2760 Type*
2761 Type::make_void_type()
2763 static Void_type singleton_void_type;
2764 return &singleton_void_type;
2767 // The boolean type.
2769 class Boolean_type : public Type
2771 public:
2772 Boolean_type()
2773 : Type(TYPE_BOOLEAN)
2776 protected:
2777 bool
2778 do_compare_is_identity(Gogo*)
2779 { return true; }
2781 Btype*
2782 do_get_backend(Gogo* gogo)
2783 { return gogo->backend()->bool_type(); }
2785 Expression*
2786 do_type_descriptor(Gogo*, Named_type* name);
2788 // We should not be asked for the reflection string of a basic type.
2789 void
2790 do_reflection(Gogo*, std::string* ret) const
2791 { ret->append("bool"); }
2793 void
2794 do_gc_symbol(Gogo*, Expression_list**, Expression**, int);
2796 void
2797 do_mangled_name(Gogo*, std::string* ret) const
2798 { ret->push_back('b'); }
2801 // Make the type descriptor.
2803 Expression*
2804 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2806 if (name != NULL)
2807 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
2808 else
2810 Named_object* no = gogo->lookup_global("bool");
2811 go_assert(no != NULL);
2812 return Type::type_descriptor(gogo, no->type_value());
2816 // Update the offset of the GC symbol.
2818 void
2819 Boolean_type::do_gc_symbol(Gogo*, Expression_list**, Expression** offset, int)
2820 { this->advance_gc_offset(offset); }
2822 Type*
2823 Type::make_boolean_type()
2825 static Boolean_type boolean_type;
2826 return &boolean_type;
2829 // The named type "bool".
2831 static Named_type* named_bool_type;
2833 // Get the named type "bool".
2835 Named_type*
2836 Type::lookup_bool_type()
2838 return named_bool_type;
2841 // Make the named type "bool".
2843 Named_type*
2844 Type::make_named_bool_type()
2846 Type* bool_type = Type::make_boolean_type();
2847 Named_object* named_object =
2848 Named_object::make_type("bool", NULL, bool_type,
2849 Linemap::predeclared_location());
2850 Named_type* named_type = named_object->type_value();
2851 named_bool_type = named_type;
2852 return named_type;
2855 // Class Integer_type.
2857 Integer_type::Named_integer_types Integer_type::named_integer_types;
2859 // Create a new integer type. Non-abstract integer types always have
2860 // names.
2862 Named_type*
2863 Integer_type::create_integer_type(const char* name, bool is_unsigned,
2864 int bits, int runtime_type_kind)
2866 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
2867 runtime_type_kind);
2868 std::string sname(name);
2869 Named_object* named_object =
2870 Named_object::make_type(sname, NULL, integer_type,
2871 Linemap::predeclared_location());
2872 Named_type* named_type = named_object->type_value();
2873 std::pair<Named_integer_types::iterator, bool> ins =
2874 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
2875 go_assert(ins.second);
2876 return named_type;
2879 // Look up an existing integer type.
2881 Named_type*
2882 Integer_type::lookup_integer_type(const char* name)
2884 Named_integer_types::const_iterator p =
2885 Integer_type::named_integer_types.find(name);
2886 go_assert(p != Integer_type::named_integer_types.end());
2887 return p->second;
2890 // Create a new abstract integer type.
2892 Integer_type*
2893 Integer_type::create_abstract_integer_type()
2895 static Integer_type* abstract_type;
2896 if (abstract_type == NULL)
2898 Type* int_type = Type::lookup_integer_type("int");
2899 abstract_type = new Integer_type(true, false,
2900 int_type->integer_type()->bits(),
2901 RUNTIME_TYPE_KIND_INT);
2903 return abstract_type;
2906 // Create a new abstract character type.
2908 Integer_type*
2909 Integer_type::create_abstract_character_type()
2911 static Integer_type* abstract_type;
2912 if (abstract_type == NULL)
2914 abstract_type = new Integer_type(true, false, 32,
2915 RUNTIME_TYPE_KIND_INT32);
2916 abstract_type->set_is_rune();
2918 return abstract_type;
2921 // Integer type compatibility.
2923 bool
2924 Integer_type::is_identical(const Integer_type* t) const
2926 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
2927 return false;
2928 return this->is_abstract_ == t->is_abstract_;
2931 // Hash code.
2933 unsigned int
2934 Integer_type::do_hash_for_method(Gogo*) const
2936 return ((this->bits_ << 4)
2937 + ((this->is_unsigned_ ? 1 : 0) << 8)
2938 + ((this->is_abstract_ ? 1 : 0) << 9));
2941 // Convert an Integer_type to the backend representation.
2943 Btype*
2944 Integer_type::do_get_backend(Gogo* gogo)
2946 if (this->is_abstract_)
2948 go_assert(saw_errors());
2949 return gogo->backend()->error_type();
2951 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
2954 // The type descriptor for an integer type. Integer types are always
2955 // named.
2957 Expression*
2958 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2960 go_assert(name != NULL || saw_errors());
2961 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2964 // We should not be asked for the reflection string of a basic type.
2966 void
2967 Integer_type::do_reflection(Gogo*, std::string*) const
2969 go_assert(saw_errors());
2972 // Mangled name.
2974 void
2975 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
2977 char buf[100];
2978 snprintf(buf, sizeof buf, "i%s%s%de",
2979 this->is_abstract_ ? "a" : "",
2980 this->is_unsigned_ ? "u" : "",
2981 this->bits_);
2982 ret->append(buf);
2985 // Make an integer type.
2987 Named_type*
2988 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
2989 int runtime_type_kind)
2991 return Integer_type::create_integer_type(name, is_unsigned, bits,
2992 runtime_type_kind);
2995 // Make an abstract integer type.
2997 Integer_type*
2998 Type::make_abstract_integer_type()
3000 return Integer_type::create_abstract_integer_type();
3003 // Make an abstract character type.
3005 Integer_type*
3006 Type::make_abstract_character_type()
3008 return Integer_type::create_abstract_character_type();
3011 // Look up an integer type.
3013 Named_type*
3014 Type::lookup_integer_type(const char* name)
3016 return Integer_type::lookup_integer_type(name);
3019 // Class Float_type.
3021 Float_type::Named_float_types Float_type::named_float_types;
3023 // Create a new float type. Non-abstract float types always have
3024 // names.
3026 Named_type*
3027 Float_type::create_float_type(const char* name, int bits,
3028 int runtime_type_kind)
3030 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
3031 std::string sname(name);
3032 Named_object* named_object =
3033 Named_object::make_type(sname, NULL, float_type,
3034 Linemap::predeclared_location());
3035 Named_type* named_type = named_object->type_value();
3036 std::pair<Named_float_types::iterator, bool> ins =
3037 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
3038 go_assert(ins.second);
3039 return named_type;
3042 // Look up an existing float type.
3044 Named_type*
3045 Float_type::lookup_float_type(const char* name)
3047 Named_float_types::const_iterator p =
3048 Float_type::named_float_types.find(name);
3049 go_assert(p != Float_type::named_float_types.end());
3050 return p->second;
3053 // Create a new abstract float type.
3055 Float_type*
3056 Float_type::create_abstract_float_type()
3058 static Float_type* abstract_type;
3059 if (abstract_type == NULL)
3060 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
3061 return abstract_type;
3064 // Whether this type is identical with T.
3066 bool
3067 Float_type::is_identical(const Float_type* t) const
3069 if (this->bits_ != t->bits_)
3070 return false;
3071 return this->is_abstract_ == t->is_abstract_;
3074 // Hash code.
3076 unsigned int
3077 Float_type::do_hash_for_method(Gogo*) const
3079 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
3082 // Convert to the backend representation.
3084 Btype*
3085 Float_type::do_get_backend(Gogo* gogo)
3087 return gogo->backend()->float_type(this->bits_);
3090 // The type descriptor for a float type. Float types are always named.
3092 Expression*
3093 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3095 go_assert(name != NULL || saw_errors());
3096 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
3099 // We should not be asked for the reflection string of a basic type.
3101 void
3102 Float_type::do_reflection(Gogo*, std::string*) const
3104 go_assert(saw_errors());
3107 // Mangled name.
3109 void
3110 Float_type::do_mangled_name(Gogo*, std::string* ret) const
3112 char buf[100];
3113 snprintf(buf, sizeof buf, "f%s%de",
3114 this->is_abstract_ ? "a" : "",
3115 this->bits_);
3116 ret->append(buf);
3119 // Make a floating point type.
3121 Named_type*
3122 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
3124 return Float_type::create_float_type(name, bits, runtime_type_kind);
3127 // Make an abstract float type.
3129 Float_type*
3130 Type::make_abstract_float_type()
3132 return Float_type::create_abstract_float_type();
3135 // Look up a float type.
3137 Named_type*
3138 Type::lookup_float_type(const char* name)
3140 return Float_type::lookup_float_type(name);
3143 // Class Complex_type.
3145 Complex_type::Named_complex_types Complex_type::named_complex_types;
3147 // Create a new complex type. Non-abstract complex types always have
3148 // names.
3150 Named_type*
3151 Complex_type::create_complex_type(const char* name, int bits,
3152 int runtime_type_kind)
3154 Complex_type* complex_type = new Complex_type(false, bits,
3155 runtime_type_kind);
3156 std::string sname(name);
3157 Named_object* named_object =
3158 Named_object::make_type(sname, NULL, complex_type,
3159 Linemap::predeclared_location());
3160 Named_type* named_type = named_object->type_value();
3161 std::pair<Named_complex_types::iterator, bool> ins =
3162 Complex_type::named_complex_types.insert(std::make_pair(sname,
3163 named_type));
3164 go_assert(ins.second);
3165 return named_type;
3168 // Look up an existing complex type.
3170 Named_type*
3171 Complex_type::lookup_complex_type(const char* name)
3173 Named_complex_types::const_iterator p =
3174 Complex_type::named_complex_types.find(name);
3175 go_assert(p != Complex_type::named_complex_types.end());
3176 return p->second;
3179 // Create a new abstract complex type.
3181 Complex_type*
3182 Complex_type::create_abstract_complex_type()
3184 static Complex_type* abstract_type;
3185 if (abstract_type == NULL)
3186 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
3187 return abstract_type;
3190 // Whether this type is identical with T.
3192 bool
3193 Complex_type::is_identical(const Complex_type *t) const
3195 if (this->bits_ != t->bits_)
3196 return false;
3197 return this->is_abstract_ == t->is_abstract_;
3200 // Hash code.
3202 unsigned int
3203 Complex_type::do_hash_for_method(Gogo*) const
3205 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
3208 // Convert to the backend representation.
3210 Btype*
3211 Complex_type::do_get_backend(Gogo* gogo)
3213 return gogo->backend()->complex_type(this->bits_);
3216 // The type descriptor for a complex type. Complex types are always
3217 // named.
3219 Expression*
3220 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3222 go_assert(name != NULL || saw_errors());
3223 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
3226 // We should not be asked for the reflection string of a basic type.
3228 void
3229 Complex_type::do_reflection(Gogo*, std::string*) const
3231 go_assert(saw_errors());
3234 // Mangled name.
3236 void
3237 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
3239 char buf[100];
3240 snprintf(buf, sizeof buf, "c%s%de",
3241 this->is_abstract_ ? "a" : "",
3242 this->bits_);
3243 ret->append(buf);
3246 // Make a complex type.
3248 Named_type*
3249 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
3251 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
3254 // Make an abstract complex type.
3256 Complex_type*
3257 Type::make_abstract_complex_type()
3259 return Complex_type::create_abstract_complex_type();
3262 // Look up a complex type.
3264 Named_type*
3265 Type::lookup_complex_type(const char* name)
3267 return Complex_type::lookup_complex_type(name);
3270 // Class String_type.
3272 // Convert String_type to the backend representation. A string is a
3273 // struct with two fields: a pointer to the characters and a length.
3275 Btype*
3276 String_type::do_get_backend(Gogo* gogo)
3278 static Btype* backend_string_type;
3279 if (backend_string_type == NULL)
3281 std::vector<Backend::Btyped_identifier> fields(2);
3283 Type* b = gogo->lookup_global("byte")->type_value();
3284 Type* pb = Type::make_pointer_type(b);
3286 // We aren't going to get back to this field to finish the
3287 // backend representation, so force it to be finished now.
3288 if (!gogo->named_types_are_converted())
3290 Btype* bt = pb->get_backend_placeholder(gogo);
3291 pb->finish_backend(gogo, bt);
3294 fields[0].name = "__data";
3295 fields[0].btype = pb->get_backend(gogo);
3296 fields[0].location = Linemap::predeclared_location();
3298 Type* int_type = Type::lookup_integer_type("int");
3299 fields[1].name = "__length";
3300 fields[1].btype = int_type->get_backend(gogo);
3301 fields[1].location = fields[0].location;
3303 backend_string_type = gogo->backend()->struct_type(fields);
3305 return backend_string_type;
3308 // The type descriptor for the string type.
3310 Expression*
3311 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3313 if (name != NULL)
3314 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
3315 else
3317 Named_object* no = gogo->lookup_global("string");
3318 go_assert(no != NULL);
3319 return Type::type_descriptor(gogo, no->type_value());
3323 // We should not be asked for the reflection string of a basic type.
3325 void
3326 String_type::do_reflection(Gogo*, std::string* ret) const
3328 ret->append("string");
3331 // Generate GC symbol for strings.
3333 void
3334 String_type::do_gc_symbol(Gogo*, Expression_list** vals,
3335 Expression** offset, int)
3337 Location bloc = Linemap::predeclared_location();
3338 Type* uintptr_type = Type::lookup_integer_type("uintptr");
3339 (*vals)->push_back(Expression::make_integer_ul(GC_STRING, uintptr_type,
3340 bloc));
3341 (*vals)->push_back(*offset);
3342 this->advance_gc_offset(offset);
3345 // Mangled name of a string type.
3347 void
3348 String_type::do_mangled_name(Gogo*, std::string* ret) const
3350 ret->push_back('z');
3353 // Make a string type.
3355 Type*
3356 Type::make_string_type()
3358 static String_type string_type;
3359 return &string_type;
3362 // The named type "string".
3364 static Named_type* named_string_type;
3366 // Get the named type "string".
3368 Named_type*
3369 Type::lookup_string_type()
3371 return named_string_type;
3374 // Make the named type string.
3376 Named_type*
3377 Type::make_named_string_type()
3379 Type* string_type = Type::make_string_type();
3380 Named_object* named_object =
3381 Named_object::make_type("string", NULL, string_type,
3382 Linemap::predeclared_location());
3383 Named_type* named_type = named_object->type_value();
3384 named_string_type = named_type;
3385 return named_type;
3388 // The sink type. This is the type of the blank identifier _. Any
3389 // type may be assigned to it.
3391 class Sink_type : public Type
3393 public:
3394 Sink_type()
3395 : Type(TYPE_SINK)
3398 protected:
3399 bool
3400 do_compare_is_identity(Gogo*)
3401 { return false; }
3403 Btype*
3404 do_get_backend(Gogo*)
3405 { go_unreachable(); }
3407 Expression*
3408 do_type_descriptor(Gogo*, Named_type*)
3409 { go_unreachable(); }
3411 void
3412 do_reflection(Gogo*, std::string*) const
3413 { go_unreachable(); }
3415 void
3416 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
3417 { go_unreachable(); }
3419 void
3420 do_mangled_name(Gogo*, std::string*) const
3421 { go_unreachable(); }
3424 // Make the sink type.
3426 Type*
3427 Type::make_sink_type()
3429 static Sink_type sink_type;
3430 return &sink_type;
3433 // Class Function_type.
3435 // Traversal.
3438 Function_type::do_traverse(Traverse* traverse)
3440 if (this->receiver_ != NULL
3441 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
3442 return TRAVERSE_EXIT;
3443 if (this->parameters_ != NULL
3444 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
3445 return TRAVERSE_EXIT;
3446 if (this->results_ != NULL
3447 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
3448 return TRAVERSE_EXIT;
3449 return TRAVERSE_CONTINUE;
3452 // Returns whether T is a valid redeclaration of this type. If this
3453 // returns false, and REASON is not NULL, *REASON may be set to a
3454 // brief explanation of why it returned false.
3456 bool
3457 Function_type::is_valid_redeclaration(const Function_type* t,
3458 std::string* reason) const
3460 if (!this->is_identical(t, false, true, reason))
3461 return false;
3463 // A redeclaration of a function is required to use the same names
3464 // for the receiver and parameters.
3465 if (this->receiver() != NULL
3466 && this->receiver()->name() != t->receiver()->name())
3468 if (reason != NULL)
3469 *reason = "receiver name changed";
3470 return false;
3473 const Typed_identifier_list* parms1 = this->parameters();
3474 const Typed_identifier_list* parms2 = t->parameters();
3475 if (parms1 != NULL)
3477 Typed_identifier_list::const_iterator p1 = parms1->begin();
3478 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3479 p2 != parms2->end();
3480 ++p2, ++p1)
3482 if (p1->name() != p2->name())
3484 if (reason != NULL)
3485 *reason = "parameter name changed";
3486 return false;
3489 // This is called at parse time, so we may have unknown
3490 // types.
3491 Type* t1 = p1->type()->forwarded();
3492 Type* t2 = p2->type()->forwarded();
3493 if (t1 != t2
3494 && t1->forward_declaration_type() != NULL
3495 && (t2->forward_declaration_type() == NULL
3496 || (t1->forward_declaration_type()->named_object()
3497 != t2->forward_declaration_type()->named_object())))
3498 return false;
3502 const Typed_identifier_list* results1 = this->results();
3503 const Typed_identifier_list* results2 = t->results();
3504 if (results1 != NULL)
3506 Typed_identifier_list::const_iterator res1 = results1->begin();
3507 for (Typed_identifier_list::const_iterator res2 = results2->begin();
3508 res2 != results2->end();
3509 ++res2, ++res1)
3511 if (res1->name() != res2->name())
3513 if (reason != NULL)
3514 *reason = "result name changed";
3515 return false;
3518 // This is called at parse time, so we may have unknown
3519 // types.
3520 Type* t1 = res1->type()->forwarded();
3521 Type* t2 = res2->type()->forwarded();
3522 if (t1 != t2
3523 && t1->forward_declaration_type() != NULL
3524 && (t2->forward_declaration_type() == NULL
3525 || (t1->forward_declaration_type()->named_object()
3526 != t2->forward_declaration_type()->named_object())))
3527 return false;
3531 return true;
3534 // Check whether T is the same as this type.
3536 bool
3537 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
3538 bool errors_are_identical,
3539 std::string* reason) const
3541 if (!ignore_receiver)
3543 const Typed_identifier* r1 = this->receiver();
3544 const Typed_identifier* r2 = t->receiver();
3545 if ((r1 != NULL) != (r2 != NULL))
3547 if (reason != NULL)
3548 *reason = _("different receiver types");
3549 return false;
3551 if (r1 != NULL)
3553 if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
3554 reason))
3556 if (reason != NULL && !reason->empty())
3557 *reason = "receiver: " + *reason;
3558 return false;
3563 const Typed_identifier_list* parms1 = this->parameters();
3564 const Typed_identifier_list* parms2 = t->parameters();
3565 if ((parms1 != NULL) != (parms2 != NULL))
3567 if (reason != NULL)
3568 *reason = _("different number of parameters");
3569 return false;
3571 if (parms1 != NULL)
3573 Typed_identifier_list::const_iterator p1 = parms1->begin();
3574 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3575 p2 != parms2->end();
3576 ++p2, ++p1)
3578 if (p1 == parms1->end())
3580 if (reason != NULL)
3581 *reason = _("different number of parameters");
3582 return false;
3585 if (!Type::are_identical(p1->type(), p2->type(),
3586 errors_are_identical, NULL))
3588 if (reason != NULL)
3589 *reason = _("different parameter types");
3590 return false;
3593 if (p1 != parms1->end())
3595 if (reason != NULL)
3596 *reason = _("different number of parameters");
3597 return false;
3601 if (this->is_varargs() != t->is_varargs())
3603 if (reason != NULL)
3604 *reason = _("different varargs");
3605 return false;
3608 const Typed_identifier_list* results1 = this->results();
3609 const Typed_identifier_list* results2 = t->results();
3610 if ((results1 != NULL) != (results2 != NULL))
3612 if (reason != NULL)
3613 *reason = _("different number of results");
3614 return false;
3616 if (results1 != NULL)
3618 Typed_identifier_list::const_iterator res1 = results1->begin();
3619 for (Typed_identifier_list::const_iterator res2 = results2->begin();
3620 res2 != results2->end();
3621 ++res2, ++res1)
3623 if (res1 == results1->end())
3625 if (reason != NULL)
3626 *reason = _("different number of results");
3627 return false;
3630 if (!Type::are_identical(res1->type(), res2->type(),
3631 errors_are_identical, NULL))
3633 if (reason != NULL)
3634 *reason = _("different result types");
3635 return false;
3638 if (res1 != results1->end())
3640 if (reason != NULL)
3641 *reason = _("different number of results");
3642 return false;
3646 return true;
3649 // Hash code.
3651 unsigned int
3652 Function_type::do_hash_for_method(Gogo* gogo) const
3654 unsigned int ret = 0;
3655 // We ignore the receiver type for hash codes, because we need to
3656 // get the same hash code for a method in an interface and a method
3657 // declared for a type. The former will not have a receiver.
3658 if (this->parameters_ != NULL)
3660 int shift = 1;
3661 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3662 p != this->parameters_->end();
3663 ++p, ++shift)
3664 ret += p->type()->hash_for_method(gogo) << shift;
3666 if (this->results_ != NULL)
3668 int shift = 2;
3669 for (Typed_identifier_list::const_iterator p = this->results_->begin();
3670 p != this->results_->end();
3671 ++p, ++shift)
3672 ret += p->type()->hash_for_method(gogo) << shift;
3674 if (this->is_varargs_)
3675 ret += 1;
3676 ret <<= 4;
3677 return ret;
3680 // Hash result parameters.
3682 unsigned int
3683 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
3685 unsigned int hash = 0;
3686 for (Typed_identifier_list::const_iterator p = t->begin();
3687 p != t->end();
3688 ++p)
3690 hash <<= 2;
3691 hash = Type::hash_string(p->name(), hash);
3692 hash += p->type()->hash_for_method(NULL);
3694 return hash;
3697 // Compare result parameters so that can map identical result
3698 // parameters to a single struct type.
3700 bool
3701 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
3702 const Typed_identifier_list* b) const
3704 if (a->size() != b->size())
3705 return false;
3706 Typed_identifier_list::const_iterator pa = a->begin();
3707 for (Typed_identifier_list::const_iterator pb = b->begin();
3708 pb != b->end();
3709 ++pa, ++pb)
3711 if (pa->name() != pb->name()
3712 || !Type::are_identical(pa->type(), pb->type(), true, NULL))
3713 return false;
3715 return true;
3718 // Hash from results to a backend struct type.
3720 Function_type::Results_structs Function_type::results_structs;
3722 // Get the backend representation for a function type.
3724 Btype*
3725 Function_type::get_backend_fntype(Gogo* gogo)
3727 if (this->fnbtype_ == NULL)
3729 Backend::Btyped_identifier breceiver;
3730 if (this->receiver_ != NULL)
3732 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
3734 // We always pass the address of the receiver parameter, in
3735 // order to make interface calls work with unknown types.
3736 Type* rtype = this->receiver_->type();
3737 if (rtype->points_to() == NULL)
3738 rtype = Type::make_pointer_type(rtype);
3739 breceiver.btype = rtype->get_backend(gogo);
3740 breceiver.location = this->receiver_->location();
3743 std::vector<Backend::Btyped_identifier> bparameters;
3744 if (this->parameters_ != NULL)
3746 bparameters.resize(this->parameters_->size());
3747 size_t i = 0;
3748 for (Typed_identifier_list::const_iterator p =
3749 this->parameters_->begin(); p != this->parameters_->end();
3750 ++p, ++i)
3752 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
3753 bparameters[i].btype = p->type()->get_backend(gogo);
3754 bparameters[i].location = p->location();
3756 go_assert(i == bparameters.size());
3759 std::vector<Backend::Btyped_identifier> bresults;
3760 Btype* bresult_struct = NULL;
3761 if (this->results_ != NULL)
3763 bresults.resize(this->results_->size());
3764 size_t i = 0;
3765 for (Typed_identifier_list::const_iterator p =
3766 this->results_->begin();
3767 p != this->results_->end();
3768 ++p, ++i)
3770 bresults[i].name = Gogo::unpack_hidden_name(p->name());
3771 bresults[i].btype = p->type()->get_backend(gogo);
3772 bresults[i].location = p->location();
3774 go_assert(i == bresults.size());
3776 if (this->results_->size() > 1)
3778 // Use the same results struct for all functions that
3779 // return the same set of results. This is useful to
3780 // unify calls to interface methods with other calls.
3781 std::pair<Typed_identifier_list*, Btype*> val;
3782 val.first = this->results_;
3783 val.second = NULL;
3784 std::pair<Results_structs::iterator, bool> ins =
3785 Function_type::results_structs.insert(val);
3786 if (ins.second)
3788 // Build a new struct type.
3789 Struct_field_list* sfl = new Struct_field_list;
3790 for (Typed_identifier_list::const_iterator p =
3791 this->results_->begin();
3792 p != this->results_->end();
3793 ++p)
3795 Typed_identifier tid = *p;
3796 if (tid.name().empty())
3797 tid = Typed_identifier("UNNAMED", tid.type(),
3798 tid.location());
3799 sfl->push_back(Struct_field(tid));
3801 Struct_type* st = Type::make_struct_type(sfl,
3802 this->location());
3803 ins.first->second = st->get_backend(gogo);
3805 bresult_struct = ins.first->second;
3809 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
3810 bresults, bresult_struct,
3811 this->location());
3815 return this->fnbtype_;
3818 // Get the backend representation for a Go function type.
3820 Btype*
3821 Function_type::do_get_backend(Gogo* gogo)
3823 // When we do anything with a function value other than call it, it
3824 // is represented as a pointer to a struct whose first field is the
3825 // actual function. So that is what we return as the type of a Go
3826 // function.
3828 Location loc = this->location();
3829 Btype* struct_type =
3830 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
3831 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
3833 std::vector<Backend::Btyped_identifier> fields(1);
3834 fields[0].name = "code";
3835 fields[0].btype = this->get_backend_fntype(gogo);
3836 fields[0].location = loc;
3837 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
3838 return gogo->backend()->error_type();
3839 return ptr_struct_type;
3842 // The type of a function type descriptor.
3844 Type*
3845 Function_type::make_function_type_descriptor_type()
3847 static Type* ret;
3848 if (ret == NULL)
3850 Type* tdt = Type::make_type_descriptor_type();
3851 Type* ptdt = Type::make_type_descriptor_ptr_type();
3853 Type* bool_type = Type::lookup_bool_type();
3855 Type* slice_type = Type::make_array_type(ptdt, NULL);
3857 Struct_type* s = Type::make_builtin_struct_type(4,
3858 "", tdt,
3859 "dotdotdot", bool_type,
3860 "in", slice_type,
3861 "out", slice_type);
3863 ret = Type::make_builtin_named_type("FuncType", s);
3866 return ret;
3869 // The type descriptor for a function type.
3871 Expression*
3872 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3874 Location bloc = Linemap::predeclared_location();
3876 Type* ftdt = Function_type::make_function_type_descriptor_type();
3878 const Struct_field_list* fields = ftdt->struct_type()->fields();
3880 Expression_list* vals = new Expression_list();
3881 vals->reserve(4);
3883 Struct_field_list::const_iterator p = fields->begin();
3884 go_assert(p->is_field_name("commonType"));
3885 vals->push_back(this->type_descriptor_constructor(gogo,
3886 RUNTIME_TYPE_KIND_FUNC,
3887 name, NULL, true));
3889 ++p;
3890 go_assert(p->is_field_name("dotdotdot"));
3891 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
3893 ++p;
3894 go_assert(p->is_field_name("in"));
3895 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
3896 this->parameters()));
3898 ++p;
3899 go_assert(p->is_field_name("out"));
3900 vals->push_back(this->type_descriptor_params(p->type(), NULL,
3901 this->results()));
3903 ++p;
3904 go_assert(p == fields->end());
3906 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
3909 // Return a composite literal for the parameters or results of a type
3910 // descriptor.
3912 Expression*
3913 Function_type::type_descriptor_params(Type* params_type,
3914 const Typed_identifier* receiver,
3915 const Typed_identifier_list* params)
3917 Location bloc = Linemap::predeclared_location();
3919 if (receiver == NULL && params == NULL)
3920 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
3922 Expression_list* vals = new Expression_list();
3923 vals->reserve((params == NULL ? 0 : params->size())
3924 + (receiver != NULL ? 1 : 0));
3926 if (receiver != NULL)
3927 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
3929 if (params != NULL)
3931 for (Typed_identifier_list::const_iterator p = params->begin();
3932 p != params->end();
3933 ++p)
3934 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
3937 return Expression::make_slice_composite_literal(params_type, vals, bloc);
3940 // The reflection string.
3942 void
3943 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
3945 // FIXME: Turn this off until we straighten out the type of the
3946 // struct field used in a go statement which calls a method.
3947 // go_assert(this->receiver_ == NULL);
3949 ret->append("func");
3951 if (this->receiver_ != NULL)
3953 ret->push_back('(');
3954 this->append_reflection(this->receiver_->type(), gogo, ret);
3955 ret->push_back(')');
3958 ret->push_back('(');
3959 const Typed_identifier_list* params = this->parameters();
3960 if (params != NULL)
3962 bool is_varargs = this->is_varargs_;
3963 for (Typed_identifier_list::const_iterator p = params->begin();
3964 p != params->end();
3965 ++p)
3967 if (p != params->begin())
3968 ret->append(", ");
3969 if (!is_varargs || p + 1 != params->end())
3970 this->append_reflection(p->type(), gogo, ret);
3971 else
3973 ret->append("...");
3974 this->append_reflection(p->type()->array_type()->element_type(),
3975 gogo, ret);
3979 ret->push_back(')');
3981 const Typed_identifier_list* results = this->results();
3982 if (results != NULL && !results->empty())
3984 if (results->size() == 1)
3985 ret->push_back(' ');
3986 else
3987 ret->append(" (");
3988 for (Typed_identifier_list::const_iterator p = results->begin();
3989 p != results->end();
3990 ++p)
3992 if (p != results->begin())
3993 ret->append(", ");
3994 this->append_reflection(p->type(), gogo, ret);
3996 if (results->size() > 1)
3997 ret->push_back(')');
4001 // Generate GC symbol for a function type.
4003 void
4004 Function_type::do_gc_symbol(Gogo*, Expression_list** vals,
4005 Expression** offset, int)
4007 Location bloc = Linemap::predeclared_location();
4008 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4010 // We use GC_APTR here because we do not currently have a way to describe the
4011 // the type of the possible function closure. FIXME.
4012 (*vals)->push_back(Expression::make_integer_ul(GC_APTR, uintptr_type, bloc));
4013 (*vals)->push_back(*offset);
4014 this->advance_gc_offset(offset);
4017 // Mangled name.
4019 void
4020 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4022 ret->push_back('F');
4024 if (this->receiver_ != NULL)
4026 ret->push_back('m');
4027 this->append_mangled_name(this->receiver_->type(), gogo, ret);
4030 const Typed_identifier_list* params = this->parameters();
4031 if (params != NULL)
4033 ret->push_back('p');
4034 for (Typed_identifier_list::const_iterator p = params->begin();
4035 p != params->end();
4036 ++p)
4037 this->append_mangled_name(p->type(), gogo, ret);
4038 if (this->is_varargs_)
4039 ret->push_back('V');
4040 ret->push_back('e');
4043 const Typed_identifier_list* results = this->results();
4044 if (results != NULL)
4046 ret->push_back('r');
4047 for (Typed_identifier_list::const_iterator p = results->begin();
4048 p != results->end();
4049 ++p)
4050 this->append_mangled_name(p->type(), gogo, ret);
4051 ret->push_back('e');
4054 ret->push_back('e');
4057 // Export a function type.
4059 void
4060 Function_type::do_export(Export* exp) const
4062 // We don't write out the receiver. The only function types which
4063 // should have a receiver are the ones associated with explicitly
4064 // defined methods. For those the receiver type is written out by
4065 // Function::export_func.
4067 exp->write_c_string("(");
4068 bool first = true;
4069 if (this->parameters_ != NULL)
4071 bool is_varargs = this->is_varargs_;
4072 for (Typed_identifier_list::const_iterator p =
4073 this->parameters_->begin();
4074 p != this->parameters_->end();
4075 ++p)
4077 if (first)
4078 first = false;
4079 else
4080 exp->write_c_string(", ");
4081 exp->write_name(p->name());
4082 exp->write_c_string(" ");
4083 if (!is_varargs || p + 1 != this->parameters_->end())
4084 exp->write_type(p->type());
4085 else
4087 exp->write_c_string("...");
4088 exp->write_type(p->type()->array_type()->element_type());
4092 exp->write_c_string(")");
4094 const Typed_identifier_list* results = this->results_;
4095 if (results != NULL)
4097 exp->write_c_string(" ");
4098 if (results->size() == 1 && results->begin()->name().empty())
4099 exp->write_type(results->begin()->type());
4100 else
4102 first = true;
4103 exp->write_c_string("(");
4104 for (Typed_identifier_list::const_iterator p = results->begin();
4105 p != results->end();
4106 ++p)
4108 if (first)
4109 first = false;
4110 else
4111 exp->write_c_string(", ");
4112 exp->write_name(p->name());
4113 exp->write_c_string(" ");
4114 exp->write_type(p->type());
4116 exp->write_c_string(")");
4121 // Import a function type.
4123 Function_type*
4124 Function_type::do_import(Import* imp)
4126 imp->require_c_string("(");
4127 Typed_identifier_list* parameters;
4128 bool is_varargs = false;
4129 if (imp->peek_char() == ')')
4130 parameters = NULL;
4131 else
4133 parameters = new Typed_identifier_list();
4134 while (true)
4136 std::string name = imp->read_name();
4137 imp->require_c_string(" ");
4139 if (imp->match_c_string("..."))
4141 imp->advance(3);
4142 is_varargs = true;
4145 Type* ptype = imp->read_type();
4146 if (is_varargs)
4147 ptype = Type::make_array_type(ptype, NULL);
4148 parameters->push_back(Typed_identifier(name, ptype,
4149 imp->location()));
4150 if (imp->peek_char() != ',')
4151 break;
4152 go_assert(!is_varargs);
4153 imp->require_c_string(", ");
4156 imp->require_c_string(")");
4158 Typed_identifier_list* results;
4159 if (imp->peek_char() != ' ')
4160 results = NULL;
4161 else
4163 imp->advance(1);
4164 results = new Typed_identifier_list;
4165 if (imp->peek_char() != '(')
4167 Type* rtype = imp->read_type();
4168 results->push_back(Typed_identifier("", rtype, imp->location()));
4170 else
4172 imp->advance(1);
4173 while (true)
4175 std::string name = imp->read_name();
4176 imp->require_c_string(" ");
4177 Type* rtype = imp->read_type();
4178 results->push_back(Typed_identifier(name, rtype,
4179 imp->location()));
4180 if (imp->peek_char() != ',')
4181 break;
4182 imp->require_c_string(", ");
4184 imp->require_c_string(")");
4188 Function_type* ret = Type::make_function_type(NULL, parameters, results,
4189 imp->location());
4190 if (is_varargs)
4191 ret->set_is_varargs();
4192 return ret;
4195 // Make a copy of a function type without a receiver.
4197 Function_type*
4198 Function_type::copy_without_receiver() const
4200 go_assert(this->is_method());
4201 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
4202 this->results_,
4203 this->location_);
4204 if (this->is_varargs())
4205 ret->set_is_varargs();
4206 if (this->is_builtin())
4207 ret->set_is_builtin();
4208 return ret;
4211 // Make a copy of a function type with a receiver.
4213 Function_type*
4214 Function_type::copy_with_receiver(Type* receiver_type) const
4216 go_assert(!this->is_method());
4217 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
4218 this->location_);
4219 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
4220 this->results_,
4221 this->location_);
4222 if (this->is_varargs_)
4223 ret->set_is_varargs();
4224 return ret;
4227 // Make a copy of a function type with the receiver as the first
4228 // parameter.
4230 Function_type*
4231 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
4233 go_assert(this->is_method());
4234 Typed_identifier_list* new_params = new Typed_identifier_list();
4235 Type* rtype = this->receiver_->type();
4236 if (want_pointer_receiver)
4237 rtype = Type::make_pointer_type(rtype);
4238 Typed_identifier receiver(this->receiver_->name(), rtype,
4239 this->receiver_->location());
4240 new_params->push_back(receiver);
4241 const Typed_identifier_list* orig_params = this->parameters_;
4242 if (orig_params != NULL && !orig_params->empty())
4244 for (Typed_identifier_list::const_iterator p = orig_params->begin();
4245 p != orig_params->end();
4246 ++p)
4247 new_params->push_back(*p);
4249 return Type::make_function_type(NULL, new_params, this->results_,
4250 this->location_);
4253 // Make a copy of a function type ignoring any receiver and adding a
4254 // closure parameter.
4256 Function_type*
4257 Function_type::copy_with_names() const
4259 Typed_identifier_list* new_params = new Typed_identifier_list();
4260 const Typed_identifier_list* orig_params = this->parameters_;
4261 if (orig_params != NULL && !orig_params->empty())
4263 static int count;
4264 char buf[50];
4265 for (Typed_identifier_list::const_iterator p = orig_params->begin();
4266 p != orig_params->end();
4267 ++p)
4269 snprintf(buf, sizeof buf, "pt.%u", count);
4270 ++count;
4271 new_params->push_back(Typed_identifier(buf, p->type(),
4272 p->location()));
4276 const Typed_identifier_list* orig_results = this->results_;
4277 Typed_identifier_list* new_results;
4278 if (orig_results == NULL || orig_results->empty())
4279 new_results = NULL;
4280 else
4282 new_results = new Typed_identifier_list();
4283 for (Typed_identifier_list::const_iterator p = orig_results->begin();
4284 p != orig_results->end();
4285 ++p)
4286 new_results->push_back(Typed_identifier("", p->type(),
4287 p->location()));
4290 return Type::make_function_type(NULL, new_params, new_results,
4291 this->location());
4294 // Make a function type.
4296 Function_type*
4297 Type::make_function_type(Typed_identifier* receiver,
4298 Typed_identifier_list* parameters,
4299 Typed_identifier_list* results,
4300 Location location)
4302 return new Function_type(receiver, parameters, results, location);
4305 // Make a backend function type.
4307 Backend_function_type*
4308 Type::make_backend_function_type(Typed_identifier* receiver,
4309 Typed_identifier_list* parameters,
4310 Typed_identifier_list* results,
4311 Location location)
4313 return new Backend_function_type(receiver, parameters, results, location);
4316 // Class Pointer_type.
4318 // Traversal.
4321 Pointer_type::do_traverse(Traverse* traverse)
4323 return Type::traverse(this->to_type_, traverse);
4326 // Hash code.
4328 unsigned int
4329 Pointer_type::do_hash_for_method(Gogo* gogo) const
4331 return this->to_type_->hash_for_method(gogo) << 4;
4334 // Get the backend representation for a pointer type.
4336 Btype*
4337 Pointer_type::do_get_backend(Gogo* gogo)
4339 Btype* to_btype = this->to_type_->get_backend(gogo);
4340 return gogo->backend()->pointer_type(to_btype);
4343 // The type of a pointer type descriptor.
4345 Type*
4346 Pointer_type::make_pointer_type_descriptor_type()
4348 static Type* ret;
4349 if (ret == NULL)
4351 Type* tdt = Type::make_type_descriptor_type();
4352 Type* ptdt = Type::make_type_descriptor_ptr_type();
4354 Struct_type* s = Type::make_builtin_struct_type(2,
4355 "", tdt,
4356 "elem", ptdt);
4358 ret = Type::make_builtin_named_type("PtrType", s);
4361 return ret;
4364 // The type descriptor for a pointer type.
4366 Expression*
4367 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4369 if (this->is_unsafe_pointer_type())
4371 go_assert(name != NULL);
4372 return this->plain_type_descriptor(gogo,
4373 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
4374 name);
4376 else
4378 Location bloc = Linemap::predeclared_location();
4380 const Methods* methods;
4381 Type* deref = this->points_to();
4382 if (deref->named_type() != NULL)
4383 methods = deref->named_type()->methods();
4384 else if (deref->struct_type() != NULL)
4385 methods = deref->struct_type()->methods();
4386 else
4387 methods = NULL;
4389 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
4391 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
4393 Expression_list* vals = new Expression_list();
4394 vals->reserve(2);
4396 Struct_field_list::const_iterator p = fields->begin();
4397 go_assert(p->is_field_name("commonType"));
4398 vals->push_back(this->type_descriptor_constructor(gogo,
4399 RUNTIME_TYPE_KIND_PTR,
4400 name, methods, false));
4402 ++p;
4403 go_assert(p->is_field_name("elem"));
4404 vals->push_back(Expression::make_type_descriptor(deref, bloc));
4406 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
4410 // Reflection string.
4412 void
4413 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
4415 ret->push_back('*');
4416 this->append_reflection(this->to_type_, gogo, ret);
4419 // Generate GC symbol for pointer types.
4421 void
4422 Pointer_type::do_gc_symbol(Gogo*, Expression_list** vals,
4423 Expression** offset, int)
4425 Location loc = Linemap::predeclared_location();
4426 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4428 unsigned long opval = this->to_type_->has_pointer() ? GC_PTR : GC_APTR;
4429 (*vals)->push_back(Expression::make_integer_ul(opval, uintptr_type, loc));
4430 (*vals)->push_back(*offset);
4432 if (this->to_type_->has_pointer())
4433 (*vals)->push_back(Expression::make_gc_symbol(this->to_type_));
4434 this->advance_gc_offset(offset);
4437 // Mangled name.
4439 void
4440 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4442 ret->push_back('p');
4443 this->append_mangled_name(this->to_type_, gogo, ret);
4446 // Export.
4448 void
4449 Pointer_type::do_export(Export* exp) const
4451 exp->write_c_string("*");
4452 if (this->is_unsafe_pointer_type())
4453 exp->write_c_string("any");
4454 else
4455 exp->write_type(this->to_type_);
4458 // Import.
4460 Pointer_type*
4461 Pointer_type::do_import(Import* imp)
4463 imp->require_c_string("*");
4464 if (imp->match_c_string("any"))
4466 imp->advance(3);
4467 return Type::make_pointer_type(Type::make_void_type());
4469 Type* to = imp->read_type();
4470 return Type::make_pointer_type(to);
4473 // Make a pointer type.
4475 Pointer_type*
4476 Type::make_pointer_type(Type* to_type)
4478 typedef Unordered_map(Type*, Pointer_type*) Hashtable;
4479 static Hashtable pointer_types;
4480 Hashtable::const_iterator p = pointer_types.find(to_type);
4481 if (p != pointer_types.end())
4482 return p->second;
4483 Pointer_type* ret = new Pointer_type(to_type);
4484 pointer_types[to_type] = ret;
4485 return ret;
4488 // The nil type. We use a special type for nil because it is not the
4489 // same as any other type. In C term nil has type void*, but there is
4490 // no such type in Go.
4492 class Nil_type : public Type
4494 public:
4495 Nil_type()
4496 : Type(TYPE_NIL)
4499 protected:
4500 bool
4501 do_compare_is_identity(Gogo*)
4502 { return false; }
4504 Btype*
4505 do_get_backend(Gogo* gogo)
4506 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
4508 Expression*
4509 do_type_descriptor(Gogo*, Named_type*)
4510 { go_unreachable(); }
4512 void
4513 do_reflection(Gogo*, std::string*) const
4514 { go_unreachable(); }
4516 void
4517 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
4518 { go_unreachable(); }
4520 void
4521 do_mangled_name(Gogo*, std::string* ret) const
4522 { ret->push_back('n'); }
4525 // Make the nil type.
4527 Type*
4528 Type::make_nil_type()
4530 static Nil_type singleton_nil_type;
4531 return &singleton_nil_type;
4534 // The type of a function call which returns multiple values. This is
4535 // really a struct, but we don't want to confuse a function call which
4536 // returns a struct with a function call which returns multiple
4537 // values.
4539 class Call_multiple_result_type : public Type
4541 public:
4542 Call_multiple_result_type(Call_expression* call)
4543 : Type(TYPE_CALL_MULTIPLE_RESULT),
4544 call_(call)
4547 protected:
4548 bool
4549 do_has_pointer() const
4550 { return false; }
4552 bool
4553 do_compare_is_identity(Gogo*)
4554 { return false; }
4556 Btype*
4557 do_get_backend(Gogo* gogo)
4559 go_assert(saw_errors());
4560 return gogo->backend()->error_type();
4563 Expression*
4564 do_type_descriptor(Gogo*, Named_type*)
4566 go_assert(saw_errors());
4567 return Expression::make_error(Linemap::unknown_location());
4570 void
4571 do_reflection(Gogo*, std::string*) const
4572 { go_assert(saw_errors()); }
4574 void
4575 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
4576 { go_unreachable(); }
4578 void
4579 do_mangled_name(Gogo*, std::string*) const
4580 { go_assert(saw_errors()); }
4582 private:
4583 // The expression being called.
4584 Call_expression* call_;
4587 // Make a call result type.
4589 Type*
4590 Type::make_call_multiple_result_type(Call_expression* call)
4592 return new Call_multiple_result_type(call);
4595 // Class Struct_field.
4597 // Get the name of a field.
4599 const std::string&
4600 Struct_field::field_name() const
4602 const std::string& name(this->typed_identifier_.name());
4603 if (!name.empty())
4604 return name;
4605 else
4607 // This is called during parsing, before anything is lowered, so
4608 // we have to be pretty careful to avoid dereferencing an
4609 // unknown type name.
4610 Type* t = this->typed_identifier_.type();
4611 Type* dt = t;
4612 if (t->classification() == Type::TYPE_POINTER)
4614 // Very ugly.
4615 Pointer_type* ptype = static_cast<Pointer_type*>(t);
4616 dt = ptype->points_to();
4618 if (dt->forward_declaration_type() != NULL)
4619 return dt->forward_declaration_type()->name();
4620 else if (dt->named_type() != NULL)
4621 return dt->named_type()->name();
4622 else if (t->is_error_type() || dt->is_error_type())
4624 static const std::string error_string = "*error*";
4625 return error_string;
4627 else
4629 // Avoid crashing in the erroneous case where T is named but
4630 // DT is not.
4631 go_assert(t != dt);
4632 if (t->forward_declaration_type() != NULL)
4633 return t->forward_declaration_type()->name();
4634 else if (t->named_type() != NULL)
4635 return t->named_type()->name();
4636 else
4637 go_unreachable();
4642 // Return whether this field is named NAME.
4644 bool
4645 Struct_field::is_field_name(const std::string& name) const
4647 const std::string& me(this->typed_identifier_.name());
4648 if (!me.empty())
4649 return me == name;
4650 else
4652 Type* t = this->typed_identifier_.type();
4653 if (t->points_to() != NULL)
4654 t = t->points_to();
4655 Named_type* nt = t->named_type();
4656 if (nt != NULL && nt->name() == name)
4657 return true;
4659 // This is a horrible hack caused by the fact that we don't pack
4660 // the names of builtin types. FIXME.
4661 if (!this->is_imported_
4662 && nt != NULL
4663 && nt->is_builtin()
4664 && nt->name() == Gogo::unpack_hidden_name(name))
4665 return true;
4667 return false;
4671 // Return whether this field is an unexported field named NAME.
4673 bool
4674 Struct_field::is_unexported_field_name(Gogo* gogo,
4675 const std::string& name) const
4677 const std::string& field_name(this->field_name());
4678 if (Gogo::is_hidden_name(field_name)
4679 && name == Gogo::unpack_hidden_name(field_name)
4680 && gogo->pack_hidden_name(name, false) != field_name)
4681 return true;
4683 // Check for the name of a builtin type. This is like the test in
4684 // is_field_name, only there we return false if this->is_imported_,
4685 // and here we return true.
4686 if (this->is_imported_ && this->is_anonymous())
4688 Type* t = this->typed_identifier_.type();
4689 if (t->points_to() != NULL)
4690 t = t->points_to();
4691 Named_type* nt = t->named_type();
4692 if (nt != NULL
4693 && nt->is_builtin()
4694 && nt->name() == Gogo::unpack_hidden_name(name))
4695 return true;
4698 return false;
4701 // Return whether this field is an embedded built-in type.
4703 bool
4704 Struct_field::is_embedded_builtin(Gogo* gogo) const
4706 const std::string& name(this->field_name());
4707 // We know that a field is an embedded type if it is anonymous.
4708 // We can decide if it is a built-in type by checking to see if it is
4709 // registered globally under the field's name.
4710 // This allows us to distinguish between embedded built-in types and
4711 // embedded types that are aliases to built-in types.
4712 return (this->is_anonymous()
4713 && !Gogo::is_hidden_name(name)
4714 && gogo->lookup_global(name.c_str()) != NULL);
4717 // Class Struct_type.
4719 // A hash table used to find identical unnamed structs so that they
4720 // share method tables.
4722 Struct_type::Identical_structs Struct_type::identical_structs;
4724 // A hash table used to merge method sets for identical unnamed
4725 // structs.
4727 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
4729 // Traversal.
4732 Struct_type::do_traverse(Traverse* traverse)
4734 Struct_field_list* fields = this->fields_;
4735 if (fields != NULL)
4737 for (Struct_field_list::iterator p = fields->begin();
4738 p != fields->end();
4739 ++p)
4741 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
4742 return TRAVERSE_EXIT;
4745 return TRAVERSE_CONTINUE;
4748 // Verify that the struct type is complete and valid.
4750 bool
4751 Struct_type::do_verify()
4753 Struct_field_list* fields = this->fields_;
4754 if (fields == NULL)
4755 return true;
4756 for (Struct_field_list::iterator p = fields->begin();
4757 p != fields->end();
4758 ++p)
4760 Type* t = p->type();
4761 if (p->is_anonymous())
4763 if (t->named_type() != NULL && t->points_to() != NULL)
4765 go_error_at(p->location(), "embedded type may not be a pointer");
4766 p->set_type(Type::make_error_type());
4768 else if (t->points_to() != NULL
4769 && t->points_to()->interface_type() != NULL)
4771 go_error_at(p->location(),
4772 "embedded type may not be pointer to interface");
4773 p->set_type(Type::make_error_type());
4777 return true;
4780 // Whether this contains a pointer.
4782 bool
4783 Struct_type::do_has_pointer() const
4785 const Struct_field_list* fields = this->fields();
4786 if (fields == NULL)
4787 return false;
4788 for (Struct_field_list::const_iterator p = fields->begin();
4789 p != fields->end();
4790 ++p)
4792 if (p->type()->has_pointer())
4793 return true;
4795 return false;
4798 // Whether this type is identical to T.
4800 bool
4801 Struct_type::is_identical(const Struct_type* t,
4802 bool errors_are_identical) const
4804 if (this->is_struct_incomparable_ != t->is_struct_incomparable_)
4805 return false;
4806 const Struct_field_list* fields1 = this->fields();
4807 const Struct_field_list* fields2 = t->fields();
4808 if (fields1 == NULL || fields2 == NULL)
4809 return fields1 == fields2;
4810 Struct_field_list::const_iterator pf2 = fields2->begin();
4811 for (Struct_field_list::const_iterator pf1 = fields1->begin();
4812 pf1 != fields1->end();
4813 ++pf1, ++pf2)
4815 if (pf2 == fields2->end())
4816 return false;
4817 if (pf1->field_name() != pf2->field_name())
4818 return false;
4819 if (pf1->is_anonymous() != pf2->is_anonymous()
4820 || !Type::are_identical(pf1->type(), pf2->type(),
4821 errors_are_identical, NULL))
4822 return false;
4823 if (!pf1->has_tag())
4825 if (pf2->has_tag())
4826 return false;
4828 else
4830 if (!pf2->has_tag())
4831 return false;
4832 if (pf1->tag() != pf2->tag())
4833 return false;
4836 if (pf2 != fields2->end())
4837 return false;
4838 return true;
4841 // Whether comparisons of this struct type are simple identity
4842 // comparisons.
4844 bool
4845 Struct_type::do_compare_is_identity(Gogo* gogo)
4847 const Struct_field_list* fields = this->fields_;
4848 if (fields == NULL)
4849 return true;
4850 int64_t offset = 0;
4851 for (Struct_field_list::const_iterator pf = fields->begin();
4852 pf != fields->end();
4853 ++pf)
4855 if (Gogo::is_sink_name(pf->field_name()))
4856 return false;
4858 if (!pf->type()->compare_is_identity(gogo))
4859 return false;
4861 int64_t field_align;
4862 if (!pf->type()->backend_type_align(gogo, &field_align))
4863 return false;
4864 if ((offset & (field_align - 1)) != 0)
4866 // This struct has padding. We don't guarantee that that
4867 // padding is zero-initialized for a stack variable, so we
4868 // can't use memcmp to compare struct values.
4869 return false;
4872 int64_t field_size;
4873 if (!pf->type()->backend_type_size(gogo, &field_size))
4874 return false;
4875 offset += field_size;
4878 int64_t struct_size;
4879 if (!this->backend_type_size(gogo, &struct_size))
4880 return false;
4881 if (offset != struct_size)
4883 // Trailing padding may not be zero when on the stack.
4884 return false;
4887 return true;
4890 // Return whether this struct type is reflexive--whether a value of
4891 // this type is always equal to itself.
4893 bool
4894 Struct_type::do_is_reflexive()
4896 const Struct_field_list* fields = this->fields_;
4897 if (fields == NULL)
4898 return true;
4899 for (Struct_field_list::const_iterator pf = fields->begin();
4900 pf != fields->end();
4901 ++pf)
4903 if (!pf->type()->is_reflexive())
4904 return false;
4906 return true;
4909 // Return whether this struct type needs a key update when used as a
4910 // map key.
4912 bool
4913 Struct_type::do_needs_key_update()
4915 const Struct_field_list* fields = this->fields_;
4916 if (fields == NULL)
4917 return false;
4918 for (Struct_field_list::const_iterator pf = fields->begin();
4919 pf != fields->end();
4920 ++pf)
4922 if (pf->type()->needs_key_update())
4923 return true;
4925 return false;
4928 // Build identity and hash functions for this struct.
4930 // Hash code.
4932 unsigned int
4933 Struct_type::do_hash_for_method(Gogo* gogo) const
4935 unsigned int ret = 0;
4936 if (this->fields() != NULL)
4938 for (Struct_field_list::const_iterator pf = this->fields()->begin();
4939 pf != this->fields()->end();
4940 ++pf)
4941 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
4943 ret <<= 2;
4944 if (this->is_struct_incomparable_)
4945 ret <<= 1;
4946 return ret;
4949 // Find the local field NAME.
4951 const Struct_field*
4952 Struct_type::find_local_field(const std::string& name,
4953 unsigned int *pindex) const
4955 const Struct_field_list* fields = this->fields_;
4956 if (fields == NULL)
4957 return NULL;
4958 unsigned int i = 0;
4959 for (Struct_field_list::const_iterator pf = fields->begin();
4960 pf != fields->end();
4961 ++pf, ++i)
4963 if (pf->is_field_name(name))
4965 if (pindex != NULL)
4966 *pindex = i;
4967 return &*pf;
4970 return NULL;
4973 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
4975 Field_reference_expression*
4976 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
4977 Location location) const
4979 unsigned int depth;
4980 return this->field_reference_depth(struct_expr, name, location, NULL,
4981 &depth);
4984 // Return an expression for a field, along with the depth at which it
4985 // was found.
4987 Field_reference_expression*
4988 Struct_type::field_reference_depth(Expression* struct_expr,
4989 const std::string& name,
4990 Location location,
4991 Saw_named_type* saw,
4992 unsigned int* depth) const
4994 const Struct_field_list* fields = this->fields_;
4995 if (fields == NULL)
4996 return NULL;
4998 // Look for a field with this name.
4999 unsigned int i = 0;
5000 for (Struct_field_list::const_iterator pf = fields->begin();
5001 pf != fields->end();
5002 ++pf, ++i)
5004 if (pf->is_field_name(name))
5006 *depth = 0;
5007 return Expression::make_field_reference(struct_expr, i, location);
5011 // Look for an anonymous field which contains a field with this
5012 // name.
5013 unsigned int found_depth = 0;
5014 Field_reference_expression* ret = NULL;
5015 i = 0;
5016 for (Struct_field_list::const_iterator pf = fields->begin();
5017 pf != fields->end();
5018 ++pf, ++i)
5020 if (!pf->is_anonymous())
5021 continue;
5023 Struct_type* st = pf->type()->deref()->struct_type();
5024 if (st == NULL)
5025 continue;
5027 Saw_named_type* hold_saw = saw;
5028 Saw_named_type saw_here;
5029 Named_type* nt = pf->type()->named_type();
5030 if (nt == NULL)
5031 nt = pf->type()->deref()->named_type();
5032 if (nt != NULL)
5034 Saw_named_type* q;
5035 for (q = saw; q != NULL; q = q->next)
5037 if (q->nt == nt)
5039 // If this is an error, it will be reported
5040 // elsewhere.
5041 break;
5044 if (q != NULL)
5045 continue;
5046 saw_here.next = saw;
5047 saw_here.nt = nt;
5048 saw = &saw_here;
5051 // Look for a reference using a NULL struct expression. If we
5052 // find one, fill in the struct expression with a reference to
5053 // this field.
5054 unsigned int subdepth;
5055 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
5056 location,
5057 saw,
5058 &subdepth);
5060 saw = hold_saw;
5062 if (sub == NULL)
5063 continue;
5065 if (ret == NULL || subdepth < found_depth)
5067 if (ret != NULL)
5068 delete ret;
5069 ret = sub;
5070 found_depth = subdepth;
5071 Expression* here = Expression::make_field_reference(struct_expr, i,
5072 location);
5073 if (pf->type()->points_to() != NULL)
5074 here = Expression::make_unary(OPERATOR_MULT, here, location);
5075 while (sub->expr() != NULL)
5077 sub = sub->expr()->deref()->field_reference_expression();
5078 go_assert(sub != NULL);
5080 sub->set_struct_expression(here);
5081 sub->set_implicit(true);
5083 else if (subdepth > found_depth)
5084 delete sub;
5085 else
5087 // We do not handle ambiguity here--it should be handled by
5088 // Type::bind_field_or_method.
5089 delete sub;
5090 found_depth = 0;
5091 ret = NULL;
5095 if (ret != NULL)
5096 *depth = found_depth + 1;
5098 return ret;
5101 // Return the total number of fields, including embedded fields.
5103 unsigned int
5104 Struct_type::total_field_count() const
5106 if (this->fields_ == NULL)
5107 return 0;
5108 unsigned int ret = 0;
5109 for (Struct_field_list::const_iterator pf = this->fields_->begin();
5110 pf != this->fields_->end();
5111 ++pf)
5113 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
5114 ++ret;
5115 else
5116 ret += pf->type()->struct_type()->total_field_count();
5118 return ret;
5121 // Return whether NAME is an unexported field, for better error reporting.
5123 bool
5124 Struct_type::is_unexported_local_field(Gogo* gogo,
5125 const std::string& name) const
5127 const Struct_field_list* fields = this->fields_;
5128 if (fields != NULL)
5130 for (Struct_field_list::const_iterator pf = fields->begin();
5131 pf != fields->end();
5132 ++pf)
5133 if (pf->is_unexported_field_name(gogo, name))
5134 return true;
5136 return false;
5139 // Finalize the methods of an unnamed struct.
5141 void
5142 Struct_type::finalize_methods(Gogo* gogo)
5144 if (this->all_methods_ != NULL)
5145 return;
5147 // It is possible to have multiple identical structs that have
5148 // methods. We want them to share method tables. Otherwise we will
5149 // emit identical methods more than once, which is bad since they
5150 // will even have the same names.
5151 std::pair<Identical_structs::iterator, bool> ins =
5152 Struct_type::identical_structs.insert(std::make_pair(this, this));
5153 if (!ins.second)
5155 // An identical struct was already entered into the hash table.
5156 // Note that finalize_methods is, fortunately, not recursive.
5157 this->all_methods_ = ins.first->second->all_methods_;
5158 return;
5161 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
5164 // Return the method NAME, or NULL if there isn't one or if it is
5165 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
5166 // ambiguous.
5168 Method*
5169 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
5171 return Type::method_function(this->all_methods_, name, is_ambiguous);
5174 // Return a pointer to the interface method table for this type for
5175 // the interface INTERFACE. IS_POINTER is true if this is for a
5176 // pointer to THIS.
5178 Expression*
5179 Struct_type::interface_method_table(Interface_type* interface,
5180 bool is_pointer)
5182 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
5183 val(this, NULL);
5184 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
5185 Struct_type::struct_method_tables.insert(val);
5187 Struct_method_table_pair* smtp;
5188 if (!ins.second)
5189 smtp = ins.first->second;
5190 else
5192 smtp = new Struct_method_table_pair();
5193 smtp->first = NULL;
5194 smtp->second = NULL;
5195 ins.first->second = smtp;
5198 return Type::interface_method_table(this, interface, is_pointer,
5199 &smtp->first, &smtp->second);
5202 // Convert struct fields to the backend representation. This is not
5203 // declared in types.h so that types.h doesn't have to #include
5204 // backend.h.
5206 static void
5207 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
5208 bool use_placeholder,
5209 std::vector<Backend::Btyped_identifier>* bfields)
5211 bfields->resize(fields->size());
5212 size_t i = 0;
5213 for (Struct_field_list::const_iterator p = fields->begin();
5214 p != fields->end();
5215 ++p, ++i)
5217 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
5218 (*bfields)[i].btype = (use_placeholder
5219 ? p->type()->get_backend_placeholder(gogo)
5220 : p->type()->get_backend(gogo));
5221 (*bfields)[i].location = p->location();
5223 go_assert(i == fields->size());
5226 // Get the backend representation for a struct type.
5228 Btype*
5229 Struct_type::do_get_backend(Gogo* gogo)
5231 std::vector<Backend::Btyped_identifier> bfields;
5232 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
5233 return gogo->backend()->struct_type(bfields);
5236 // Finish the backend representation of the fields of a struct.
5238 void
5239 Struct_type::finish_backend_fields(Gogo* gogo)
5241 const Struct_field_list* fields = this->fields_;
5242 if (fields != NULL)
5244 for (Struct_field_list::const_iterator p = fields->begin();
5245 p != fields->end();
5246 ++p)
5247 p->type()->get_backend(gogo);
5251 // The type of a struct type descriptor.
5253 Type*
5254 Struct_type::make_struct_type_descriptor_type()
5256 static Type* ret;
5257 if (ret == NULL)
5259 Type* tdt = Type::make_type_descriptor_type();
5260 Type* ptdt = Type::make_type_descriptor_ptr_type();
5262 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5263 Type* string_type = Type::lookup_string_type();
5264 Type* pointer_string_type = Type::make_pointer_type(string_type);
5266 Struct_type* sf =
5267 Type::make_builtin_struct_type(5,
5268 "name", pointer_string_type,
5269 "pkgPath", pointer_string_type,
5270 "typ", ptdt,
5271 "tag", pointer_string_type,
5272 "offset", uintptr_type);
5273 Type* nsf = Type::make_builtin_named_type("structField", sf);
5275 Type* slice_type = Type::make_array_type(nsf, NULL);
5277 Struct_type* s = Type::make_builtin_struct_type(2,
5278 "", tdt,
5279 "fields", slice_type);
5281 ret = Type::make_builtin_named_type("StructType", s);
5284 return ret;
5287 // Build a type descriptor for a struct type.
5289 Expression*
5290 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5292 Location bloc = Linemap::predeclared_location();
5294 Type* stdt = Struct_type::make_struct_type_descriptor_type();
5296 const Struct_field_list* fields = stdt->struct_type()->fields();
5298 Expression_list* vals = new Expression_list();
5299 vals->reserve(2);
5301 const Methods* methods = this->methods();
5302 // A named struct should not have methods--the methods should attach
5303 // to the named type.
5304 go_assert(methods == NULL || name == NULL);
5306 Struct_field_list::const_iterator ps = fields->begin();
5307 go_assert(ps->is_field_name("commonType"));
5308 vals->push_back(this->type_descriptor_constructor(gogo,
5309 RUNTIME_TYPE_KIND_STRUCT,
5310 name, methods, true));
5312 ++ps;
5313 go_assert(ps->is_field_name("fields"));
5315 Expression_list* elements = new Expression_list();
5316 elements->reserve(this->fields_->size());
5317 Type* element_type = ps->type()->array_type()->element_type();
5318 for (Struct_field_list::const_iterator pf = this->fields_->begin();
5319 pf != this->fields_->end();
5320 ++pf)
5322 const Struct_field_list* f = element_type->struct_type()->fields();
5324 Expression_list* fvals = new Expression_list();
5325 fvals->reserve(5);
5327 Struct_field_list::const_iterator q = f->begin();
5328 go_assert(q->is_field_name("name"));
5329 if (pf->is_anonymous())
5330 fvals->push_back(Expression::make_nil(bloc));
5331 else
5333 std::string n = Gogo::unpack_hidden_name(pf->field_name());
5334 Expression* s = Expression::make_string(n, bloc);
5335 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
5338 ++q;
5339 go_assert(q->is_field_name("pkgPath"));
5340 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
5341 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
5342 fvals->push_back(Expression::make_nil(bloc));
5343 else
5345 std::string n;
5346 if (is_embedded_builtin)
5347 n = gogo->package_name();
5348 else
5349 n = Gogo::hidden_name_pkgpath(pf->field_name());
5350 Expression* s = Expression::make_string(n, bloc);
5351 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
5354 ++q;
5355 go_assert(q->is_field_name("typ"));
5356 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
5358 ++q;
5359 go_assert(q->is_field_name("tag"));
5360 if (!pf->has_tag())
5361 fvals->push_back(Expression::make_nil(bloc));
5362 else
5364 Expression* s = Expression::make_string(pf->tag(), bloc);
5365 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
5368 ++q;
5369 go_assert(q->is_field_name("offset"));
5370 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
5372 Expression* v = Expression::make_struct_composite_literal(element_type,
5373 fvals, bloc);
5374 elements->push_back(v);
5377 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
5378 elements, bloc));
5380 return Expression::make_struct_composite_literal(stdt, vals, bloc);
5383 // Write the hash function for a struct which can not use the identity
5384 // function.
5386 void
5387 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
5388 Function_type* hash_fntype,
5389 Function_type* equal_fntype)
5391 Location bloc = Linemap::predeclared_location();
5393 // The pointer to the struct that we are going to hash. This is an
5394 // argument to the hash function we are implementing here.
5395 Named_object* key_arg = gogo->lookup("key", NULL);
5396 go_assert(key_arg != NULL);
5397 Type* key_arg_type = key_arg->var_value()->type();
5399 // The seed argument to the hash function.
5400 Named_object* seed_arg = gogo->lookup("seed", NULL);
5401 go_assert(seed_arg != NULL);
5403 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5405 // Make a temporary to hold the return value, initialized to the seed.
5406 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
5407 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
5408 bloc);
5409 gogo->add_statement(retval);
5411 // Make a temporary to hold the key as a uintptr.
5412 ref = Expression::make_var_reference(key_arg, bloc);
5413 ref = Expression::make_cast(uintptr_type, ref, bloc);
5414 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
5415 bloc);
5416 gogo->add_statement(key);
5418 // Loop over the struct fields.
5419 bool first = true;
5420 const Struct_field_list* fields = this->fields_;
5421 for (Struct_field_list::const_iterator pf = fields->begin();
5422 pf != fields->end();
5423 ++pf)
5425 if (Gogo::is_sink_name(pf->field_name()))
5426 continue;
5428 if (first)
5429 first = false;
5430 else
5432 // Multiply retval by 33.
5433 Expression* i33 = Expression::make_integer_ul(33, uintptr_type,
5434 bloc);
5435 ref = Expression::make_temporary_reference(retval, bloc);
5436 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ,
5437 ref, i33, bloc);
5438 gogo->add_statement(s);
5441 // Get a pointer to the value of this field.
5442 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
5443 ref = Expression::make_temporary_reference(key, bloc);
5444 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
5445 bloc);
5446 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
5448 // Get the size of this field.
5449 Expression* size = Expression::make_type_info(pf->type(),
5450 Expression::TYPE_INFO_SIZE);
5452 // Get the hash function to use for the type of this field.
5453 Named_object* hash_fn;
5454 Named_object* equal_fn;
5455 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
5456 equal_fntype, &hash_fn, &equal_fn);
5458 // Call the hash function for the field, passing retval as the seed.
5459 ref = Expression::make_temporary_reference(retval, bloc);
5460 Expression_list* args = new Expression_list();
5461 args->push_back(subkey);
5462 args->push_back(ref);
5463 args->push_back(size);
5464 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
5465 Expression* call = Expression::make_call(func, args, false, bloc);
5467 // Set retval to the result.
5468 Temporary_reference_expression* tref =
5469 Expression::make_temporary_reference(retval, bloc);
5470 tref->set_is_lvalue();
5471 Statement* s = Statement::make_assignment(tref, call, bloc);
5472 gogo->add_statement(s);
5475 // Return retval to the caller of the hash function.
5476 Expression_list* vals = new Expression_list();
5477 ref = Expression::make_temporary_reference(retval, bloc);
5478 vals->push_back(ref);
5479 Statement* s = Statement::make_return_statement(vals, bloc);
5480 gogo->add_statement(s);
5483 // Write the equality function for a struct which can not use the
5484 // identity function.
5486 void
5487 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
5489 Location bloc = Linemap::predeclared_location();
5491 // The pointers to the structs we are going to compare.
5492 Named_object* key1_arg = gogo->lookup("key1", NULL);
5493 Named_object* key2_arg = gogo->lookup("key2", NULL);
5494 go_assert(key1_arg != NULL && key2_arg != NULL);
5496 // Build temporaries with the right types.
5497 Type* pt = Type::make_pointer_type(name != NULL
5498 ? static_cast<Type*>(name)
5499 : static_cast<Type*>(this));
5501 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
5502 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5503 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
5504 gogo->add_statement(p1);
5506 ref = Expression::make_var_reference(key2_arg, bloc);
5507 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5508 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
5509 gogo->add_statement(p2);
5511 const Struct_field_list* fields = this->fields_;
5512 unsigned int field_index = 0;
5513 for (Struct_field_list::const_iterator pf = fields->begin();
5514 pf != fields->end();
5515 ++pf, ++field_index)
5517 if (Gogo::is_sink_name(pf->field_name()))
5518 continue;
5520 // Compare one field in both P1 and P2.
5521 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
5522 f1 = Expression::make_unary(OPERATOR_MULT, f1, bloc);
5523 f1 = Expression::make_field_reference(f1, field_index, bloc);
5525 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
5526 f2 = Expression::make_unary(OPERATOR_MULT, f2, bloc);
5527 f2 = Expression::make_field_reference(f2, field_index, bloc);
5529 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
5531 // If the values are not equal, return false.
5532 gogo->start_block(bloc);
5533 Expression_list* vals = new Expression_list();
5534 vals->push_back(Expression::make_boolean(false, bloc));
5535 Statement* s = Statement::make_return_statement(vals, bloc);
5536 gogo->add_statement(s);
5537 Block* then_block = gogo->finish_block(bloc);
5539 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
5540 gogo->add_statement(s);
5543 // All the fields are equal, so return true.
5544 Expression_list* vals = new Expression_list();
5545 vals->push_back(Expression::make_boolean(true, bloc));
5546 Statement* s = Statement::make_return_statement(vals, bloc);
5547 gogo->add_statement(s);
5550 // Reflection string.
5552 void
5553 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
5555 ret->append("struct {");
5557 for (Struct_field_list::const_iterator p = this->fields_->begin();
5558 p != this->fields_->end();
5559 ++p)
5561 if (p != this->fields_->begin())
5562 ret->push_back(';');
5563 ret->push_back(' ');
5564 if (p->is_anonymous())
5565 ret->push_back('?');
5566 else
5567 ret->append(Gogo::unpack_hidden_name(p->field_name()));
5568 ret->push_back(' ');
5569 this->append_reflection(p->type(), gogo, ret);
5571 if (p->has_tag())
5573 const std::string& tag(p->tag());
5574 ret->append(" \"");
5575 for (std::string::const_iterator p = tag.begin();
5576 p != tag.end();
5577 ++p)
5579 if (*p == '\0')
5580 ret->append("\\x00");
5581 else if (*p == '\n')
5582 ret->append("\\n");
5583 else if (*p == '\t')
5584 ret->append("\\t");
5585 else if (*p == '"')
5586 ret->append("\\\"");
5587 else if (*p == '\\')
5588 ret->append("\\\\");
5589 else
5590 ret->push_back(*p);
5592 ret->push_back('"');
5596 if (!this->fields_->empty())
5597 ret->push_back(' ');
5599 ret->push_back('}');
5602 // Generate GC symbol for struct types.
5604 void
5605 Struct_type::do_gc_symbol(Gogo* gogo, Expression_list** vals,
5606 Expression** offset, int stack_size)
5608 Location bloc = Linemap::predeclared_location();
5609 const Struct_field_list* sfl = this->fields();
5610 for (Struct_field_list::const_iterator p = sfl->begin();
5611 p != sfl->end();
5612 ++p)
5614 Expression* field_offset =
5615 Expression::make_struct_field_offset(this, &*p);
5616 Expression* o =
5617 Expression::make_binary(OPERATOR_PLUS, *offset, field_offset, bloc);
5618 Type::gc_symbol(gogo, p->type(), vals, &o, stack_size);
5620 this->advance_gc_offset(offset);
5623 // Mangled name.
5625 void
5626 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5628 ret->push_back('S');
5630 const Struct_field_list* fields = this->fields_;
5631 if (fields != NULL)
5633 for (Struct_field_list::const_iterator p = fields->begin();
5634 p != fields->end();
5635 ++p)
5637 if (p->is_anonymous())
5638 ret->append("0_");
5639 else
5641 std::string n = Gogo::unpack_hidden_name(p->field_name());
5642 char buf[20];
5643 snprintf(buf, sizeof buf, "%u_",
5644 static_cast<unsigned int>(n.length()));
5645 ret->append(buf);
5646 ret->append(n);
5648 this->append_mangled_name(p->type(), gogo, ret);
5649 if (p->has_tag())
5651 const std::string& tag(p->tag());
5652 std::string out;
5653 for (std::string::const_iterator p = tag.begin();
5654 p != tag.end();
5655 ++p)
5657 if (ISALNUM(*p) || *p == '_')
5658 out.push_back(*p);
5659 else
5661 char buf[20];
5662 snprintf(buf, sizeof buf, ".%x.",
5663 static_cast<unsigned int>(*p));
5664 out.append(buf);
5667 char buf[20];
5668 snprintf(buf, sizeof buf, "T%u_",
5669 static_cast<unsigned int>(out.length()));
5670 ret->append(buf);
5671 ret->append(out);
5676 if (this->is_struct_incomparable_)
5677 ret->push_back('x');
5679 ret->push_back('e');
5682 // If the offset of field INDEX in the backend implementation can be
5683 // determined, set *POFFSET to the offset in bytes and return true.
5684 // Otherwise, return false.
5686 bool
5687 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
5688 int64_t* poffset)
5690 if (!this->is_backend_type_size_known(gogo))
5691 return false;
5692 Btype* bt = this->get_backend_placeholder(gogo);
5693 *poffset = gogo->backend()->type_field_offset(bt, index);
5694 return true;
5697 // Export.
5699 void
5700 Struct_type::do_export(Export* exp) const
5702 exp->write_c_string("struct { ");
5703 const Struct_field_list* fields = this->fields_;
5704 go_assert(fields != NULL);
5705 for (Struct_field_list::const_iterator p = fields->begin();
5706 p != fields->end();
5707 ++p)
5709 if (p->is_anonymous())
5710 exp->write_string("? ");
5711 else
5713 exp->write_string(p->field_name());
5714 exp->write_c_string(" ");
5716 exp->write_type(p->type());
5718 if (p->has_tag())
5720 exp->write_c_string(" ");
5721 Expression* expr =
5722 Expression::make_string(p->tag(), Linemap::predeclared_location());
5723 expr->export_expression(exp);
5724 delete expr;
5727 exp->write_c_string("; ");
5729 exp->write_c_string("}");
5732 // Import.
5734 Struct_type*
5735 Struct_type::do_import(Import* imp)
5737 imp->require_c_string("struct { ");
5738 Struct_field_list* fields = new Struct_field_list;
5739 if (imp->peek_char() != '}')
5741 while (true)
5743 std::string name;
5744 if (imp->match_c_string("? "))
5745 imp->advance(2);
5746 else
5748 name = imp->read_identifier();
5749 imp->require_c_string(" ");
5751 Type* ftype = imp->read_type();
5753 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
5754 sf.set_is_imported();
5756 if (imp->peek_char() == ' ')
5758 imp->advance(1);
5759 Expression* expr = Expression::import_expression(imp);
5760 String_expression* sexpr = expr->string_expression();
5761 go_assert(sexpr != NULL);
5762 sf.set_tag(sexpr->val());
5763 delete sexpr;
5766 imp->require_c_string("; ");
5767 fields->push_back(sf);
5768 if (imp->peek_char() == '}')
5769 break;
5772 imp->require_c_string("}");
5774 return Type::make_struct_type(fields, imp->location());
5777 // Whether we can write this struct type to a C header file.
5778 // We can't if any of the fields are structs defined in a different package.
5780 bool
5781 Struct_type::can_write_to_c_header(
5782 std::vector<const Named_object*>* requires,
5783 std::vector<const Named_object*>* declare) const
5785 const Struct_field_list* fields = this->fields_;
5786 if (fields == NULL || fields->empty())
5787 return false;
5788 for (Struct_field_list::const_iterator p = fields->begin();
5789 p != fields->end();
5790 ++p)
5792 if (p->is_anonymous())
5793 return false;
5794 if (!this->can_write_type_to_c_header(p->type(), requires, declare))
5795 return false;
5797 return true;
5800 // Whether we can write the type T to a C header file.
5802 bool
5803 Struct_type::can_write_type_to_c_header(
5804 const Type* t,
5805 std::vector<const Named_object*>* requires,
5806 std::vector<const Named_object*>* declare) const
5808 t = t->forwarded();
5809 switch (t->classification())
5811 case TYPE_ERROR:
5812 case TYPE_FORWARD:
5813 return false;
5815 case TYPE_VOID:
5816 case TYPE_BOOLEAN:
5817 case TYPE_INTEGER:
5818 case TYPE_FLOAT:
5819 case TYPE_COMPLEX:
5820 case TYPE_STRING:
5821 case TYPE_FUNCTION:
5822 case TYPE_MAP:
5823 case TYPE_CHANNEL:
5824 case TYPE_INTERFACE:
5825 return true;
5827 case TYPE_POINTER:
5828 // Don't try to handle a pointer to an array.
5829 if (t->points_to()->array_type() != NULL
5830 && !t->points_to()->is_slice_type())
5831 return false;
5833 if (t->points_to()->named_type() != NULL
5834 && t->points_to()->struct_type() != NULL)
5835 declare->push_back(t->points_to()->named_type()->named_object());
5836 return true;
5838 case TYPE_STRUCT:
5839 return t->struct_type()->can_write_to_c_header(requires, declare);
5841 case TYPE_ARRAY:
5842 if (t->is_slice_type())
5843 return true;
5844 return this->can_write_type_to_c_header(t->array_type()->element_type(),
5845 requires, declare);
5847 case TYPE_NAMED:
5849 const Named_object* no = t->named_type()->named_object();
5850 if (no->package() != NULL)
5852 if (t->is_unsafe_pointer_type())
5853 return true;
5854 return false;
5856 if (t->struct_type() != NULL)
5858 requires->push_back(no);
5859 return t->struct_type()->can_write_to_c_header(requires, declare);
5861 return this->can_write_type_to_c_header(t->base(), requires, declare);
5864 case TYPE_CALL_MULTIPLE_RESULT:
5865 case TYPE_NIL:
5866 case TYPE_SINK:
5867 default:
5868 go_unreachable();
5872 // Write this struct to a C header file.
5874 void
5875 Struct_type::write_to_c_header(std::ostream& os) const
5877 const Struct_field_list* fields = this->fields_;
5878 for (Struct_field_list::const_iterator p = fields->begin();
5879 p != fields->end();
5880 ++p)
5882 os << '\t';
5883 this->write_field_to_c_header(os, p->field_name(), p->type());
5884 os << ';' << std::endl;
5888 // Write the type of a struct field to a C header file.
5890 void
5891 Struct_type::write_field_to_c_header(std::ostream& os, const std::string& name,
5892 const Type *t) const
5894 bool print_name = true;
5895 t = t->forwarded();
5896 switch (t->classification())
5898 case TYPE_VOID:
5899 os << "void";
5900 break;
5902 case TYPE_BOOLEAN:
5903 os << "_Bool";
5904 break;
5906 case TYPE_INTEGER:
5908 const Integer_type* it = t->integer_type();
5909 if (it->is_unsigned())
5910 os << 'u';
5911 os << "int" << it->bits() << "_t";
5913 break;
5915 case TYPE_FLOAT:
5916 switch (t->float_type()->bits())
5918 case 32:
5919 os << "float";
5920 break;
5921 case 64:
5922 os << "double";
5923 break;
5924 default:
5925 go_unreachable();
5927 break;
5929 case TYPE_COMPLEX:
5930 switch (t->complex_type()->bits())
5932 case 64:
5933 os << "float _Complex";
5934 break;
5935 case 128:
5936 os << "double _Complex";
5937 break;
5938 default:
5939 go_unreachable();
5941 break;
5943 case TYPE_STRING:
5944 os << "String";
5945 break;
5947 case TYPE_FUNCTION:
5948 os << "FuncVal*";
5949 break;
5951 case TYPE_POINTER:
5953 std::vector<const Named_object*> requires;
5954 std::vector<const Named_object*> declare;
5955 if (!this->can_write_type_to_c_header(t->points_to(), &requires,
5956 &declare))
5957 os << "void*";
5958 else
5960 this->write_field_to_c_header(os, "", t->points_to());
5961 os << '*';
5964 break;
5966 case TYPE_MAP:
5967 os << "Map*";
5968 break;
5970 case TYPE_CHANNEL:
5971 os << "Chan*";
5972 break;
5974 case TYPE_INTERFACE:
5975 if (t->interface_type()->is_empty())
5976 os << "Eface";
5977 else
5978 os << "Iface";
5979 break;
5981 case TYPE_STRUCT:
5982 os << "struct {" << std::endl;
5983 t->struct_type()->write_to_c_header(os);
5984 os << "\t}";
5985 break;
5987 case TYPE_ARRAY:
5988 if (t->is_slice_type())
5989 os << "Slice";
5990 else
5992 const Type *ele = t;
5993 std::vector<const Type*> array_types;
5994 while (ele->array_type() != NULL && !ele->is_slice_type())
5996 array_types.push_back(ele);
5997 ele = ele->array_type()->element_type();
5999 this->write_field_to_c_header(os, "", ele);
6000 os << ' ' << Gogo::message_name(name);
6001 print_name = false;
6002 while (!array_types.empty())
6004 ele = array_types.back();
6005 array_types.pop_back();
6006 os << '[';
6007 Numeric_constant nc;
6008 if (!ele->array_type()->length()->numeric_constant_value(&nc))
6009 go_unreachable();
6010 mpz_t val;
6011 if (!nc.to_int(&val))
6012 go_unreachable();
6013 char* s = mpz_get_str(NULL, 10, val);
6014 os << s;
6015 free(s);
6016 mpz_clear(val);
6017 os << ']';
6020 break;
6022 case TYPE_NAMED:
6024 const Named_object* no = t->named_type()->named_object();
6025 if (t->struct_type() != NULL)
6026 os << "struct " << no->message_name();
6027 else if (t->is_unsafe_pointer_type())
6028 os << "void*";
6029 else if (t == Type::lookup_integer_type("uintptr"))
6030 os << "uintptr_t";
6031 else
6033 this->write_field_to_c_header(os, name, t->base());
6034 print_name = false;
6037 break;
6039 case TYPE_ERROR:
6040 case TYPE_FORWARD:
6041 case TYPE_CALL_MULTIPLE_RESULT:
6042 case TYPE_NIL:
6043 case TYPE_SINK:
6044 default:
6045 go_unreachable();
6048 if (print_name && !name.empty())
6049 os << ' ' << Gogo::message_name(name);
6052 // Make a struct type.
6054 Struct_type*
6055 Type::make_struct_type(Struct_field_list* fields,
6056 Location location)
6058 return new Struct_type(fields, location);
6061 // Class Array_type.
6063 // Whether two array types are identical.
6065 bool
6066 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
6068 if (!Type::are_identical(this->element_type(), t->element_type(),
6069 errors_are_identical, NULL))
6070 return false;
6072 if (this->is_array_incomparable_ != t->is_array_incomparable_)
6073 return false;
6075 Expression* l1 = this->length();
6076 Expression* l2 = t->length();
6078 // Slices of the same element type are identical.
6079 if (l1 == NULL && l2 == NULL)
6080 return true;
6082 // Arrays of the same element type are identical if they have the
6083 // same length.
6084 if (l1 != NULL && l2 != NULL)
6086 if (l1 == l2)
6087 return true;
6089 // Try to determine the lengths. If we can't, assume the arrays
6090 // are not identical.
6091 bool ret = false;
6092 Numeric_constant nc1, nc2;
6093 if (l1->numeric_constant_value(&nc1)
6094 && l2->numeric_constant_value(&nc2))
6096 mpz_t v1;
6097 if (nc1.to_int(&v1))
6099 mpz_t v2;
6100 if (nc2.to_int(&v2))
6102 ret = mpz_cmp(v1, v2) == 0;
6103 mpz_clear(v2);
6105 mpz_clear(v1);
6108 return ret;
6111 // Otherwise the arrays are not identical.
6112 return false;
6115 // Traversal.
6118 Array_type::do_traverse(Traverse* traverse)
6120 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
6121 return TRAVERSE_EXIT;
6122 if (this->length_ != NULL
6123 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
6124 return TRAVERSE_EXIT;
6125 return TRAVERSE_CONTINUE;
6128 // Check that the length is valid.
6130 bool
6131 Array_type::verify_length()
6133 if (this->length_ == NULL)
6134 return true;
6136 Type_context context(Type::lookup_integer_type("int"), false);
6137 this->length_->determine_type(&context);
6139 if (!this->length_->is_constant())
6141 go_error_at(this->length_->location(), "array bound is not constant");
6142 return false;
6145 Numeric_constant nc;
6146 if (!this->length_->numeric_constant_value(&nc))
6148 if (this->length_->type()->integer_type() != NULL
6149 || this->length_->type()->float_type() != NULL)
6150 go_error_at(this->length_->location(), "array bound is not constant");
6151 else
6152 go_error_at(this->length_->location(), "array bound is not numeric");
6153 return false;
6156 Type* int_type = Type::lookup_integer_type("int");
6157 unsigned int tbits = int_type->integer_type()->bits();
6158 unsigned long val;
6159 switch (nc.to_unsigned_long(&val))
6161 case Numeric_constant::NC_UL_VALID:
6162 if (sizeof(val) >= tbits / 8 && val >> (tbits - 1) != 0)
6164 go_error_at(this->length_->location(), "array bound overflows");
6165 return false;
6167 break;
6168 case Numeric_constant::NC_UL_NOTINT:
6169 go_error_at(this->length_->location(), "array bound truncated to integer");
6170 return false;
6171 case Numeric_constant::NC_UL_NEGATIVE:
6172 go_error_at(this->length_->location(), "negative array bound");
6173 return false;
6174 case Numeric_constant::NC_UL_BIG:
6176 mpz_t val;
6177 if (!nc.to_int(&val))
6178 go_unreachable();
6179 unsigned int bits = mpz_sizeinbase(val, 2);
6180 mpz_clear(val);
6181 if (bits >= tbits)
6183 go_error_at(this->length_->location(), "array bound overflows");
6184 return false;
6187 break;
6188 default:
6189 go_unreachable();
6192 return true;
6195 // Verify the type.
6197 bool
6198 Array_type::do_verify()
6200 if (this->element_type()->is_error_type())
6201 return false;
6202 if (!this->verify_length())
6203 this->length_ = Expression::make_error(this->length_->location());
6204 return true;
6207 // Whether we can use memcmp to compare this array.
6209 bool
6210 Array_type::do_compare_is_identity(Gogo* gogo)
6212 if (this->length_ == NULL)
6213 return false;
6215 // Check for [...], which indicates that this is not a real type.
6216 if (this->length_->is_nil_expression())
6217 return false;
6219 if (!this->element_type_->compare_is_identity(gogo))
6220 return false;
6222 // If there is any padding, then we can't use memcmp.
6223 int64_t size;
6224 int64_t align;
6225 if (!this->element_type_->backend_type_size(gogo, &size)
6226 || !this->element_type_->backend_type_align(gogo, &align))
6227 return false;
6228 if ((size & (align - 1)) != 0)
6229 return false;
6231 return true;
6234 // Array type hash code.
6236 unsigned int
6237 Array_type::do_hash_for_method(Gogo* gogo) const
6239 unsigned int ret;
6241 // There is no very convenient way to get a hash code for the
6242 // length.
6243 ret = this->element_type_->hash_for_method(gogo) + 1;
6244 if (this->is_array_incomparable_)
6245 ret <<= 1;
6246 return ret;
6249 // Write the hash function for an array which can not use the identify
6250 // function.
6252 void
6253 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
6254 Function_type* hash_fntype,
6255 Function_type* equal_fntype)
6257 Location bloc = Linemap::predeclared_location();
6259 // The pointer to the array that we are going to hash. This is an
6260 // argument to the hash function we are implementing here.
6261 Named_object* key_arg = gogo->lookup("key", NULL);
6262 go_assert(key_arg != NULL);
6263 Type* key_arg_type = key_arg->var_value()->type();
6265 // The seed argument to the hash function.
6266 Named_object* seed_arg = gogo->lookup("seed", NULL);
6267 go_assert(seed_arg != NULL);
6269 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6271 // Make a temporary to hold the return value, initialized to the seed.
6272 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
6273 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
6274 bloc);
6275 gogo->add_statement(retval);
6277 // Make a temporary to hold the key as a uintptr.
6278 ref = Expression::make_var_reference(key_arg, bloc);
6279 ref = Expression::make_cast(uintptr_type, ref, bloc);
6280 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
6281 bloc);
6282 gogo->add_statement(key);
6284 // Loop over the array elements.
6285 // for i = range a
6286 Type* int_type = Type::lookup_integer_type("int");
6287 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
6288 gogo->add_statement(index);
6290 Expression* iref = Expression::make_temporary_reference(index, bloc);
6291 Expression* aref = Expression::make_var_reference(key_arg, bloc);
6292 Type* pt = Type::make_pointer_type(name != NULL
6293 ? static_cast<Type*>(name)
6294 : static_cast<Type*>(this));
6295 aref = Expression::make_cast(pt, aref, bloc);
6296 For_range_statement* for_range = Statement::make_for_range_statement(iref,
6297 NULL,
6298 aref,
6299 bloc);
6301 gogo->start_block(bloc);
6303 // Multiply retval by 33.
6304 Expression* i33 = Expression::make_integer_ul(33, uintptr_type, bloc);
6306 ref = Expression::make_temporary_reference(retval, bloc);
6307 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ, ref,
6308 i33, bloc);
6309 gogo->add_statement(s);
6311 // Get the hash function for the element type.
6312 Named_object* hash_fn;
6313 Named_object* equal_fn;
6314 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
6315 hash_fntype, equal_fntype, &hash_fn,
6316 &equal_fn);
6318 // Get a pointer to this element in the loop.
6319 Expression* subkey = Expression::make_temporary_reference(key, bloc);
6320 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6322 // Get the size of each element.
6323 Expression* ele_size = Expression::make_type_info(this->element_type_,
6324 Expression::TYPE_INFO_SIZE);
6326 // Get the hash of this element, passing retval as the seed.
6327 ref = Expression::make_temporary_reference(retval, bloc);
6328 Expression_list* args = new Expression_list();
6329 args->push_back(subkey);
6330 args->push_back(ref);
6331 args->push_back(ele_size);
6332 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6333 Expression* call = Expression::make_call(func, args, false, bloc);
6335 // Set retval to the result.
6336 Temporary_reference_expression* tref =
6337 Expression::make_temporary_reference(retval, bloc);
6338 tref->set_is_lvalue();
6339 s = Statement::make_assignment(tref, call, bloc);
6340 gogo->add_statement(s);
6342 // Increase the element pointer.
6343 tref = Expression::make_temporary_reference(key, bloc);
6344 tref->set_is_lvalue();
6345 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
6346 bloc);
6347 Block* statements = gogo->finish_block(bloc);
6349 for_range->add_statements(statements);
6350 gogo->add_statement(for_range);
6352 // Return retval to the caller of the hash function.
6353 Expression_list* vals = new Expression_list();
6354 ref = Expression::make_temporary_reference(retval, bloc);
6355 vals->push_back(ref);
6356 s = Statement::make_return_statement(vals, bloc);
6357 gogo->add_statement(s);
6360 // Write the equality function for an array which can not use the
6361 // identity function.
6363 void
6364 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
6366 Location bloc = Linemap::predeclared_location();
6368 // The pointers to the arrays we are going to compare.
6369 Named_object* key1_arg = gogo->lookup("key1", NULL);
6370 Named_object* key2_arg = gogo->lookup("key2", NULL);
6371 go_assert(key1_arg != NULL && key2_arg != NULL);
6373 // Build temporaries for the keys with the right types.
6374 Type* pt = Type::make_pointer_type(name != NULL
6375 ? static_cast<Type*>(name)
6376 : static_cast<Type*>(this));
6378 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6379 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6380 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6381 gogo->add_statement(p1);
6383 ref = Expression::make_var_reference(key2_arg, bloc);
6384 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6385 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6386 gogo->add_statement(p2);
6388 // Loop over the array elements.
6389 // for i = range a
6390 Type* int_type = Type::lookup_integer_type("int");
6391 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
6392 gogo->add_statement(index);
6394 Expression* iref = Expression::make_temporary_reference(index, bloc);
6395 Expression* aref = Expression::make_temporary_reference(p1, bloc);
6396 For_range_statement* for_range = Statement::make_for_range_statement(iref,
6397 NULL,
6398 aref,
6399 bloc);
6401 gogo->start_block(bloc);
6403 // Compare element in P1 and P2.
6404 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
6405 e1 = Expression::make_unary(OPERATOR_MULT, e1, bloc);
6406 ref = Expression::make_temporary_reference(index, bloc);
6407 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
6409 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
6410 e2 = Expression::make_unary(OPERATOR_MULT, e2, bloc);
6411 ref = Expression::make_temporary_reference(index, bloc);
6412 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
6414 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
6416 // If the elements are not equal, return false.
6417 gogo->start_block(bloc);
6418 Expression_list* vals = new Expression_list();
6419 vals->push_back(Expression::make_boolean(false, bloc));
6420 Statement* s = Statement::make_return_statement(vals, bloc);
6421 gogo->add_statement(s);
6422 Block* then_block = gogo->finish_block(bloc);
6424 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6425 gogo->add_statement(s);
6427 Block* statements = gogo->finish_block(bloc);
6429 for_range->add_statements(statements);
6430 gogo->add_statement(for_range);
6432 // All the elements are equal, so return true.
6433 vals = new Expression_list();
6434 vals->push_back(Expression::make_boolean(true, bloc));
6435 s = Statement::make_return_statement(vals, bloc);
6436 gogo->add_statement(s);
6439 // Get the backend representation of the fields of a slice. This is
6440 // not declared in types.h so that types.h doesn't have to #include
6441 // backend.h.
6443 // We use int for the count and capacity fields. This matches 6g.
6444 // The language more or less assumes that we can't allocate space of a
6445 // size which does not fit in int.
6447 static void
6448 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
6449 std::vector<Backend::Btyped_identifier>* bfields)
6451 bfields->resize(3);
6453 Type* pet = Type::make_pointer_type(type->element_type());
6454 Btype* pbet = (use_placeholder
6455 ? pet->get_backend_placeholder(gogo)
6456 : pet->get_backend(gogo));
6457 Location ploc = Linemap::predeclared_location();
6459 Backend::Btyped_identifier* p = &(*bfields)[0];
6460 p->name = "__values";
6461 p->btype = pbet;
6462 p->location = ploc;
6464 Type* int_type = Type::lookup_integer_type("int");
6466 p = &(*bfields)[1];
6467 p->name = "__count";
6468 p->btype = int_type->get_backend(gogo);
6469 p->location = ploc;
6471 p = &(*bfields)[2];
6472 p->name = "__capacity";
6473 p->btype = int_type->get_backend(gogo);
6474 p->location = ploc;
6477 // Get the backend representation for the type of this array. A fixed array is
6478 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
6479 // just like an array in C. An open array is a struct with three
6480 // fields: a data pointer, the length, and the capacity.
6482 Btype*
6483 Array_type::do_get_backend(Gogo* gogo)
6485 if (this->length_ == NULL)
6487 std::vector<Backend::Btyped_identifier> bfields;
6488 get_backend_slice_fields(gogo, this, false, &bfields);
6489 return gogo->backend()->struct_type(bfields);
6491 else
6493 Btype* element = this->get_backend_element(gogo, false);
6494 Bexpression* len = this->get_backend_length(gogo);
6495 return gogo->backend()->array_type(element, len);
6499 // Return the backend representation of the element type.
6501 Btype*
6502 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
6504 if (use_placeholder)
6505 return this->element_type_->get_backend_placeholder(gogo);
6506 else
6507 return this->element_type_->get_backend(gogo);
6510 // Return the backend representation of the length. The length may be
6511 // computed using a function call, so we must only evaluate it once.
6513 Bexpression*
6514 Array_type::get_backend_length(Gogo* gogo)
6516 go_assert(this->length_ != NULL);
6517 if (this->blength_ == NULL)
6519 Numeric_constant nc;
6520 mpz_t val;
6521 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
6523 if (mpz_sgn(val) < 0)
6525 this->blength_ = gogo->backend()->error_expression();
6526 return this->blength_;
6528 Type* t = nc.type();
6529 if (t == NULL)
6530 t = Type::lookup_integer_type("int");
6531 else if (t->is_abstract())
6532 t = t->make_non_abstract_type();
6533 Btype* btype = t->get_backend(gogo);
6534 this->blength_ =
6535 gogo->backend()->integer_constant_expression(btype, val);
6536 mpz_clear(val);
6538 else
6540 // Make up a translation context for the array length
6541 // expression. FIXME: This won't work in general.
6542 Translate_context context(gogo, NULL, NULL, NULL);
6543 this->blength_ = this->length_->get_backend(&context);
6545 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
6546 this->blength_ =
6547 gogo->backend()->convert_expression(ibtype, this->blength_,
6548 this->length_->location());
6551 return this->blength_;
6554 // Finish backend representation of the array.
6556 void
6557 Array_type::finish_backend_element(Gogo* gogo)
6559 Type* et = this->array_type()->element_type();
6560 et->get_backend(gogo);
6561 if (this->is_slice_type())
6563 // This relies on the fact that we always use the same
6564 // structure for a pointer to any given type.
6565 Type* pet = Type::make_pointer_type(et);
6566 pet->get_backend(gogo);
6570 // Return an expression for a pointer to the values in ARRAY.
6572 Expression*
6573 Array_type::get_value_pointer(Gogo*, Expression* array) const
6575 if (this->length() != NULL)
6577 // Fixed array.
6578 go_assert(array->type()->array_type() != NULL);
6579 Type* etype = array->type()->array_type()->element_type();
6580 array = Expression::make_unary(OPERATOR_AND, array, array->location());
6581 return Expression::make_cast(Type::make_pointer_type(etype), array,
6582 array->location());
6585 // Slice.
6586 return Expression::make_slice_info(array,
6587 Expression::SLICE_INFO_VALUE_POINTER,
6588 array->location());
6591 // Return an expression for the length of the array ARRAY which has this
6592 // type.
6594 Expression*
6595 Array_type::get_length(Gogo*, Expression* array) const
6597 if (this->length_ != NULL)
6598 return this->length_;
6600 // This is a slice. We need to read the length field.
6601 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
6602 array->location());
6605 // Return an expression for the capacity of the array ARRAY which has this
6606 // type.
6608 Expression*
6609 Array_type::get_capacity(Gogo*, Expression* array) const
6611 if (this->length_ != NULL)
6612 return this->length_;
6614 // This is a slice. We need to read the capacity field.
6615 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
6616 array->location());
6619 // Export.
6621 void
6622 Array_type::do_export(Export* exp) const
6624 exp->write_c_string("[");
6625 if (this->length_ != NULL)
6626 this->length_->export_expression(exp);
6627 exp->write_c_string("] ");
6628 exp->write_type(this->element_type_);
6631 // Import.
6633 Array_type*
6634 Array_type::do_import(Import* imp)
6636 imp->require_c_string("[");
6637 Expression* length;
6638 if (imp->peek_char() == ']')
6639 length = NULL;
6640 else
6641 length = Expression::import_expression(imp);
6642 imp->require_c_string("] ");
6643 Type* element_type = imp->read_type();
6644 return Type::make_array_type(element_type, length);
6647 // The type of an array type descriptor.
6649 Type*
6650 Array_type::make_array_type_descriptor_type()
6652 static Type* ret;
6653 if (ret == NULL)
6655 Type* tdt = Type::make_type_descriptor_type();
6656 Type* ptdt = Type::make_type_descriptor_ptr_type();
6658 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6660 Struct_type* sf =
6661 Type::make_builtin_struct_type(4,
6662 "", tdt,
6663 "elem", ptdt,
6664 "slice", ptdt,
6665 "len", uintptr_type);
6667 ret = Type::make_builtin_named_type("ArrayType", sf);
6670 return ret;
6673 // The type of an slice type descriptor.
6675 Type*
6676 Array_type::make_slice_type_descriptor_type()
6678 static Type* ret;
6679 if (ret == NULL)
6681 Type* tdt = Type::make_type_descriptor_type();
6682 Type* ptdt = Type::make_type_descriptor_ptr_type();
6684 Struct_type* sf =
6685 Type::make_builtin_struct_type(2,
6686 "", tdt,
6687 "elem", ptdt);
6689 ret = Type::make_builtin_named_type("SliceType", sf);
6692 return ret;
6695 // Build a type descriptor for an array/slice type.
6697 Expression*
6698 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6700 if (this->length_ != NULL)
6701 return this->array_type_descriptor(gogo, name);
6702 else
6703 return this->slice_type_descriptor(gogo, name);
6706 // Build a type descriptor for an array type.
6708 Expression*
6709 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
6711 Location bloc = Linemap::predeclared_location();
6713 Type* atdt = Array_type::make_array_type_descriptor_type();
6715 const Struct_field_list* fields = atdt->struct_type()->fields();
6717 Expression_list* vals = new Expression_list();
6718 vals->reserve(3);
6720 Struct_field_list::const_iterator p = fields->begin();
6721 go_assert(p->is_field_name("commonType"));
6722 vals->push_back(this->type_descriptor_constructor(gogo,
6723 RUNTIME_TYPE_KIND_ARRAY,
6724 name, NULL, true));
6726 ++p;
6727 go_assert(p->is_field_name("elem"));
6728 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
6730 ++p;
6731 go_assert(p->is_field_name("slice"));
6732 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
6733 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
6735 ++p;
6736 go_assert(p->is_field_name("len"));
6737 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
6739 ++p;
6740 go_assert(p == fields->end());
6742 return Expression::make_struct_composite_literal(atdt, vals, bloc);
6745 // Build a type descriptor for a slice type.
6747 Expression*
6748 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
6750 Location bloc = Linemap::predeclared_location();
6752 Type* stdt = Array_type::make_slice_type_descriptor_type();
6754 const Struct_field_list* fields = stdt->struct_type()->fields();
6756 Expression_list* vals = new Expression_list();
6757 vals->reserve(2);
6759 Struct_field_list::const_iterator p = fields->begin();
6760 go_assert(p->is_field_name("commonType"));
6761 vals->push_back(this->type_descriptor_constructor(gogo,
6762 RUNTIME_TYPE_KIND_SLICE,
6763 name, NULL, true));
6765 ++p;
6766 go_assert(p->is_field_name("elem"));
6767 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
6769 ++p;
6770 go_assert(p == fields->end());
6772 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6775 // Reflection string.
6777 void
6778 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
6780 ret->push_back('[');
6781 if (this->length_ != NULL)
6783 Numeric_constant nc;
6784 if (!this->length_->numeric_constant_value(&nc))
6786 go_assert(saw_errors());
6787 return;
6789 mpz_t val;
6790 if (!nc.to_int(&val))
6792 go_assert(saw_errors());
6793 return;
6795 char* s = mpz_get_str(NULL, 10, val);
6796 ret->append(s);
6797 free(s);
6798 mpz_clear(val);
6800 ret->push_back(']');
6802 this->append_reflection(this->element_type_, gogo, ret);
6805 // GC Symbol construction for array types.
6807 void
6808 Array_type::do_gc_symbol(Gogo* gogo, Expression_list** vals,
6809 Expression** offset, int stack_size)
6811 if (this->length_ == NULL)
6812 this->slice_gc_symbol(gogo, vals, offset, stack_size);
6813 else
6814 this->array_gc_symbol(gogo, vals, offset, stack_size);
6817 // Generate the GC Symbol for a slice.
6819 void
6820 Array_type::slice_gc_symbol(Gogo* gogo, Expression_list** vals,
6821 Expression** offset, int)
6823 Location bloc = Linemap::predeclared_location();
6825 // Differentiate between slices with zero-length and non-zero-length values.
6826 Type* element_type = this->element_type();
6827 int64_t element_size;
6828 bool ok = element_type->backend_type_size(gogo, &element_size);
6829 if (!ok) {
6830 go_assert(saw_errors());
6831 element_size = 4;
6834 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6835 unsigned long opval = element_size == 0 ? GC_APTR : GC_SLICE;
6836 (*vals)->push_back(Expression::make_integer_ul(opval, uintptr_type, bloc));
6837 (*vals)->push_back(*offset);
6839 if (element_size != 0 && ok)
6840 (*vals)->push_back(Expression::make_gc_symbol(element_type));
6841 this->advance_gc_offset(offset);
6844 // Generate the GC symbol for an array.
6846 void
6847 Array_type::array_gc_symbol(Gogo* gogo, Expression_list** vals,
6848 Expression** offset, int stack_size)
6850 Location bloc = Linemap::predeclared_location();
6852 Numeric_constant nc;
6853 unsigned long bound;
6854 if (!this->length_->numeric_constant_value(&nc)
6855 || nc.to_unsigned_long(&bound) == Numeric_constant::NC_UL_NOTINT)
6857 go_assert(saw_errors());
6858 return;
6861 Btype* pbtype = gogo->backend()->pointer_type(gogo->backend()->void_type());
6862 int64_t pwidth = gogo->backend()->type_size(pbtype);
6863 int64_t iwidth;
6864 bool ok = this->backend_type_size(gogo, &iwidth);
6865 if (!ok)
6867 go_assert(saw_errors());
6868 iwidth = 4;
6871 Type* element_type = this->element_type();
6872 if (bound < 1 || !element_type->has_pointer())
6873 this->advance_gc_offset(offset);
6874 else if (ok && (bound == 1 || iwidth <= 4 * pwidth))
6876 for (unsigned int i = 0; i < bound; ++i)
6877 Type::gc_symbol(gogo, element_type, vals, offset, stack_size);
6879 else
6881 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6883 if (stack_size < GC_STACK_CAPACITY)
6885 (*vals)->push_back(Expression::make_integer_ul(GC_ARRAY_START,
6886 uintptr_type, bloc));
6887 (*vals)->push_back(*offset);
6888 Expression* uintptr_len =
6889 Expression::make_cast(uintptr_type, this->length_, bloc);
6890 (*vals)->push_back(uintptr_len);
6892 Expression* width =
6893 Expression::make_type_info(element_type,
6894 Expression::TYPE_INFO_SIZE);
6895 (*vals)->push_back(width);
6897 Expression* offset2 = Expression::make_integer_ul(0, uintptr_type,
6898 bloc);
6900 Type::gc_symbol(gogo, element_type, vals, &offset2, stack_size + 1);
6901 (*vals)->push_back(Expression::make_integer_ul(GC_ARRAY_NEXT,
6902 uintptr_type, bloc));
6904 else
6906 (*vals)->push_back(Expression::make_integer_ul(GC_REGION,
6907 uintptr_type, bloc));
6908 (*vals)->push_back(*offset);
6910 Expression* width =
6911 Expression::make_type_info(this, Expression::TYPE_INFO_SIZE);
6912 (*vals)->push_back(width);
6913 (*vals)->push_back(Expression::make_gc_symbol(this));
6915 this->advance_gc_offset(offset);
6919 // Mangled name.
6921 void
6922 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6924 ret->push_back('A');
6925 this->append_mangled_name(this->element_type_, gogo, ret);
6926 if (this->length_ != NULL)
6928 Numeric_constant nc;
6929 if (!this->length_->numeric_constant_value(&nc))
6931 go_assert(saw_errors());
6932 return;
6934 mpz_t val;
6935 if (!nc.to_int(&val))
6937 go_assert(saw_errors());
6938 return;
6940 char *s = mpz_get_str(NULL, 10, val);
6941 ret->append(s);
6942 free(s);
6943 mpz_clear(val);
6944 if (this->is_array_incomparable_)
6945 ret->push_back('x');
6947 ret->push_back('e');
6950 // Make an array type.
6952 Array_type*
6953 Type::make_array_type(Type* element_type, Expression* length)
6955 return new Array_type(element_type, length);
6958 // Class Map_type.
6960 Named_object* Map_type::zero_value;
6961 int64_t Map_type::zero_value_size;
6962 int64_t Map_type::zero_value_align;
6964 // If this map requires the "fat" functions, return the pointer to
6965 // pass as the zero value to those functions. Otherwise, in the
6966 // normal case, return NULL. The map requires the "fat" functions if
6967 // the value size is larger than max_zero_size bytes. max_zero_size
6968 // must match maxZero in libgo/go/runtime/hashmap.go.
6970 Expression*
6971 Map_type::fat_zero_value(Gogo* gogo)
6973 int64_t valsize;
6974 if (!this->val_type_->backend_type_size(gogo, &valsize))
6976 go_assert(saw_errors());
6977 return NULL;
6979 if (valsize <= Map_type::max_zero_size)
6980 return NULL;
6982 if (Map_type::zero_value_size < valsize)
6983 Map_type::zero_value_size = valsize;
6985 int64_t valalign;
6986 if (!this->val_type_->backend_type_align(gogo, &valalign))
6988 go_assert(saw_errors());
6989 return NULL;
6992 if (Map_type::zero_value_align < valalign)
6993 Map_type::zero_value_align = valalign;
6995 Location bloc = Linemap::predeclared_location();
6997 if (Map_type::zero_value == NULL)
6999 // The final type will be set in backend_zero_value.
7000 Type* uint8_type = Type::lookup_integer_type("uint8");
7001 Expression* size = Expression::make_integer_ul(0, NULL, bloc);
7002 Type* array_type = Type::make_array_type(uint8_type, size);
7003 Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
7004 Map_type::zero_value = Named_object::make_variable("go$zerovalue", NULL,
7005 var);
7008 Expression* z = Expression::make_var_reference(Map_type::zero_value, bloc);
7009 z = Expression::make_unary(OPERATOR_AND, z, bloc);
7010 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
7011 z = Expression::make_cast(unsafe_ptr_type, z, bloc);
7012 return z;
7015 // Return whether VAR is the map zero value.
7017 bool
7018 Map_type::is_zero_value(Variable* var)
7020 return (Map_type::zero_value != NULL
7021 && Map_type::zero_value->var_value() == var);
7024 // Return the backend representation for the zero value.
7026 Bvariable*
7027 Map_type::backend_zero_value(Gogo* gogo)
7029 Location bloc = Linemap::predeclared_location();
7031 go_assert(Map_type::zero_value != NULL);
7033 Type* uint8_type = Type::lookup_integer_type("uint8");
7034 Btype* buint8_type = uint8_type->get_backend(gogo);
7036 Type* int_type = Type::lookup_integer_type("int");
7038 Expression* e = Expression::make_integer_int64(Map_type::zero_value_size,
7039 int_type, bloc);
7040 Translate_context context(gogo, NULL, NULL, NULL);
7041 Bexpression* blength = e->get_backend(&context);
7043 Btype* barray_type = gogo->backend()->array_type(buint8_type, blength);
7045 std::string zname = Map_type::zero_value->name();
7046 std::string asm_name(go_selectively_encode_id(zname));
7047 Bvariable* zvar =
7048 gogo->backend()->implicit_variable(zname, asm_name,
7049 barray_type, false, true, true,
7050 Map_type::zero_value_align);
7051 gogo->backend()->implicit_variable_set_init(zvar, zname, barray_type,
7052 false, true, true, NULL);
7053 return zvar;
7056 // Traversal.
7059 Map_type::do_traverse(Traverse* traverse)
7061 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
7062 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
7063 return TRAVERSE_EXIT;
7064 return TRAVERSE_CONTINUE;
7067 // Check that the map type is OK.
7069 bool
7070 Map_type::do_verify()
7072 // The runtime support uses "map[void]void".
7073 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
7074 go_error_at(this->location_, "invalid map key type");
7075 return true;
7078 // Whether two map types are identical.
7080 bool
7081 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
7083 return (Type::are_identical(this->key_type(), t->key_type(),
7084 errors_are_identical, NULL)
7085 && Type::are_identical(this->val_type(), t->val_type(),
7086 errors_are_identical, NULL));
7089 // Hash code.
7091 unsigned int
7092 Map_type::do_hash_for_method(Gogo* gogo) const
7094 return (this->key_type_->hash_for_method(gogo)
7095 + this->val_type_->hash_for_method(gogo)
7096 + 2);
7099 // Get the backend representation for a map type. A map type is
7100 // represented as a pointer to a struct. The struct is hmap in
7101 // runtime/hashmap.go.
7103 Btype*
7104 Map_type::do_get_backend(Gogo* gogo)
7106 static Btype* backend_map_type;
7107 if (backend_map_type == NULL)
7109 std::vector<Backend::Btyped_identifier> bfields(8);
7111 Location bloc = Linemap::predeclared_location();
7113 Type* int_type = Type::lookup_integer_type("int");
7114 bfields[0].name = "count";
7115 bfields[0].btype = int_type->get_backend(gogo);
7116 bfields[0].location = bloc;
7118 Type* uint8_type = Type::lookup_integer_type("uint8");
7119 bfields[1].name = "flags";
7120 bfields[1].btype = uint8_type->get_backend(gogo);
7121 bfields[1].location = bloc;
7123 bfields[2].name = "B";
7124 bfields[2].btype = bfields[1].btype;
7125 bfields[2].location = bloc;
7127 Type* uint32_type = Type::lookup_integer_type("uint32");
7128 bfields[3].name = "hash0";
7129 bfields[3].btype = uint32_type->get_backend(gogo);
7130 bfields[3].location = bloc;
7132 Btype* bvt = gogo->backend()->void_type();
7133 Btype* bpvt = gogo->backend()->pointer_type(bvt);
7134 bfields[4].name = "buckets";
7135 bfields[4].btype = bpvt;
7136 bfields[4].location = bloc;
7138 bfields[5].name = "oldbuckets";
7139 bfields[5].btype = bpvt;
7140 bfields[5].location = bloc;
7142 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7143 bfields[6].name = "nevacuate";
7144 bfields[6].btype = uintptr_type->get_backend(gogo);
7145 bfields[6].location = bloc;
7147 bfields[7].name = "overflow";
7148 bfields[7].btype = bpvt;
7149 bfields[7].location = bloc;
7151 Btype *bt = gogo->backend()->struct_type(bfields);
7152 bt = gogo->backend()->named_type("runtime.hmap", bt, bloc);
7153 backend_map_type = gogo->backend()->pointer_type(bt);
7155 return backend_map_type;
7158 // The type of a map type descriptor.
7160 Type*
7161 Map_type::make_map_type_descriptor_type()
7163 static Type* ret;
7164 if (ret == NULL)
7166 Type* tdt = Type::make_type_descriptor_type();
7167 Type* ptdt = Type::make_type_descriptor_ptr_type();
7168 Type* uint8_type = Type::lookup_integer_type("uint8");
7169 Type* uint16_type = Type::lookup_integer_type("uint16");
7170 Type* bool_type = Type::lookup_bool_type();
7172 Struct_type* sf =
7173 Type::make_builtin_struct_type(12,
7174 "", tdt,
7175 "key", ptdt,
7176 "elem", ptdt,
7177 "bucket", ptdt,
7178 "hmap", ptdt,
7179 "keysize", uint8_type,
7180 "indirectkey", bool_type,
7181 "valuesize", uint8_type,
7182 "indirectvalue", bool_type,
7183 "bucketsize", uint16_type,
7184 "reflexivekey", bool_type,
7185 "needkeyupdate", bool_type);
7187 ret = Type::make_builtin_named_type("MapType", sf);
7190 return ret;
7193 // Build a type descriptor for a map type.
7195 Expression*
7196 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7198 Location bloc = Linemap::predeclared_location();
7200 Type* mtdt = Map_type::make_map_type_descriptor_type();
7201 Type* uint8_type = Type::lookup_integer_type("uint8");
7202 Type* uint16_type = Type::lookup_integer_type("uint16");
7204 int64_t keysize;
7205 if (!this->key_type_->backend_type_size(gogo, &keysize))
7207 go_error_at(this->location_, "error determining map key type size");
7208 return Expression::make_error(this->location_);
7211 int64_t valsize;
7212 if (!this->val_type_->backend_type_size(gogo, &valsize))
7214 go_error_at(this->location_, "error determining map value type size");
7215 return Expression::make_error(this->location_);
7218 int64_t ptrsize;
7219 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptrsize))
7221 go_assert(saw_errors());
7222 return Expression::make_error(this->location_);
7225 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
7226 if (bucket_type == NULL)
7228 go_assert(saw_errors());
7229 return Expression::make_error(this->location_);
7232 int64_t bucketsize;
7233 if (!bucket_type->backend_type_size(gogo, &bucketsize))
7235 go_assert(saw_errors());
7236 return Expression::make_error(this->location_);
7239 const Struct_field_list* fields = mtdt->struct_type()->fields();
7241 Expression_list* vals = new Expression_list();
7242 vals->reserve(12);
7244 Struct_field_list::const_iterator p = fields->begin();
7245 go_assert(p->is_field_name("commonType"));
7246 vals->push_back(this->type_descriptor_constructor(gogo,
7247 RUNTIME_TYPE_KIND_MAP,
7248 name, NULL, true));
7250 ++p;
7251 go_assert(p->is_field_name("key"));
7252 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
7254 ++p;
7255 go_assert(p->is_field_name("elem"));
7256 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
7258 ++p;
7259 go_assert(p->is_field_name("bucket"));
7260 vals->push_back(Expression::make_type_descriptor(bucket_type, bloc));
7262 ++p;
7263 go_assert(p->is_field_name("hmap"));
7264 Type* hmap_type = this->hmap_type(bucket_type);
7265 vals->push_back(Expression::make_type_descriptor(hmap_type, bloc));
7267 ++p;
7268 go_assert(p->is_field_name("keysize"));
7269 if (keysize > Map_type::max_key_size)
7270 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
7271 else
7272 vals->push_back(Expression::make_integer_int64(keysize, uint8_type, bloc));
7274 ++p;
7275 go_assert(p->is_field_name("indirectkey"));
7276 vals->push_back(Expression::make_boolean(keysize > Map_type::max_key_size,
7277 bloc));
7279 ++p;
7280 go_assert(p->is_field_name("valuesize"));
7281 if (valsize > Map_type::max_val_size)
7282 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
7283 else
7284 vals->push_back(Expression::make_integer_int64(valsize, uint8_type, bloc));
7286 ++p;
7287 go_assert(p->is_field_name("indirectvalue"));
7288 vals->push_back(Expression::make_boolean(valsize > Map_type::max_val_size,
7289 bloc));
7291 ++p;
7292 go_assert(p->is_field_name("bucketsize"));
7293 vals->push_back(Expression::make_integer_int64(bucketsize, uint16_type,
7294 bloc));
7296 ++p;
7297 go_assert(p->is_field_name("reflexivekey"));
7298 vals->push_back(Expression::make_boolean(this->key_type_->is_reflexive(),
7299 bloc));
7301 ++p;
7302 go_assert(p->is_field_name("needkeyupdate"));
7303 vals->push_back(Expression::make_boolean(this->key_type_->needs_key_update(),
7304 bloc));
7306 ++p;
7307 go_assert(p == fields->end());
7309 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
7312 // Return the bucket type to use for a map type. This must correspond
7313 // to libgo/go/runtime/hashmap.go.
7315 Type*
7316 Map_type::bucket_type(Gogo* gogo, int64_t keysize, int64_t valsize)
7318 if (this->bucket_type_ != NULL)
7319 return this->bucket_type_;
7321 Type* key_type = this->key_type_;
7322 if (keysize > Map_type::max_key_size)
7323 key_type = Type::make_pointer_type(key_type);
7325 Type* val_type = this->val_type_;
7326 if (valsize > Map_type::max_val_size)
7327 val_type = Type::make_pointer_type(val_type);
7329 Expression* bucket_size = Expression::make_integer_ul(Map_type::bucket_size,
7330 NULL, this->location_);
7332 Type* uint8_type = Type::lookup_integer_type("uint8");
7333 Array_type* topbits_type = Type::make_array_type(uint8_type, bucket_size);
7334 topbits_type->set_is_array_incomparable();
7335 Array_type* keys_type = Type::make_array_type(key_type, bucket_size);
7336 keys_type->set_is_array_incomparable();
7337 Array_type* values_type = Type::make_array_type(val_type, bucket_size);
7338 values_type->set_is_array_incomparable();
7340 // If keys and values have no pointers, the map implementation can
7341 // keep a list of overflow pointers on the side so that buckets can
7342 // be marked as having no pointers. Arrange for the bucket to have
7343 // no pointers by changing the type of the overflow field to uintptr
7344 // in this case. See comment on the hmap.overflow field in
7345 // libgo/go/runtime/hashmap.go.
7346 Type* overflow_type;
7347 if (!key_type->has_pointer() && !val_type->has_pointer())
7348 overflow_type = Type::lookup_integer_type("uintptr");
7349 else
7351 // This should really be a pointer to the bucket type itself,
7352 // but that would require us to construct a Named_type for it to
7353 // give it a way to refer to itself. Since nothing really cares
7354 // (except perhaps for someone using a debugger) just use an
7355 // unsafe pointer.
7356 overflow_type = Type::make_pointer_type(Type::make_void_type());
7359 // Make sure the overflow pointer is the last memory in the struct,
7360 // because the runtime assumes it can use size-ptrSize as the offset
7361 // of the overflow pointer. We double-check that property below
7362 // once the offsets and size are computed.
7364 int64_t topbits_field_size, topbits_field_align;
7365 int64_t keys_field_size, keys_field_align;
7366 int64_t values_field_size, values_field_align;
7367 int64_t overflow_field_size, overflow_field_align;
7368 if (!topbits_type->backend_type_size(gogo, &topbits_field_size)
7369 || !topbits_type->backend_type_field_align(gogo, &topbits_field_align)
7370 || !keys_type->backend_type_size(gogo, &keys_field_size)
7371 || !keys_type->backend_type_field_align(gogo, &keys_field_align)
7372 || !values_type->backend_type_size(gogo, &values_field_size)
7373 || !values_type->backend_type_field_align(gogo, &values_field_align)
7374 || !overflow_type->backend_type_size(gogo, &overflow_field_size)
7375 || !overflow_type->backend_type_field_align(gogo, &overflow_field_align))
7377 go_assert(saw_errors());
7378 return NULL;
7381 Struct_type* ret;
7382 int64_t max_align = std::max(std::max(topbits_field_align, keys_field_align),
7383 values_field_align);
7384 if (max_align <= overflow_field_align)
7385 ret = make_builtin_struct_type(4,
7386 "topbits", topbits_type,
7387 "keys", keys_type,
7388 "values", values_type,
7389 "overflow", overflow_type);
7390 else
7392 size_t off = topbits_field_size;
7393 off = ((off + keys_field_align - 1)
7394 &~ static_cast<size_t>(keys_field_align - 1));
7395 off += keys_field_size;
7396 off = ((off + values_field_align - 1)
7397 &~ static_cast<size_t>(values_field_align - 1));
7398 off += values_field_size;
7400 int64_t padded_overflow_field_size =
7401 ((overflow_field_size + max_align - 1)
7402 &~ static_cast<size_t>(max_align - 1));
7404 size_t ovoff = off;
7405 ovoff = ((ovoff + max_align - 1)
7406 &~ static_cast<size_t>(max_align - 1));
7407 size_t pad = (ovoff - off
7408 + padded_overflow_field_size - overflow_field_size);
7410 Expression* pad_expr = Expression::make_integer_ul(pad, NULL,
7411 this->location_);
7412 Type* pad_type = Type::make_array_type(uint8_type, pad_expr);
7414 ret = make_builtin_struct_type(5,
7415 "topbits", topbits_type,
7416 "keys", keys_type,
7417 "values", values_type,
7418 "pad", pad_type,
7419 "overflow", overflow_type);
7422 // Verify that the overflow field is just before the end of the
7423 // bucket type.
7425 Btype* btype = ret->get_backend(gogo);
7426 int64_t offset = gogo->backend()->type_field_offset(btype,
7427 ret->field_count() - 1);
7428 int64_t size;
7429 if (!ret->backend_type_size(gogo, &size))
7431 go_assert(saw_errors());
7432 return NULL;
7435 int64_t ptr_size;
7436 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptr_size))
7438 go_assert(saw_errors());
7439 return NULL;
7442 go_assert(offset + ptr_size == size);
7444 ret->set_is_struct_incomparable();
7446 this->bucket_type_ = ret;
7447 return ret;
7450 // Return the hashmap type for a map type.
7452 Type*
7453 Map_type::hmap_type(Type* bucket_type)
7455 if (this->hmap_type_ != NULL)
7456 return this->hmap_type_;
7458 Type* int_type = Type::lookup_integer_type("int");
7459 Type* uint8_type = Type::lookup_integer_type("uint8");
7460 Type* uint32_type = Type::lookup_integer_type("uint32");
7461 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7462 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
7464 Type* ptr_bucket_type = Type::make_pointer_type(bucket_type);
7466 Struct_type* ret = make_builtin_struct_type(8,
7467 "count", int_type,
7468 "flags", uint8_type,
7469 "B", uint8_type,
7470 "hash0", uint32_type,
7471 "buckets", ptr_bucket_type,
7472 "oldbuckets", ptr_bucket_type,
7473 "nevacuate", uintptr_type,
7474 "overflow", void_ptr_type);
7475 ret->set_is_struct_incomparable();
7476 this->hmap_type_ = ret;
7477 return ret;
7480 // Return the iterator type for a map type. This is the type of the
7481 // value used when doing a range over a map.
7483 Type*
7484 Map_type::hiter_type(Gogo* gogo)
7486 if (this->hiter_type_ != NULL)
7487 return this->hiter_type_;
7489 int64_t keysize, valsize;
7490 if (!this->key_type_->backend_type_size(gogo, &keysize)
7491 || !this->val_type_->backend_type_size(gogo, &valsize))
7493 go_assert(saw_errors());
7494 return NULL;
7497 Type* key_ptr_type = Type::make_pointer_type(this->key_type_);
7498 Type* val_ptr_type = Type::make_pointer_type(this->val_type_);
7499 Type* uint8_type = Type::lookup_integer_type("uint8");
7500 Type* uint8_ptr_type = Type::make_pointer_type(uint8_type);
7501 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7502 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
7503 Type* bucket_ptr_type = Type::make_pointer_type(bucket_type);
7504 Type* hmap_type = this->hmap_type(bucket_type);
7505 Type* hmap_ptr_type = Type::make_pointer_type(hmap_type);
7506 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
7508 Struct_type* ret = make_builtin_struct_type(12,
7509 "key", key_ptr_type,
7510 "val", val_ptr_type,
7511 "t", uint8_ptr_type,
7512 "h", hmap_ptr_type,
7513 "buckets", bucket_ptr_type,
7514 "bptr", bucket_ptr_type,
7515 "overflow0", void_ptr_type,
7516 "overflow1", void_ptr_type,
7517 "startBucket", uintptr_type,
7518 "stuff", uintptr_type,
7519 "bucket", uintptr_type,
7520 "checkBucket", uintptr_type);
7521 ret->set_is_struct_incomparable();
7522 this->hiter_type_ = ret;
7523 return ret;
7526 // Reflection string for a map.
7528 void
7529 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
7531 ret->append("map[");
7532 this->append_reflection(this->key_type_, gogo, ret);
7533 ret->append("]");
7534 this->append_reflection(this->val_type_, gogo, ret);
7537 // Generate GC symbol for a map.
7539 void
7540 Map_type::do_gc_symbol(Gogo*, Expression_list** vals,
7541 Expression** offset, int)
7543 // TODO(cmang): Generate GC data for the Map elements.
7544 Location bloc = Linemap::predeclared_location();
7545 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7547 (*vals)->push_back(Expression::make_integer_ul(GC_APTR, uintptr_type, bloc));
7548 (*vals)->push_back(*offset);
7549 this->advance_gc_offset(offset);
7552 // Mangled name for a map.
7554 void
7555 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7557 ret->push_back('M');
7558 this->append_mangled_name(this->key_type_, gogo, ret);
7559 ret->append("__");
7560 this->append_mangled_name(this->val_type_, gogo, ret);
7563 // Export a map type.
7565 void
7566 Map_type::do_export(Export* exp) const
7568 exp->write_c_string("map [");
7569 exp->write_type(this->key_type_);
7570 exp->write_c_string("] ");
7571 exp->write_type(this->val_type_);
7574 // Import a map type.
7576 Map_type*
7577 Map_type::do_import(Import* imp)
7579 imp->require_c_string("map [");
7580 Type* key_type = imp->read_type();
7581 imp->require_c_string("] ");
7582 Type* val_type = imp->read_type();
7583 return Type::make_map_type(key_type, val_type, imp->location());
7586 // Make a map type.
7588 Map_type*
7589 Type::make_map_type(Type* key_type, Type* val_type, Location location)
7591 return new Map_type(key_type, val_type, location);
7594 // Class Channel_type.
7596 // Hash code.
7598 unsigned int
7599 Channel_type::do_hash_for_method(Gogo* gogo) const
7601 unsigned int ret = 0;
7602 if (this->may_send_)
7603 ret += 1;
7604 if (this->may_receive_)
7605 ret += 2;
7606 if (this->element_type_ != NULL)
7607 ret += this->element_type_->hash_for_method(gogo) << 2;
7608 return ret << 3;
7611 // Whether this type is the same as T.
7613 bool
7614 Channel_type::is_identical(const Channel_type* t,
7615 bool errors_are_identical) const
7617 if (!Type::are_identical(this->element_type(), t->element_type(),
7618 errors_are_identical, NULL))
7619 return false;
7620 return (this->may_send_ == t->may_send_
7621 && this->may_receive_ == t->may_receive_);
7624 // Return the backend representation for a channel type. A channel is a pointer
7625 // to a __go_channel struct. The __go_channel struct is defined in
7626 // libgo/runtime/channel.h.
7628 Btype*
7629 Channel_type::do_get_backend(Gogo* gogo)
7631 static Btype* backend_channel_type;
7632 if (backend_channel_type == NULL)
7634 std::vector<Backend::Btyped_identifier> bfields;
7635 Btype* bt = gogo->backend()->struct_type(bfields);
7636 bt = gogo->backend()->named_type("__go_channel", bt,
7637 Linemap::predeclared_location());
7638 backend_channel_type = gogo->backend()->pointer_type(bt);
7640 return backend_channel_type;
7643 // Build a type descriptor for a channel type.
7645 Type*
7646 Channel_type::make_chan_type_descriptor_type()
7648 static Type* ret;
7649 if (ret == NULL)
7651 Type* tdt = Type::make_type_descriptor_type();
7652 Type* ptdt = Type::make_type_descriptor_ptr_type();
7654 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7656 Struct_type* sf =
7657 Type::make_builtin_struct_type(3,
7658 "", tdt,
7659 "elem", ptdt,
7660 "dir", uintptr_type);
7662 ret = Type::make_builtin_named_type("ChanType", sf);
7665 return ret;
7668 // Build a type descriptor for a map type.
7670 Expression*
7671 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7673 Location bloc = Linemap::predeclared_location();
7675 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
7677 const Struct_field_list* fields = ctdt->struct_type()->fields();
7679 Expression_list* vals = new Expression_list();
7680 vals->reserve(3);
7682 Struct_field_list::const_iterator p = fields->begin();
7683 go_assert(p->is_field_name("commonType"));
7684 vals->push_back(this->type_descriptor_constructor(gogo,
7685 RUNTIME_TYPE_KIND_CHAN,
7686 name, NULL, true));
7688 ++p;
7689 go_assert(p->is_field_name("elem"));
7690 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7692 ++p;
7693 go_assert(p->is_field_name("dir"));
7694 // These bits must match the ones in libgo/runtime/go-type.h.
7695 int val = 0;
7696 if (this->may_receive_)
7697 val |= 1;
7698 if (this->may_send_)
7699 val |= 2;
7700 vals->push_back(Expression::make_integer_ul(val, p->type(), bloc));
7702 ++p;
7703 go_assert(p == fields->end());
7705 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
7708 // Reflection string.
7710 void
7711 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
7713 if (!this->may_send_)
7714 ret->append("<-");
7715 ret->append("chan");
7716 if (!this->may_receive_)
7717 ret->append("<-");
7718 ret->push_back(' ');
7719 this->append_reflection(this->element_type_, gogo, ret);
7722 // Generate GC symbol for channels.
7724 void
7725 Channel_type::do_gc_symbol(Gogo*, Expression_list** vals,
7726 Expression** offset, int)
7728 Location bloc = Linemap::predeclared_location();
7729 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7731 (*vals)->push_back(Expression::make_integer_ul(GC_CHAN_PTR, uintptr_type,
7732 bloc));
7733 (*vals)->push_back(*offset);
7735 Type* unsafeptr_type = Type::make_pointer_type(Type::make_void_type());
7736 Expression* type_descriptor =
7737 Expression::make_type_descriptor(this, bloc);
7738 type_descriptor =
7739 Expression::make_unsafe_cast(unsafeptr_type, type_descriptor, bloc);
7740 (*vals)->push_back(type_descriptor);
7741 this->advance_gc_offset(offset);
7744 // Mangled name.
7746 void
7747 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7749 ret->push_back('C');
7750 this->append_mangled_name(this->element_type_, gogo, ret);
7751 if (this->may_send_)
7752 ret->push_back('s');
7753 if (this->may_receive_)
7754 ret->push_back('r');
7755 ret->push_back('e');
7758 // Export.
7760 void
7761 Channel_type::do_export(Export* exp) const
7763 exp->write_c_string("chan ");
7764 if (this->may_send_ && !this->may_receive_)
7765 exp->write_c_string("-< ");
7766 else if (this->may_receive_ && !this->may_send_)
7767 exp->write_c_string("<- ");
7768 exp->write_type(this->element_type_);
7771 // Import.
7773 Channel_type*
7774 Channel_type::do_import(Import* imp)
7776 imp->require_c_string("chan ");
7778 bool may_send;
7779 bool may_receive;
7780 if (imp->match_c_string("-< "))
7782 imp->advance(3);
7783 may_send = true;
7784 may_receive = false;
7786 else if (imp->match_c_string("<- "))
7788 imp->advance(3);
7789 may_receive = true;
7790 may_send = false;
7792 else
7794 may_send = true;
7795 may_receive = true;
7798 Type* element_type = imp->read_type();
7800 return Type::make_channel_type(may_send, may_receive, element_type);
7803 // Return the type to manage a select statement with ncases case
7804 // statements. A value of this type is allocated on the stack. This
7805 // must match the type hselect in libgo/go/runtime/select.go.
7807 Type*
7808 Channel_type::select_type(int ncases)
7810 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
7811 Type* uint16_type = Type::lookup_integer_type("uint16");
7813 static Struct_type* scase_type;
7814 if (scase_type == NULL)
7816 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7817 Type* uint64_type = Type::lookup_integer_type("uint64");
7818 scase_type =
7819 Type::make_builtin_struct_type(7,
7820 "elem", unsafe_pointer_type,
7821 "chan", unsafe_pointer_type,
7822 "pc", uintptr_type,
7823 "kind", uint16_type,
7824 "index", uint16_type,
7825 "receivedp", unsafe_pointer_type,
7826 "releasetime", uint64_type);
7827 scase_type->set_is_struct_incomparable();
7830 Expression* ncases_expr =
7831 Expression::make_integer_ul(ncases, NULL, Linemap::predeclared_location());
7832 Array_type* scases = Type::make_array_type(scase_type, ncases_expr);
7833 scases->set_is_array_incomparable();
7834 Array_type* order = Type::make_array_type(uint16_type, ncases_expr);
7835 order->set_is_array_incomparable();
7837 Struct_type* ret =
7838 Type::make_builtin_struct_type(7,
7839 "tcase", uint16_type,
7840 "ncase", uint16_type,
7841 "pollorder", unsafe_pointer_type,
7842 "lockorder", unsafe_pointer_type,
7843 "scase", scases,
7844 "lockorderarr", order,
7845 "pollorderarr", order);
7846 ret->set_is_struct_incomparable();
7847 return ret;
7850 // Make a new channel type.
7852 Channel_type*
7853 Type::make_channel_type(bool send, bool receive, Type* element_type)
7855 return new Channel_type(send, receive, element_type);
7858 // Class Interface_type.
7860 // Return the list of methods.
7862 const Typed_identifier_list*
7863 Interface_type::methods() const
7865 go_assert(this->methods_are_finalized_ || saw_errors());
7866 return this->all_methods_;
7869 // Return the number of methods.
7871 size_t
7872 Interface_type::method_count() const
7874 go_assert(this->methods_are_finalized_ || saw_errors());
7875 return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
7878 // Traversal.
7881 Interface_type::do_traverse(Traverse* traverse)
7883 Typed_identifier_list* methods = (this->methods_are_finalized_
7884 ? this->all_methods_
7885 : this->parse_methods_);
7886 if (methods == NULL)
7887 return TRAVERSE_CONTINUE;
7888 return methods->traverse(traverse);
7891 // Finalize the methods. This handles interface inheritance.
7893 void
7894 Interface_type::finalize_methods()
7896 if (this->methods_are_finalized_)
7897 return;
7898 this->methods_are_finalized_ = true;
7899 if (this->parse_methods_ == NULL)
7900 return;
7902 this->all_methods_ = new Typed_identifier_list();
7903 this->all_methods_->reserve(this->parse_methods_->size());
7904 Typed_identifier_list inherit;
7905 for (Typed_identifier_list::const_iterator pm =
7906 this->parse_methods_->begin();
7907 pm != this->parse_methods_->end();
7908 ++pm)
7910 const Typed_identifier* p = &*pm;
7911 if (p->name().empty())
7912 inherit.push_back(*p);
7913 else if (this->find_method(p->name()) == NULL)
7914 this->all_methods_->push_back(*p);
7915 else
7916 go_error_at(p->location(), "duplicate method %qs",
7917 Gogo::message_name(p->name()).c_str());
7920 std::vector<Named_type*> seen;
7921 seen.reserve(inherit.size());
7922 bool issued_recursive_error = false;
7923 while (!inherit.empty())
7925 Type* t = inherit.back().type();
7926 Location tl = inherit.back().location();
7927 inherit.pop_back();
7929 Interface_type* it = t->interface_type();
7930 if (it == NULL)
7932 if (!t->is_error())
7933 go_error_at(tl, "interface contains embedded non-interface");
7934 continue;
7936 if (it == this)
7938 if (!issued_recursive_error)
7940 go_error_at(tl, "invalid recursive interface");
7941 issued_recursive_error = true;
7943 continue;
7946 Named_type* nt = t->named_type();
7947 if (nt != NULL && it->parse_methods_ != NULL)
7949 std::vector<Named_type*>::const_iterator q;
7950 for (q = seen.begin(); q != seen.end(); ++q)
7952 if (*q == nt)
7954 go_error_at(tl, "inherited interface loop");
7955 break;
7958 if (q != seen.end())
7959 continue;
7960 seen.push_back(nt);
7963 const Typed_identifier_list* imethods = it->parse_methods_;
7964 if (imethods == NULL)
7965 continue;
7966 for (Typed_identifier_list::const_iterator q = imethods->begin();
7967 q != imethods->end();
7968 ++q)
7970 if (q->name().empty())
7971 inherit.push_back(*q);
7972 else if (this->find_method(q->name()) == NULL)
7973 this->all_methods_->push_back(Typed_identifier(q->name(),
7974 q->type(), tl));
7975 else
7976 go_error_at(tl, "inherited method %qs is ambiguous",
7977 Gogo::message_name(q->name()).c_str());
7981 if (!this->all_methods_->empty())
7982 this->all_methods_->sort_by_name();
7983 else
7985 delete this->all_methods_;
7986 this->all_methods_ = NULL;
7990 // Return the method NAME, or NULL.
7992 const Typed_identifier*
7993 Interface_type::find_method(const std::string& name) const
7995 go_assert(this->methods_are_finalized_);
7996 if (this->all_methods_ == NULL)
7997 return NULL;
7998 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
7999 p != this->all_methods_->end();
8000 ++p)
8001 if (p->name() == name)
8002 return &*p;
8003 return NULL;
8006 // Return the method index.
8008 size_t
8009 Interface_type::method_index(const std::string& name) const
8011 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
8012 size_t ret = 0;
8013 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8014 p != this->all_methods_->end();
8015 ++p, ++ret)
8016 if (p->name() == name)
8017 return ret;
8018 go_unreachable();
8021 // Return whether NAME is an unexported method, for better error
8022 // reporting.
8024 bool
8025 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
8027 go_assert(this->methods_are_finalized_);
8028 if (this->all_methods_ == NULL)
8029 return false;
8030 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8031 p != this->all_methods_->end();
8032 ++p)
8034 const std::string& method_name(p->name());
8035 if (Gogo::is_hidden_name(method_name)
8036 && name == Gogo::unpack_hidden_name(method_name)
8037 && gogo->pack_hidden_name(name, false) != method_name)
8038 return true;
8040 return false;
8043 // Whether this type is identical with T.
8045 bool
8046 Interface_type::is_identical(const Interface_type* t,
8047 bool errors_are_identical) const
8049 // If methods have not been finalized, then we are asking whether
8050 // func redeclarations are the same. This is an error, so for
8051 // simplicity we say they are never the same.
8052 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
8053 return false;
8055 // We require the same methods with the same types. The methods
8056 // have already been sorted.
8057 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
8058 return this->all_methods_ == t->all_methods_;
8060 if (this->assume_identical(this, t) || t->assume_identical(t, this))
8061 return true;
8063 Assume_identical* hold_ai = this->assume_identical_;
8064 Assume_identical ai;
8065 ai.t1 = this;
8066 ai.t2 = t;
8067 ai.next = hold_ai;
8068 this->assume_identical_ = &ai;
8070 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
8071 Typed_identifier_list::const_iterator p2;
8072 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
8074 if (p1 == this->all_methods_->end())
8075 break;
8076 if (p1->name() != p2->name()
8077 || !Type::are_identical(p1->type(), p2->type(),
8078 errors_are_identical, NULL))
8079 break;
8082 this->assume_identical_ = hold_ai;
8084 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
8087 // Return true if T1 and T2 are assumed to be identical during a type
8088 // comparison.
8090 bool
8091 Interface_type::assume_identical(const Interface_type* t1,
8092 const Interface_type* t2) const
8094 for (Assume_identical* p = this->assume_identical_;
8095 p != NULL;
8096 p = p->next)
8097 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
8098 return true;
8099 return false;
8102 // Whether we can assign the interface type T to this type. The types
8103 // are known to not be identical. An interface assignment is only
8104 // permitted if T is known to implement all methods in THIS.
8105 // Otherwise a type guard is required.
8107 bool
8108 Interface_type::is_compatible_for_assign(const Interface_type* t,
8109 std::string* reason) const
8111 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
8112 if (this->all_methods_ == NULL)
8113 return true;
8114 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8115 p != this->all_methods_->end();
8116 ++p)
8118 const Typed_identifier* m = t->find_method(p->name());
8119 if (m == NULL)
8121 if (reason != NULL)
8123 char buf[200];
8124 snprintf(buf, sizeof buf,
8125 _("need explicit conversion; missing method %s%s%s"),
8126 go_open_quote(), Gogo::message_name(p->name()).c_str(),
8127 go_close_quote());
8128 reason->assign(buf);
8130 return false;
8133 std::string subreason;
8134 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
8136 if (reason != NULL)
8138 std::string n = Gogo::message_name(p->name());
8139 size_t len = 100 + n.length() + subreason.length();
8140 char* buf = new char[len];
8141 if (subreason.empty())
8142 snprintf(buf, len, _("incompatible type for method %s%s%s"),
8143 go_open_quote(), n.c_str(), go_close_quote());
8144 else
8145 snprintf(buf, len,
8146 _("incompatible type for method %s%s%s (%s)"),
8147 go_open_quote(), n.c_str(), go_close_quote(),
8148 subreason.c_str());
8149 reason->assign(buf);
8150 delete[] buf;
8152 return false;
8156 return true;
8159 // Hash code.
8161 unsigned int
8162 Interface_type::do_hash_for_method(Gogo*) const
8164 go_assert(this->methods_are_finalized_);
8165 unsigned int ret = 0;
8166 if (this->all_methods_ != NULL)
8168 for (Typed_identifier_list::const_iterator p =
8169 this->all_methods_->begin();
8170 p != this->all_methods_->end();
8171 ++p)
8173 ret = Type::hash_string(p->name(), ret);
8174 // We don't use the method type in the hash, to avoid
8175 // infinite recursion if an interface method uses a type
8176 // which is an interface which inherits from the interface
8177 // itself.
8178 // type T interface { F() interface {T}}
8179 ret <<= 1;
8182 return ret;
8185 // Return true if T implements the interface. If it does not, and
8186 // REASON is not NULL, set *REASON to a useful error message.
8188 bool
8189 Interface_type::implements_interface(const Type* t, std::string* reason) const
8191 go_assert(this->methods_are_finalized_);
8192 if (this->all_methods_ == NULL)
8193 return true;
8195 bool is_pointer = false;
8196 const Named_type* nt = t->named_type();
8197 const Struct_type* st = t->struct_type();
8198 // If we start with a named type, we don't dereference it to find
8199 // methods.
8200 if (nt == NULL)
8202 const Type* pt = t->points_to();
8203 if (pt != NULL)
8205 // If T is a pointer to a named type, then we need to look at
8206 // the type to which it points.
8207 is_pointer = true;
8208 nt = pt->named_type();
8209 st = pt->struct_type();
8213 // If we have a named type, get the methods from it rather than from
8214 // any struct type.
8215 if (nt != NULL)
8216 st = NULL;
8218 // Only named and struct types have methods.
8219 if (nt == NULL && st == NULL)
8221 if (reason != NULL)
8223 if (t->points_to() != NULL
8224 && t->points_to()->interface_type() != NULL)
8225 reason->assign(_("pointer to interface type has no methods"));
8226 else
8227 reason->assign(_("type has no methods"));
8229 return false;
8232 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
8234 if (reason != NULL)
8236 if (t->points_to() != NULL
8237 && t->points_to()->interface_type() != NULL)
8238 reason->assign(_("pointer to interface type has no methods"));
8239 else
8240 reason->assign(_("type has no methods"));
8242 return false;
8245 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8246 p != this->all_methods_->end();
8247 ++p)
8249 bool is_ambiguous = false;
8250 Method* m = (nt != NULL
8251 ? nt->method_function(p->name(), &is_ambiguous)
8252 : st->method_function(p->name(), &is_ambiguous));
8253 if (m == NULL)
8255 if (reason != NULL)
8257 std::string n = Gogo::message_name(p->name());
8258 size_t len = n.length() + 100;
8259 char* buf = new char[len];
8260 if (is_ambiguous)
8261 snprintf(buf, len, _("ambiguous method %s%s%s"),
8262 go_open_quote(), n.c_str(), go_close_quote());
8263 else
8264 snprintf(buf, len, _("missing method %s%s%s"),
8265 go_open_quote(), n.c_str(), go_close_quote());
8266 reason->assign(buf);
8267 delete[] buf;
8269 return false;
8272 Function_type *p_fn_type = p->type()->function_type();
8273 Function_type* m_fn_type = m->type()->function_type();
8274 go_assert(p_fn_type != NULL && m_fn_type != NULL);
8275 std::string subreason;
8276 if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
8278 if (reason != NULL)
8280 std::string n = Gogo::message_name(p->name());
8281 size_t len = 100 + n.length() + subreason.length();
8282 char* buf = new char[len];
8283 if (subreason.empty())
8284 snprintf(buf, len, _("incompatible type for method %s%s%s"),
8285 go_open_quote(), n.c_str(), go_close_quote());
8286 else
8287 snprintf(buf, len,
8288 _("incompatible type for method %s%s%s (%s)"),
8289 go_open_quote(), n.c_str(), go_close_quote(),
8290 subreason.c_str());
8291 reason->assign(buf);
8292 delete[] buf;
8294 return false;
8297 if (!is_pointer && !m->is_value_method())
8299 if (reason != NULL)
8301 std::string n = Gogo::message_name(p->name());
8302 size_t len = 100 + n.length();
8303 char* buf = new char[len];
8304 snprintf(buf, len,
8305 _("method %s%s%s requires a pointer receiver"),
8306 go_open_quote(), n.c_str(), go_close_quote());
8307 reason->assign(buf);
8308 delete[] buf;
8310 return false;
8313 // If the magic //go:nointerface comment was used, the method
8314 // may not be used to implement interfaces.
8315 if (m->nointerface())
8317 if (reason != NULL)
8319 std::string n = Gogo::message_name(p->name());
8320 size_t len = 100 + n.length();
8321 char* buf = new char[len];
8322 snprintf(buf, len,
8323 _("method %s%s%s is marked go:nointerface"),
8324 go_open_quote(), n.c_str(), go_close_quote());
8325 reason->assign(buf);
8326 delete[] buf;
8328 return false;
8332 return true;
8335 // Return the backend representation of the empty interface type. We
8336 // use the same struct for all empty interfaces.
8338 Btype*
8339 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
8341 static Btype* empty_interface_type;
8342 if (empty_interface_type == NULL)
8344 std::vector<Backend::Btyped_identifier> bfields(2);
8346 Location bloc = Linemap::predeclared_location();
8348 Type* pdt = Type::make_type_descriptor_ptr_type();
8349 bfields[0].name = "__type_descriptor";
8350 bfields[0].btype = pdt->get_backend(gogo);
8351 bfields[0].location = bloc;
8353 Type* vt = Type::make_pointer_type(Type::make_void_type());
8354 bfields[1].name = "__object";
8355 bfields[1].btype = vt->get_backend(gogo);
8356 bfields[1].location = bloc;
8358 empty_interface_type = gogo->backend()->struct_type(bfields);
8360 return empty_interface_type;
8363 // Return a pointer to the backend representation of the method table.
8365 Btype*
8366 Interface_type::get_backend_methods(Gogo* gogo)
8368 if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
8369 return this->bmethods_;
8371 Location loc = this->location();
8373 std::vector<Backend::Btyped_identifier>
8374 mfields(this->all_methods_->size() + 1);
8376 Type* pdt = Type::make_type_descriptor_ptr_type();
8377 mfields[0].name = "__type_descriptor";
8378 mfields[0].btype = pdt->get_backend(gogo);
8379 mfields[0].location = loc;
8381 std::string last_name = "";
8382 size_t i = 1;
8383 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8384 p != this->all_methods_->end();
8385 ++p, ++i)
8387 // The type of the method in Go only includes the parameters.
8388 // The actual method also has a receiver, which is always a
8389 // pointer. We need to add that pointer type here in order to
8390 // generate the correct type for the backend.
8391 Function_type* ft = p->type()->function_type();
8392 go_assert(ft->receiver() == NULL);
8394 const Typed_identifier_list* params = ft->parameters();
8395 Typed_identifier_list* mparams = new Typed_identifier_list();
8396 if (params != NULL)
8397 mparams->reserve(params->size() + 1);
8398 Type* vt = Type::make_pointer_type(Type::make_void_type());
8399 mparams->push_back(Typed_identifier("", vt, ft->location()));
8400 if (params != NULL)
8402 for (Typed_identifier_list::const_iterator pp = params->begin();
8403 pp != params->end();
8404 ++pp)
8405 mparams->push_back(*pp);
8408 Typed_identifier_list* mresults = (ft->results() == NULL
8409 ? NULL
8410 : ft->results()->copy());
8411 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
8412 ft->location());
8414 mfields[i].name = Gogo::unpack_hidden_name(p->name());
8415 mfields[i].btype = mft->get_backend_fntype(gogo);
8416 mfields[i].location = loc;
8418 // Sanity check: the names should be sorted.
8419 go_assert(Gogo::unpack_hidden_name(p->name())
8420 > Gogo::unpack_hidden_name(last_name));
8421 last_name = p->name();
8424 Btype* st = gogo->backend()->struct_type(mfields);
8425 Btype* ret = gogo->backend()->pointer_type(st);
8427 if (this->bmethods_ != NULL && this->bmethods_is_placeholder_)
8428 gogo->backend()->set_placeholder_pointer_type(this->bmethods_, ret);
8429 this->bmethods_ = ret;
8430 this->bmethods_is_placeholder_ = false;
8431 return ret;
8434 // Return a placeholder for the pointer to the backend methods table.
8436 Btype*
8437 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
8439 if (this->bmethods_ == NULL)
8441 Location loc = this->location();
8442 this->bmethods_ = gogo->backend()->placeholder_pointer_type("", loc,
8443 false);
8444 this->bmethods_is_placeholder_ = true;
8446 return this->bmethods_;
8449 // Return the fields of a non-empty interface type. This is not
8450 // declared in types.h so that types.h doesn't have to #include
8451 // backend.h.
8453 static void
8454 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
8455 bool use_placeholder,
8456 std::vector<Backend::Btyped_identifier>* bfields)
8458 Location loc = type->location();
8460 bfields->resize(2);
8462 (*bfields)[0].name = "__methods";
8463 (*bfields)[0].btype = (use_placeholder
8464 ? type->get_backend_methods_placeholder(gogo)
8465 : type->get_backend_methods(gogo));
8466 (*bfields)[0].location = loc;
8468 Type* vt = Type::make_pointer_type(Type::make_void_type());
8469 (*bfields)[1].name = "__object";
8470 (*bfields)[1].btype = vt->get_backend(gogo);
8471 (*bfields)[1].location = Linemap::predeclared_location();
8474 // Return the backend representation for an interface type. An interface is a
8475 // pointer to a struct. The struct has three fields. The first field is a
8476 // pointer to the type descriptor for the dynamic type of the object.
8477 // The second field is a pointer to a table of methods for the
8478 // interface to be used with the object. The third field is the value
8479 // of the object itself.
8481 Btype*
8482 Interface_type::do_get_backend(Gogo* gogo)
8484 if (this->is_empty())
8485 return Interface_type::get_backend_empty_interface_type(gogo);
8486 else
8488 if (this->interface_btype_ != NULL)
8489 return this->interface_btype_;
8490 this->interface_btype_ =
8491 gogo->backend()->placeholder_struct_type("", this->location_);
8492 std::vector<Backend::Btyped_identifier> bfields;
8493 get_backend_interface_fields(gogo, this, false, &bfields);
8494 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
8495 bfields))
8496 this->interface_btype_ = gogo->backend()->error_type();
8497 return this->interface_btype_;
8501 // Finish the backend representation of the methods.
8503 void
8504 Interface_type::finish_backend_methods(Gogo* gogo)
8506 if (!this->is_empty())
8508 const Typed_identifier_list* methods = this->methods();
8509 if (methods != NULL)
8511 for (Typed_identifier_list::const_iterator p = methods->begin();
8512 p != methods->end();
8513 ++p)
8514 p->type()->get_backend(gogo);
8517 // Getting the backend methods now will set the placeholder
8518 // pointer.
8519 this->get_backend_methods(gogo);
8523 // The type of an interface type descriptor.
8525 Type*
8526 Interface_type::make_interface_type_descriptor_type()
8528 static Type* ret;
8529 if (ret == NULL)
8531 Type* tdt = Type::make_type_descriptor_type();
8532 Type* ptdt = Type::make_type_descriptor_ptr_type();
8534 Type* string_type = Type::lookup_string_type();
8535 Type* pointer_string_type = Type::make_pointer_type(string_type);
8537 Struct_type* sm =
8538 Type::make_builtin_struct_type(3,
8539 "name", pointer_string_type,
8540 "pkgPath", pointer_string_type,
8541 "typ", ptdt);
8543 Type* nsm = Type::make_builtin_named_type("imethod", sm);
8545 Type* slice_nsm = Type::make_array_type(nsm, NULL);
8547 Struct_type* s = Type::make_builtin_struct_type(2,
8548 "", tdt,
8549 "methods", slice_nsm);
8551 ret = Type::make_builtin_named_type("InterfaceType", s);
8554 return ret;
8557 // Build a type descriptor for an interface type.
8559 Expression*
8560 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8562 Location bloc = Linemap::predeclared_location();
8564 Type* itdt = Interface_type::make_interface_type_descriptor_type();
8566 const Struct_field_list* ifields = itdt->struct_type()->fields();
8568 Expression_list* ivals = new Expression_list();
8569 ivals->reserve(2);
8571 Struct_field_list::const_iterator pif = ifields->begin();
8572 go_assert(pif->is_field_name("commonType"));
8573 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
8574 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
8575 true));
8577 ++pif;
8578 go_assert(pif->is_field_name("methods"));
8580 Expression_list* methods = new Expression_list();
8581 if (this->all_methods_ != NULL)
8583 Type* elemtype = pif->type()->array_type()->element_type();
8585 methods->reserve(this->all_methods_->size());
8586 for (Typed_identifier_list::const_iterator pm =
8587 this->all_methods_->begin();
8588 pm != this->all_methods_->end();
8589 ++pm)
8591 const Struct_field_list* mfields = elemtype->struct_type()->fields();
8593 Expression_list* mvals = new Expression_list();
8594 mvals->reserve(3);
8596 Struct_field_list::const_iterator pmf = mfields->begin();
8597 go_assert(pmf->is_field_name("name"));
8598 std::string s = Gogo::unpack_hidden_name(pm->name());
8599 Expression* e = Expression::make_string(s, bloc);
8600 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
8602 ++pmf;
8603 go_assert(pmf->is_field_name("pkgPath"));
8604 if (!Gogo::is_hidden_name(pm->name()))
8605 mvals->push_back(Expression::make_nil(bloc));
8606 else
8608 s = Gogo::hidden_name_pkgpath(pm->name());
8609 e = Expression::make_string(s, bloc);
8610 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
8613 ++pmf;
8614 go_assert(pmf->is_field_name("typ"));
8615 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
8617 ++pmf;
8618 go_assert(pmf == mfields->end());
8620 e = Expression::make_struct_composite_literal(elemtype, mvals,
8621 bloc);
8622 methods->push_back(e);
8626 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
8627 methods, bloc));
8629 ++pif;
8630 go_assert(pif == ifields->end());
8632 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
8635 // Reflection string.
8637 void
8638 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
8640 ret->append("interface {");
8641 const Typed_identifier_list* methods = this->parse_methods_;
8642 if (methods != NULL)
8644 ret->push_back(' ');
8645 for (Typed_identifier_list::const_iterator p = methods->begin();
8646 p != methods->end();
8647 ++p)
8649 if (p != methods->begin())
8650 ret->append("; ");
8651 if (p->name().empty())
8652 this->append_reflection(p->type(), gogo, ret);
8653 else
8655 if (!Gogo::is_hidden_name(p->name()))
8656 ret->append(p->name());
8657 else if (gogo->pkgpath_from_option())
8658 ret->append(p->name().substr(1));
8659 else
8661 // If no -fgo-pkgpath option, backward compatibility
8662 // for how this used to work before -fgo-pkgpath was
8663 // introduced.
8664 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
8665 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
8666 ret->push_back('.');
8667 ret->append(Gogo::unpack_hidden_name(p->name()));
8669 std::string sub = p->type()->reflection(gogo);
8670 go_assert(sub.compare(0, 4, "func") == 0);
8671 sub = sub.substr(4);
8672 ret->append(sub);
8675 ret->push_back(' ');
8677 ret->append("}");
8680 // Generate GC symbol for interface types.
8682 void
8683 Interface_type::do_gc_symbol(Gogo*, Expression_list** vals,
8684 Expression** offset, int)
8686 Location bloc = Linemap::predeclared_location();
8687 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8689 unsigned long opval = this->is_empty() ? GC_EFACE : GC_IFACE;
8690 (*vals)->push_back(Expression::make_integer_ul(opval, uintptr_type, bloc));
8691 (*vals)->push_back(*offset);
8692 this->advance_gc_offset(offset);
8695 // Mangled name.
8697 void
8698 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8700 go_assert(this->methods_are_finalized_);
8702 ret->push_back('I');
8704 const Typed_identifier_list* methods = this->all_methods_;
8705 if (methods != NULL && !this->seen_)
8707 this->seen_ = true;
8708 for (Typed_identifier_list::const_iterator p = methods->begin();
8709 p != methods->end();
8710 ++p)
8712 if (!p->name().empty())
8714 std::string n;
8715 if (!Gogo::is_hidden_name(p->name()))
8716 n = p->name();
8717 else
8719 n = ".";
8720 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
8721 n.append(Gogo::pkgpath_for_symbol(pkgpath));
8722 n.append(1, '.');
8723 n.append(Gogo::unpack_hidden_name(p->name()));
8725 char buf[20];
8726 snprintf(buf, sizeof buf, "%u_",
8727 static_cast<unsigned int>(n.length()));
8728 ret->append(buf);
8729 ret->append(n);
8731 this->append_mangled_name(p->type(), gogo, ret);
8733 this->seen_ = false;
8736 ret->push_back('e');
8739 // Export.
8741 void
8742 Interface_type::do_export(Export* exp) const
8744 exp->write_c_string("interface { ");
8746 const Typed_identifier_list* methods = this->parse_methods_;
8747 if (methods != NULL)
8749 for (Typed_identifier_list::const_iterator pm = methods->begin();
8750 pm != methods->end();
8751 ++pm)
8753 if (pm->name().empty())
8755 exp->write_c_string("? ");
8756 exp->write_type(pm->type());
8758 else
8760 exp->write_string(pm->name());
8761 exp->write_c_string(" (");
8763 const Function_type* fntype = pm->type()->function_type();
8765 bool first = true;
8766 const Typed_identifier_list* parameters = fntype->parameters();
8767 if (parameters != NULL)
8769 bool is_varargs = fntype->is_varargs();
8770 for (Typed_identifier_list::const_iterator pp =
8771 parameters->begin();
8772 pp != parameters->end();
8773 ++pp)
8775 if (first)
8776 first = false;
8777 else
8778 exp->write_c_string(", ");
8779 exp->write_name(pp->name());
8780 exp->write_c_string(" ");
8781 if (!is_varargs || pp + 1 != parameters->end())
8782 exp->write_type(pp->type());
8783 else
8785 exp->write_c_string("...");
8786 Type *pptype = pp->type();
8787 exp->write_type(pptype->array_type()->element_type());
8792 exp->write_c_string(")");
8794 const Typed_identifier_list* results = fntype->results();
8795 if (results != NULL)
8797 exp->write_c_string(" ");
8798 if (results->size() == 1 && results->begin()->name().empty())
8799 exp->write_type(results->begin()->type());
8800 else
8802 first = true;
8803 exp->write_c_string("(");
8804 for (Typed_identifier_list::const_iterator p =
8805 results->begin();
8806 p != results->end();
8807 ++p)
8809 if (first)
8810 first = false;
8811 else
8812 exp->write_c_string(", ");
8813 exp->write_name(p->name());
8814 exp->write_c_string(" ");
8815 exp->write_type(p->type());
8817 exp->write_c_string(")");
8822 exp->write_c_string("; ");
8826 exp->write_c_string("}");
8829 // Import an interface type.
8831 Interface_type*
8832 Interface_type::do_import(Import* imp)
8834 imp->require_c_string("interface { ");
8836 Typed_identifier_list* methods = new Typed_identifier_list;
8837 while (imp->peek_char() != '}')
8839 std::string name = imp->read_identifier();
8841 if (name == "?")
8843 imp->require_c_string(" ");
8844 Type* t = imp->read_type();
8845 methods->push_back(Typed_identifier("", t, imp->location()));
8846 imp->require_c_string("; ");
8847 continue;
8850 imp->require_c_string(" (");
8852 Typed_identifier_list* parameters;
8853 bool is_varargs = false;
8854 if (imp->peek_char() == ')')
8855 parameters = NULL;
8856 else
8858 parameters = new Typed_identifier_list;
8859 while (true)
8861 std::string name = imp->read_name();
8862 imp->require_c_string(" ");
8864 if (imp->match_c_string("..."))
8866 imp->advance(3);
8867 is_varargs = true;
8870 Type* ptype = imp->read_type();
8871 if (is_varargs)
8872 ptype = Type::make_array_type(ptype, NULL);
8873 parameters->push_back(Typed_identifier(name, ptype,
8874 imp->location()));
8875 if (imp->peek_char() != ',')
8876 break;
8877 go_assert(!is_varargs);
8878 imp->require_c_string(", ");
8881 imp->require_c_string(")");
8883 Typed_identifier_list* results;
8884 if (imp->peek_char() != ' ')
8885 results = NULL;
8886 else
8888 results = new Typed_identifier_list;
8889 imp->advance(1);
8890 if (imp->peek_char() != '(')
8892 Type* rtype = imp->read_type();
8893 results->push_back(Typed_identifier("", rtype, imp->location()));
8895 else
8897 imp->advance(1);
8898 while (true)
8900 std::string name = imp->read_name();
8901 imp->require_c_string(" ");
8902 Type* rtype = imp->read_type();
8903 results->push_back(Typed_identifier(name, rtype,
8904 imp->location()));
8905 if (imp->peek_char() != ',')
8906 break;
8907 imp->require_c_string(", ");
8909 imp->require_c_string(")");
8913 Function_type* fntype = Type::make_function_type(NULL, parameters,
8914 results,
8915 imp->location());
8916 if (is_varargs)
8917 fntype->set_is_varargs();
8918 methods->push_back(Typed_identifier(name, fntype, imp->location()));
8920 imp->require_c_string("; ");
8923 imp->require_c_string("}");
8925 if (methods->empty())
8927 delete methods;
8928 methods = NULL;
8931 return Type::make_interface_type(methods, imp->location());
8934 // Make an interface type.
8936 Interface_type*
8937 Type::make_interface_type(Typed_identifier_list* methods,
8938 Location location)
8940 return new Interface_type(methods, location);
8943 // Make an empty interface type.
8945 Interface_type*
8946 Type::make_empty_interface_type(Location location)
8948 Interface_type* ret = new Interface_type(NULL, location);
8949 ret->finalize_methods();
8950 return ret;
8953 // Class Method.
8955 // Bind a method to an object.
8957 Expression*
8958 Method::bind_method(Expression* expr, Location location) const
8960 if (this->stub_ == NULL)
8962 // When there is no stub object, the binding is determined by
8963 // the child class.
8964 return this->do_bind_method(expr, location);
8966 return Expression::make_bound_method(expr, this, this->stub_, location);
8969 // Return the named object associated with a method. This may only be
8970 // called after methods are finalized.
8972 Named_object*
8973 Method::named_object() const
8975 if (this->stub_ != NULL)
8976 return this->stub_;
8977 return this->do_named_object();
8980 // Class Named_method.
8982 // The type of the method.
8984 Function_type*
8985 Named_method::do_type() const
8987 if (this->named_object_->is_function())
8988 return this->named_object_->func_value()->type();
8989 else if (this->named_object_->is_function_declaration())
8990 return this->named_object_->func_declaration_value()->type();
8991 else
8992 go_unreachable();
8995 // Return the location of the method receiver.
8997 Location
8998 Named_method::do_receiver_location() const
9000 return this->do_type()->receiver()->location();
9003 // Bind a method to an object.
9005 Expression*
9006 Named_method::do_bind_method(Expression* expr, Location location) const
9008 Named_object* no = this->named_object_;
9009 Bound_method_expression* bme = Expression::make_bound_method(expr, this,
9010 no, location);
9011 // If this is not a local method, and it does not use a stub, then
9012 // the real method expects a different type. We need to cast the
9013 // first argument.
9014 if (this->depth() > 0 && !this->needs_stub_method())
9016 Function_type* ftype = this->do_type();
9017 go_assert(ftype->is_method());
9018 Type* frtype = ftype->receiver()->type();
9019 bme->set_first_argument_type(frtype);
9021 return bme;
9024 // Return whether this method should not participate in interfaces.
9026 bool
9027 Named_method::do_nointerface() const
9029 Named_object* no = this->named_object_;
9030 return no->is_function() && no->func_value()->nointerface();
9033 // Class Interface_method.
9035 // Bind a method to an object.
9037 Expression*
9038 Interface_method::do_bind_method(Expression* expr,
9039 Location location) const
9041 return Expression::make_interface_field_reference(expr, this->name_,
9042 location);
9045 // Class Methods.
9047 // Insert a new method. Return true if it was inserted, false
9048 // otherwise.
9050 bool
9051 Methods::insert(const std::string& name, Method* m)
9053 std::pair<Method_map::iterator, bool> ins =
9054 this->methods_.insert(std::make_pair(name, m));
9055 if (ins.second)
9056 return true;
9057 else
9059 Method* old_method = ins.first->second;
9060 if (m->depth() < old_method->depth())
9062 delete old_method;
9063 ins.first->second = m;
9064 return true;
9066 else
9068 if (m->depth() == old_method->depth())
9069 old_method->set_is_ambiguous();
9070 return false;
9075 // Return the number of unambiguous methods.
9077 size_t
9078 Methods::count() const
9080 size_t ret = 0;
9081 for (Method_map::const_iterator p = this->methods_.begin();
9082 p != this->methods_.end();
9083 ++p)
9084 if (!p->second->is_ambiguous())
9085 ++ret;
9086 return ret;
9089 // Class Named_type.
9091 // Return the name of the type.
9093 const std::string&
9094 Named_type::name() const
9096 return this->named_object_->name();
9099 // Return the name of the type to use in an error message.
9101 std::string
9102 Named_type::message_name() const
9104 return this->named_object_->message_name();
9107 // Whether this is an alias. There are currently only two aliases so
9108 // we just recognize them by name.
9110 bool
9111 Named_type::is_alias() const
9113 if (!this->is_builtin())
9114 return false;
9115 const std::string& name(this->name());
9116 return name == "byte" || name == "rune";
9119 // Return the base type for this type. We have to be careful about
9120 // circular type definitions, which are invalid but may be seen here.
9122 Type*
9123 Named_type::named_base()
9125 if (this->seen_)
9126 return this;
9127 this->seen_ = true;
9128 Type* ret = this->type_->base();
9129 this->seen_ = false;
9130 return ret;
9133 const Type*
9134 Named_type::named_base() const
9136 if (this->seen_)
9137 return this;
9138 this->seen_ = true;
9139 const Type* ret = this->type_->base();
9140 this->seen_ = false;
9141 return ret;
9144 // Return whether this is an error type. We have to be careful about
9145 // circular type definitions, which are invalid but may be seen here.
9147 bool
9148 Named_type::is_named_error_type() const
9150 if (this->seen_)
9151 return false;
9152 this->seen_ = true;
9153 bool ret = this->type_->is_error_type();
9154 this->seen_ = false;
9155 return ret;
9158 // Whether this type is comparable. We have to be careful about
9159 // circular type definitions.
9161 bool
9162 Named_type::named_type_is_comparable(std::string* reason) const
9164 if (this->seen_)
9165 return false;
9166 this->seen_ = true;
9167 bool ret = Type::are_compatible_for_comparison(true, this->type_,
9168 this->type_, reason);
9169 this->seen_ = false;
9170 return ret;
9173 // Add a method to this type.
9175 Named_object*
9176 Named_type::add_method(const std::string& name, Function* function)
9178 if (this->local_methods_ == NULL)
9179 this->local_methods_ = new Bindings(NULL);
9180 return this->local_methods_->add_function(name, NULL, function);
9183 // Add a method declaration to this type.
9185 Named_object*
9186 Named_type::add_method_declaration(const std::string& name, Package* package,
9187 Function_type* type,
9188 Location location)
9190 if (this->local_methods_ == NULL)
9191 this->local_methods_ = new Bindings(NULL);
9192 return this->local_methods_->add_function_declaration(name, package, type,
9193 location);
9196 // Add an existing method to this type.
9198 void
9199 Named_type::add_existing_method(Named_object* no)
9201 if (this->local_methods_ == NULL)
9202 this->local_methods_ = new Bindings(NULL);
9203 this->local_methods_->add_named_object(no);
9206 // Look for a local method NAME, and returns its named object, or NULL
9207 // if not there.
9209 Named_object*
9210 Named_type::find_local_method(const std::string& name) const
9212 if (this->local_methods_ == NULL)
9213 return NULL;
9214 return this->local_methods_->lookup(name);
9217 // Return whether NAME is an unexported field or method, for better
9218 // error reporting.
9220 bool
9221 Named_type::is_unexported_local_method(Gogo* gogo,
9222 const std::string& name) const
9224 Bindings* methods = this->local_methods_;
9225 if (methods != NULL)
9227 for (Bindings::const_declarations_iterator p =
9228 methods->begin_declarations();
9229 p != methods->end_declarations();
9230 ++p)
9232 if (Gogo::is_hidden_name(p->first)
9233 && name == Gogo::unpack_hidden_name(p->first)
9234 && gogo->pack_hidden_name(name, false) != p->first)
9235 return true;
9238 return false;
9241 // Build the complete list of methods for this type, which means
9242 // recursively including all methods for anonymous fields. Create all
9243 // stub methods.
9245 void
9246 Named_type::finalize_methods(Gogo* gogo)
9248 if (this->all_methods_ != NULL)
9249 return;
9251 if (this->local_methods_ != NULL
9252 && (this->points_to() != NULL || this->interface_type() != NULL))
9254 const Bindings* lm = this->local_methods_;
9255 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
9256 p != lm->end_declarations();
9257 ++p)
9258 go_error_at(p->second->location(),
9259 "invalid pointer or interface receiver type");
9260 delete this->local_methods_;
9261 this->local_methods_ = NULL;
9262 return;
9265 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
9268 // Return the method NAME, or NULL if there isn't one or if it is
9269 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
9270 // ambiguous.
9272 Method*
9273 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
9275 return Type::method_function(this->all_methods_, name, is_ambiguous);
9278 // Return a pointer to the interface method table for this type for
9279 // the interface INTERFACE. IS_POINTER is true if this is for a
9280 // pointer to THIS.
9282 Expression*
9283 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
9285 return Type::interface_method_table(this, interface, is_pointer,
9286 &this->interface_method_tables_,
9287 &this->pointer_interface_method_tables_);
9290 // Look for a use of a complete type within another type. This is
9291 // used to check that we don't try to use a type within itself.
9293 class Find_type_use : public Traverse
9295 public:
9296 Find_type_use(Named_type* find_type)
9297 : Traverse(traverse_types),
9298 find_type_(find_type), found_(false)
9301 // Whether we found the type.
9302 bool
9303 found() const
9304 { return this->found_; }
9306 protected:
9308 type(Type*);
9310 private:
9311 // The type we are looking for.
9312 Named_type* find_type_;
9313 // Whether we found the type.
9314 bool found_;
9317 // Check for FIND_TYPE in TYPE.
9320 Find_type_use::type(Type* type)
9322 if (type->named_type() != NULL && this->find_type_ == type->named_type())
9324 this->found_ = true;
9325 return TRAVERSE_EXIT;
9328 // It's OK if we see a reference to the type in any type which is
9329 // essentially a pointer: a pointer, a slice, a function, a map, or
9330 // a channel.
9331 if (type->points_to() != NULL
9332 || type->is_slice_type()
9333 || type->function_type() != NULL
9334 || type->map_type() != NULL
9335 || type->channel_type() != NULL)
9336 return TRAVERSE_SKIP_COMPONENTS;
9338 // For an interface, a reference to the type in a method type should
9339 // be ignored, but we have to consider direct inheritance. When
9340 // this is called, there may be cases of direct inheritance
9341 // represented as a method with no name.
9342 if (type->interface_type() != NULL)
9344 const Typed_identifier_list* methods = type->interface_type()->methods();
9345 if (methods != NULL)
9347 for (Typed_identifier_list::const_iterator p = methods->begin();
9348 p != methods->end();
9349 ++p)
9351 if (p->name().empty())
9353 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
9354 return TRAVERSE_EXIT;
9358 return TRAVERSE_SKIP_COMPONENTS;
9361 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
9362 // to convert TYPE to the backend representation before we convert
9363 // FIND_TYPE_.
9364 if (type->named_type() != NULL)
9366 switch (type->base()->classification())
9368 case Type::TYPE_ERROR:
9369 case Type::TYPE_BOOLEAN:
9370 case Type::TYPE_INTEGER:
9371 case Type::TYPE_FLOAT:
9372 case Type::TYPE_COMPLEX:
9373 case Type::TYPE_STRING:
9374 case Type::TYPE_NIL:
9375 break;
9377 case Type::TYPE_ARRAY:
9378 case Type::TYPE_STRUCT:
9379 this->find_type_->add_dependency(type->named_type());
9380 break;
9382 case Type::TYPE_NAMED:
9383 case Type::TYPE_FORWARD:
9384 go_assert(saw_errors());
9385 break;
9387 case Type::TYPE_VOID:
9388 case Type::TYPE_SINK:
9389 case Type::TYPE_FUNCTION:
9390 case Type::TYPE_POINTER:
9391 case Type::TYPE_CALL_MULTIPLE_RESULT:
9392 case Type::TYPE_MAP:
9393 case Type::TYPE_CHANNEL:
9394 case Type::TYPE_INTERFACE:
9395 default:
9396 go_unreachable();
9400 return TRAVERSE_CONTINUE;
9403 // Verify that a named type does not refer to itself.
9405 bool
9406 Named_type::do_verify()
9408 if (this->is_verified_)
9409 return true;
9410 this->is_verified_ = true;
9412 Find_type_use find(this);
9413 Type::traverse(this->type_, &find);
9414 if (find.found())
9416 go_error_at(this->location_, "invalid recursive type %qs",
9417 this->message_name().c_str());
9418 this->is_error_ = true;
9419 return false;
9422 // Check whether any of the local methods overloads an existing
9423 // struct field or interface method. We don't need to check the
9424 // list of methods against itself: that is handled by the Bindings
9425 // code.
9426 if (this->local_methods_ != NULL)
9428 Struct_type* st = this->type_->struct_type();
9429 if (st != NULL)
9431 for (Bindings::const_declarations_iterator p =
9432 this->local_methods_->begin_declarations();
9433 p != this->local_methods_->end_declarations();
9434 ++p)
9436 const std::string& name(p->first);
9437 if (st != NULL && st->find_local_field(name, NULL) != NULL)
9439 go_error_at(p->second->location(),
9440 "method %qs redeclares struct field name",
9441 Gogo::message_name(name).c_str());
9447 return true;
9450 // Return whether this type is or contains a pointer.
9452 bool
9453 Named_type::do_has_pointer() const
9455 if (this->seen_)
9456 return false;
9457 this->seen_ = true;
9458 bool ret = this->type_->has_pointer();
9459 this->seen_ = false;
9460 return ret;
9463 // Return whether comparisons for this type can use the identity
9464 // function.
9466 bool
9467 Named_type::do_compare_is_identity(Gogo* gogo)
9469 // We don't use this->seen_ here because compare_is_identity may
9470 // call base() later, and that will mess up if seen_ is set here.
9471 if (this->seen_in_compare_is_identity_)
9472 return false;
9473 this->seen_in_compare_is_identity_ = true;
9474 bool ret = this->type_->compare_is_identity(gogo);
9475 this->seen_in_compare_is_identity_ = false;
9476 return ret;
9479 // Return whether this type is reflexive--whether it is always equal
9480 // to itself.
9482 bool
9483 Named_type::do_is_reflexive()
9485 if (this->seen_in_compare_is_identity_)
9486 return false;
9487 this->seen_in_compare_is_identity_ = true;
9488 bool ret = this->type_->is_reflexive();
9489 this->seen_in_compare_is_identity_ = false;
9490 return ret;
9493 // Return whether this type needs a key update when used as a map key.
9495 bool
9496 Named_type::do_needs_key_update()
9498 if (this->seen_in_compare_is_identity_)
9499 return true;
9500 this->seen_in_compare_is_identity_ = true;
9501 bool ret = this->type_->needs_key_update();
9502 this->seen_in_compare_is_identity_ = false;
9503 return ret;
9506 // Return a hash code. This is used for method lookup. We simply
9507 // hash on the name itself.
9509 unsigned int
9510 Named_type::do_hash_for_method(Gogo* gogo) const
9512 if (this->is_alias())
9513 return this->type_->named_type()->do_hash_for_method(gogo);
9515 const std::string& name(this->named_object()->name());
9516 unsigned int ret = Type::hash_string(name, 0);
9518 // GOGO will be NULL here when called from Type_hash_identical.
9519 // That is OK because that is only used for internal hash tables
9520 // where we are going to be comparing named types for equality. In
9521 // other cases, which are cases where the runtime is going to
9522 // compare hash codes to see if the types are the same, we need to
9523 // include the pkgpath in the hash.
9524 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
9526 const Package* package = this->named_object()->package();
9527 if (package == NULL)
9528 ret = Type::hash_string(gogo->pkgpath(), ret);
9529 else
9530 ret = Type::hash_string(package->pkgpath(), ret);
9533 return ret;
9536 // Convert a named type to the backend representation. In order to
9537 // get dependencies right, we fill in a dummy structure for this type,
9538 // then convert all the dependencies, then complete this type. When
9539 // this function is complete, the size of the type is known.
9541 void
9542 Named_type::convert(Gogo* gogo)
9544 if (this->is_error_ || this->is_converted_)
9545 return;
9547 this->create_placeholder(gogo);
9549 // If we are called to turn unsafe.Sizeof into a constant, we may
9550 // not have verified the type yet. We have to make sure it is
9551 // verified, since that sets the list of dependencies.
9552 this->verify();
9554 // Convert all the dependencies. If they refer indirectly back to
9555 // this type, they will pick up the intermediate representation we just
9556 // created.
9557 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
9558 p != this->dependencies_.end();
9559 ++p)
9560 (*p)->convert(gogo);
9562 // Complete this type.
9563 Btype* bt = this->named_btype_;
9564 Type* base = this->type_->base();
9565 switch (base->classification())
9567 case TYPE_VOID:
9568 case TYPE_BOOLEAN:
9569 case TYPE_INTEGER:
9570 case TYPE_FLOAT:
9571 case TYPE_COMPLEX:
9572 case TYPE_STRING:
9573 case TYPE_NIL:
9574 break;
9576 case TYPE_MAP:
9577 case TYPE_CHANNEL:
9578 break;
9580 case TYPE_FUNCTION:
9581 case TYPE_POINTER:
9582 // The size of these types is already correct. We don't worry
9583 // about filling them in until later, when we also track
9584 // circular references.
9585 break;
9587 case TYPE_STRUCT:
9589 std::vector<Backend::Btyped_identifier> bfields;
9590 get_backend_struct_fields(gogo, base->struct_type()->fields(),
9591 true, &bfields);
9592 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
9593 bt = gogo->backend()->error_type();
9595 break;
9597 case TYPE_ARRAY:
9598 // Slice types were completed in create_placeholder.
9599 if (!base->is_slice_type())
9601 Btype* bet = base->array_type()->get_backend_element(gogo, true);
9602 Bexpression* blen = base->array_type()->get_backend_length(gogo);
9603 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
9604 bt = gogo->backend()->error_type();
9606 break;
9608 case TYPE_INTERFACE:
9609 // Interface types were completed in create_placeholder.
9610 break;
9612 case TYPE_ERROR:
9613 return;
9615 default:
9616 case TYPE_SINK:
9617 case TYPE_CALL_MULTIPLE_RESULT:
9618 case TYPE_NAMED:
9619 case TYPE_FORWARD:
9620 go_unreachable();
9623 this->named_btype_ = bt;
9624 this->is_converted_ = true;
9625 this->is_placeholder_ = false;
9628 // Create the placeholder for a named type. This is the first step in
9629 // converting to the backend representation.
9631 void
9632 Named_type::create_placeholder(Gogo* gogo)
9634 if (this->is_error_)
9635 this->named_btype_ = gogo->backend()->error_type();
9637 if (this->named_btype_ != NULL)
9638 return;
9640 // Create the structure for this type. Note that because we call
9641 // base() here, we don't attempt to represent a named type defined
9642 // as another named type. Instead both named types will point to
9643 // different base representations.
9644 Type* base = this->type_->base();
9645 Btype* bt;
9646 bool set_name = true;
9647 switch (base->classification())
9649 case TYPE_ERROR:
9650 this->is_error_ = true;
9651 this->named_btype_ = gogo->backend()->error_type();
9652 return;
9654 case TYPE_VOID:
9655 case TYPE_BOOLEAN:
9656 case TYPE_INTEGER:
9657 case TYPE_FLOAT:
9658 case TYPE_COMPLEX:
9659 case TYPE_STRING:
9660 case TYPE_NIL:
9661 // These are simple basic types, we can just create them
9662 // directly.
9663 bt = Type::get_named_base_btype(gogo, base);
9664 break;
9666 case TYPE_MAP:
9667 case TYPE_CHANNEL:
9668 // All maps and channels have the same backend representation.
9669 bt = Type::get_named_base_btype(gogo, base);
9670 break;
9672 case TYPE_FUNCTION:
9673 case TYPE_POINTER:
9675 bool for_function = base->classification() == TYPE_FUNCTION;
9676 bt = gogo->backend()->placeholder_pointer_type(this->name(),
9677 this->location_,
9678 for_function);
9679 set_name = false;
9681 break;
9683 case TYPE_STRUCT:
9684 bt = gogo->backend()->placeholder_struct_type(this->name(),
9685 this->location_);
9686 this->is_placeholder_ = true;
9687 set_name = false;
9688 break;
9690 case TYPE_ARRAY:
9691 if (base->is_slice_type())
9692 bt = gogo->backend()->placeholder_struct_type(this->name(),
9693 this->location_);
9694 else
9696 bt = gogo->backend()->placeholder_array_type(this->name(),
9697 this->location_);
9698 this->is_placeholder_ = true;
9700 set_name = false;
9701 break;
9703 case TYPE_INTERFACE:
9704 if (base->interface_type()->is_empty())
9705 bt = Interface_type::get_backend_empty_interface_type(gogo);
9706 else
9708 bt = gogo->backend()->placeholder_struct_type(this->name(),
9709 this->location_);
9710 set_name = false;
9712 break;
9714 default:
9715 case TYPE_SINK:
9716 case TYPE_CALL_MULTIPLE_RESULT:
9717 case TYPE_NAMED:
9718 case TYPE_FORWARD:
9719 go_unreachable();
9722 if (set_name)
9723 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
9725 this->named_btype_ = bt;
9727 if (base->is_slice_type())
9729 // We do not record slices as dependencies of other types,
9730 // because we can fill them in completely here with the final
9731 // size.
9732 std::vector<Backend::Btyped_identifier> bfields;
9733 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
9734 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
9735 this->named_btype_ = gogo->backend()->error_type();
9737 else if (base->interface_type() != NULL
9738 && !base->interface_type()->is_empty())
9740 // We do not record interfaces as dependencies of other types,
9741 // because we can fill them in completely here with the final
9742 // size.
9743 std::vector<Backend::Btyped_identifier> bfields;
9744 get_backend_interface_fields(gogo, base->interface_type(), true,
9745 &bfields);
9746 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
9747 this->named_btype_ = gogo->backend()->error_type();
9751 // Get the backend representation for a named type.
9753 Btype*
9754 Named_type::do_get_backend(Gogo* gogo)
9756 if (this->is_error_)
9757 return gogo->backend()->error_type();
9759 Btype* bt = this->named_btype_;
9761 if (!gogo->named_types_are_converted())
9763 // We have not completed converting named types. NAMED_BTYPE_
9764 // is a placeholder and we shouldn't do anything further.
9765 if (bt != NULL)
9766 return bt;
9768 // We don't build dependencies for types whose sizes do not
9769 // change or are not relevant, so we may see them here while
9770 // converting types.
9771 this->create_placeholder(gogo);
9772 bt = this->named_btype_;
9773 go_assert(bt != NULL);
9774 return bt;
9777 // We are not converting types. This should only be called if the
9778 // type has already been converted.
9779 if (!this->is_converted_)
9781 go_assert(saw_errors());
9782 return gogo->backend()->error_type();
9785 go_assert(bt != NULL);
9787 // Complete the backend representation.
9788 Type* base = this->type_->base();
9789 Btype* bt1;
9790 switch (base->classification())
9792 case TYPE_ERROR:
9793 return gogo->backend()->error_type();
9795 case TYPE_VOID:
9796 case TYPE_BOOLEAN:
9797 case TYPE_INTEGER:
9798 case TYPE_FLOAT:
9799 case TYPE_COMPLEX:
9800 case TYPE_STRING:
9801 case TYPE_NIL:
9802 case TYPE_MAP:
9803 case TYPE_CHANNEL:
9804 return bt;
9806 case TYPE_STRUCT:
9807 if (!this->seen_in_get_backend_)
9809 this->seen_in_get_backend_ = true;
9810 base->struct_type()->finish_backend_fields(gogo);
9811 this->seen_in_get_backend_ = false;
9813 return bt;
9815 case TYPE_ARRAY:
9816 if (!this->seen_in_get_backend_)
9818 this->seen_in_get_backend_ = true;
9819 base->array_type()->finish_backend_element(gogo);
9820 this->seen_in_get_backend_ = false;
9822 return bt;
9824 case TYPE_INTERFACE:
9825 if (!this->seen_in_get_backend_)
9827 this->seen_in_get_backend_ = true;
9828 base->interface_type()->finish_backend_methods(gogo);
9829 this->seen_in_get_backend_ = false;
9831 return bt;
9833 case TYPE_FUNCTION:
9834 // Don't build a circular data structure. GENERIC can't handle
9835 // it.
9836 if (this->seen_in_get_backend_)
9838 this->is_circular_ = true;
9839 return gogo->backend()->circular_pointer_type(bt, false);
9841 this->seen_in_get_backend_ = true;
9842 bt1 = Type::get_named_base_btype(gogo, base);
9843 this->seen_in_get_backend_ = false;
9844 if (this->is_circular_)
9845 bt1 = gogo->backend()->circular_pointer_type(bt, false);
9846 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
9847 bt = gogo->backend()->error_type();
9848 return bt;
9850 case TYPE_POINTER:
9851 // Don't build a circular data structure. GENERIC can't handle
9852 // it.
9853 if (this->seen_in_get_backend_)
9855 this->is_circular_ = true;
9856 return gogo->backend()->circular_pointer_type(bt, false);
9858 this->seen_in_get_backend_ = true;
9859 bt1 = Type::get_named_base_btype(gogo, base);
9860 this->seen_in_get_backend_ = false;
9861 if (this->is_circular_)
9862 bt1 = gogo->backend()->circular_pointer_type(bt, false);
9863 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
9864 bt = gogo->backend()->error_type();
9865 return bt;
9867 default:
9868 case TYPE_SINK:
9869 case TYPE_CALL_MULTIPLE_RESULT:
9870 case TYPE_NAMED:
9871 case TYPE_FORWARD:
9872 go_unreachable();
9875 go_unreachable();
9878 // Build a type descriptor for a named type.
9880 Expression*
9881 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9883 if (name == NULL && this->is_alias())
9884 return this->type_->type_descriptor(gogo, this->type_);
9886 // If NAME is not NULL, then we don't really want the type
9887 // descriptor for this type; we want the descriptor for the
9888 // underlying type, giving it the name NAME.
9889 return this->named_type_descriptor(gogo, this->type_,
9890 name == NULL ? this : name);
9893 // Add to the reflection string. This is used mostly for the name of
9894 // the type used in a type descriptor, not for actual reflection
9895 // strings.
9897 void
9898 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
9900 if (this->is_alias())
9902 this->append_reflection(this->type_, gogo, ret);
9903 return;
9905 if (!this->is_builtin())
9907 // When -fgo-pkgpath or -fgo-prefix is specified, we use it to
9908 // make a unique reflection string, so that the type
9909 // canonicalization in the reflect package will work. In order
9910 // to be compatible with the gc compiler, we put tabs into the
9911 // package path, so that the reflect methods can discard it.
9912 const Package* package = this->named_object_->package();
9913 ret->push_back('\t');
9914 ret->append(package != NULL
9915 ? package->pkgpath_symbol()
9916 : gogo->pkgpath_symbol());
9917 ret->push_back('\t');
9918 ret->append(package != NULL
9919 ? package->package_name()
9920 : gogo->package_name());
9921 ret->push_back('.');
9923 if (this->in_function_ != NULL)
9925 ret->push_back('\t');
9926 const Typed_identifier* rcvr =
9927 this->in_function_->func_value()->type()->receiver();
9928 if (rcvr != NULL)
9930 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
9931 ret->append(Gogo::unpack_hidden_name(rcvr_type->name()));
9932 ret->push_back('.');
9934 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
9935 ret->push_back('$');
9936 if (this->in_function_index_ > 0)
9938 char buf[30];
9939 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
9940 ret->append(buf);
9941 ret->push_back('$');
9943 ret->push_back('\t');
9945 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
9948 // Generate GC symbol for named types.
9950 void
9951 Named_type::do_gc_symbol(Gogo* gogo, Expression_list** vals,
9952 Expression** offset, int stack)
9954 if (!this->seen_)
9956 this->seen_ = true;
9957 Type::gc_symbol(gogo, this->real_type(), vals, offset, stack);
9958 this->seen_ = false;
9962 // Get the mangled name.
9964 void
9965 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
9967 if (this->is_alias())
9969 this->append_mangled_name(this->type_, gogo, ret);
9970 return;
9972 Named_object* no = this->named_object_;
9973 std::string name;
9974 if (this->is_builtin())
9975 go_assert(this->in_function_ == NULL);
9976 else
9978 const std::string& pkgpath(no->package() == NULL
9979 ? gogo->pkgpath_symbol()
9980 : no->package()->pkgpath_symbol());
9981 name = pkgpath;
9982 name.append(1, '.');
9983 if (this->in_function_ != NULL)
9985 const Typed_identifier* rcvr =
9986 this->in_function_->func_value()->type()->receiver();
9987 if (rcvr != NULL)
9989 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
9990 name.append(Gogo::unpack_hidden_name(rcvr_type->name()));
9991 name.append(1, '.');
9993 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
9994 name.append(1, '$');
9995 if (this->in_function_index_ > 0)
9997 char buf[30];
9998 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
9999 name.append(buf);
10000 name.append(1, '$');
10004 name.append(Gogo::unpack_hidden_name(no->name()));
10005 char buf[20];
10006 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
10007 ret->append(buf);
10008 ret->append(name);
10011 // Export the type. This is called to export a global type.
10013 void
10014 Named_type::export_named_type(Export* exp, const std::string&) const
10016 // We don't need to write the name of the type here, because it will
10017 // be written by Export::write_type anyhow.
10018 exp->write_c_string("type ");
10019 exp->write_type(this);
10020 exp->write_c_string(";\n");
10023 // Import a named type.
10025 void
10026 Named_type::import_named_type(Import* imp, Named_type** ptype)
10028 imp->require_c_string("type ");
10029 Type *type = imp->read_type();
10030 *ptype = type->named_type();
10031 go_assert(*ptype != NULL);
10032 imp->require_c_string(";\n");
10035 // Export the type when it is referenced by another type. In this
10036 // case Export::export_type will already have issued the name.
10038 void
10039 Named_type::do_export(Export* exp) const
10041 exp->write_type(this->type_);
10043 // To save space, we only export the methods directly attached to
10044 // this type.
10045 Bindings* methods = this->local_methods_;
10046 if (methods == NULL)
10047 return;
10049 exp->write_c_string("\n");
10050 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
10051 p != methods->end_definitions();
10052 ++p)
10054 exp->write_c_string(" ");
10055 (*p)->export_named_object(exp);
10058 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
10059 p != methods->end_declarations();
10060 ++p)
10062 if (p->second->is_function_declaration())
10064 exp->write_c_string(" ");
10065 p->second->export_named_object(exp);
10070 // Make a named type.
10072 Named_type*
10073 Type::make_named_type(Named_object* named_object, Type* type,
10074 Location location)
10076 return new Named_type(named_object, type, location);
10079 // Finalize the methods for TYPE. It will be a named type or a struct
10080 // type. This sets *ALL_METHODS to the list of methods, and builds
10081 // all required stubs.
10083 void
10084 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
10085 Methods** all_methods)
10087 *all_methods = new Methods();
10088 std::vector<const Named_type*> seen;
10089 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
10090 if ((*all_methods)->empty())
10092 delete *all_methods;
10093 *all_methods = NULL;
10095 Type::build_stub_methods(gogo, type, *all_methods, location);
10098 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
10099 // build up the struct field indexes as we go. DEPTH is the depth of
10100 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
10101 // adding these methods for an anonymous field with pointer type.
10102 // NEEDS_STUB_METHOD is true if we need to use a stub method which
10103 // calls the real method. TYPES_SEEN is used to avoid infinite
10104 // recursion.
10106 void
10107 Type::add_methods_for_type(const Type* type,
10108 const Method::Field_indexes* field_indexes,
10109 unsigned int depth,
10110 bool is_embedded_pointer,
10111 bool needs_stub_method,
10112 std::vector<const Named_type*>* seen,
10113 Methods* methods)
10115 // Pointer types may not have methods.
10116 if (type->points_to() != NULL)
10117 return;
10119 const Named_type* nt = type->named_type();
10120 if (nt != NULL)
10122 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
10123 p != seen->end();
10124 ++p)
10126 if (*p == nt)
10127 return;
10130 seen->push_back(nt);
10132 Type::add_local_methods_for_type(nt, field_indexes, depth,
10133 is_embedded_pointer, needs_stub_method,
10134 methods);
10137 Type::add_embedded_methods_for_type(type, field_indexes, depth,
10138 is_embedded_pointer, needs_stub_method,
10139 seen, methods);
10141 // If we are called with depth > 0, then we are looking at an
10142 // anonymous field of a struct. If such a field has interface type,
10143 // then we need to add the interface methods. We don't want to add
10144 // them when depth == 0, because we will already handle them
10145 // following the usual rules for an interface type.
10146 if (depth > 0)
10147 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
10149 if (nt != NULL)
10150 seen->pop_back();
10153 // Add the local methods for the named type NT to *METHODS. The
10154 // parameters are as for add_methods_to_type.
10156 void
10157 Type::add_local_methods_for_type(const Named_type* nt,
10158 const Method::Field_indexes* field_indexes,
10159 unsigned int depth,
10160 bool is_embedded_pointer,
10161 bool needs_stub_method,
10162 Methods* methods)
10164 const Bindings* local_methods = nt->local_methods();
10165 if (local_methods == NULL)
10166 return;
10168 for (Bindings::const_declarations_iterator p =
10169 local_methods->begin_declarations();
10170 p != local_methods->end_declarations();
10171 ++p)
10173 Named_object* no = p->second;
10174 bool is_value_method = (is_embedded_pointer
10175 || !Type::method_expects_pointer(no));
10176 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
10177 (needs_stub_method || depth > 0));
10178 if (!methods->insert(no->name(), m))
10179 delete m;
10183 // Add the embedded methods for TYPE to *METHODS. These are the
10184 // methods attached to anonymous fields. The parameters are as for
10185 // add_methods_to_type.
10187 void
10188 Type::add_embedded_methods_for_type(const Type* type,
10189 const Method::Field_indexes* field_indexes,
10190 unsigned int depth,
10191 bool is_embedded_pointer,
10192 bool needs_stub_method,
10193 std::vector<const Named_type*>* seen,
10194 Methods* methods)
10196 // Look for anonymous fields in TYPE. TYPE has fields if it is a
10197 // struct.
10198 const Struct_type* st = type->struct_type();
10199 if (st == NULL)
10200 return;
10202 const Struct_field_list* fields = st->fields();
10203 if (fields == NULL)
10204 return;
10206 unsigned int i = 0;
10207 for (Struct_field_list::const_iterator pf = fields->begin();
10208 pf != fields->end();
10209 ++pf, ++i)
10211 if (!pf->is_anonymous())
10212 continue;
10214 Type* ftype = pf->type();
10215 bool is_pointer = false;
10216 if (ftype->points_to() != NULL)
10218 ftype = ftype->points_to();
10219 is_pointer = true;
10221 Named_type* fnt = ftype->named_type();
10222 if (fnt == NULL)
10224 // This is an error, but it will be diagnosed elsewhere.
10225 continue;
10228 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
10229 sub_field_indexes->next = field_indexes;
10230 sub_field_indexes->field_index = i;
10232 Methods tmp_methods;
10233 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
10234 (is_embedded_pointer || is_pointer),
10235 (needs_stub_method
10236 || is_pointer
10237 || i > 0),
10238 seen,
10239 &tmp_methods);
10240 // Check if there are promoted methods that conflict with field names and
10241 // don't add them to the method map.
10242 for (Methods::const_iterator p = tmp_methods.begin();
10243 p != tmp_methods.end();
10244 ++p)
10246 bool found = false;
10247 for (Struct_field_list::const_iterator fp = fields->begin();
10248 fp != fields->end();
10249 ++fp)
10251 if (fp->field_name() == p->first)
10253 found = true;
10254 break;
10257 if (!found &&
10258 !methods->insert(p->first, p->second))
10259 delete p->second;
10264 // If TYPE is an interface type, then add its method to *METHODS.
10265 // This is for interface methods attached to an anonymous field. The
10266 // parameters are as for add_methods_for_type.
10268 void
10269 Type::add_interface_methods_for_type(const Type* type,
10270 const Method::Field_indexes* field_indexes,
10271 unsigned int depth,
10272 Methods* methods)
10274 const Interface_type* it = type->interface_type();
10275 if (it == NULL)
10276 return;
10278 const Typed_identifier_list* imethods = it->methods();
10279 if (imethods == NULL)
10280 return;
10282 for (Typed_identifier_list::const_iterator pm = imethods->begin();
10283 pm != imethods->end();
10284 ++pm)
10286 Function_type* fntype = pm->type()->function_type();
10287 if (fntype == NULL)
10289 // This is an error, but it should be reported elsewhere
10290 // when we look at the methods for IT.
10291 continue;
10293 go_assert(!fntype->is_method());
10294 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
10295 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
10296 field_indexes, depth);
10297 if (!methods->insert(pm->name(), m))
10298 delete m;
10302 // Build stub methods for TYPE as needed. METHODS is the set of
10303 // methods for the type. A stub method may be needed when a type
10304 // inherits a method from an anonymous field. When we need the
10305 // address of the method, as in a type descriptor, we need to build a
10306 // little stub which does the required field dereferences and jumps to
10307 // the real method. LOCATION is the location of the type definition.
10309 void
10310 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
10311 Location location)
10313 if (methods == NULL)
10314 return;
10315 for (Methods::const_iterator p = methods->begin();
10316 p != methods->end();
10317 ++p)
10319 Method* m = p->second;
10320 if (m->is_ambiguous() || !m->needs_stub_method())
10321 continue;
10323 const std::string& name(p->first);
10325 // Build a stub method.
10327 const Function_type* fntype = m->type();
10329 static unsigned int counter;
10330 char buf[100];
10331 snprintf(buf, sizeof buf, "$this%u", counter);
10332 ++counter;
10334 Type* receiver_type = const_cast<Type*>(type);
10335 if (!m->is_value_method())
10336 receiver_type = Type::make_pointer_type(receiver_type);
10337 Location receiver_location = m->receiver_location();
10338 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
10339 receiver_location);
10341 const Typed_identifier_list* fnparams = fntype->parameters();
10342 Typed_identifier_list* stub_params;
10343 if (fnparams == NULL || fnparams->empty())
10344 stub_params = NULL;
10345 else
10347 // We give each stub parameter a unique name.
10348 stub_params = new Typed_identifier_list();
10349 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
10350 pp != fnparams->end();
10351 ++pp)
10353 char pbuf[100];
10354 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
10355 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
10356 pp->location()));
10357 ++counter;
10361 const Typed_identifier_list* fnresults = fntype->results();
10362 Typed_identifier_list* stub_results;
10363 if (fnresults == NULL || fnresults->empty())
10364 stub_results = NULL;
10365 else
10367 // We create the result parameters without any names, since
10368 // we won't refer to them.
10369 stub_results = new Typed_identifier_list();
10370 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
10371 pr != fnresults->end();
10372 ++pr)
10373 stub_results->push_back(Typed_identifier("", pr->type(),
10374 pr->location()));
10377 Function_type* stub_type = Type::make_function_type(receiver,
10378 stub_params,
10379 stub_results,
10380 fntype->location());
10381 if (fntype->is_varargs())
10382 stub_type->set_is_varargs();
10384 // We only create the function in the package which creates the
10385 // type.
10386 const Package* package;
10387 if (type->named_type() == NULL)
10388 package = NULL;
10389 else
10390 package = type->named_type()->named_object()->package();
10391 std::string stub_name = name + "$stub";
10392 Named_object* stub;
10393 if (package != NULL)
10394 stub = Named_object::make_function_declaration(stub_name, package,
10395 stub_type, location);
10396 else
10398 stub = gogo->start_function(stub_name, stub_type, false,
10399 fntype->location());
10400 Type::build_one_stub_method(gogo, m, buf, stub_params,
10401 fntype->is_varargs(), location);
10402 gogo->finish_function(fntype->location());
10404 if (type->named_type() == NULL && stub->is_function())
10405 stub->func_value()->set_is_unnamed_type_stub_method();
10406 if (m->nointerface() && stub->is_function())
10407 stub->func_value()->set_nointerface();
10410 m->set_stub_object(stub);
10414 // Build a stub method which adjusts the receiver as required to call
10415 // METHOD. RECEIVER_NAME is the name we used for the receiver.
10416 // PARAMS is the list of function parameters.
10418 void
10419 Type::build_one_stub_method(Gogo* gogo, Method* method,
10420 const char* receiver_name,
10421 const Typed_identifier_list* params,
10422 bool is_varargs,
10423 Location location)
10425 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
10426 go_assert(receiver_object != NULL);
10428 Expression* expr = Expression::make_var_reference(receiver_object, location);
10429 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
10430 if (expr->type()->points_to() == NULL)
10431 expr = Expression::make_unary(OPERATOR_AND, expr, location);
10433 Expression_list* arguments;
10434 if (params == NULL || params->empty())
10435 arguments = NULL;
10436 else
10438 arguments = new Expression_list();
10439 for (Typed_identifier_list::const_iterator p = params->begin();
10440 p != params->end();
10441 ++p)
10443 Named_object* param = gogo->lookup(p->name(), NULL);
10444 go_assert(param != NULL);
10445 Expression* param_ref = Expression::make_var_reference(param,
10446 location);
10447 arguments->push_back(param_ref);
10451 Expression* func = method->bind_method(expr, location);
10452 go_assert(func != NULL);
10453 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
10454 location);
10456 gogo->add_statement(Statement::make_return_from_call(call, location));
10459 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
10460 // in reverse order.
10462 Expression*
10463 Type::apply_field_indexes(Expression* expr,
10464 const Method::Field_indexes* field_indexes,
10465 Location location)
10467 if (field_indexes == NULL)
10468 return expr;
10469 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
10470 Struct_type* stype = expr->type()->deref()->struct_type();
10471 go_assert(stype != NULL
10472 && field_indexes->field_index < stype->field_count());
10473 if (expr->type()->struct_type() == NULL)
10475 go_assert(expr->type()->points_to() != NULL);
10476 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
10477 go_assert(expr->type()->struct_type() == stype);
10479 return Expression::make_field_reference(expr, field_indexes->field_index,
10480 location);
10483 // Return whether NO is a method for which the receiver is a pointer.
10485 bool
10486 Type::method_expects_pointer(const Named_object* no)
10488 const Function_type *fntype;
10489 if (no->is_function())
10490 fntype = no->func_value()->type();
10491 else if (no->is_function_declaration())
10492 fntype = no->func_declaration_value()->type();
10493 else
10494 go_unreachable();
10495 return fntype->receiver()->type()->points_to() != NULL;
10498 // Given a set of methods for a type, METHODS, return the method NAME,
10499 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
10500 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
10501 // but is ambiguous (and return NULL).
10503 Method*
10504 Type::method_function(const Methods* methods, const std::string& name,
10505 bool* is_ambiguous)
10507 if (is_ambiguous != NULL)
10508 *is_ambiguous = false;
10509 if (methods == NULL)
10510 return NULL;
10511 Methods::const_iterator p = methods->find(name);
10512 if (p == methods->end())
10513 return NULL;
10514 Method* m = p->second;
10515 if (m->is_ambiguous())
10517 if (is_ambiguous != NULL)
10518 *is_ambiguous = true;
10519 return NULL;
10521 return m;
10524 // Return a pointer to the interface method table for TYPE for the
10525 // interface INTERFACE.
10527 Expression*
10528 Type::interface_method_table(Type* type,
10529 Interface_type *interface,
10530 bool is_pointer,
10531 Interface_method_tables** method_tables,
10532 Interface_method_tables** pointer_tables)
10534 go_assert(!interface->is_empty());
10536 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
10538 if (*pimt == NULL)
10539 *pimt = new Interface_method_tables(5);
10541 std::pair<Interface_type*, Expression*> val(interface, NULL);
10542 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
10544 Location loc = Linemap::predeclared_location();
10545 if (ins.second)
10547 // This is a new entry in the hash table.
10548 go_assert(ins.first->second == NULL);
10549 ins.first->second =
10550 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
10552 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
10555 // Look for field or method NAME for TYPE. Return an Expression for
10556 // the field or method bound to EXPR. If there is no such field or
10557 // method, give an appropriate error and return an error expression.
10559 Expression*
10560 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
10561 const std::string& name,
10562 Location location)
10564 if (type->deref()->is_error_type())
10565 return Expression::make_error(location);
10567 const Named_type* nt = type->deref()->named_type();
10568 const Struct_type* st = type->deref()->struct_type();
10569 const Interface_type* it = type->interface_type();
10571 // If this is a pointer to a pointer, then it is possible that the
10572 // pointed-to type has methods.
10573 bool dereferenced = false;
10574 if (nt == NULL
10575 && st == NULL
10576 && it == NULL
10577 && type->points_to() != NULL
10578 && type->points_to()->points_to() != NULL)
10580 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
10581 type = type->points_to();
10582 if (type->deref()->is_error_type())
10583 return Expression::make_error(location);
10584 nt = type->points_to()->named_type();
10585 st = type->points_to()->struct_type();
10586 dereferenced = true;
10589 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
10590 || expr->is_addressable());
10591 std::vector<const Named_type*> seen;
10592 bool is_method = false;
10593 bool found_pointer_method = false;
10594 std::string ambig1;
10595 std::string ambig2;
10596 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
10597 &seen, NULL, &is_method,
10598 &found_pointer_method, &ambig1, &ambig2))
10600 Expression* ret;
10601 if (!is_method)
10603 go_assert(st != NULL);
10604 if (type->struct_type() == NULL)
10606 go_assert(type->points_to() != NULL);
10607 expr = Expression::make_unary(OPERATOR_MULT, expr,
10608 location);
10609 go_assert(expr->type()->struct_type() == st);
10611 ret = st->field_reference(expr, name, location);
10613 else if (it != NULL && it->find_method(name) != NULL)
10614 ret = Expression::make_interface_field_reference(expr, name,
10615 location);
10616 else
10618 Method* m;
10619 if (nt != NULL)
10620 m = nt->method_function(name, NULL);
10621 else if (st != NULL)
10622 m = st->method_function(name, NULL);
10623 else
10624 go_unreachable();
10625 go_assert(m != NULL);
10626 if (dereferenced)
10628 go_error_at(location,
10629 "calling method %qs requires explicit dereference",
10630 Gogo::message_name(name).c_str());
10631 return Expression::make_error(location);
10633 if (!m->is_value_method() && expr->type()->points_to() == NULL)
10634 expr = Expression::make_unary(OPERATOR_AND, expr, location);
10635 ret = m->bind_method(expr, location);
10637 go_assert(ret != NULL);
10638 return ret;
10640 else
10642 if (Gogo::is_erroneous_name(name))
10644 // An error was already reported.
10646 else if (!ambig1.empty())
10647 go_error_at(location, "%qs is ambiguous via %qs and %qs",
10648 Gogo::message_name(name).c_str(), ambig1.c_str(),
10649 ambig2.c_str());
10650 else if (found_pointer_method)
10651 go_error_at(location, "method requires a pointer receiver");
10652 else if (nt == NULL && st == NULL && it == NULL)
10653 go_error_at(location,
10654 ("reference to field %qs in object which "
10655 "has no fields or methods"),
10656 Gogo::message_name(name).c_str());
10657 else
10659 bool is_unexported;
10660 // The test for 'a' and 'z' is to handle builtin names,
10661 // which are not hidden.
10662 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
10663 is_unexported = false;
10664 else
10666 std::string unpacked = Gogo::unpack_hidden_name(name);
10667 seen.clear();
10668 is_unexported = Type::is_unexported_field_or_method(gogo, type,
10669 unpacked,
10670 &seen);
10672 if (is_unexported)
10673 go_error_at(location, "reference to unexported field or method %qs",
10674 Gogo::message_name(name).c_str());
10675 else
10676 go_error_at(location, "reference to undefined field or method %qs",
10677 Gogo::message_name(name).c_str());
10679 return Expression::make_error(location);
10683 // Look in TYPE for a field or method named NAME, return true if one
10684 // is found. This looks through embedded anonymous fields and handles
10685 // ambiguity. If a method is found, sets *IS_METHOD to true;
10686 // otherwise, if a field is found, set it to false. If
10687 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
10688 // whose address can not be taken. SEEN is used to avoid infinite
10689 // recursion on invalid types.
10691 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
10692 // method we couldn't use because it requires a pointer. LEVEL is
10693 // used for recursive calls, and can be NULL for a non-recursive call.
10694 // When this function returns false because it finds that the name is
10695 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
10696 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
10697 // will be unchanged.
10699 // This function just returns whether or not there is a field or
10700 // method, and whether it is a field or method. It doesn't build an
10701 // expression to refer to it. If it is a method, we then look in the
10702 // list of all methods for the type. If it is a field, the search has
10703 // to be done again, looking only for fields, and building up the
10704 // expression as we go.
10706 bool
10707 Type::find_field_or_method(const Type* type,
10708 const std::string& name,
10709 bool receiver_can_be_pointer,
10710 std::vector<const Named_type*>* seen,
10711 int* level,
10712 bool* is_method,
10713 bool* found_pointer_method,
10714 std::string* ambig1,
10715 std::string* ambig2)
10717 // Named types can have locally defined methods.
10718 const Named_type* nt = type->named_type();
10719 if (nt == NULL && type->points_to() != NULL)
10720 nt = type->points_to()->named_type();
10721 if (nt != NULL)
10723 Named_object* no = nt->find_local_method(name);
10724 if (no != NULL)
10726 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
10728 *is_method = true;
10729 return true;
10732 // Record that we have found a pointer method in order to
10733 // give a better error message if we don't find anything
10734 // else.
10735 *found_pointer_method = true;
10738 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
10739 p != seen->end();
10740 ++p)
10742 if (*p == nt)
10744 // We've already seen this type when searching for methods.
10745 return false;
10750 // Interface types can have methods.
10751 const Interface_type* it = type->interface_type();
10752 if (it != NULL && it->find_method(name) != NULL)
10754 *is_method = true;
10755 return true;
10758 // Struct types can have fields. They can also inherit fields and
10759 // methods from anonymous fields.
10760 const Struct_type* st = type->deref()->struct_type();
10761 if (st == NULL)
10762 return false;
10763 const Struct_field_list* fields = st->fields();
10764 if (fields == NULL)
10765 return false;
10767 if (nt != NULL)
10768 seen->push_back(nt);
10770 int found_level = 0;
10771 bool found_is_method = false;
10772 std::string found_ambig1;
10773 std::string found_ambig2;
10774 const Struct_field* found_parent = NULL;
10775 for (Struct_field_list::const_iterator pf = fields->begin();
10776 pf != fields->end();
10777 ++pf)
10779 if (pf->is_field_name(name))
10781 *is_method = false;
10782 if (nt != NULL)
10783 seen->pop_back();
10784 return true;
10787 if (!pf->is_anonymous())
10788 continue;
10790 if (pf->type()->deref()->is_error_type()
10791 || pf->type()->deref()->is_undefined())
10792 continue;
10794 Named_type* fnt = pf->type()->named_type();
10795 if (fnt == NULL)
10796 fnt = pf->type()->deref()->named_type();
10797 go_assert(fnt != NULL);
10799 // Methods with pointer receivers on embedded field are
10800 // inherited by the pointer to struct, and also by the struct
10801 // type if the field itself is a pointer.
10802 bool can_be_pointer = (receiver_can_be_pointer
10803 || pf->type()->points_to() != NULL);
10804 int sublevel = level == NULL ? 1 : *level + 1;
10805 bool sub_is_method;
10806 std::string subambig1;
10807 std::string subambig2;
10808 bool subfound = Type::find_field_or_method(fnt,
10809 name,
10810 can_be_pointer,
10811 seen,
10812 &sublevel,
10813 &sub_is_method,
10814 found_pointer_method,
10815 &subambig1,
10816 &subambig2);
10817 if (!subfound)
10819 if (!subambig1.empty())
10821 // The name was found via this field, but is ambiguous.
10822 // if the ambiguity is lower or at the same level as
10823 // anything else we have already found, then we want to
10824 // pass the ambiguity back to the caller.
10825 if (found_level == 0 || sublevel <= found_level)
10827 found_ambig1 = (Gogo::message_name(pf->field_name())
10828 + '.' + subambig1);
10829 found_ambig2 = (Gogo::message_name(pf->field_name())
10830 + '.' + subambig2);
10831 found_level = sublevel;
10835 else
10837 // The name was found via this field. Use the level to see
10838 // if we want to use this one, or whether it introduces an
10839 // ambiguity.
10840 if (found_level == 0 || sublevel < found_level)
10842 found_level = sublevel;
10843 found_is_method = sub_is_method;
10844 found_ambig1.clear();
10845 found_ambig2.clear();
10846 found_parent = &*pf;
10848 else if (sublevel > found_level)
10850 else if (found_ambig1.empty())
10852 // We found an ambiguity.
10853 go_assert(found_parent != NULL);
10854 found_ambig1 = Gogo::message_name(found_parent->field_name());
10855 found_ambig2 = Gogo::message_name(pf->field_name());
10857 else
10859 // We found an ambiguity, but we already know of one.
10860 // Just report the earlier one.
10865 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
10866 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
10867 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
10868 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
10870 if (nt != NULL)
10871 seen->pop_back();
10873 if (found_level == 0)
10874 return false;
10875 else if (found_is_method
10876 && type->named_type() != NULL
10877 && type->points_to() != NULL)
10879 // If this is a method inherited from a struct field in a named pointer
10880 // type, it is invalid to automatically dereference the pointer to the
10881 // struct to find this method.
10882 if (level != NULL)
10883 *level = found_level;
10884 *is_method = true;
10885 return false;
10887 else if (!found_ambig1.empty())
10889 go_assert(!found_ambig1.empty());
10890 ambig1->assign(found_ambig1);
10891 ambig2->assign(found_ambig2);
10892 if (level != NULL)
10893 *level = found_level;
10894 return false;
10896 else
10898 if (level != NULL)
10899 *level = found_level;
10900 *is_method = found_is_method;
10901 return true;
10905 // Return whether NAME is an unexported field or method for TYPE.
10907 bool
10908 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
10909 const std::string& name,
10910 std::vector<const Named_type*>* seen)
10912 const Named_type* nt = type->named_type();
10913 if (nt == NULL)
10914 nt = type->deref()->named_type();
10915 if (nt != NULL)
10917 if (nt->is_unexported_local_method(gogo, name))
10918 return true;
10920 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
10921 p != seen->end();
10922 ++p)
10924 if (*p == nt)
10926 // We've already seen this type.
10927 return false;
10932 const Interface_type* it = type->interface_type();
10933 if (it != NULL && it->is_unexported_method(gogo, name))
10934 return true;
10936 type = type->deref();
10938 const Struct_type* st = type->struct_type();
10939 if (st != NULL && st->is_unexported_local_field(gogo, name))
10940 return true;
10942 if (st == NULL)
10943 return false;
10945 const Struct_field_list* fields = st->fields();
10946 if (fields == NULL)
10947 return false;
10949 if (nt != NULL)
10950 seen->push_back(nt);
10952 for (Struct_field_list::const_iterator pf = fields->begin();
10953 pf != fields->end();
10954 ++pf)
10956 if (pf->is_anonymous()
10957 && !pf->type()->deref()->is_error_type()
10958 && !pf->type()->deref()->is_undefined())
10960 Named_type* subtype = pf->type()->named_type();
10961 if (subtype == NULL)
10962 subtype = pf->type()->deref()->named_type();
10963 if (subtype == NULL)
10965 // This is an error, but it will be diagnosed elsewhere.
10966 continue;
10968 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
10970 if (nt != NULL)
10971 seen->pop_back();
10972 return true;
10977 if (nt != NULL)
10978 seen->pop_back();
10980 return false;
10983 // Class Forward_declaration.
10985 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
10986 : Type(TYPE_FORWARD),
10987 named_object_(named_object->resolve()), warned_(false)
10989 go_assert(this->named_object_->is_unknown()
10990 || this->named_object_->is_type_declaration());
10993 // Return the named object.
10995 Named_object*
10996 Forward_declaration_type::named_object()
10998 return this->named_object_->resolve();
11001 const Named_object*
11002 Forward_declaration_type::named_object() const
11004 return this->named_object_->resolve();
11007 // Return the name of the forward declared type.
11009 const std::string&
11010 Forward_declaration_type::name() const
11012 return this->named_object()->name();
11015 // Warn about a use of a type which has been declared but not defined.
11017 void
11018 Forward_declaration_type::warn() const
11020 Named_object* no = this->named_object_->resolve();
11021 if (no->is_unknown())
11023 // The name was not defined anywhere.
11024 if (!this->warned_)
11026 go_error_at(this->named_object_->location(),
11027 "use of undefined type %qs",
11028 no->message_name().c_str());
11029 this->warned_ = true;
11032 else if (no->is_type_declaration())
11034 // The name was seen as a type, but the type was never defined.
11035 if (no->type_declaration_value()->using_type())
11037 go_error_at(this->named_object_->location(),
11038 "use of undefined type %qs",
11039 no->message_name().c_str());
11040 this->warned_ = true;
11043 else
11045 // The name was defined, but not as a type.
11046 if (!this->warned_)
11048 go_error_at(this->named_object_->location(), "expected type");
11049 this->warned_ = true;
11054 // Get the base type of a declaration. This gives an error if the
11055 // type has not yet been defined.
11057 Type*
11058 Forward_declaration_type::real_type()
11060 if (this->is_defined())
11062 Named_type* nt = this->named_object()->type_value();
11063 if (!nt->is_valid())
11064 return Type::make_error_type();
11065 return this->named_object()->type_value();
11067 else
11069 this->warn();
11070 return Type::make_error_type();
11074 const Type*
11075 Forward_declaration_type::real_type() const
11077 if (this->is_defined())
11079 const Named_type* nt = this->named_object()->type_value();
11080 if (!nt->is_valid())
11081 return Type::make_error_type();
11082 return this->named_object()->type_value();
11084 else
11086 this->warn();
11087 return Type::make_error_type();
11091 // Return whether the base type is defined.
11093 bool
11094 Forward_declaration_type::is_defined() const
11096 return this->named_object()->is_type();
11099 // Add a method. This is used when methods are defined before the
11100 // type.
11102 Named_object*
11103 Forward_declaration_type::add_method(const std::string& name,
11104 Function* function)
11106 Named_object* no = this->named_object();
11107 if (no->is_unknown())
11108 no->declare_as_type();
11109 return no->type_declaration_value()->add_method(name, function);
11112 // Add a method declaration. This is used when methods are declared
11113 // before the type.
11115 Named_object*
11116 Forward_declaration_type::add_method_declaration(const std::string& name,
11117 Package* package,
11118 Function_type* type,
11119 Location location)
11121 Named_object* no = this->named_object();
11122 if (no->is_unknown())
11123 no->declare_as_type();
11124 Type_declaration* td = no->type_declaration_value();
11125 return td->add_method_declaration(name, package, type, location);
11128 // Traversal.
11131 Forward_declaration_type::do_traverse(Traverse* traverse)
11133 if (this->is_defined()
11134 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
11135 return TRAVERSE_EXIT;
11136 return TRAVERSE_CONTINUE;
11139 // Verify the type.
11141 bool
11142 Forward_declaration_type::do_verify()
11144 if (!this->is_defined() && !this->is_nil_constant_as_type())
11146 this->warn();
11147 return false;
11149 return true;
11152 // Get the backend representation for the type.
11154 Btype*
11155 Forward_declaration_type::do_get_backend(Gogo* gogo)
11157 if (this->is_defined())
11158 return Type::get_named_base_btype(gogo, this->real_type());
11160 if (this->warned_)
11161 return gogo->backend()->error_type();
11163 // We represent an undefined type as a struct with no fields. That
11164 // should work fine for the backend, since the same case can arise
11165 // in C.
11166 std::vector<Backend::Btyped_identifier> fields;
11167 Btype* bt = gogo->backend()->struct_type(fields);
11168 return gogo->backend()->named_type(this->name(), bt,
11169 this->named_object()->location());
11172 // Build a type descriptor for a forwarded type.
11174 Expression*
11175 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
11177 Location ploc = Linemap::predeclared_location();
11178 if (!this->is_defined())
11179 return Expression::make_error(ploc);
11180 else
11182 Type* t = this->real_type();
11183 if (name != NULL)
11184 return this->named_type_descriptor(gogo, t, name);
11185 else
11186 return Expression::make_type_descriptor(t, ploc);
11190 // The reflection string.
11192 void
11193 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
11195 this->append_reflection(this->real_type(), gogo, ret);
11198 // The mangled name.
11200 void
11201 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
11203 if (this->is_defined())
11204 this->append_mangled_name(this->real_type(), gogo, ret);
11205 else
11207 const Named_object* no = this->named_object();
11208 std::string name;
11209 if (no->package() == NULL)
11210 name = gogo->pkgpath_symbol();
11211 else
11212 name = no->package()->pkgpath_symbol();
11213 name += '.';
11214 name += Gogo::unpack_hidden_name(no->name());
11215 char buf[20];
11216 snprintf(buf, sizeof buf, "N%u_",
11217 static_cast<unsigned int>(name.length()));
11218 ret->append(buf);
11219 ret->append(name);
11223 // Export a forward declaration. This can happen when a defined type
11224 // refers to a type which is only declared (and is presumably defined
11225 // in some other file in the same package).
11227 void
11228 Forward_declaration_type::do_export(Export*) const
11230 // If there is a base type, that should be exported instead of this.
11231 go_assert(!this->is_defined());
11233 // We don't output anything.
11236 // Make a forward declaration.
11238 Type*
11239 Type::make_forward_declaration(Named_object* named_object)
11241 return new Forward_declaration_type(named_object);
11244 // Class Typed_identifier_list.
11246 // Sort the entries by name.
11248 struct Typed_identifier_list_sort
11250 public:
11251 bool
11252 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
11254 return (Gogo::unpack_hidden_name(t1.name())
11255 < Gogo::unpack_hidden_name(t2.name()));
11259 void
11260 Typed_identifier_list::sort_by_name()
11262 std::sort(this->entries_.begin(), this->entries_.end(),
11263 Typed_identifier_list_sort());
11266 // Traverse types.
11269 Typed_identifier_list::traverse(Traverse* traverse)
11271 for (Typed_identifier_list::const_iterator p = this->begin();
11272 p != this->end();
11273 ++p)
11275 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
11276 return TRAVERSE_EXIT;
11278 return TRAVERSE_CONTINUE;
11281 // Copy the list.
11283 Typed_identifier_list*
11284 Typed_identifier_list::copy() const
11286 Typed_identifier_list* ret = new Typed_identifier_list();
11287 for (Typed_identifier_list::const_iterator p = this->begin();
11288 p != this->end();
11289 ++p)
11290 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
11291 return ret;