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.
11 #ifndef ENABLE_BUILD_WITH_CXX
23 #ifndef ENABLE_BUILD_WITH_CXX
30 #include "expressions.h"
31 #include "statements.h"
37 // Forward declarations so that we don't have to make types.h #include
41 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
43 std::vector<Backend::Btyped_identifier>* bfields);
46 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
47 std::vector<Backend::Btyped_identifier>* bfields);
50 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
52 std::vector<Backend::Btyped_identifier>* bfields);
56 Type::Type(Type_classification classification)
57 : classification_(classification), btype_is_placeholder_(false),
58 btype_(NULL), type_descriptor_var_(NULL)
66 // Get the base type for a type--skip names and forward declarations.
71 switch (this->classification_)
74 return this->named_type()->named_base();
76 return this->forward_declaration_type()->real_type()->base();
85 switch (this->classification_)
88 return this->named_type()->named_base();
90 return this->forward_declaration_type()->real_type()->base();
96 // Skip defined forward declarations.
102 Forward_declaration_type* ftype = t->forward_declaration_type();
103 while (ftype != NULL && ftype->is_defined())
105 t = ftype->real_type();
106 ftype = t->forward_declaration_type();
112 Type::forwarded() const
114 const Type* t = this;
115 const Forward_declaration_type* ftype = t->forward_declaration_type();
116 while (ftype != NULL && ftype->is_defined())
118 t = ftype->real_type();
119 ftype = t->forward_declaration_type();
124 // If this is a named type, return it. Otherwise, return NULL.
129 return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
133 Type::named_type() const
135 return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
138 // Return true if this type is not defined.
141 Type::is_undefined() const
143 return this->forwarded()->forward_declaration_type() != NULL;
146 // Return true if this is a basic type: a type which is not composed
147 // of other types, and is not void.
150 Type::is_basic_type() const
152 switch (this->classification_)
175 return this->base()->is_basic_type();
182 // Return true if this is an abstract type.
185 Type::is_abstract() const
187 switch (this->classification())
190 return this->integer_type()->is_abstract();
192 return this->float_type()->is_abstract();
194 return this->complex_type()->is_abstract();
196 return this->is_abstract_string_type();
198 return this->is_abstract_boolean_type();
204 // Return a non-abstract version of an abstract type.
207 Type::make_non_abstract_type()
209 go_assert(this->is_abstract());
210 switch (this->classification())
213 if (this->integer_type()->is_rune())
214 return Type::lookup_integer_type("int32");
216 return Type::lookup_integer_type("int");
218 return Type::lookup_float_type("float64");
220 return Type::lookup_complex_type("complex128");
222 return Type::lookup_string_type();
224 return Type::lookup_bool_type();
230 // Return true if this is an error type. Don't give an error if we
231 // try to dereference an undefined forwarding type, as this is called
232 // in the parser when the type may legitimately be undefined.
235 Type::is_error_type() const
237 const Type* t = this->forwarded();
238 // Note that we return false for an undefined forward type.
239 switch (t->classification_)
244 return t->named_type()->is_named_error_type();
250 // If this is a pointer type, return the type to which it points.
251 // Otherwise, return NULL.
254 Type::points_to() const
256 const Pointer_type* ptype = this->convert<const Pointer_type,
258 return ptype == NULL ? NULL : ptype->points_to();
261 // Return whether this is an open array type.
264 Type::is_slice_type() const
266 return this->array_type() != NULL && this->array_type()->length() == NULL;
269 // Return whether this is the predeclared constant nil being used as a
273 Type::is_nil_constant_as_type() const
275 const Type* t = this->forwarded();
276 if (t->forward_declaration_type() != NULL)
278 const Named_object* no = t->forward_declaration_type()->named_object();
279 if (no->is_unknown())
280 no = no->unknown_value()->real_named_object();
283 && no->const_value()->expr()->is_nil_expression())
292 Type::traverse(Type* type, Traverse* traverse)
294 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
295 || (traverse->traverse_mask()
296 & Traverse::traverse_expressions) != 0);
297 if (traverse->remember_type(type))
299 // We have already traversed this type.
300 return TRAVERSE_CONTINUE;
302 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
304 int t = traverse->type(type);
305 if (t == TRAVERSE_EXIT)
306 return TRAVERSE_EXIT;
307 else if (t == TRAVERSE_SKIP_COMPONENTS)
308 return TRAVERSE_CONTINUE;
310 // An array type has an expression which we need to traverse if
311 // traverse_expressions is set.
312 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
313 return TRAVERSE_EXIT;
314 return TRAVERSE_CONTINUE;
317 // Default implementation for do_traverse for child class.
320 Type::do_traverse(Traverse*)
322 return TRAVERSE_CONTINUE;
325 // Return whether two types are identical. If ERRORS_ARE_IDENTICAL,
326 // then return true for all erroneous types; this is used to avoid
327 // cascading errors. If REASON is not NULL, optionally set *REASON to
328 // the reason the types are not identical.
331 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
334 if (t1 == NULL || t2 == NULL)
336 // Something is wrong.
337 return errors_are_identical ? true : t1 == t2;
340 // Skip defined forward declarations.
341 t1 = t1->forwarded();
342 t2 = t2->forwarded();
344 // Ignore aliases for purposes of type identity.
345 if (t1->named_type() != NULL && t1->named_type()->is_alias())
346 t1 = t1->named_type()->real_type();
347 if (t2->named_type() != NULL && t2->named_type()->is_alias())
348 t2 = t2->named_type()->real_type();
353 // An undefined forward declaration is an error.
354 if (t1->forward_declaration_type() != NULL
355 || t2->forward_declaration_type() != NULL)
356 return errors_are_identical;
358 // Avoid cascading errors with error types.
359 if (t1->is_error_type() || t2->is_error_type())
361 if (errors_are_identical)
363 return t1->is_error_type() && t2->is_error_type();
366 // Get a good reason for the sink type. Note that the sink type on
367 // the left hand side of an assignment is handled in are_assignable.
368 if (t1->is_sink_type() || t2->is_sink_type())
371 *reason = "invalid use of _";
375 // A named type is only identical to itself.
376 if (t1->named_type() != NULL || t2->named_type() != NULL)
379 // Check type shapes.
380 if (t1->classification() != t2->classification())
383 switch (t1->classification())
389 // These types are always identical.
393 return t1->integer_type()->is_identical(t2->integer_type());
396 return t1->float_type()->is_identical(t2->float_type());
399 return t1->complex_type()->is_identical(t2->complex_type());
402 return t1->function_type()->is_identical(t2->function_type(),
404 errors_are_identical,
408 return Type::are_identical(t1->points_to(), t2->points_to(),
409 errors_are_identical, reason);
412 return t1->struct_type()->is_identical(t2->struct_type(),
413 errors_are_identical);
416 return t1->array_type()->is_identical(t2->array_type(),
417 errors_are_identical);
420 return t1->map_type()->is_identical(t2->map_type(),
421 errors_are_identical);
424 return t1->channel_type()->is_identical(t2->channel_type(),
425 errors_are_identical);
428 return t1->interface_type()->is_identical(t2->interface_type(),
429 errors_are_identical);
431 case TYPE_CALL_MULTIPLE_RESULT:
433 *reason = "invalid use of multiple value function call";
441 // Return true if it's OK to have a binary operation with types LHS
442 // and RHS. This is not used for shifts or comparisons.
445 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
447 if (Type::are_identical(lhs, rhs, true, NULL))
450 // A constant of abstract bool type may be mixed with any bool type.
451 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
452 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
455 // A constant of abstract string type may be mixed with any string
457 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
458 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
464 // A constant of abstract integer, float, or complex type may be
465 // mixed with an integer, float, or complex type.
466 if ((rhs->is_abstract()
467 && (rhs->integer_type() != NULL
468 || rhs->float_type() != NULL
469 || rhs->complex_type() != NULL)
470 && (lhs->integer_type() != NULL
471 || lhs->float_type() != NULL
472 || lhs->complex_type() != NULL))
473 || (lhs->is_abstract()
474 && (lhs->integer_type() != NULL
475 || lhs->float_type() != NULL
476 || lhs->complex_type() != NULL)
477 && (rhs->integer_type() != NULL
478 || rhs->float_type() != NULL
479 || rhs->complex_type() != NULL)))
482 // The nil type may be compared to a pointer, an interface type, a
483 // slice type, a channel type, a map type, or a function type.
484 if (lhs->is_nil_type()
485 && (rhs->points_to() != NULL
486 || rhs->interface_type() != NULL
487 || rhs->is_slice_type()
488 || rhs->map_type() != NULL
489 || rhs->channel_type() != NULL
490 || rhs->function_type() != NULL))
492 if (rhs->is_nil_type()
493 && (lhs->points_to() != NULL
494 || lhs->interface_type() != NULL
495 || lhs->is_slice_type()
496 || lhs->map_type() != NULL
497 || lhs->channel_type() != NULL
498 || lhs->function_type() != NULL))
504 // Return true if a value with type T1 may be compared with a value of
505 // type T2. IS_EQUALITY_OP is true for == or !=, false for <, etc.
508 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
509 const Type *t2, std::string *reason)
512 && !Type::are_assignable(t1, t2, NULL)
513 && !Type::are_assignable(t2, t1, NULL))
516 *reason = "incompatible types in binary expression";
522 if (t1->integer_type() == NULL
523 && t1->float_type() == NULL
524 && !t1->is_string_type())
527 *reason = _("invalid comparison of non-ordered type");
531 else if (t1->is_slice_type()
532 || t1->map_type() != NULL
533 || t1->function_type() != NULL
534 || t2->is_slice_type()
535 || t2->map_type() != NULL
536 || t2->function_type() != NULL)
538 if (!t1->is_nil_type() && !t2->is_nil_type())
542 if (t1->is_slice_type() || t2->is_slice_type())
543 *reason = _("slice can only be compared to nil");
544 else if (t1->map_type() != NULL || t2->map_type() != NULL)
545 *reason = _("map can only be compared to nil");
547 *reason = _("func can only be compared to nil");
549 // Match 6g error messages.
550 if (t1->interface_type() != NULL || t2->interface_type() != NULL)
553 snprintf(buf, sizeof buf, _("invalid operation (%s)"),
563 if (!t1->is_boolean_type()
564 && t1->integer_type() == NULL
565 && t1->float_type() == NULL
566 && t1->complex_type() == NULL
567 && !t1->is_string_type()
568 && t1->points_to() == NULL
569 && t1->channel_type() == NULL
570 && t1->interface_type() == NULL
571 && t1->struct_type() == NULL
572 && t1->array_type() == NULL
573 && !t1->is_nil_type())
576 *reason = _("invalid comparison of non-comparable type");
580 if (t1->named_type() != NULL)
581 return t1->named_type()->named_type_is_comparable(reason);
582 else if (t2->named_type() != NULL)
583 return t2->named_type()->named_type_is_comparable(reason);
584 else if (t1->struct_type() != NULL)
586 const Struct_field_list* fields = t1->struct_type()->fields();
587 for (Struct_field_list::const_iterator p = fields->begin();
591 if (!p->type()->is_comparable())
594 *reason = _("invalid comparison of non-comparable struct");
599 else if (t1->array_type() != NULL)
601 if (t1->array_type()->length()->is_nil_expression()
602 || !t1->array_type()->element_type()->is_comparable())
605 *reason = _("invalid comparison of non-comparable array");
614 // Return true if a value with type RHS may be assigned to a variable
615 // with type LHS. If CHECK_HIDDEN_FIELDS is true, check whether any
616 // hidden fields are modified. If REASON is not NULL, set *REASON to
617 // the reason the types are not assignable.
620 Type::are_assignable_check_hidden(const Type* lhs, const Type* rhs,
621 bool check_hidden_fields,
624 // Do some checks first. Make sure the types are defined.
626 && rhs->forwarded()->forward_declaration_type() == NULL
627 && rhs->is_void_type())
630 *reason = "non-value used as value";
634 if (lhs != NULL && lhs->forwarded()->forward_declaration_type() == NULL)
636 // Any value may be assigned to the blank identifier.
637 if (lhs->is_sink_type())
640 // All fields of a struct must be exported, or the assignment
641 // must be in the same package.
642 if (check_hidden_fields
644 && rhs->forwarded()->forward_declaration_type() == NULL)
646 if (lhs->has_hidden_fields(NULL, reason)
647 || rhs->has_hidden_fields(NULL, reason))
652 // Identical types are assignable.
653 if (Type::are_identical(lhs, rhs, true, reason))
656 // The types are assignable if they have identical underlying types
657 // and either LHS or RHS is not a named type.
658 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
659 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
660 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
663 // The types are assignable if LHS is an interface type and RHS
664 // implements the required methods.
665 const Interface_type* lhs_interface_type = lhs->interface_type();
666 if (lhs_interface_type != NULL)
668 if (lhs_interface_type->implements_interface(rhs, reason))
670 const Interface_type* rhs_interface_type = rhs->interface_type();
671 if (rhs_interface_type != NULL
672 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
677 // The type are assignable if RHS is a bidirectional channel type,
678 // LHS is a channel type, they have identical element types, and
679 // either LHS or RHS is not a named type.
680 if (lhs->channel_type() != NULL
681 && rhs->channel_type() != NULL
682 && rhs->channel_type()->may_send()
683 && rhs->channel_type()->may_receive()
684 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
685 && Type::are_identical(lhs->channel_type()->element_type(),
686 rhs->channel_type()->element_type(),
691 // The nil type may be assigned to a pointer, function, slice, map,
692 // channel, or interface type.
693 if (rhs->is_nil_type()
694 && (lhs->points_to() != NULL
695 || lhs->function_type() != NULL
696 || lhs->is_slice_type()
697 || lhs->map_type() != NULL
698 || lhs->channel_type() != NULL
699 || lhs->interface_type() != NULL))
702 // An untyped numeric constant may be assigned to a numeric type if
703 // it is representable in that type.
704 if ((rhs->is_abstract()
705 && (rhs->integer_type() != NULL
706 || rhs->float_type() != NULL
707 || rhs->complex_type() != NULL))
708 && (lhs->integer_type() != NULL
709 || lhs->float_type() != NULL
710 || lhs->complex_type() != NULL))
713 // Give some better error messages.
714 if (reason != NULL && reason->empty())
716 if (rhs->interface_type() != NULL)
717 reason->assign(_("need explicit conversion"));
718 else if (rhs->is_call_multiple_result_type())
719 reason->assign(_("multiple value function call in "
720 "single value context"));
721 else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
723 size_t len = (lhs->named_type()->name().length()
724 + rhs->named_type()->name().length()
726 char* buf = new char[len];
727 snprintf(buf, len, _("cannot use type %s as type %s"),
728 rhs->named_type()->message_name().c_str(),
729 lhs->named_type()->message_name().c_str());
738 // Return true if a value with type RHS may be assigned to a variable
739 // with type LHS. If REASON is not NULL, set *REASON to the reason
740 // the types are not assignable.
743 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
745 return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
748 // Like are_assignable but don't check for hidden fields.
751 Type::are_assignable_hidden_ok(const Type* lhs, const Type* rhs,
754 return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
757 // Return true if a value with type RHS may be converted to type LHS.
758 // If REASON is not NULL, set *REASON to the reason the types are not
762 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
764 // The types are convertible if they are assignable.
765 if (Type::are_assignable(lhs, rhs, reason))
768 // The types are convertible if they have identical underlying
770 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
771 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
774 // The types are convertible if they are both unnamed pointer types
775 // and their pointer base types have identical underlying types.
776 if (lhs->named_type() == NULL
777 && rhs->named_type() == NULL
778 && lhs->points_to() != NULL
779 && rhs->points_to() != NULL
780 && (lhs->points_to()->named_type() != NULL
781 || rhs->points_to()->named_type() != NULL)
782 && Type::are_identical(lhs->points_to()->base(),
783 rhs->points_to()->base(),
788 // Integer and floating point types are convertible to each other.
789 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
790 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
793 // Complex types are convertible to each other.
794 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
797 // An integer, or []byte, or []rune, may be converted to a string.
798 if (lhs->is_string_type())
800 if (rhs->integer_type() != NULL)
802 if (rhs->is_slice_type())
804 const Type* e = rhs->array_type()->element_type()->forwarded();
805 if (e->integer_type() != NULL
806 && (e->integer_type()->is_byte()
807 || e->integer_type()->is_rune()))
812 // A string may be converted to []byte or []rune.
813 if (rhs->is_string_type() && lhs->is_slice_type())
815 const Type* e = lhs->array_type()->element_type()->forwarded();
816 if (e->integer_type() != NULL
817 && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
821 // An unsafe.Pointer type may be converted to any pointer type or to
822 // uintptr, and vice-versa.
823 if (lhs->is_unsafe_pointer_type()
824 && (rhs->points_to() != NULL
825 || (rhs->integer_type() != NULL
826 && rhs->forwarded() == Type::lookup_integer_type("uintptr"))))
828 if (rhs->is_unsafe_pointer_type()
829 && (lhs->points_to() != NULL
830 || (lhs->integer_type() != NULL
831 && lhs->forwarded() == Type::lookup_integer_type("uintptr"))))
834 // Give a better error message.
838 *reason = "invalid type conversion";
841 std::string s = "invalid type conversion (";
851 // Return whether this type has any hidden fields. This is only a
852 // possibility for a few types.
855 Type::has_hidden_fields(const Named_type* within, std::string* reason) const
857 switch (this->forwarded()->classification_)
860 return this->named_type()->named_type_has_hidden_fields(reason);
862 return this->struct_type()->struct_has_hidden_fields(within, reason);
864 return this->array_type()->array_has_hidden_fields(within, reason);
870 // Return a hash code for the type to be used for method lookup.
873 Type::hash_for_method(Gogo* gogo) const
875 unsigned int ret = 0;
876 if (this->classification_ != TYPE_FORWARD)
877 ret += this->classification_;
878 return ret + this->do_hash_for_method(gogo);
881 // Default implementation of do_hash_for_method. This is appropriate
882 // for types with no subfields.
885 Type::do_hash_for_method(Gogo*) const
890 // Return a hash code for a string, given a starting hash.
893 Type::hash_string(const std::string& s, unsigned int h)
895 const char* p = s.data();
896 size_t len = s.length();
897 for (; len > 0; --len)
905 // A hash table mapping unnamed types to the backend representation of
908 Type::Type_btypes Type::type_btypes;
910 // Return a tree representing this type.
913 Type::get_backend(Gogo* gogo)
915 if (this->btype_ != NULL)
917 if (this->btype_is_placeholder_ && gogo->named_types_are_converted())
918 this->finish_backend(gogo);
922 if (this->forward_declaration_type() != NULL
923 || this->named_type() != NULL)
924 return this->get_btype_without_hash(gogo);
926 if (this->is_error_type())
927 return gogo->backend()->error_type();
929 // To avoid confusing the backend, translate all identical Go types
930 // to the same backend representation. We use a hash table to do
931 // that. There is no need to use the hash table for named types, as
932 // named types are only identical to themselves.
934 std::pair<Type*, Btype*> val(this, NULL);
935 std::pair<Type_btypes::iterator, bool> ins =
936 Type::type_btypes.insert(val);
937 if (!ins.second && ins.first->second != NULL)
939 if (gogo != NULL && gogo->named_types_are_converted())
940 this->btype_ = ins.first->second;
941 return ins.first->second;
944 Btype* bt = this->get_btype_without_hash(gogo);
946 if (ins.first->second == NULL)
947 ins.first->second = bt;
950 // We have already created a backend representation for this
951 // type. This can happen when an unnamed type is defined using
952 // a named type which in turns uses an identical unnamed type.
953 // Use the tree we created earlier and ignore the one we just
955 bt = ins.first->second;
956 if (gogo == NULL || !gogo->named_types_are_converted())
964 // Return the backend representation for a type without looking in the
965 // hash table for identical types. This is used for named types,
966 // since a named type is never identical to any other type.
969 Type::get_btype_without_hash(Gogo* gogo)
971 if (this->btype_ == NULL)
973 Btype* bt = this->do_get_backend(gogo);
975 // For a recursive function or pointer type, we will temporarily
976 // return a circular pointer type during the recursion. We
977 // don't want to record that for a forwarding type, as it may
979 if (this->forward_declaration_type() != NULL
980 && gogo->backend()->is_circular_pointer_type(bt))
983 if (gogo == NULL || !gogo->named_types_are_converted())
991 // Get the backend representation of a type without forcing the
992 // creation of the backend representation of all supporting types.
993 // This will return a backend type that has the correct size but may
994 // be incomplete. E.g., a pointer will just be a placeholder pointer,
995 // and will not contain the final representation of the type to which
996 // it points. This is used while converting all named types to the
997 // backend representation, to avoid problems with indirect references
998 // to types which are not yet complete. When this is called, the
999 // sizes of all direct references (e.g., a struct field) should be
1000 // known, but the sizes of indirect references (e.g., the type to
1001 // which a pointer points) may not.
1004 Type::get_backend_placeholder(Gogo* gogo)
1006 if (gogo->named_types_are_converted())
1007 return this->get_backend(gogo);
1008 if (this->btype_ != NULL)
1009 return this->btype_;
1012 switch (this->classification_)
1022 // These are simple types that can just be created directly.
1023 return this->get_backend(gogo);
1027 Location loc = this->function_type()->location();
1028 bt = gogo->backend()->placeholder_pointer_type("", loc, true);
1034 Location loc = Linemap::unknown_location();
1035 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1040 // We don't have to make the struct itself be a placeholder. We
1041 // are promised that we know the sizes of the struct fields.
1042 // But we may have to use a placeholder for any particular
1045 std::vector<Backend::Btyped_identifier> bfields;
1046 get_backend_struct_fields(gogo, this->struct_type()->fields(),
1048 bt = gogo->backend()->struct_type(bfields);
1053 if (this->is_slice_type())
1055 std::vector<Backend::Btyped_identifier> bfields;
1056 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1057 bt = gogo->backend()->struct_type(bfields);
1061 Btype* element = this->array_type()->get_backend_element(gogo, true);
1062 Bexpression* len = this->array_type()->get_backend_length(gogo);
1063 bt = gogo->backend()->array_type(element, len);
1069 // All maps and channels have the same backend representation.
1070 return this->get_backend(gogo);
1072 case TYPE_INTERFACE:
1073 if (this->interface_type()->is_empty())
1074 return Interface_type::get_backend_empty_interface_type(gogo);
1077 std::vector<Backend::Btyped_identifier> bfields;
1078 get_backend_interface_fields(gogo, this->interface_type(), true,
1080 bt = gogo->backend()->struct_type(bfields);
1086 // Named types keep track of their own dependencies and manage
1087 // their own placeholders.
1088 return this->get_backend(gogo);
1091 case TYPE_CALL_MULTIPLE_RESULT:
1097 this->btype_is_placeholder_ = true;
1101 // Complete the backend representation. This is called for a type
1102 // using a placeholder type.
1105 Type::finish_backend(Gogo* gogo)
1107 go_assert(this->btype_ != NULL);
1108 if (!this->btype_is_placeholder_)
1111 switch (this->classification_)
1125 Btype* bt = this->do_get_backend(gogo);
1126 if (!gogo->backend()->set_placeholder_function_type(this->btype_, bt))
1127 go_assert(saw_errors());
1133 Btype* bt = this->do_get_backend(gogo);
1134 if (!gogo->backend()->set_placeholder_pointer_type(this->btype_, bt))
1135 go_assert(saw_errors());
1140 // The struct type itself is done, but we have to make sure that
1141 // all the field types are converted.
1142 this->struct_type()->finish_backend_fields(gogo);
1146 // The array type itself is done, but make sure the element type
1148 this->array_type()->finish_backend_element(gogo);
1155 case TYPE_INTERFACE:
1156 // The interface type itself is done, but make sure the method
1157 // types are converted.
1158 this->interface_type()->finish_backend_methods(gogo);
1166 case TYPE_CALL_MULTIPLE_RESULT:
1171 this->btype_is_placeholder_ = false;
1174 // Return a pointer to the type descriptor for this type.
1177 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1179 Type* t = this->forwarded();
1180 if (t->named_type() != NULL && t->named_type()->is_alias())
1181 t = t->named_type()->real_type();
1182 if (t->type_descriptor_var_ == NULL)
1184 t->make_type_descriptor_var(gogo);
1185 go_assert(t->type_descriptor_var_ != NULL);
1187 tree var_tree = var_to_tree(t->type_descriptor_var_);
1188 if (var_tree == error_mark_node)
1189 return error_mark_node;
1190 return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
1193 // A mapping from unnamed types to type descriptor variables.
1195 Type::Type_descriptor_vars Type::type_descriptor_vars;
1197 // Build the type descriptor for this type.
1200 Type::make_type_descriptor_var(Gogo* gogo)
1202 go_assert(this->type_descriptor_var_ == NULL);
1204 Named_type* nt = this->named_type();
1206 // We can have multiple instances of unnamed types, but we only want
1207 // to emit the type descriptor once. We use a hash table. This is
1208 // not necessary for named types, as they are unique, and we store
1209 // the type descriptor in the type itself.
1210 Bvariable** phash = NULL;
1213 Bvariable* bvnull = NULL;
1214 std::pair<Type_descriptor_vars::iterator, bool> ins =
1215 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1218 // We've already build a type descriptor for this type.
1219 this->type_descriptor_var_ = ins.first->second;
1222 phash = &ins.first->second;
1225 std::string var_name = this->type_descriptor_var_name(gogo, nt);
1227 // Build the contents of the type descriptor.
1228 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1230 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1232 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1234 const Package* dummy;
1235 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1237 this->type_descriptor_var_ =
1238 gogo->backend()->immutable_struct_reference(var_name,
1242 *phash = this->type_descriptor_var_;
1246 // See if this type descriptor can appear in multiple packages.
1247 bool is_common = false;
1250 // We create the descriptor for a builtin type whenever we need
1252 is_common = nt->is_builtin();
1256 // This is an unnamed type. The descriptor could be defined in
1257 // any package where it is needed, and the linker will pick one
1258 // descriptor to keep.
1262 // We are going to build the type descriptor in this package. We
1263 // must create the variable before we convert the initializer to the
1264 // backend representation, because the initializer may refer to the
1265 // type descriptor of this type. By setting type_descriptor_var_ we
1266 // ensure that type_descriptor_pointer will work if called while
1267 // converting INITIALIZER.
1269 this->type_descriptor_var_ =
1270 gogo->backend()->immutable_struct(var_name, is_common, initializer_btype,
1273 *phash = this->type_descriptor_var_;
1275 Translate_context context(gogo, NULL, NULL, NULL);
1276 context.set_is_const();
1277 Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
1279 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1280 var_name, is_common,
1281 initializer_btype, loc,
1285 // Return the name of the type descriptor variable. If NT is not
1286 // NULL, use it to get the name. Otherwise this is an unnamed type.
1289 Type::type_descriptor_var_name(Gogo* gogo, Named_type* nt)
1292 return "__go_td_" + this->mangled_name(gogo);
1294 Named_object* no = nt->named_object();
1295 const Named_object* in_function = nt->in_function();
1296 std::string ret = "__go_tdn_";
1297 if (nt->is_builtin())
1298 go_assert(in_function == NULL);
1301 const std::string& unique_prefix(no->package() == NULL
1302 ? gogo->unique_prefix()
1303 : no->package()->unique_prefix());
1304 const std::string& package_name(no->package() == NULL
1305 ? gogo->package_name()
1306 : no->package()->name());
1307 ret.append(unique_prefix);
1309 ret.append(package_name);
1311 if (in_function != NULL)
1313 ret.append(Gogo::unpack_hidden_name(in_function->name()));
1317 ret.append(no->name());
1321 // Return true if this type descriptor is defined in a different
1322 // package. If this returns true it sets *PACKAGE to the package.
1325 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1326 const Package** package)
1330 if (nt->named_object()->package() != NULL)
1332 // This is a named type defined in a different package. The
1333 // type descriptor should be defined in that package.
1334 *package = nt->named_object()->package();
1340 if (this->points_to() != NULL
1341 && this->points_to()->named_type() != NULL
1342 && this->points_to()->named_type()->named_object()->package() != NULL)
1344 // This is an unnamed pointer to a named type defined in a
1345 // different package. The descriptor should be defined in
1347 *package = this->points_to()->named_type()->named_object()->package();
1354 // Return a composite literal for a type descriptor.
1357 Type::type_descriptor(Gogo* gogo, Type* type)
1359 return type->do_type_descriptor(gogo, NULL);
1362 // Return a composite literal for a type descriptor with a name.
1365 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1367 go_assert(name != NULL && type->named_type() != name);
1368 return type->do_type_descriptor(gogo, name);
1371 // Make a builtin struct type from a list of fields. The fields are
1372 // pairs of a name and a type.
1375 Type::make_builtin_struct_type(int nfields, ...)
1378 va_start(ap, nfields);
1380 Location bloc = Linemap::predeclared_location();
1381 Struct_field_list* sfl = new Struct_field_list();
1382 for (int i = 0; i < nfields; i++)
1384 const char* field_name = va_arg(ap, const char *);
1385 Type* type = va_arg(ap, Type*);
1386 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1391 return Type::make_struct_type(sfl, bloc);
1394 // A list of builtin named types.
1396 std::vector<Named_type*> Type::named_builtin_types;
1398 // Make a builtin named type.
1401 Type::make_builtin_named_type(const char* name, Type* type)
1403 Location bloc = Linemap::predeclared_location();
1404 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1405 Named_type* ret = no->type_value();
1406 Type::named_builtin_types.push_back(ret);
1410 // Convert the named builtin types.
1413 Type::convert_builtin_named_types(Gogo* gogo)
1415 for (std::vector<Named_type*>::const_iterator p =
1416 Type::named_builtin_types.begin();
1417 p != Type::named_builtin_types.end();
1420 bool r = (*p)->verify();
1422 (*p)->convert(gogo);
1426 // Return the type of a type descriptor. We should really tie this to
1427 // runtime.Type rather than copying it. This must match commonType in
1428 // libgo/go/runtime/type.go.
1431 Type::make_type_descriptor_type()
1436 Location bloc = Linemap::predeclared_location();
1438 Type* uint8_type = Type::lookup_integer_type("uint8");
1439 Type* uint32_type = Type::lookup_integer_type("uint32");
1440 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1441 Type* string_type = Type::lookup_string_type();
1442 Type* pointer_string_type = Type::make_pointer_type(string_type);
1444 // This is an unnamed version of unsafe.Pointer. Perhaps we
1445 // should use the named version instead, although that would
1446 // require us to create the unsafe package if it has not been
1447 // imported. It probably doesn't matter.
1448 Type* void_type = Type::make_void_type();
1449 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1451 // Forward declaration for the type descriptor type.
1452 Named_object* named_type_descriptor_type =
1453 Named_object::make_type_declaration("commonType", NULL, bloc);
1454 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1455 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1457 // The type of a method on a concrete type.
1458 Struct_type* method_type =
1459 Type::make_builtin_struct_type(5,
1460 "name", pointer_string_type,
1461 "pkgPath", pointer_string_type,
1462 "mtyp", pointer_type_descriptor_type,
1463 "typ", pointer_type_descriptor_type,
1464 "tfn", unsafe_pointer_type);
1465 Named_type* named_method_type =
1466 Type::make_builtin_named_type("method", method_type);
1468 // Information for types with a name or methods.
1469 Type* slice_named_method_type =
1470 Type::make_array_type(named_method_type, NULL);
1471 Struct_type* uncommon_type =
1472 Type::make_builtin_struct_type(3,
1473 "name", pointer_string_type,
1474 "pkgPath", pointer_string_type,
1475 "methods", slice_named_method_type);
1476 Named_type* named_uncommon_type =
1477 Type::make_builtin_named_type("uncommonType", uncommon_type);
1479 Type* pointer_uncommon_type =
1480 Type::make_pointer_type(named_uncommon_type);
1482 // The type descriptor type.
1484 Typed_identifier_list* params = new Typed_identifier_list();
1485 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1486 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1488 Typed_identifier_list* results = new Typed_identifier_list();
1489 results->push_back(Typed_identifier("", uintptr_type, bloc));
1491 Type* hashfn_type = Type::make_function_type(NULL, params, results, bloc);
1493 params = new Typed_identifier_list();
1494 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1495 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1496 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1498 results = new Typed_identifier_list();
1499 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1501 Type* equalfn_type = Type::make_function_type(NULL, params, results,
1504 Struct_type* type_descriptor_type =
1505 Type::make_builtin_struct_type(10,
1507 "align", uint8_type,
1508 "fieldAlign", uint8_type,
1509 "size", uintptr_type,
1510 "hash", uint32_type,
1511 "hashfn", hashfn_type,
1512 "equalfn", equalfn_type,
1513 "string", pointer_string_type,
1514 "", pointer_uncommon_type,
1516 pointer_type_descriptor_type);
1518 Named_type* named = Type::make_builtin_named_type("commonType",
1519 type_descriptor_type);
1521 named_type_descriptor_type->set_type_value(named);
1529 // Make the type of a pointer to a type descriptor as represented in
1533 Type::make_type_descriptor_ptr_type()
1537 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1541 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1542 // hash code for this type and which compare whether two values of
1543 // this type are equal. If NAME is not NULL it is the name of this
1544 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1545 // functions, for convenience; they may be NULL.
1548 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1549 Function_type* equal_fntype, Named_object** hash_fn,
1550 Named_object** equal_fn)
1552 if (hash_fntype == NULL || equal_fntype == NULL)
1554 Location bloc = Linemap::predeclared_location();
1556 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1557 Type* void_type = Type::make_void_type();
1558 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1560 if (hash_fntype == NULL)
1562 Typed_identifier_list* params = new Typed_identifier_list();
1563 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1565 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1567 Typed_identifier_list* results = new Typed_identifier_list();
1568 results->push_back(Typed_identifier("", uintptr_type, bloc));
1570 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1572 if (equal_fntype == NULL)
1574 Typed_identifier_list* params = new Typed_identifier_list();
1575 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1577 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1579 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1581 Typed_identifier_list* results = new Typed_identifier_list();
1582 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1585 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1589 const char* hash_fnname;
1590 const char* equal_fnname;
1591 if (this->compare_is_identity(gogo))
1593 hash_fnname = "__go_type_hash_identity";
1594 equal_fnname = "__go_type_equal_identity";
1596 else if (!this->is_comparable())
1598 hash_fnname = "__go_type_hash_error";
1599 equal_fnname = "__go_type_equal_error";
1603 switch (this->base()->classification())
1605 case Type::TYPE_ERROR:
1606 case Type::TYPE_VOID:
1607 case Type::TYPE_NIL:
1608 case Type::TYPE_FUNCTION:
1609 case Type::TYPE_MAP:
1610 // For these types is_comparable should have returned false.
1613 case Type::TYPE_BOOLEAN:
1614 case Type::TYPE_INTEGER:
1615 case Type::TYPE_POINTER:
1616 case Type::TYPE_CHANNEL:
1617 // For these types compare_is_identity should have returned true.
1620 case Type::TYPE_FLOAT:
1621 hash_fnname = "__go_type_hash_float";
1622 equal_fnname = "__go_type_equal_float";
1625 case Type::TYPE_COMPLEX:
1626 hash_fnname = "__go_type_hash_complex";
1627 equal_fnname = "__go_type_equal_complex";
1630 case Type::TYPE_STRING:
1631 hash_fnname = "__go_type_hash_string";
1632 equal_fnname = "__go_type_equal_string";
1635 case Type::TYPE_STRUCT:
1637 // This is a struct which can not be compared using a
1638 // simple identity function. We need to build a function
1640 this->specific_type_functions(gogo, name, hash_fntype,
1641 equal_fntype, hash_fn, equal_fn);
1645 case Type::TYPE_ARRAY:
1646 if (this->is_slice_type())
1648 // Type::is_compatible_for_comparison should have
1654 // This is an array which can not be compared using a
1655 // simple identity function. We need to build a
1656 // function for comparison.
1657 this->specific_type_functions(gogo, name, hash_fntype,
1658 equal_fntype, hash_fn, equal_fn);
1663 case Type::TYPE_INTERFACE:
1664 if (this->interface_type()->is_empty())
1666 hash_fnname = "__go_type_hash_empty_interface";
1667 equal_fnname = "__go_type_equal_empty_interface";
1671 hash_fnname = "__go_type_hash_interface";
1672 equal_fnname = "__go_type_equal_interface";
1676 case Type::TYPE_NAMED:
1677 case Type::TYPE_FORWARD:
1686 Location bloc = Linemap::predeclared_location();
1687 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1689 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1690 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1691 equal_fntype, bloc);
1692 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1695 // A hash table mapping types to the specific hash functions.
1697 Type::Type_functions Type::type_functions_table;
1699 // Handle a type function which is specific to a type: a struct or
1700 // array which can not use an identity comparison.
1703 Type::specific_type_functions(Gogo* gogo, Named_type* name,
1704 Function_type* hash_fntype,
1705 Function_type* equal_fntype,
1706 Named_object** hash_fn,
1707 Named_object** equal_fn)
1709 Hash_equal_fn fnull(NULL, NULL);
1710 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1711 std::pair<Type_functions::iterator, bool> ins =
1712 Type::type_functions_table.insert(val);
1715 // We already have functions for this type
1716 *hash_fn = ins.first->second.first;
1717 *equal_fn = ins.first->second.second;
1721 std::string base_name;
1724 // Mangled names can have '.' if they happen to refer to named
1725 // types in some way. That's fine if this is simply a named
1726 // type, but otherwise it will confuse the code that builds
1727 // function identifiers. Remove '.' when necessary.
1728 base_name = this->mangled_name(gogo);
1730 while ((i = base_name.find('.')) != std::string::npos)
1732 base_name = gogo->pack_hidden_name(base_name, false);
1736 // This name is already hidden or not as appropriate.
1737 base_name = name->name();
1738 const Named_object* in_function = name->in_function();
1739 if (in_function != NULL)
1740 base_name += '$' + in_function->name();
1742 std::string hash_name = base_name + "$hash";
1743 std::string equal_name = base_name + "$equal";
1745 Location bloc = Linemap::predeclared_location();
1747 const Package* package = NULL;
1748 bool is_defined_elsewhere =
1749 this->type_descriptor_defined_elsewhere(name, &package);
1750 if (is_defined_elsewhere)
1752 *hash_fn = Named_object::make_function_declaration(hash_name, package,
1754 *equal_fn = Named_object::make_function_declaration(equal_name, package,
1755 equal_fntype, bloc);
1759 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
1760 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
1764 ins.first->second.first = *hash_fn;
1765 ins.first->second.second = *equal_fn;
1767 if (!is_defined_elsewhere)
1769 if (gogo->in_global_scope())
1770 this->write_specific_type_functions(gogo, name, hash_name, hash_fntype,
1771 equal_name, equal_fntype);
1773 gogo->queue_specific_type_function(this, name, hash_name, hash_fntype,
1774 equal_name, equal_fntype);
1778 // Write the hash and equality functions for a type which needs to be
1779 // written specially.
1782 Type::write_specific_type_functions(Gogo* gogo, Named_type* name,
1783 const std::string& hash_name,
1784 Function_type* hash_fntype,
1785 const std::string& equal_name,
1786 Function_type* equal_fntype)
1788 Location bloc = Linemap::predeclared_location();
1790 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
1792 gogo->start_block(bloc);
1794 if (this->struct_type() != NULL)
1795 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
1797 else if (this->array_type() != NULL)
1798 this->array_type()->write_hash_function(gogo, name, hash_fntype,
1803 Block* b = gogo->finish_block(bloc);
1804 gogo->add_block(b, bloc);
1805 gogo->lower_block(hash_fn, b);
1806 gogo->finish_function(bloc);
1808 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
1810 gogo->start_block(bloc);
1812 if (this->struct_type() != NULL)
1813 this->struct_type()->write_equal_function(gogo, name);
1814 else if (this->array_type() != NULL)
1815 this->array_type()->write_equal_function(gogo, name);
1819 b = gogo->finish_block(bloc);
1820 gogo->add_block(b, bloc);
1821 gogo->lower_block(equal_fn, b);
1822 gogo->finish_function(bloc);
1825 // Return a composite literal for the type descriptor for a plain type
1826 // of kind RUNTIME_TYPE_KIND named NAME.
1829 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
1830 Named_type* name, const Methods* methods,
1831 bool only_value_methods)
1833 Location bloc = Linemap::predeclared_location();
1835 Type* td_type = Type::make_type_descriptor_type();
1836 const Struct_field_list* fields = td_type->struct_type()->fields();
1838 Expression_list* vals = new Expression_list();
1841 if (!this->has_pointer())
1842 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
1843 Struct_field_list::const_iterator p = fields->begin();
1844 go_assert(p->is_field_name("Kind"));
1846 mpz_init_set_ui(iv, runtime_type_kind);
1847 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1850 go_assert(p->is_field_name("align"));
1851 Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT;
1852 vals->push_back(Expression::make_type_info(this, type_info));
1855 go_assert(p->is_field_name("fieldAlign"));
1856 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
1857 vals->push_back(Expression::make_type_info(this, type_info));
1860 go_assert(p->is_field_name("size"));
1861 type_info = Expression::TYPE_INFO_SIZE;
1862 vals->push_back(Expression::make_type_info(this, type_info));
1865 go_assert(p->is_field_name("hash"));
1868 h = name->hash_for_method(gogo);
1870 h = this->hash_for_method(gogo);
1872 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1875 go_assert(p->is_field_name("hashfn"));
1876 Function_type* hash_fntype = p->type()->function_type();
1879 go_assert(p->is_field_name("equalfn"));
1880 Function_type* equal_fntype = p->type()->function_type();
1882 Named_object* hash_fn;
1883 Named_object* equal_fn;
1884 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
1886 vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
1887 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
1890 go_assert(p->is_field_name("string"));
1891 Expression* s = Expression::make_string((name != NULL
1892 ? name->reflection(gogo)
1893 : this->reflection(gogo)),
1895 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1898 go_assert(p->is_field_name("uncommonType"));
1899 if (name == NULL && methods == NULL)
1900 vals->push_back(Expression::make_nil(bloc));
1903 if (methods == NULL)
1904 methods = name->methods();
1905 vals->push_back(this->uncommon_type_constructor(gogo,
1908 only_value_methods));
1912 go_assert(p->is_field_name("ptrToThis"));
1914 vals->push_back(Expression::make_nil(bloc));
1917 Type* pt = Type::make_pointer_type(name);
1918 vals->push_back(Expression::make_type_descriptor(pt, bloc));
1922 go_assert(p == fields->end());
1926 return Expression::make_struct_composite_literal(td_type, vals, bloc);
1929 // Return a composite literal for the uncommon type information for
1930 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
1931 // struct. If name is not NULL, it is the name of the type. If
1932 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
1933 // is true if only value methods should be included. At least one of
1934 // NAME and METHODS must not be NULL.
1937 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
1938 Named_type* name, const Methods* methods,
1939 bool only_value_methods) const
1941 Location bloc = Linemap::predeclared_location();
1943 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
1945 Expression_list* vals = new Expression_list();
1948 Struct_field_list::const_iterator p = fields->begin();
1949 go_assert(p->is_field_name("name"));
1952 go_assert(p->is_field_name("pkgPath"));
1956 vals->push_back(Expression::make_nil(bloc));
1957 vals->push_back(Expression::make_nil(bloc));
1961 Named_object* no = name->named_object();
1962 std::string n = Gogo::unpack_hidden_name(no->name());
1963 Expression* s = Expression::make_string(n, bloc);
1964 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1966 if (name->is_builtin())
1967 vals->push_back(Expression::make_nil(bloc));
1970 const Package* package = no->package();
1971 const std::string& unique_prefix(package == NULL
1972 ? gogo->unique_prefix()
1973 : package->unique_prefix());
1974 const std::string& package_name(package == NULL
1975 ? gogo->package_name()
1977 n.assign(unique_prefix);
1979 n.append(package_name);
1980 if (name->in_function() != NULL)
1983 n.append(Gogo::unpack_hidden_name(name->in_function()->name()));
1985 s = Expression::make_string(n, bloc);
1986 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1991 go_assert(p->is_field_name("methods"));
1992 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
1993 only_value_methods));
1996 go_assert(p == fields->end());
1998 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
2000 return Expression::make_unary(OPERATOR_AND, r, bloc);
2003 // Sort methods by name.
2009 operator()(const std::pair<std::string, const Method*>& m1,
2010 const std::pair<std::string, const Method*>& m2) const
2011 { return m1.first < m2.first; }
2014 // Return a composite literal for the type method table for this type.
2015 // METHODS_TYPE is the type of the table, and is a slice type.
2016 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
2017 // then only value methods are used.
2020 Type::methods_constructor(Gogo* gogo, Type* methods_type,
2021 const Methods* methods,
2022 bool only_value_methods) const
2024 Location bloc = Linemap::predeclared_location();
2026 std::vector<std::pair<std::string, const Method*> > smethods;
2027 if (methods != NULL)
2029 smethods.reserve(methods->count());
2030 for (Methods::const_iterator p = methods->begin();
2031 p != methods->end();
2034 if (p->second->is_ambiguous())
2036 if (only_value_methods && !p->second->is_value_method())
2038 smethods.push_back(std::make_pair(p->first, p->second));
2042 if (smethods.empty())
2043 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
2045 std::sort(smethods.begin(), smethods.end(), Sort_methods());
2047 Type* method_type = methods_type->array_type()->element_type();
2049 Expression_list* vals = new Expression_list();
2050 vals->reserve(smethods.size());
2051 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
2053 p != smethods.end();
2055 vals->push_back(this->method_constructor(gogo, method_type, p->first,
2056 p->second, only_value_methods));
2058 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
2061 // Return a composite literal for a single method. METHOD_TYPE is the
2062 // type of the entry. METHOD_NAME is the name of the method and M is
2063 // the method information.
2066 Type::method_constructor(Gogo*, Type* method_type,
2067 const std::string& method_name,
2069 bool only_value_methods) const
2071 Location bloc = Linemap::predeclared_location();
2073 const Struct_field_list* fields = method_type->struct_type()->fields();
2075 Expression_list* vals = new Expression_list();
2078 Struct_field_list::const_iterator p = fields->begin();
2079 go_assert(p->is_field_name("name"));
2080 const std::string n = Gogo::unpack_hidden_name(method_name);
2081 Expression* s = Expression::make_string(n, bloc);
2082 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2085 go_assert(p->is_field_name("pkgPath"));
2086 if (!Gogo::is_hidden_name(method_name))
2087 vals->push_back(Expression::make_nil(bloc));
2090 s = Expression::make_string(Gogo::hidden_name_prefix(method_name), bloc);
2091 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2094 Named_object* no = (m->needs_stub_method()
2096 : m->named_object());
2098 Function_type* mtype;
2099 if (no->is_function())
2100 mtype = no->func_value()->type();
2102 mtype = no->func_declaration_value()->type();
2103 go_assert(mtype->is_method());
2104 Type* nonmethod_type = mtype->copy_without_receiver();
2107 go_assert(p->is_field_name("mtyp"));
2108 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
2111 go_assert(p->is_field_name("typ"));
2112 if (!only_value_methods && m->is_value_method())
2114 // This is a value method on a pointer type. Change the type of
2115 // the method to use a pointer receiver. The implementation
2116 // always uses a pointer receiver anyhow.
2117 Type* rtype = mtype->receiver()->type();
2118 Type* prtype = Type::make_pointer_type(rtype);
2119 Typed_identifier* receiver =
2120 new Typed_identifier(mtype->receiver()->name(), prtype,
2121 mtype->receiver()->location());
2122 mtype = Type::make_function_type(receiver,
2123 (mtype->parameters() == NULL
2125 : mtype->parameters()->copy()),
2126 (mtype->results() == NULL
2128 : mtype->results()->copy()),
2131 vals->push_back(Expression::make_type_descriptor(mtype, bloc));
2134 go_assert(p->is_field_name("tfn"));
2135 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
2138 go_assert(p == fields->end());
2140 return Expression::make_struct_composite_literal(method_type, vals, bloc);
2143 // Return a composite literal for the type descriptor of a plain type.
2144 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
2145 // NULL, it is the name to use as well as the list of methods.
2148 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
2151 return this->type_descriptor_constructor(gogo, runtime_type_kind,
2155 // Return the type reflection string for this type.
2158 Type::reflection(Gogo* gogo) const
2162 // The do_reflection virtual function should set RET to the
2163 // reflection string.
2164 this->do_reflection(gogo, &ret);
2169 // Return a mangled name for the type.
2172 Type::mangled_name(Gogo* gogo) const
2176 // The do_mangled_name virtual function should set RET to the
2177 // mangled name. For a composite type it should append a code for
2178 // the composition and then call do_mangled_name on the components.
2179 this->do_mangled_name(gogo, &ret);
2184 // Return whether the backend size of the type is known.
2187 Type::is_backend_type_size_known(Gogo* gogo)
2189 switch (this->classification_)
2203 case TYPE_INTERFACE:
2208 const Struct_field_list* fields = this->struct_type()->fields();
2209 for (Struct_field_list::const_iterator pf = fields->begin();
2210 pf != fields->end();
2212 if (!pf->type()->is_backend_type_size_known(gogo))
2219 const Array_type* at = this->array_type();
2220 if (at->length() == NULL)
2227 bool length_known = at->length()->integer_constant_value(true,
2233 return at->element_type()->is_backend_type_size_known(gogo);
2238 // Begin converting this type to the backend representation.
2239 // This will create a placeholder if necessary.
2240 this->get_backend(gogo);
2241 return this->named_type()->is_named_backend_type_size_known();
2245 Forward_declaration_type* fdt = this->forward_declaration_type();
2246 return fdt->real_type()->is_backend_type_size_known(gogo);
2250 case TYPE_CALL_MULTIPLE_RESULT:
2258 // If the size of the type can be determined, set *PSIZE to the size
2259 // in bytes and return true. Otherwise, return false. This queries
2263 Type::backend_type_size(Gogo* gogo, unsigned int *psize)
2265 if (!this->is_backend_type_size_known(gogo))
2267 Btype* bt = this->get_backend_placeholder(gogo);
2268 size_t size = gogo->backend()->type_size(bt);
2269 *psize = static_cast<unsigned int>(size);
2275 // If the alignment of the type can be determined, set *PALIGN to
2276 // the alignment in bytes and return true. Otherwise, return false.
2279 Type::backend_type_align(Gogo* gogo, unsigned int *palign)
2281 if (!this->is_backend_type_size_known(gogo))
2283 Btype* bt = this->get_backend_placeholder(gogo);
2284 size_t align = gogo->backend()->type_alignment(bt);
2285 *palign = static_cast<unsigned int>(align);
2286 if (*palign != align)
2291 // Like backend_type_align, but return the alignment when used as a
2295 Type::backend_type_field_align(Gogo* gogo, unsigned int *palign)
2297 if (!this->is_backend_type_size_known(gogo))
2299 Btype* bt = this->get_backend_placeholder(gogo);
2300 size_t a = gogo->backend()->type_field_alignment(bt);
2301 *palign = static_cast<unsigned int>(a);
2307 // Default function to export a type.
2310 Type::do_export(Export*) const
2318 Type::import_type(Import* imp)
2320 if (imp->match_c_string("("))
2321 return Function_type::do_import(imp);
2322 else if (imp->match_c_string("*"))
2323 return Pointer_type::do_import(imp);
2324 else if (imp->match_c_string("struct "))
2325 return Struct_type::do_import(imp);
2326 else if (imp->match_c_string("["))
2327 return Array_type::do_import(imp);
2328 else if (imp->match_c_string("map "))
2329 return Map_type::do_import(imp);
2330 else if (imp->match_c_string("chan "))
2331 return Channel_type::do_import(imp);
2332 else if (imp->match_c_string("interface"))
2333 return Interface_type::do_import(imp);
2336 error_at(imp->location(), "import error: expected type");
2337 return Type::make_error_type();
2341 // A type used to indicate a parsing error. This exists to simplify
2342 // later error detection.
2344 class Error_type : public Type
2353 do_compare_is_identity(Gogo*) const
2357 do_get_backend(Gogo* gogo)
2358 { return gogo->backend()->error_type(); }
2361 do_type_descriptor(Gogo*, Named_type*)
2362 { return Expression::make_error(Linemap::predeclared_location()); }
2365 do_reflection(Gogo*, std::string*) const
2366 { go_assert(saw_errors()); }
2369 do_mangled_name(Gogo*, std::string* ret) const
2370 { ret->push_back('E'); }
2374 Type::make_error_type()
2376 static Error_type singleton_error_type;
2377 return &singleton_error_type;
2382 class Void_type : public Type
2391 do_compare_is_identity(Gogo*) const
2395 do_get_backend(Gogo* gogo)
2396 { return gogo->backend()->void_type(); }
2399 do_type_descriptor(Gogo*, Named_type*)
2400 { go_unreachable(); }
2403 do_reflection(Gogo*, std::string*) const
2407 do_mangled_name(Gogo*, std::string* ret) const
2408 { ret->push_back('v'); }
2412 Type::make_void_type()
2414 static Void_type singleton_void_type;
2415 return &singleton_void_type;
2418 // The boolean type.
2420 class Boolean_type : public Type
2424 : Type(TYPE_BOOLEAN)
2429 do_compare_is_identity(Gogo*) const
2433 do_get_backend(Gogo* gogo)
2434 { return gogo->backend()->bool_type(); }
2437 do_type_descriptor(Gogo*, Named_type* name);
2439 // We should not be asked for the reflection string of a basic type.
2441 do_reflection(Gogo*, std::string* ret) const
2442 { ret->append("bool"); }
2445 do_mangled_name(Gogo*, std::string* ret) const
2446 { ret->push_back('b'); }
2449 // Make the type descriptor.
2452 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2455 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
2458 Named_object* no = gogo->lookup_global("bool");
2459 go_assert(no != NULL);
2460 return Type::type_descriptor(gogo, no->type_value());
2465 Type::make_boolean_type()
2467 static Boolean_type boolean_type;
2468 return &boolean_type;
2471 // The named type "bool".
2473 static Named_type* named_bool_type;
2475 // Get the named type "bool".
2478 Type::lookup_bool_type()
2480 return named_bool_type;
2483 // Make the named type "bool".
2486 Type::make_named_bool_type()
2488 Type* bool_type = Type::make_boolean_type();
2489 Named_object* named_object =
2490 Named_object::make_type("bool", NULL, bool_type,
2491 Linemap::predeclared_location());
2492 Named_type* named_type = named_object->type_value();
2493 named_bool_type = named_type;
2497 // Class Integer_type.
2499 Integer_type::Named_integer_types Integer_type::named_integer_types;
2501 // Create a new integer type. Non-abstract integer types always have
2505 Integer_type::create_integer_type(const char* name, bool is_unsigned,
2506 int bits, int runtime_type_kind)
2508 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
2510 std::string sname(name);
2511 Named_object* named_object =
2512 Named_object::make_type(sname, NULL, integer_type,
2513 Linemap::predeclared_location());
2514 Named_type* named_type = named_object->type_value();
2515 std::pair<Named_integer_types::iterator, bool> ins =
2516 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
2517 go_assert(ins.second);
2521 // Look up an existing integer type.
2524 Integer_type::lookup_integer_type(const char* name)
2526 Named_integer_types::const_iterator p =
2527 Integer_type::named_integer_types.find(name);
2528 go_assert(p != Integer_type::named_integer_types.end());
2532 // Create a new abstract integer type.
2535 Integer_type::create_abstract_integer_type()
2537 static Integer_type* abstract_type;
2538 if (abstract_type == NULL)
2539 abstract_type = new Integer_type(true, false, INT_TYPE_SIZE,
2540 RUNTIME_TYPE_KIND_INT);
2541 return abstract_type;
2544 // Create a new abstract character type.
2547 Integer_type::create_abstract_character_type()
2549 static Integer_type* abstract_type;
2550 if (abstract_type == NULL)
2552 abstract_type = new Integer_type(true, false, 32,
2553 RUNTIME_TYPE_KIND_INT32);
2554 abstract_type->set_is_rune();
2556 return abstract_type;
2559 // Integer type compatibility.
2562 Integer_type::is_identical(const Integer_type* t) const
2564 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
2566 return this->is_abstract_ == t->is_abstract_;
2572 Integer_type::do_hash_for_method(Gogo*) const
2574 return ((this->bits_ << 4)
2575 + ((this->is_unsigned_ ? 1 : 0) << 8)
2576 + ((this->is_abstract_ ? 1 : 0) << 9));
2579 // Convert an Integer_type to the backend representation.
2582 Integer_type::do_get_backend(Gogo* gogo)
2584 if (this->is_abstract_)
2586 go_assert(saw_errors());
2587 return gogo->backend()->error_type();
2589 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
2592 // The type descriptor for an integer type. Integer types are always
2596 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2598 go_assert(name != NULL || saw_errors());
2599 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2602 // We should not be asked for the reflection string of a basic type.
2605 Integer_type::do_reflection(Gogo*, std::string*) const
2607 go_assert(saw_errors());
2613 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
2616 snprintf(buf, sizeof buf, "i%s%s%de",
2617 this->is_abstract_ ? "a" : "",
2618 this->is_unsigned_ ? "u" : "",
2623 // Make an integer type.
2626 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
2627 int runtime_type_kind)
2629 return Integer_type::create_integer_type(name, is_unsigned, bits,
2633 // Make an abstract integer type.
2636 Type::make_abstract_integer_type()
2638 return Integer_type::create_abstract_integer_type();
2641 // Make an abstract character type.
2644 Type::make_abstract_character_type()
2646 return Integer_type::create_abstract_character_type();
2649 // Look up an integer type.
2652 Type::lookup_integer_type(const char* name)
2654 return Integer_type::lookup_integer_type(name);
2657 // Class Float_type.
2659 Float_type::Named_float_types Float_type::named_float_types;
2661 // Create a new float type. Non-abstract float types always have
2665 Float_type::create_float_type(const char* name, int bits,
2666 int runtime_type_kind)
2668 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
2669 std::string sname(name);
2670 Named_object* named_object =
2671 Named_object::make_type(sname, NULL, float_type,
2672 Linemap::predeclared_location());
2673 Named_type* named_type = named_object->type_value();
2674 std::pair<Named_float_types::iterator, bool> ins =
2675 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
2676 go_assert(ins.second);
2680 // Look up an existing float type.
2683 Float_type::lookup_float_type(const char* name)
2685 Named_float_types::const_iterator p =
2686 Float_type::named_float_types.find(name);
2687 go_assert(p != Float_type::named_float_types.end());
2691 // Create a new abstract float type.
2694 Float_type::create_abstract_float_type()
2696 static Float_type* abstract_type;
2697 if (abstract_type == NULL)
2698 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
2699 return abstract_type;
2702 // Whether this type is identical with T.
2705 Float_type::is_identical(const Float_type* t) const
2707 if (this->bits_ != t->bits_)
2709 return this->is_abstract_ == t->is_abstract_;
2715 Float_type::do_hash_for_method(Gogo*) const
2717 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2720 // Convert to the backend representation.
2723 Float_type::do_get_backend(Gogo* gogo)
2725 return gogo->backend()->float_type(this->bits_);
2728 // The type descriptor for a float type. Float types are always named.
2731 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2733 go_assert(name != NULL || saw_errors());
2734 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2737 // We should not be asked for the reflection string of a basic type.
2740 Float_type::do_reflection(Gogo*, std::string*) const
2742 go_assert(saw_errors());
2748 Float_type::do_mangled_name(Gogo*, std::string* ret) const
2751 snprintf(buf, sizeof buf, "f%s%de",
2752 this->is_abstract_ ? "a" : "",
2757 // Make a floating point type.
2760 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
2762 return Float_type::create_float_type(name, bits, runtime_type_kind);
2765 // Make an abstract float type.
2768 Type::make_abstract_float_type()
2770 return Float_type::create_abstract_float_type();
2773 // Look up a float type.
2776 Type::lookup_float_type(const char* name)
2778 return Float_type::lookup_float_type(name);
2781 // Class Complex_type.
2783 Complex_type::Named_complex_types Complex_type::named_complex_types;
2785 // Create a new complex type. Non-abstract complex types always have
2789 Complex_type::create_complex_type(const char* name, int bits,
2790 int runtime_type_kind)
2792 Complex_type* complex_type = new Complex_type(false, bits,
2794 std::string sname(name);
2795 Named_object* named_object =
2796 Named_object::make_type(sname, NULL, complex_type,
2797 Linemap::predeclared_location());
2798 Named_type* named_type = named_object->type_value();
2799 std::pair<Named_complex_types::iterator, bool> ins =
2800 Complex_type::named_complex_types.insert(std::make_pair(sname,
2802 go_assert(ins.second);
2806 // Look up an existing complex type.
2809 Complex_type::lookup_complex_type(const char* name)
2811 Named_complex_types::const_iterator p =
2812 Complex_type::named_complex_types.find(name);
2813 go_assert(p != Complex_type::named_complex_types.end());
2817 // Create a new abstract complex type.
2820 Complex_type::create_abstract_complex_type()
2822 static Complex_type* abstract_type;
2823 if (abstract_type == NULL)
2824 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
2825 return abstract_type;
2828 // Whether this type is identical with T.
2831 Complex_type::is_identical(const Complex_type *t) const
2833 if (this->bits_ != t->bits_)
2835 return this->is_abstract_ == t->is_abstract_;
2841 Complex_type::do_hash_for_method(Gogo*) const
2843 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2846 // Convert to the backend representation.
2849 Complex_type::do_get_backend(Gogo* gogo)
2851 return gogo->backend()->complex_type(this->bits_);
2854 // The type descriptor for a complex type. Complex types are always
2858 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2860 go_assert(name != NULL || saw_errors());
2861 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2864 // We should not be asked for the reflection string of a basic type.
2867 Complex_type::do_reflection(Gogo*, std::string*) const
2869 go_assert(saw_errors());
2875 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
2878 snprintf(buf, sizeof buf, "c%s%de",
2879 this->is_abstract_ ? "a" : "",
2884 // Make a complex type.
2887 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
2889 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
2892 // Make an abstract complex type.
2895 Type::make_abstract_complex_type()
2897 return Complex_type::create_abstract_complex_type();
2900 // Look up a complex type.
2903 Type::lookup_complex_type(const char* name)
2905 return Complex_type::lookup_complex_type(name);
2908 // Class String_type.
2910 // Convert String_type to the backend representation. A string is a
2911 // struct with two fields: a pointer to the characters and a length.
2914 String_type::do_get_backend(Gogo* gogo)
2916 static Btype* backend_string_type;
2917 if (backend_string_type == NULL)
2919 std::vector<Backend::Btyped_identifier> fields(2);
2921 Type* b = gogo->lookup_global("byte")->type_value();
2922 Type* pb = Type::make_pointer_type(b);
2924 // We aren't going to get back to this field to finish the
2925 // backend representation, so force it to be finished now.
2926 if (!gogo->named_types_are_converted())
2928 pb->get_backend_placeholder(gogo);
2929 pb->finish_backend(gogo);
2932 fields[0].name = "__data";
2933 fields[0].btype = pb->get_backend(gogo);
2934 fields[0].location = Linemap::predeclared_location();
2936 Type* int_type = Type::lookup_integer_type("int");
2937 fields[1].name = "__length";
2938 fields[1].btype = int_type->get_backend(gogo);
2939 fields[1].location = fields[0].location;
2941 backend_string_type = gogo->backend()->struct_type(fields);
2943 return backend_string_type;
2946 // Return a tree for the length of STRING.
2949 String_type::length_tree(Gogo*, tree string)
2951 tree string_type = TREE_TYPE(string);
2952 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2953 tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type));
2954 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)),
2956 return fold_build3(COMPONENT_REF, integer_type_node, string,
2957 length_field, NULL_TREE);
2960 // Return a tree for a pointer to the bytes of STRING.
2963 String_type::bytes_tree(Gogo*, tree string)
2965 tree string_type = TREE_TYPE(string);
2966 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2967 tree bytes_field = TYPE_FIELDS(string_type);
2968 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)),
2970 return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string,
2971 bytes_field, NULL_TREE);
2974 // The type descriptor for the string type.
2977 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2980 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
2983 Named_object* no = gogo->lookup_global("string");
2984 go_assert(no != NULL);
2985 return Type::type_descriptor(gogo, no->type_value());
2989 // We should not be asked for the reflection string of a basic type.
2992 String_type::do_reflection(Gogo*, std::string* ret) const
2994 ret->append("string");
2997 // Mangled name of a string type.
3000 String_type::do_mangled_name(Gogo*, std::string* ret) const
3002 ret->push_back('z');
3005 // Make a string type.
3008 Type::make_string_type()
3010 static String_type string_type;
3011 return &string_type;
3014 // The named type "string".
3016 static Named_type* named_string_type;
3018 // Get the named type "string".
3021 Type::lookup_string_type()
3023 return named_string_type;
3026 // Make the named type string.
3029 Type::make_named_string_type()
3031 Type* string_type = Type::make_string_type();
3032 Named_object* named_object =
3033 Named_object::make_type("string", NULL, string_type,
3034 Linemap::predeclared_location());
3035 Named_type* named_type = named_object->type_value();
3036 named_string_type = named_type;
3040 // The sink type. This is the type of the blank identifier _. Any
3041 // type may be assigned to it.
3043 class Sink_type : public Type
3052 do_compare_is_identity(Gogo*) const
3056 do_get_backend(Gogo*)
3057 { go_unreachable(); }
3060 do_type_descriptor(Gogo*, Named_type*)
3061 { go_unreachable(); }
3064 do_reflection(Gogo*, std::string*) const
3065 { go_unreachable(); }
3068 do_mangled_name(Gogo*, std::string*) const
3069 { go_unreachable(); }
3072 // Make the sink type.
3075 Type::make_sink_type()
3077 static Sink_type sink_type;
3081 // Class Function_type.
3086 Function_type::do_traverse(Traverse* traverse)
3088 if (this->receiver_ != NULL
3089 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
3090 return TRAVERSE_EXIT;
3091 if (this->parameters_ != NULL
3092 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
3093 return TRAVERSE_EXIT;
3094 if (this->results_ != NULL
3095 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
3096 return TRAVERSE_EXIT;
3097 return TRAVERSE_CONTINUE;
3100 // Returns whether T is a valid redeclaration of this type. If this
3101 // returns false, and REASON is not NULL, *REASON may be set to a
3102 // brief explanation of why it returned false.
3105 Function_type::is_valid_redeclaration(const Function_type* t,
3106 std::string* reason) const
3108 if (!this->is_identical(t, false, true, reason))
3111 // A redeclaration of a function is required to use the same names
3112 // for the receiver and parameters.
3113 if (this->receiver() != NULL
3114 && this->receiver()->name() != t->receiver()->name())
3117 *reason = "receiver name changed";
3121 const Typed_identifier_list* parms1 = this->parameters();
3122 const Typed_identifier_list* parms2 = t->parameters();
3125 Typed_identifier_list::const_iterator p1 = parms1->begin();
3126 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3127 p2 != parms2->end();
3130 if (p1->name() != p2->name())
3133 *reason = "parameter name changed";
3137 // This is called at parse time, so we may have unknown
3139 Type* t1 = p1->type()->forwarded();
3140 Type* t2 = p2->type()->forwarded();
3142 && t1->forward_declaration_type() != NULL
3143 && (t2->forward_declaration_type() == NULL
3144 || (t1->forward_declaration_type()->named_object()
3145 != t2->forward_declaration_type()->named_object())))
3150 const Typed_identifier_list* results1 = this->results();
3151 const Typed_identifier_list* results2 = t->results();
3152 if (results1 != NULL)
3154 Typed_identifier_list::const_iterator res1 = results1->begin();
3155 for (Typed_identifier_list::const_iterator res2 = results2->begin();
3156 res2 != results2->end();
3159 if (res1->name() != res2->name())
3162 *reason = "result name changed";
3166 // This is called at parse time, so we may have unknown
3168 Type* t1 = res1->type()->forwarded();
3169 Type* t2 = res2->type()->forwarded();
3171 && t1->forward_declaration_type() != NULL
3172 && (t2->forward_declaration_type() == NULL
3173 || (t1->forward_declaration_type()->named_object()
3174 != t2->forward_declaration_type()->named_object())))
3182 // Check whether T is the same as this type.
3185 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
3186 bool errors_are_identical,
3187 std::string* reason) const
3189 if (!ignore_receiver)
3191 const Typed_identifier* r1 = this->receiver();
3192 const Typed_identifier* r2 = t->receiver();
3193 if ((r1 != NULL) != (r2 != NULL))
3196 *reason = _("different receiver types");
3201 if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
3204 if (reason != NULL && !reason->empty())
3205 *reason = "receiver: " + *reason;
3211 const Typed_identifier_list* parms1 = this->parameters();
3212 const Typed_identifier_list* parms2 = t->parameters();
3213 if ((parms1 != NULL) != (parms2 != NULL))
3216 *reason = _("different number of parameters");
3221 Typed_identifier_list::const_iterator p1 = parms1->begin();
3222 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3223 p2 != parms2->end();
3226 if (p1 == parms1->end())
3229 *reason = _("different number of parameters");
3233 if (!Type::are_identical(p1->type(), p2->type(),
3234 errors_are_identical, NULL))
3237 *reason = _("different parameter types");
3241 if (p1 != parms1->end())
3244 *reason = _("different number of parameters");
3249 if (this->is_varargs() != t->is_varargs())
3252 *reason = _("different varargs");
3256 const Typed_identifier_list* results1 = this->results();
3257 const Typed_identifier_list* results2 = t->results();
3258 if ((results1 != NULL) != (results2 != NULL))
3261 *reason = _("different number of results");
3264 if (results1 != NULL)
3266 Typed_identifier_list::const_iterator res1 = results1->begin();
3267 for (Typed_identifier_list::const_iterator res2 = results2->begin();
3268 res2 != results2->end();
3271 if (res1 == results1->end())
3274 *reason = _("different number of results");
3278 if (!Type::are_identical(res1->type(), res2->type(),
3279 errors_are_identical, NULL))
3282 *reason = _("different result types");
3286 if (res1 != results1->end())
3289 *reason = _("different number of results");
3300 Function_type::do_hash_for_method(Gogo* gogo) const
3302 unsigned int ret = 0;
3303 // We ignore the receiver type for hash codes, because we need to
3304 // get the same hash code for a method in an interface and a method
3305 // declared for a type. The former will not have a receiver.
3306 if (this->parameters_ != NULL)
3309 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3310 p != this->parameters_->end();
3312 ret += p->type()->hash_for_method(gogo) << shift;
3314 if (this->results_ != NULL)
3317 for (Typed_identifier_list::const_iterator p = this->results_->begin();
3318 p != this->results_->end();
3320 ret += p->type()->hash_for_method(gogo) << shift;
3322 if (this->is_varargs_)
3328 // Get the backend representation for a function type.
3331 Function_type::do_get_backend(Gogo* gogo)
3333 Backend::Btyped_identifier breceiver;
3334 if (this->receiver_ != NULL)
3336 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
3338 // We always pass the address of the receiver parameter, in
3339 // order to make interface calls work with unknown types.
3340 Type* rtype = this->receiver_->type();
3341 if (rtype->points_to() == NULL)
3342 rtype = Type::make_pointer_type(rtype);
3343 breceiver.btype = rtype->get_backend(gogo);
3344 breceiver.location = this->receiver_->location();
3347 std::vector<Backend::Btyped_identifier> bparameters;
3348 if (this->parameters_ != NULL)
3350 bparameters.resize(this->parameters_->size());
3352 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3353 p != this->parameters_->end();
3356 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
3357 bparameters[i].btype = p->type()->get_backend(gogo);
3358 bparameters[i].location = p->location();
3360 go_assert(i == bparameters.size());
3363 std::vector<Backend::Btyped_identifier> bresults;
3364 if (this->results_ != NULL)
3366 bresults.resize(this->results_->size());
3368 for (Typed_identifier_list::const_iterator p = this->results_->begin();
3369 p != this->results_->end();
3372 bresults[i].name = Gogo::unpack_hidden_name(p->name());
3373 bresults[i].btype = p->type()->get_backend(gogo);
3374 bresults[i].location = p->location();
3376 go_assert(i == bresults.size());
3379 return gogo->backend()->function_type(breceiver, bparameters, bresults,
3383 // The type of a function type descriptor.
3386 Function_type::make_function_type_descriptor_type()
3391 Type* tdt = Type::make_type_descriptor_type();
3392 Type* ptdt = Type::make_type_descriptor_ptr_type();
3394 Type* bool_type = Type::lookup_bool_type();
3396 Type* slice_type = Type::make_array_type(ptdt, NULL);
3398 Struct_type* s = Type::make_builtin_struct_type(4,
3400 "dotdotdot", bool_type,
3404 ret = Type::make_builtin_named_type("FuncType", s);
3410 // The type descriptor for a function type.
3413 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3415 Location bloc = Linemap::predeclared_location();
3417 Type* ftdt = Function_type::make_function_type_descriptor_type();
3419 const Struct_field_list* fields = ftdt->struct_type()->fields();
3421 Expression_list* vals = new Expression_list();
3424 Struct_field_list::const_iterator p = fields->begin();
3425 go_assert(p->is_field_name("commonType"));
3426 vals->push_back(this->type_descriptor_constructor(gogo,
3427 RUNTIME_TYPE_KIND_FUNC,
3431 go_assert(p->is_field_name("dotdotdot"));
3432 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
3435 go_assert(p->is_field_name("in"));
3436 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
3437 this->parameters()));
3440 go_assert(p->is_field_name("out"));
3441 vals->push_back(this->type_descriptor_params(p->type(), NULL,
3445 go_assert(p == fields->end());
3447 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
3450 // Return a composite literal for the parameters or results of a type
3454 Function_type::type_descriptor_params(Type* params_type,
3455 const Typed_identifier* receiver,
3456 const Typed_identifier_list* params)
3458 Location bloc = Linemap::predeclared_location();
3460 if (receiver == NULL && params == NULL)
3461 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
3463 Expression_list* vals = new Expression_list();
3464 vals->reserve((params == NULL ? 0 : params->size())
3465 + (receiver != NULL ? 1 : 0));
3467 if (receiver != NULL)
3468 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
3472 for (Typed_identifier_list::const_iterator p = params->begin();
3475 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
3478 return Expression::make_slice_composite_literal(params_type, vals, bloc);
3481 // The reflection string.
3484 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
3486 // FIXME: Turn this off until we straighten out the type of the
3487 // struct field used in a go statement which calls a method.
3488 // go_assert(this->receiver_ == NULL);
3490 ret->append("func");
3492 if (this->receiver_ != NULL)
3494 ret->push_back('(');
3495 this->append_reflection(this->receiver_->type(), gogo, ret);
3496 ret->push_back(')');
3499 ret->push_back('(');
3500 const Typed_identifier_list* params = this->parameters();
3503 bool is_varargs = this->is_varargs_;
3504 for (Typed_identifier_list::const_iterator p = params->begin();
3508 if (p != params->begin())
3510 if (!is_varargs || p + 1 != params->end())
3511 this->append_reflection(p->type(), gogo, ret);
3515 this->append_reflection(p->type()->array_type()->element_type(),
3520 ret->push_back(')');
3522 const Typed_identifier_list* results = this->results();
3523 if (results != NULL && !results->empty())
3525 if (results->size() == 1)
3526 ret->push_back(' ');
3529 for (Typed_identifier_list::const_iterator p = results->begin();
3530 p != results->end();
3533 if (p != results->begin())
3535 this->append_reflection(p->type(), gogo, ret);
3537 if (results->size() > 1)
3538 ret->push_back(')');
3545 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3547 ret->push_back('F');
3549 if (this->receiver_ != NULL)
3551 ret->push_back('m');
3552 this->append_mangled_name(this->receiver_->type(), gogo, ret);
3555 const Typed_identifier_list* params = this->parameters();
3558 ret->push_back('p');
3559 for (Typed_identifier_list::const_iterator p = params->begin();
3562 this->append_mangled_name(p->type(), gogo, ret);
3563 if (this->is_varargs_)
3564 ret->push_back('V');
3565 ret->push_back('e');
3568 const Typed_identifier_list* results = this->results();
3569 if (results != NULL)
3571 ret->push_back('r');
3572 for (Typed_identifier_list::const_iterator p = results->begin();
3573 p != results->end();
3575 this->append_mangled_name(p->type(), gogo, ret);
3576 ret->push_back('e');
3579 ret->push_back('e');
3582 // Export a function type.
3585 Function_type::do_export(Export* exp) const
3587 // We don't write out the receiver. The only function types which
3588 // should have a receiver are the ones associated with explicitly
3589 // defined methods. For those the receiver type is written out by
3590 // Function::export_func.
3592 exp->write_c_string("(");
3594 if (this->parameters_ != NULL)
3596 bool is_varargs = this->is_varargs_;
3597 for (Typed_identifier_list::const_iterator p =
3598 this->parameters_->begin();
3599 p != this->parameters_->end();
3605 exp->write_c_string(", ");
3606 exp->write_name(p->name());
3607 exp->write_c_string(" ");
3608 if (!is_varargs || p + 1 != this->parameters_->end())
3609 exp->write_type(p->type());
3612 exp->write_c_string("...");
3613 exp->write_type(p->type()->array_type()->element_type());
3617 exp->write_c_string(")");
3619 const Typed_identifier_list* results = this->results_;
3620 if (results != NULL)
3622 exp->write_c_string(" ");
3623 if (results->size() == 1 && results->begin()->name().empty())
3624 exp->write_type(results->begin()->type());
3628 exp->write_c_string("(");
3629 for (Typed_identifier_list::const_iterator p = results->begin();
3630 p != results->end();
3636 exp->write_c_string(", ");
3637 exp->write_name(p->name());
3638 exp->write_c_string(" ");
3639 exp->write_type(p->type());
3641 exp->write_c_string(")");
3646 // Import a function type.
3649 Function_type::do_import(Import* imp)
3651 imp->require_c_string("(");
3652 Typed_identifier_list* parameters;
3653 bool is_varargs = false;
3654 if (imp->peek_char() == ')')
3658 parameters = new Typed_identifier_list();
3661 std::string name = imp->read_name();
3662 imp->require_c_string(" ");
3664 if (imp->match_c_string("..."))
3670 Type* ptype = imp->read_type();
3672 ptype = Type::make_array_type(ptype, NULL);
3673 parameters->push_back(Typed_identifier(name, ptype,
3675 if (imp->peek_char() != ',')
3677 go_assert(!is_varargs);
3678 imp->require_c_string(", ");
3681 imp->require_c_string(")");
3683 Typed_identifier_list* results;
3684 if (imp->peek_char() != ' ')
3689 results = new Typed_identifier_list;
3690 if (imp->peek_char() != '(')
3692 Type* rtype = imp->read_type();
3693 results->push_back(Typed_identifier("", rtype, imp->location()));
3700 std::string name = imp->read_name();
3701 imp->require_c_string(" ");
3702 Type* rtype = imp->read_type();
3703 results->push_back(Typed_identifier(name, rtype,
3705 if (imp->peek_char() != ',')
3707 imp->require_c_string(", ");
3709 imp->require_c_string(")");
3713 Function_type* ret = Type::make_function_type(NULL, parameters, results,
3716 ret->set_is_varargs();
3720 // Make a copy of a function type without a receiver.
3723 Function_type::copy_without_receiver() const
3725 go_assert(this->is_method());
3726 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
3729 if (this->is_varargs())
3730 ret->set_is_varargs();
3731 if (this->is_builtin())
3732 ret->set_is_builtin();
3736 // Make a copy of a function type with a receiver.
3739 Function_type::copy_with_receiver(Type* receiver_type) const
3741 go_assert(!this->is_method());
3742 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
3744 return Type::make_function_type(receiver, this->parameters_,
3745 this->results_, this->location_);
3748 // Make a function type.
3751 Type::make_function_type(Typed_identifier* receiver,
3752 Typed_identifier_list* parameters,
3753 Typed_identifier_list* results,
3756 return new Function_type(receiver, parameters, results, location);
3759 // Class Pointer_type.
3764 Pointer_type::do_traverse(Traverse* traverse)
3766 return Type::traverse(this->to_type_, traverse);
3772 Pointer_type::do_hash_for_method(Gogo* gogo) const
3774 return this->to_type_->hash_for_method(gogo) << 4;
3777 // Get the backend representation for a pointer type.
3780 Pointer_type::do_get_backend(Gogo* gogo)
3782 Btype* to_btype = this->to_type_->get_backend(gogo);
3783 return gogo->backend()->pointer_type(to_btype);
3786 // The type of a pointer type descriptor.
3789 Pointer_type::make_pointer_type_descriptor_type()
3794 Type* tdt = Type::make_type_descriptor_type();
3795 Type* ptdt = Type::make_type_descriptor_ptr_type();
3797 Struct_type* s = Type::make_builtin_struct_type(2,
3801 ret = Type::make_builtin_named_type("PtrType", s);
3807 // The type descriptor for a pointer type.
3810 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3812 if (this->is_unsafe_pointer_type())
3814 go_assert(name != NULL);
3815 return this->plain_type_descriptor(gogo,
3816 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
3821 Location bloc = Linemap::predeclared_location();
3823 const Methods* methods;
3824 Type* deref = this->points_to();
3825 if (deref->named_type() != NULL)
3826 methods = deref->named_type()->methods();
3827 else if (deref->struct_type() != NULL)
3828 methods = deref->struct_type()->methods();
3832 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
3834 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
3836 Expression_list* vals = new Expression_list();
3839 Struct_field_list::const_iterator p = fields->begin();
3840 go_assert(p->is_field_name("commonType"));
3841 vals->push_back(this->type_descriptor_constructor(gogo,
3842 RUNTIME_TYPE_KIND_PTR,
3843 name, methods, false));
3846 go_assert(p->is_field_name("elem"));
3847 vals->push_back(Expression::make_type_descriptor(deref, bloc));
3849 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
3853 // Reflection string.
3856 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
3858 ret->push_back('*');
3859 this->append_reflection(this->to_type_, gogo, ret);
3865 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3867 ret->push_back('p');
3868 this->append_mangled_name(this->to_type_, gogo, ret);
3874 Pointer_type::do_export(Export* exp) const
3876 exp->write_c_string("*");
3877 if (this->is_unsafe_pointer_type())
3878 exp->write_c_string("any");
3880 exp->write_type(this->to_type_);
3886 Pointer_type::do_import(Import* imp)
3888 imp->require_c_string("*");
3889 if (imp->match_c_string("any"))
3892 return Type::make_pointer_type(Type::make_void_type());
3894 Type* to = imp->read_type();
3895 return Type::make_pointer_type(to);
3898 // Make a pointer type.
3901 Type::make_pointer_type(Type* to_type)
3903 typedef Unordered_map(Type*, Pointer_type*) Hashtable;
3904 static Hashtable pointer_types;
3905 Hashtable::const_iterator p = pointer_types.find(to_type);
3906 if (p != pointer_types.end())
3908 Pointer_type* ret = new Pointer_type(to_type);
3909 pointer_types[to_type] = ret;
3913 // The nil type. We use a special type for nil because it is not the
3914 // same as any other type. In C term nil has type void*, but there is
3915 // no such type in Go.
3917 class Nil_type : public Type
3926 do_compare_is_identity(Gogo*) const
3930 do_get_backend(Gogo* gogo)
3931 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
3934 do_type_descriptor(Gogo*, Named_type*)
3935 { go_unreachable(); }
3938 do_reflection(Gogo*, std::string*) const
3939 { go_unreachable(); }
3942 do_mangled_name(Gogo*, std::string* ret) const
3943 { ret->push_back('n'); }
3946 // Make the nil type.
3949 Type::make_nil_type()
3951 static Nil_type singleton_nil_type;
3952 return &singleton_nil_type;
3955 // The type of a function call which returns multiple values. This is
3956 // really a struct, but we don't want to confuse a function call which
3957 // returns a struct with a function call which returns multiple
3960 class Call_multiple_result_type : public Type
3963 Call_multiple_result_type(Call_expression* call)
3964 : Type(TYPE_CALL_MULTIPLE_RESULT),
3970 do_has_pointer() const
3972 go_assert(saw_errors());
3977 do_compare_is_identity(Gogo*) const
3981 do_get_backend(Gogo* gogo)
3983 go_assert(saw_errors());
3984 return gogo->backend()->error_type();
3988 do_type_descriptor(Gogo*, Named_type*)
3990 go_assert(saw_errors());
3991 return Expression::make_error(Linemap::unknown_location());
3995 do_reflection(Gogo*, std::string*) const
3996 { go_assert(saw_errors()); }
3999 do_mangled_name(Gogo*, std::string*) const
4000 { go_assert(saw_errors()); }
4003 // The expression being called.
4004 Call_expression* call_;
4007 // Make a call result type.
4010 Type::make_call_multiple_result_type(Call_expression* call)
4012 return new Call_multiple_result_type(call);
4015 // Class Struct_field.
4017 // Get the name of a field.
4020 Struct_field::field_name() const
4022 const std::string& name(this->typed_identifier_.name());
4027 // This is called during parsing, before anything is lowered, so
4028 // we have to be pretty careful to avoid dereferencing an
4029 // unknown type name.
4030 Type* t = this->typed_identifier_.type();
4032 if (t->classification() == Type::TYPE_POINTER)
4035 Pointer_type* ptype = static_cast<Pointer_type*>(t);
4036 dt = ptype->points_to();
4038 if (dt->forward_declaration_type() != NULL)
4039 return dt->forward_declaration_type()->name();
4040 else if (dt->named_type() != NULL)
4041 return dt->named_type()->name();
4042 else if (t->is_error_type() || dt->is_error_type())
4044 static const std::string error_string = "*error*";
4045 return error_string;
4049 // Avoid crashing in the erroneous case where T is named but
4052 if (t->forward_declaration_type() != NULL)
4053 return t->forward_declaration_type()->name();
4054 else if (t->named_type() != NULL)
4055 return t->named_type()->name();
4062 // Return whether this field is named NAME.
4065 Struct_field::is_field_name(const std::string& name) const
4067 const std::string& me(this->typed_identifier_.name());
4072 Type* t = this->typed_identifier_.type();
4073 if (t->points_to() != NULL)
4075 Named_type* nt = t->named_type();
4076 if (nt != NULL && nt->name() == name)
4079 // This is a horrible hack caused by the fact that we don't pack
4080 // the names of builtin types. FIXME.
4083 && nt->name() == Gogo::unpack_hidden_name(name))
4090 // Class Struct_type.
4095 Struct_type::do_traverse(Traverse* traverse)
4097 Struct_field_list* fields = this->fields_;
4100 for (Struct_field_list::iterator p = fields->begin();
4104 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
4105 return TRAVERSE_EXIT;
4108 return TRAVERSE_CONTINUE;
4111 // Verify that the struct type is complete and valid.
4114 Struct_type::do_verify()
4116 Struct_field_list* fields = this->fields_;
4120 for (Struct_field_list::iterator p = fields->begin();
4124 Type* t = p->type();
4125 if (t->is_undefined())
4127 error_at(p->location(), "struct field type is incomplete");
4128 p->set_type(Type::make_error_type());
4131 else if (p->is_anonymous())
4133 if (t->named_type() != NULL && t->points_to() != NULL)
4135 error_at(p->location(), "embedded type may not be a pointer");
4136 p->set_type(Type::make_error_type());
4139 if (t->points_to() != NULL
4140 && t->points_to()->interface_type() != NULL)
4142 error_at(p->location(),
4143 "embedded type may not be pointer to interface");
4144 p->set_type(Type::make_error_type());
4152 // Whether this contains a pointer.
4155 Struct_type::do_has_pointer() const
4157 const Struct_field_list* fields = this->fields();
4160 for (Struct_field_list::const_iterator p = fields->begin();
4164 if (p->type()->has_pointer())
4170 // Whether this type is identical to T.
4173 Struct_type::is_identical(const Struct_type* t,
4174 bool errors_are_identical) const
4176 const Struct_field_list* fields1 = this->fields();
4177 const Struct_field_list* fields2 = t->fields();
4178 if (fields1 == NULL || fields2 == NULL)
4179 return fields1 == fields2;
4180 Struct_field_list::const_iterator pf2 = fields2->begin();
4181 for (Struct_field_list::const_iterator pf1 = fields1->begin();
4182 pf1 != fields1->end();
4185 if (pf2 == fields2->end())
4187 if (pf1->field_name() != pf2->field_name())
4189 if (pf1->is_anonymous() != pf2->is_anonymous()
4190 || !Type::are_identical(pf1->type(), pf2->type(),
4191 errors_are_identical, NULL))
4193 if (!pf1->has_tag())
4200 if (!pf2->has_tag())
4202 if (pf1->tag() != pf2->tag())
4206 if (pf2 != fields2->end())
4211 // Whether this struct type has any hidden fields.
4214 Struct_type::struct_has_hidden_fields(const Named_type* within,
4215 std::string* reason) const
4217 const Struct_field_list* fields = this->fields();
4220 const Package* within_package = (within == NULL
4222 : within->named_object()->package());
4223 for (Struct_field_list::const_iterator pf = fields->begin();
4224 pf != fields->end();
4227 if (within_package != NULL
4228 && !pf->is_anonymous()
4229 && Gogo::is_hidden_name(pf->field_name()))
4233 std::string within_name = within->named_object()->message_name();
4234 std::string name = Gogo::message_name(pf->field_name());
4235 size_t bufsize = 200 + within_name.length() + name.length();
4236 char* buf = new char[bufsize];
4237 snprintf(buf, bufsize,
4238 _("implicit assignment of %s%s%s hidden field %s%s%s"),
4239 open_quote, within_name.c_str(), close_quote,
4240 open_quote, name.c_str(), close_quote);
4241 reason->assign(buf);
4247 if (pf->type()->has_hidden_fields(within, reason))
4254 // Whether comparisons of this struct type are simple identity
4258 Struct_type::do_compare_is_identity(Gogo* gogo) const
4260 const Struct_field_list* fields = this->fields_;
4263 unsigned int offset = 0;
4264 for (Struct_field_list::const_iterator pf = fields->begin();
4265 pf != fields->end();
4268 if (!pf->type()->compare_is_identity(gogo))
4271 unsigned int field_align;
4272 if (!pf->type()->backend_type_align(gogo, &field_align))
4274 if ((offset & (field_align - 1)) != 0)
4276 // This struct has padding. We don't guarantee that that
4277 // padding is zero-initialized for a stack variable, so we
4278 // can't use memcmp to compare struct values.
4282 unsigned int field_size;
4283 if (!pf->type()->backend_type_size(gogo, &field_size))
4285 offset += field_size;
4290 // Build identity and hash functions for this struct.
4295 Struct_type::do_hash_for_method(Gogo* gogo) const
4297 unsigned int ret = 0;
4298 if (this->fields() != NULL)
4300 for (Struct_field_list::const_iterator pf = this->fields()->begin();
4301 pf != this->fields()->end();
4303 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
4308 // Find the local field NAME.
4311 Struct_type::find_local_field(const std::string& name,
4312 unsigned int *pindex) const
4314 const Struct_field_list* fields = this->fields_;
4318 for (Struct_field_list::const_iterator pf = fields->begin();
4319 pf != fields->end();
4322 if (pf->is_field_name(name))
4332 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
4334 Field_reference_expression*
4335 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
4336 Location location) const
4339 return this->field_reference_depth(struct_expr, name, location, NULL,
4343 // Return an expression for a field, along with the depth at which it
4346 Field_reference_expression*
4347 Struct_type::field_reference_depth(Expression* struct_expr,
4348 const std::string& name,
4350 Saw_named_type* saw,
4351 unsigned int* depth) const
4353 const Struct_field_list* fields = this->fields_;
4357 // Look for a field with this name.
4359 for (Struct_field_list::const_iterator pf = fields->begin();
4360 pf != fields->end();
4363 if (pf->is_field_name(name))
4366 return Expression::make_field_reference(struct_expr, i, location);
4370 // Look for an anonymous field which contains a field with this
4372 unsigned int found_depth = 0;
4373 Field_reference_expression* ret = NULL;
4375 for (Struct_field_list::const_iterator pf = fields->begin();
4376 pf != fields->end();
4379 if (!pf->is_anonymous())
4382 Struct_type* st = pf->type()->deref()->struct_type();
4386 Saw_named_type* hold_saw = saw;
4387 Saw_named_type saw_here;
4388 Named_type* nt = pf->type()->named_type();
4390 nt = pf->type()->deref()->named_type();
4394 for (q = saw; q != NULL; q = q->next)
4398 // If this is an error, it will be reported
4405 saw_here.next = saw;
4410 // Look for a reference using a NULL struct expression. If we
4411 // find one, fill in the struct expression with a reference to
4413 unsigned int subdepth;
4414 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
4424 if (ret == NULL || subdepth < found_depth)
4429 found_depth = subdepth;
4430 Expression* here = Expression::make_field_reference(struct_expr, i,
4432 if (pf->type()->points_to() != NULL)
4433 here = Expression::make_unary(OPERATOR_MULT, here, location);
4434 while (sub->expr() != NULL)
4436 sub = sub->expr()->deref()->field_reference_expression();
4437 go_assert(sub != NULL);
4439 sub->set_struct_expression(here);
4441 else if (subdepth > found_depth)
4445 // We do not handle ambiguity here--it should be handled by
4446 // Type::bind_field_or_method.
4454 *depth = found_depth + 1;
4459 // Return the total number of fields, including embedded fields.
4462 Struct_type::total_field_count() const
4464 if (this->fields_ == NULL)
4466 unsigned int ret = 0;
4467 for (Struct_field_list::const_iterator pf = this->fields_->begin();
4468 pf != this->fields_->end();
4471 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
4474 ret += pf->type()->struct_type()->total_field_count();
4479 // Return whether NAME is an unexported field, for better error reporting.
4482 Struct_type::is_unexported_local_field(Gogo* gogo,
4483 const std::string& name) const
4485 const Struct_field_list* fields = this->fields_;
4488 for (Struct_field_list::const_iterator pf = fields->begin();
4489 pf != fields->end();
4492 const std::string& field_name(pf->field_name());
4493 if (Gogo::is_hidden_name(field_name)
4494 && name == Gogo::unpack_hidden_name(field_name)
4495 && gogo->pack_hidden_name(name, false) != field_name)
4502 // Finalize the methods of an unnamed struct.
4505 Struct_type::finalize_methods(Gogo* gogo)
4507 if (this->all_methods_ != NULL)
4509 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
4512 // Return the method NAME, or NULL if there isn't one or if it is
4513 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
4517 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
4519 return Type::method_function(this->all_methods_, name, is_ambiguous);
4522 // Convert struct fields to the backend representation. This is not
4523 // declared in types.h so that types.h doesn't have to #include
4527 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
4528 bool use_placeholder,
4529 std::vector<Backend::Btyped_identifier>* bfields)
4531 bfields->resize(fields->size());
4533 for (Struct_field_list::const_iterator p = fields->begin();
4537 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
4538 (*bfields)[i].btype = (use_placeholder
4539 ? p->type()->get_backend_placeholder(gogo)
4540 : p->type()->get_backend(gogo));
4541 (*bfields)[i].location = p->location();
4543 go_assert(i == fields->size());
4546 // Get the tree for a struct type.
4549 Struct_type::do_get_backend(Gogo* gogo)
4551 std::vector<Backend::Btyped_identifier> bfields;
4552 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
4553 return gogo->backend()->struct_type(bfields);
4556 // Finish the backend representation of the fields of a struct.
4559 Struct_type::finish_backend_fields(Gogo* gogo)
4561 const Struct_field_list* fields = this->fields_;
4564 for (Struct_field_list::const_iterator p = fields->begin();
4567 p->type()->get_backend(gogo);
4571 // The type of a struct type descriptor.
4574 Struct_type::make_struct_type_descriptor_type()
4579 Type* tdt = Type::make_type_descriptor_type();
4580 Type* ptdt = Type::make_type_descriptor_ptr_type();
4582 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4583 Type* string_type = Type::lookup_string_type();
4584 Type* pointer_string_type = Type::make_pointer_type(string_type);
4587 Type::make_builtin_struct_type(5,
4588 "name", pointer_string_type,
4589 "pkgPath", pointer_string_type,
4591 "tag", pointer_string_type,
4592 "offset", uintptr_type);
4593 Type* nsf = Type::make_builtin_named_type("structField", sf);
4595 Type* slice_type = Type::make_array_type(nsf, NULL);
4597 Struct_type* s = Type::make_builtin_struct_type(2,
4599 "fields", slice_type);
4601 ret = Type::make_builtin_named_type("StructType", s);
4607 // Build a type descriptor for a struct type.
4610 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4612 Location bloc = Linemap::predeclared_location();
4614 Type* stdt = Struct_type::make_struct_type_descriptor_type();
4616 const Struct_field_list* fields = stdt->struct_type()->fields();
4618 Expression_list* vals = new Expression_list();
4621 const Methods* methods = this->methods();
4622 // A named struct should not have methods--the methods should attach
4623 // to the named type.
4624 go_assert(methods == NULL || name == NULL);
4626 Struct_field_list::const_iterator ps = fields->begin();
4627 go_assert(ps->is_field_name("commonType"));
4628 vals->push_back(this->type_descriptor_constructor(gogo,
4629 RUNTIME_TYPE_KIND_STRUCT,
4630 name, methods, true));
4633 go_assert(ps->is_field_name("fields"));
4635 Expression_list* elements = new Expression_list();
4636 elements->reserve(this->fields_->size());
4637 Type* element_type = ps->type()->array_type()->element_type();
4638 for (Struct_field_list::const_iterator pf = this->fields_->begin();
4639 pf != this->fields_->end();
4642 const Struct_field_list* f = element_type->struct_type()->fields();
4644 Expression_list* fvals = new Expression_list();
4647 Struct_field_list::const_iterator q = f->begin();
4648 go_assert(q->is_field_name("name"));
4649 if (pf->is_anonymous())
4650 fvals->push_back(Expression::make_nil(bloc));
4653 std::string n = Gogo::unpack_hidden_name(pf->field_name());
4654 Expression* s = Expression::make_string(n, bloc);
4655 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4659 go_assert(q->is_field_name("pkgPath"));
4660 if (!Gogo::is_hidden_name(pf->field_name()))
4661 fvals->push_back(Expression::make_nil(bloc));
4664 std::string n = Gogo::hidden_name_prefix(pf->field_name());
4665 Expression* s = Expression::make_string(n, bloc);
4666 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4670 go_assert(q->is_field_name("typ"));
4671 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
4674 go_assert(q->is_field_name("tag"));
4676 fvals->push_back(Expression::make_nil(bloc));
4679 Expression* s = Expression::make_string(pf->tag(), bloc);
4680 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4684 go_assert(q->is_field_name("offset"));
4685 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
4687 Expression* v = Expression::make_struct_composite_literal(element_type,
4689 elements->push_back(v);
4692 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
4695 return Expression::make_struct_composite_literal(stdt, vals, bloc);
4698 // Write the hash function for a struct which can not use the identity
4702 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
4703 Function_type* hash_fntype,
4704 Function_type* equal_fntype)
4706 Location bloc = Linemap::predeclared_location();
4708 // The pointer to the struct that we are going to hash. This is an
4709 // argument to the hash function we are implementing here.
4710 Named_object* key_arg = gogo->lookup("key", NULL);
4711 go_assert(key_arg != NULL);
4712 Type* key_arg_type = key_arg->var_value()->type();
4714 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4718 mpz_init_set_ui(ival, 0);
4719 Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
4722 // Make a temporary to hold the return value, initialized to 0.
4723 Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
4725 gogo->add_statement(retval);
4727 // Make a temporary to hold the key as a uintptr.
4728 Expression* ref = Expression::make_var_reference(key_arg, bloc);
4729 ref = Expression::make_cast(uintptr_type, ref, bloc);
4730 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
4732 gogo->add_statement(key);
4734 // Loop over the struct fields.
4736 const Struct_field_list* fields = this->fields_;
4737 for (Struct_field_list::const_iterator pf = fields->begin();
4738 pf != fields->end();
4745 // Multiply retval by 33.
4746 mpz_init_set_ui(ival, 33);
4747 Expression* i33 = Expression::make_integer(&ival, uintptr_type,
4751 ref = Expression::make_temporary_reference(retval, bloc);
4752 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ,
4754 gogo->add_statement(s);
4757 // Get a pointer to the value of this field.
4758 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
4759 ref = Expression::make_temporary_reference(key, bloc);
4760 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
4762 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
4764 // Get the size of this field.
4765 Expression* size = Expression::make_type_info(pf->type(),
4766 Expression::TYPE_INFO_SIZE);
4768 // Get the hash function to use for the type of this field.
4769 Named_object* hash_fn;
4770 Named_object* equal_fn;
4771 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
4772 equal_fntype, &hash_fn, &equal_fn);
4774 // Call the hash function for the field.
4775 Expression_list* args = new Expression_list();
4776 args->push_back(subkey);
4777 args->push_back(size);
4778 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
4779 Expression* call = Expression::make_call(func, args, false, bloc);
4781 // Add the field's hash value to retval.
4782 Temporary_reference_expression* tref =
4783 Expression::make_temporary_reference(retval, bloc);
4784 tref->set_is_lvalue();
4785 Statement* s = Statement::make_assignment_operation(OPERATOR_PLUSEQ,
4787 gogo->add_statement(s);
4790 // Return retval to the caller of the hash function.
4791 Expression_list* vals = new Expression_list();
4792 ref = Expression::make_temporary_reference(retval, bloc);
4793 vals->push_back(ref);
4794 Statement* s = Statement::make_return_statement(vals, bloc);
4795 gogo->add_statement(s);
4798 // Write the equality function for a struct which can not use the
4799 // identity function.
4802 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
4804 Location bloc = Linemap::predeclared_location();
4806 // The pointers to the structs we are going to compare.
4807 Named_object* key1_arg = gogo->lookup("key1", NULL);
4808 Named_object* key2_arg = gogo->lookup("key2", NULL);
4809 go_assert(key1_arg != NULL && key2_arg != NULL);
4811 // Build temporaries with the right types.
4812 Type* pt = Type::make_pointer_type(name != NULL
4813 ? static_cast<Type*>(name)
4814 : static_cast<Type*>(this));
4816 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
4817 ref = Expression::make_unsafe_cast(pt, ref, bloc);
4818 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
4819 gogo->add_statement(p1);
4821 ref = Expression::make_var_reference(key2_arg, bloc);
4822 ref = Expression::make_unsafe_cast(pt, ref, bloc);
4823 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
4824 gogo->add_statement(p2);
4826 const Struct_field_list* fields = this->fields_;
4827 unsigned int field_index = 0;
4828 for (Struct_field_list::const_iterator pf = fields->begin();
4829 pf != fields->end();
4830 ++pf, ++field_index)
4832 // Compare one field in both P1 and P2.
4833 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
4834 f1 = Expression::make_unary(OPERATOR_MULT, f1, bloc);
4835 f1 = Expression::make_field_reference(f1, field_index, bloc);
4837 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
4838 f2 = Expression::make_unary(OPERATOR_MULT, f2, bloc);
4839 f2 = Expression::make_field_reference(f2, field_index, bloc);
4841 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
4843 // If the values are not equal, return false.
4844 gogo->start_block(bloc);
4845 Expression_list* vals = new Expression_list();
4846 vals->push_back(Expression::make_boolean(false, bloc));
4847 Statement* s = Statement::make_return_statement(vals, bloc);
4848 gogo->add_statement(s);
4849 Block* then_block = gogo->finish_block(bloc);
4851 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
4852 gogo->add_statement(s);
4855 // All the fields are equal, so return true.
4856 Expression_list* vals = new Expression_list();
4857 vals->push_back(Expression::make_boolean(true, bloc));
4858 Statement* s = Statement::make_return_statement(vals, bloc);
4859 gogo->add_statement(s);
4862 // Reflection string.
4865 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
4867 ret->append("struct { ");
4869 for (Struct_field_list::const_iterator p = this->fields_->begin();
4870 p != this->fields_->end();
4873 if (p != this->fields_->begin())
4875 if (p->is_anonymous())
4876 ret->push_back('?');
4878 ret->append(Gogo::unpack_hidden_name(p->field_name()));
4879 ret->push_back(' ');
4880 this->append_reflection(p->type(), gogo, ret);
4884 const std::string& tag(p->tag());
4886 for (std::string::const_iterator p = tag.begin();
4891 ret->append("\\x00");
4892 else if (*p == '\n')
4894 else if (*p == '\t')
4897 ret->append("\\\"");
4898 else if (*p == '\\')
4899 ret->append("\\\\");
4903 ret->push_back('"');
4913 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4915 ret->push_back('S');
4917 const Struct_field_list* fields = this->fields_;
4920 for (Struct_field_list::const_iterator p = fields->begin();
4924 if (p->is_anonymous())
4928 std::string n = Gogo::unpack_hidden_name(p->field_name());
4930 snprintf(buf, sizeof buf, "%u_",
4931 static_cast<unsigned int>(n.length()));
4935 this->append_mangled_name(p->type(), gogo, ret);
4938 const std::string& tag(p->tag());
4940 for (std::string::const_iterator p = tag.begin();
4944 if (ISALNUM(*p) || *p == '_')
4949 snprintf(buf, sizeof buf, ".%x.",
4950 static_cast<unsigned int>(*p));
4955 snprintf(buf, sizeof buf, "T%u_",
4956 static_cast<unsigned int>(out.length()));
4963 ret->push_back('e');
4966 // If the offset of field INDEX in the backend implementation can be
4967 // determined, set *POFFSET to the offset in bytes and return true.
4968 // Otherwise, return false.
4971 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
4972 unsigned int* poffset)
4974 if (!this->is_backend_type_size_known(gogo))
4976 Btype* bt = this->get_backend_placeholder(gogo);
4977 size_t offset = gogo->backend()->type_field_offset(bt, index);
4978 *poffset = static_cast<unsigned int>(offset);
4979 if (*poffset != offset)
4987 Struct_type::do_export(Export* exp) const
4989 exp->write_c_string("struct { ");
4990 const Struct_field_list* fields = this->fields_;
4991 go_assert(fields != NULL);
4992 for (Struct_field_list::const_iterator p = fields->begin();
4996 if (p->is_anonymous())
4997 exp->write_string("? ");
5000 exp->write_string(p->field_name());
5001 exp->write_c_string(" ");
5003 exp->write_type(p->type());
5007 exp->write_c_string(" ");
5009 Expression::make_string(p->tag(), Linemap::predeclared_location());
5010 expr->export_expression(exp);
5014 exp->write_c_string("; ");
5016 exp->write_c_string("}");
5022 Struct_type::do_import(Import* imp)
5024 imp->require_c_string("struct { ");
5025 Struct_field_list* fields = new Struct_field_list;
5026 if (imp->peek_char() != '}')
5031 if (imp->match_c_string("? "))
5035 name = imp->read_identifier();
5036 imp->require_c_string(" ");
5038 Type* ftype = imp->read_type();
5040 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
5042 if (imp->peek_char() == ' ')
5045 Expression* expr = Expression::import_expression(imp);
5046 String_expression* sexpr = expr->string_expression();
5047 go_assert(sexpr != NULL);
5048 sf.set_tag(sexpr->val());
5052 imp->require_c_string("; ");
5053 fields->push_back(sf);
5054 if (imp->peek_char() == '}')
5058 imp->require_c_string("}");
5060 return Type::make_struct_type(fields, imp->location());
5063 // Make a struct type.
5066 Type::make_struct_type(Struct_field_list* fields,
5069 return new Struct_type(fields, location);
5072 // Class Array_type.
5074 // Whether two array types are identical.
5077 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
5079 if (!Type::are_identical(this->element_type(), t->element_type(),
5080 errors_are_identical, NULL))
5083 Expression* l1 = this->length();
5084 Expression* l2 = t->length();
5086 // Slices of the same element type are identical.
5087 if (l1 == NULL && l2 == NULL)
5090 // Arrays of the same element type are identical if they have the
5092 if (l1 != NULL && l2 != NULL)
5097 // Try to determine the lengths. If we can't, assume the arrays
5098 // are not identical.
5106 if (l1->integer_constant_value(true, v1, &type1)
5107 && l2->integer_constant_value(true, v2, &type2))
5108 ret = mpz_cmp(v1, v2) == 0;
5114 // Otherwise the arrays are not identical.
5121 Array_type::do_traverse(Traverse* traverse)
5123 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
5124 return TRAVERSE_EXIT;
5125 if (this->length_ != NULL
5126 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
5127 return TRAVERSE_EXIT;
5128 return TRAVERSE_CONTINUE;
5131 // Check that the length is valid.
5134 Array_type::verify_length()
5136 if (this->length_ == NULL)
5139 Type_context context(Type::lookup_integer_type("int"), false);
5140 this->length_->determine_type(&context);
5142 if (!this->length_->is_constant())
5144 error_at(this->length_->location(), "array bound is not constant");
5151 if (!this->length_->integer_constant_value(true, val, &vt))
5155 if (!this->length_->float_constant_value(fval, &vt))
5157 if (this->length_->type()->integer_type() != NULL
5158 || this->length_->type()->float_type() != NULL)
5159 error_at(this->length_->location(),
5160 "array bound is not constant");
5162 error_at(this->length_->location(),
5163 "array bound is not numeric");
5168 if (!mpfr_integer_p(fval))
5170 error_at(this->length_->location(),
5171 "array bound truncated to integer");
5177 mpfr_get_z(val, fval, GMP_RNDN);
5181 if (mpz_sgn(val) < 0)
5183 error_at(this->length_->location(), "negative array bound");
5188 Type* int_type = Type::lookup_integer_type("int");
5189 int tbits = int_type->integer_type()->bits();
5190 int vbits = mpz_sizeinbase(val, 2);
5191 if (vbits + 1 > tbits)
5193 error_at(this->length_->location(), "array bound overflows");
5206 Array_type::do_verify()
5208 if (!this->verify_length())
5210 this->length_ = Expression::make_error(this->length_->location());
5216 // Whether we can use memcmp to compare this array.
5219 Array_type::do_compare_is_identity(Gogo* gogo) const
5221 if (this->length_ == NULL)
5224 // Check for [...], which indicates that this is not a real type.
5225 if (this->length_->is_nil_expression())
5228 if (!this->element_type_->compare_is_identity(gogo))
5231 // If there is any padding, then we can't use memcmp.
5234 if (!this->element_type_->backend_type_size(gogo, &size)
5235 || !this->element_type_->backend_type_align(gogo, &align))
5237 if ((size & (align - 1)) != 0)
5243 // Array type hash code.
5246 Array_type::do_hash_for_method(Gogo* gogo) const
5248 // There is no very convenient way to get a hash code for the
5250 return this->element_type_->hash_for_method(gogo) + 1;
5253 // Write the hash function for an array which can not use the identify
5257 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
5258 Function_type* hash_fntype,
5259 Function_type* equal_fntype)
5261 Location bloc = Linemap::predeclared_location();
5263 // The pointer to the array that we are going to hash. This is an
5264 // argument to the hash function we are implementing here.
5265 Named_object* key_arg = gogo->lookup("key", NULL);
5266 go_assert(key_arg != NULL);
5267 Type* key_arg_type = key_arg->var_value()->type();
5269 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5273 mpz_init_set_ui(ival, 0);
5274 Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
5277 // Make a temporary to hold the return value, initialized to 0.
5278 Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
5280 gogo->add_statement(retval);
5282 // Make a temporary to hold the key as a uintptr.
5283 Expression* ref = Expression::make_var_reference(key_arg, bloc);
5284 ref = Expression::make_cast(uintptr_type, ref, bloc);
5285 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
5287 gogo->add_statement(key);
5289 // Loop over the array elements.
5291 Type* int_type = Type::lookup_integer_type("int");
5292 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
5293 gogo->add_statement(index);
5295 Expression* iref = Expression::make_temporary_reference(index, bloc);
5296 Expression* aref = Expression::make_var_reference(key_arg, bloc);
5297 Type* pt = Type::make_pointer_type(name != NULL
5298 ? static_cast<Type*>(name)
5299 : static_cast<Type*>(this));
5300 aref = Expression::make_cast(pt, aref, bloc);
5301 For_range_statement* for_range = Statement::make_for_range_statement(iref,
5306 gogo->start_block(bloc);
5308 // Multiply retval by 33.
5309 mpz_init_set_ui(ival, 33);
5310 Expression* i33 = Expression::make_integer(&ival, uintptr_type, bloc);
5313 ref = Expression::make_temporary_reference(retval, bloc);
5314 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ, ref,
5316 gogo->add_statement(s);
5318 // Get the hash function for the element type.
5319 Named_object* hash_fn;
5320 Named_object* equal_fn;
5321 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
5322 hash_fntype, equal_fntype, &hash_fn,
5325 // Get a pointer to this element in the loop.
5326 Expression* subkey = Expression::make_temporary_reference(key, bloc);
5327 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
5329 // Get the size of each element.
5330 Expression* ele_size = Expression::make_type_info(this->element_type_,
5331 Expression::TYPE_INFO_SIZE);
5333 // Get the hash of this element.
5334 Expression_list* args = new Expression_list();
5335 args->push_back(subkey);
5336 args->push_back(ele_size);
5337 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
5338 Expression* call = Expression::make_call(func, args, false, bloc);
5340 // Add the element's hash value to retval.
5341 Temporary_reference_expression* tref =
5342 Expression::make_temporary_reference(retval, bloc);
5343 tref->set_is_lvalue();
5344 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, call, bloc);
5345 gogo->add_statement(s);
5347 // Increase the element pointer.
5348 tref = Expression::make_temporary_reference(key, bloc);
5349 tref->set_is_lvalue();
5350 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
5353 Block* statements = gogo->finish_block(bloc);
5355 for_range->add_statements(statements);
5356 gogo->add_statement(for_range);
5358 // Return retval to the caller of the hash function.
5359 Expression_list* vals = new Expression_list();
5360 ref = Expression::make_temporary_reference(retval, bloc);
5361 vals->push_back(ref);
5362 s = Statement::make_return_statement(vals, bloc);
5363 gogo->add_statement(s);
5366 // Write the equality function for an array which can not use the
5367 // identity function.
5370 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
5372 Location bloc = Linemap::predeclared_location();
5374 // The pointers to the arrays we are going to compare.
5375 Named_object* key1_arg = gogo->lookup("key1", NULL);
5376 Named_object* key2_arg = gogo->lookup("key2", NULL);
5377 go_assert(key1_arg != NULL && key2_arg != NULL);
5379 // Build temporaries for the keys with the right types.
5380 Type* pt = Type::make_pointer_type(name != NULL
5381 ? static_cast<Type*>(name)
5382 : static_cast<Type*>(this));
5384 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
5385 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5386 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
5387 gogo->add_statement(p1);
5389 ref = Expression::make_var_reference(key2_arg, bloc);
5390 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5391 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
5392 gogo->add_statement(p2);
5394 // Loop over the array elements.
5396 Type* int_type = Type::lookup_integer_type("int");
5397 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
5398 gogo->add_statement(index);
5400 Expression* iref = Expression::make_temporary_reference(index, bloc);
5401 Expression* aref = Expression::make_temporary_reference(p1, bloc);
5402 For_range_statement* for_range = Statement::make_for_range_statement(iref,
5407 gogo->start_block(bloc);
5409 // Compare element in P1 and P2.
5410 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
5411 e1 = Expression::make_unary(OPERATOR_MULT, e1, bloc);
5412 ref = Expression::make_temporary_reference(index, bloc);
5413 e1 = Expression::make_array_index(e1, ref, NULL, bloc);
5415 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
5416 e2 = Expression::make_unary(OPERATOR_MULT, e2, bloc);
5417 ref = Expression::make_temporary_reference(index, bloc);
5418 e2 = Expression::make_array_index(e2, ref, NULL, bloc);
5420 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
5422 // If the elements are not equal, return false.
5423 gogo->start_block(bloc);
5424 Expression_list* vals = new Expression_list();
5425 vals->push_back(Expression::make_boolean(false, bloc));
5426 Statement* s = Statement::make_return_statement(vals, bloc);
5427 gogo->add_statement(s);
5428 Block* then_block = gogo->finish_block(bloc);
5430 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
5431 gogo->add_statement(s);
5433 Block* statements = gogo->finish_block(bloc);
5435 for_range->add_statements(statements);
5436 gogo->add_statement(for_range);
5438 // All the elements are equal, so return true.
5439 vals = new Expression_list();
5440 vals->push_back(Expression::make_boolean(true, bloc));
5441 s = Statement::make_return_statement(vals, bloc);
5442 gogo->add_statement(s);
5445 // Get a tree for the length of a fixed array. The length may be
5446 // computed using a function call, so we must only evaluate it once.
5449 Array_type::get_length_tree(Gogo* gogo)
5451 go_assert(this->length_ != NULL);
5452 if (this->length_tree_ == NULL_TREE)
5457 if (this->length_->integer_constant_value(true, val, &t))
5460 t = Type::lookup_integer_type("int");
5461 else if (t->is_abstract())
5462 t = t->make_non_abstract_type();
5463 tree tt = type_to_tree(t->get_backend(gogo));
5464 this->length_tree_ = Expression::integer_constant_tree(val, tt);
5471 // Make up a translation context for the array length
5472 // expression. FIXME: This won't work in general.
5473 Translate_context context(gogo, NULL, NULL, NULL);
5474 tree len = this->length_->get_tree(&context);
5475 if (len != error_mark_node)
5477 len = convert_to_integer(integer_type_node, len);
5478 len = save_expr(len);
5480 this->length_tree_ = len;
5483 return this->length_tree_;
5486 // Get the backend representation of the fields of a slice. This is
5487 // not declared in types.h so that types.h doesn't have to #include
5490 // We use int for the count and capacity fields. This matches 6g.
5491 // The language more or less assumes that we can't allocate space of a
5492 // size which does not fit in int.
5495 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
5496 std::vector<Backend::Btyped_identifier>* bfields)
5500 Type* pet = Type::make_pointer_type(type->element_type());
5501 Btype* pbet = (use_placeholder
5502 ? pet->get_backend_placeholder(gogo)
5503 : pet->get_backend(gogo));
5504 Location ploc = Linemap::predeclared_location();
5506 Backend::Btyped_identifier* p = &(*bfields)[0];
5507 p->name = "__values";
5511 Type* int_type = Type::lookup_integer_type("int");
5514 p->name = "__count";
5515 p->btype = int_type->get_backend(gogo);
5519 p->name = "__capacity";
5520 p->btype = int_type->get_backend(gogo);
5524 // Get a tree for the type of this array. A fixed array is simply
5525 // represented as ARRAY_TYPE with the appropriate index--i.e., it is
5526 // just like an array in C. An open array is a struct with three
5527 // fields: a data pointer, the length, and the capacity.
5530 Array_type::do_get_backend(Gogo* gogo)
5532 if (this->length_ == NULL)
5534 std::vector<Backend::Btyped_identifier> bfields;
5535 get_backend_slice_fields(gogo, this, false, &bfields);
5536 return gogo->backend()->struct_type(bfields);
5540 Btype* element = this->get_backend_element(gogo, false);
5541 Bexpression* len = this->get_backend_length(gogo);
5542 return gogo->backend()->array_type(element, len);
5546 // Return the backend representation of the element type.
5549 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
5551 if (use_placeholder)
5552 return this->element_type_->get_backend_placeholder(gogo);
5554 return this->element_type_->get_backend(gogo);
5557 // Return the backend representation of the length.
5560 Array_type::get_backend_length(Gogo* gogo)
5562 return tree_to_expr(this->get_length_tree(gogo));
5565 // Finish backend representation of the array.
5568 Array_type::finish_backend_element(Gogo* gogo)
5570 Type* et = this->array_type()->element_type();
5571 et->get_backend(gogo);
5572 if (this->is_slice_type())
5574 // This relies on the fact that we always use the same
5575 // structure for a pointer to any given type.
5576 Type* pet = Type::make_pointer_type(et);
5577 pet->get_backend(gogo);
5581 // Return a tree for a pointer to the values in ARRAY.
5584 Array_type::value_pointer_tree(Gogo*, tree array) const
5587 if (this->length() != NULL)
5590 ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))),
5591 build_fold_addr_expr(array));
5596 tree field = TYPE_FIELDS(TREE_TYPE(array));
5597 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
5599 ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field,
5602 if (TREE_CONSTANT(array))
5603 TREE_CONSTANT(ret) = 1;
5607 // Return a tree for the length of the array ARRAY which has this
5611 Array_type::length_tree(Gogo* gogo, tree array)
5613 if (this->length_ != NULL)
5615 if (TREE_CODE(array) == SAVE_EXPR)
5616 return fold_convert(integer_type_node, this->get_length_tree(gogo));
5618 return omit_one_operand(integer_type_node,
5619 this->get_length_tree(gogo), array);
5622 // This is an open array. We need to read the length field.
5624 tree type = TREE_TYPE(array);
5625 go_assert(TREE_CODE(type) == RECORD_TYPE);
5627 tree field = DECL_CHAIN(TYPE_FIELDS(type));
5628 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
5630 tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
5631 if (TREE_CONSTANT(array))
5632 TREE_CONSTANT(ret) = 1;
5636 // Return a tree for the capacity of the array ARRAY which has this
5640 Array_type::capacity_tree(Gogo* gogo, tree array)
5642 if (this->length_ != NULL)
5643 return omit_one_operand(integer_type_node, this->get_length_tree(gogo),
5646 // This is an open array. We need to read the capacity field.
5648 tree type = TREE_TYPE(array);
5649 go_assert(TREE_CODE(type) == RECORD_TYPE);
5651 tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type)));
5652 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
5654 return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
5660 Array_type::do_export(Export* exp) const
5662 exp->write_c_string("[");
5663 if (this->length_ != NULL)
5664 this->length_->export_expression(exp);
5665 exp->write_c_string("] ");
5666 exp->write_type(this->element_type_);
5672 Array_type::do_import(Import* imp)
5674 imp->require_c_string("[");
5676 if (imp->peek_char() == ']')
5679 length = Expression::import_expression(imp);
5680 imp->require_c_string("] ");
5681 Type* element_type = imp->read_type();
5682 return Type::make_array_type(element_type, length);
5685 // The type of an array type descriptor.
5688 Array_type::make_array_type_descriptor_type()
5693 Type* tdt = Type::make_type_descriptor_type();
5694 Type* ptdt = Type::make_type_descriptor_ptr_type();
5696 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5699 Type::make_builtin_struct_type(4,
5703 "len", uintptr_type);
5705 ret = Type::make_builtin_named_type("ArrayType", sf);
5711 // The type of an slice type descriptor.
5714 Array_type::make_slice_type_descriptor_type()
5719 Type* tdt = Type::make_type_descriptor_type();
5720 Type* ptdt = Type::make_type_descriptor_ptr_type();
5723 Type::make_builtin_struct_type(2,
5727 ret = Type::make_builtin_named_type("SliceType", sf);
5733 // Build a type descriptor for an array/slice type.
5736 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5738 if (this->length_ != NULL)
5739 return this->array_type_descriptor(gogo, name);
5741 return this->slice_type_descriptor(gogo, name);
5744 // Build a type descriptor for an array type.
5747 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
5749 Location bloc = Linemap::predeclared_location();
5751 Type* atdt = Array_type::make_array_type_descriptor_type();
5753 const Struct_field_list* fields = atdt->struct_type()->fields();
5755 Expression_list* vals = new Expression_list();
5758 Struct_field_list::const_iterator p = fields->begin();
5759 go_assert(p->is_field_name("commonType"));
5760 vals->push_back(this->type_descriptor_constructor(gogo,
5761 RUNTIME_TYPE_KIND_ARRAY,
5765 go_assert(p->is_field_name("elem"));
5766 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5769 go_assert(p->is_field_name("slice"));
5770 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
5771 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
5774 go_assert(p->is_field_name("len"));
5775 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
5778 go_assert(p == fields->end());
5780 return Expression::make_struct_composite_literal(atdt, vals, bloc);
5783 // Build a type descriptor for a slice type.
5786 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
5788 Location bloc = Linemap::predeclared_location();
5790 Type* stdt = Array_type::make_slice_type_descriptor_type();
5792 const Struct_field_list* fields = stdt->struct_type()->fields();
5794 Expression_list* vals = new Expression_list();
5797 Struct_field_list::const_iterator p = fields->begin();
5798 go_assert(p->is_field_name("commonType"));
5799 vals->push_back(this->type_descriptor_constructor(gogo,
5800 RUNTIME_TYPE_KIND_SLICE,
5804 go_assert(p->is_field_name("elem"));
5805 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5808 go_assert(p == fields->end());
5810 return Expression::make_struct_composite_literal(stdt, vals, bloc);
5813 // Reflection string.
5816 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
5818 ret->push_back('[');
5819 if (this->length_ != NULL)
5824 if (!this->length_->integer_constant_value(true, val, &type))
5825 error_at(this->length_->location(),
5826 "array length must be integer constant expression");
5827 else if (mpz_cmp_si(val, 0) < 0)
5828 error_at(this->length_->location(), "array length is negative");
5829 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
5830 error_at(this->length_->location(), "array length is too large");
5834 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
5839 ret->push_back(']');
5841 this->append_reflection(this->element_type_, gogo, ret);
5847 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5849 ret->push_back('A');
5850 this->append_mangled_name(this->element_type_, gogo, ret);
5851 if (this->length_ != NULL)
5856 if (!this->length_->integer_constant_value(true, val, &type))
5857 error_at(this->length_->location(),
5858 "array length must be integer constant expression");
5859 else if (mpz_cmp_si(val, 0) < 0)
5860 error_at(this->length_->location(), "array length is negative");
5861 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
5862 error_at(this->length_->location(), "array size is too large");
5866 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
5871 ret->push_back('e');
5874 // Make an array type.
5877 Type::make_array_type(Type* element_type, Expression* length)
5879 return new Array_type(element_type, length);
5887 Map_type::do_traverse(Traverse* traverse)
5889 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
5890 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
5891 return TRAVERSE_EXIT;
5892 return TRAVERSE_CONTINUE;
5895 // Check that the map type is OK.
5898 Map_type::do_verify()
5900 // The runtime support uses "map[void]void".
5901 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
5903 error_at(this->location_, "invalid map key type");
5909 // Whether two map types are identical.
5912 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
5914 return (Type::are_identical(this->key_type(), t->key_type(),
5915 errors_are_identical, NULL)
5916 && Type::are_identical(this->val_type(), t->val_type(),
5917 errors_are_identical, NULL));
5923 Map_type::do_hash_for_method(Gogo* gogo) const
5925 return (this->key_type_->hash_for_method(gogo)
5926 + this->val_type_->hash_for_method(gogo)
5930 // Get the backend representation for a map type. A map type is
5931 // represented as a pointer to a struct. The struct is __go_map in
5935 Map_type::do_get_backend(Gogo* gogo)
5937 static Btype* backend_map_type;
5938 if (backend_map_type == NULL)
5940 std::vector<Backend::Btyped_identifier> bfields(4);
5942 Location bloc = Linemap::predeclared_location();
5944 Type* pdt = Type::make_type_descriptor_ptr_type();
5945 bfields[0].name = "__descriptor";
5946 bfields[0].btype = pdt->get_backend(gogo);
5947 bfields[0].location = bloc;
5949 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5950 bfields[1].name = "__element_count";
5951 bfields[1].btype = uintptr_type->get_backend(gogo);
5952 bfields[1].location = bloc;
5954 bfields[2].name = "__bucket_count";
5955 bfields[2].btype = bfields[1].btype;
5956 bfields[2].location = bloc;
5958 Btype* bvt = gogo->backend()->void_type();
5959 Btype* bpvt = gogo->backend()->pointer_type(bvt);
5960 Btype* bppvt = gogo->backend()->pointer_type(bpvt);
5961 bfields[3].name = "__buckets";
5962 bfields[3].btype = bppvt;
5963 bfields[3].location = bloc;
5965 Btype *bt = gogo->backend()->struct_type(bfields);
5966 bt = gogo->backend()->named_type("__go_map", bt, bloc);
5967 backend_map_type = gogo->backend()->pointer_type(bt);
5969 return backend_map_type;
5972 // The type of a map type descriptor.
5975 Map_type::make_map_type_descriptor_type()
5980 Type* tdt = Type::make_type_descriptor_type();
5981 Type* ptdt = Type::make_type_descriptor_ptr_type();
5984 Type::make_builtin_struct_type(3,
5989 ret = Type::make_builtin_named_type("MapType", sf);
5995 // Build a type descriptor for a map type.
5998 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6000 Location bloc = Linemap::predeclared_location();
6002 Type* mtdt = Map_type::make_map_type_descriptor_type();
6004 const Struct_field_list* fields = mtdt->struct_type()->fields();
6006 Expression_list* vals = new Expression_list();
6009 Struct_field_list::const_iterator p = fields->begin();
6010 go_assert(p->is_field_name("commonType"));
6011 vals->push_back(this->type_descriptor_constructor(gogo,
6012 RUNTIME_TYPE_KIND_MAP,
6016 go_assert(p->is_field_name("key"));
6017 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
6020 go_assert(p->is_field_name("elem"));
6021 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
6024 go_assert(p == fields->end());
6026 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
6029 // A mapping from map types to map descriptors.
6031 Map_type::Map_descriptors Map_type::map_descriptors;
6033 // Build a map descriptor for this type. Return a pointer to it.
6036 Map_type::map_descriptor_pointer(Gogo* gogo, Location location)
6038 Bvariable* bvar = this->map_descriptor(gogo);
6039 tree var_tree = var_to_tree(bvar);
6040 if (var_tree == error_mark_node)
6041 return error_mark_node;
6042 return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
6045 // Build a map descriptor for this type.
6048 Map_type::map_descriptor(Gogo* gogo)
6050 std::pair<Map_type*, Bvariable*> val(this, NULL);
6051 std::pair<Map_type::Map_descriptors::iterator, bool> ins =
6052 Map_type::map_descriptors.insert(val);
6054 return ins.first->second;
6056 Type* key_type = this->key_type_;
6057 Type* val_type = this->val_type_;
6059 // The map entry type is a struct with three fields. Build that
6060 // struct so that we can get the offsets of the key and value within
6061 // a map entry. The first field should technically be a pointer to
6062 // this type itself, but since we only care about field offsets we
6063 // just use pointer to bool.
6064 Type* pbool = Type::make_pointer_type(Type::make_boolean_type());
6065 Struct_type* map_entry_type =
6066 Type::make_builtin_struct_type(3,
6071 Type* map_descriptor_type = Map_type::make_map_descriptor_type();
6073 const Struct_field_list* fields =
6074 map_descriptor_type->struct_type()->fields();
6076 Expression_list* vals = new Expression_list();
6079 Location bloc = Linemap::predeclared_location();
6081 Struct_field_list::const_iterator p = fields->begin();
6083 go_assert(p->is_field_name("__map_descriptor"));
6084 vals->push_back(Expression::make_type_descriptor(this, bloc));
6087 go_assert(p->is_field_name("__entry_size"));
6088 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
6089 vals->push_back(Expression::make_type_info(map_entry_type, type_info));
6091 Struct_field_list::const_iterator pf = map_entry_type->fields()->begin();
6093 go_assert(pf->is_field_name("__key"));
6096 go_assert(p->is_field_name("__key_offset"));
6097 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6100 go_assert(pf->is_field_name("__val"));
6103 go_assert(p->is_field_name("__val_offset"));
6104 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6107 go_assert(p == fields->end());
6109 Expression* initializer =
6110 Expression::make_struct_composite_literal(map_descriptor_type, vals, bloc);
6112 std::string mangled_name = "__go_map_" + this->mangled_name(gogo);
6113 Btype* map_descriptor_btype = map_descriptor_type->get_backend(gogo);
6114 Bvariable* bvar = gogo->backend()->immutable_struct(mangled_name, true,
6115 map_descriptor_btype,
6118 Translate_context context(gogo, NULL, NULL, NULL);
6119 context.set_is_const();
6120 Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
6122 gogo->backend()->immutable_struct_set_init(bvar, mangled_name, true,
6123 map_descriptor_btype, bloc,
6126 ins.first->second = bvar;
6130 // Build the type of a map descriptor. This must match the struct
6131 // __go_map_descriptor in libgo/runtime/map.h.
6134 Map_type::make_map_descriptor_type()
6139 Type* ptdt = Type::make_type_descriptor_ptr_type();
6140 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6142 Type::make_builtin_struct_type(4,
6143 "__map_descriptor", ptdt,
6144 "__entry_size", uintptr_type,
6145 "__key_offset", uintptr_type,
6146 "__val_offset", uintptr_type);
6147 ret = Type::make_builtin_named_type("__go_map_descriptor", sf);
6152 // Reflection string for a map.
6155 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
6157 ret->append("map[");
6158 this->append_reflection(this->key_type_, gogo, ret);
6160 this->append_reflection(this->val_type_, gogo, ret);
6163 // Mangled name for a map.
6166 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6168 ret->push_back('M');
6169 this->append_mangled_name(this->key_type_, gogo, ret);
6171 this->append_mangled_name(this->val_type_, gogo, ret);
6174 // Export a map type.
6177 Map_type::do_export(Export* exp) const
6179 exp->write_c_string("map [");
6180 exp->write_type(this->key_type_);
6181 exp->write_c_string("] ");
6182 exp->write_type(this->val_type_);
6185 // Import a map type.
6188 Map_type::do_import(Import* imp)
6190 imp->require_c_string("map [");
6191 Type* key_type = imp->read_type();
6192 imp->require_c_string("] ");
6193 Type* val_type = imp->read_type();
6194 return Type::make_map_type(key_type, val_type, imp->location());
6200 Type::make_map_type(Type* key_type, Type* val_type, Location location)
6202 return new Map_type(key_type, val_type, location);
6205 // Class Channel_type.
6210 Channel_type::do_hash_for_method(Gogo* gogo) const
6212 unsigned int ret = 0;
6213 if (this->may_send_)
6215 if (this->may_receive_)
6217 if (this->element_type_ != NULL)
6218 ret += this->element_type_->hash_for_method(gogo) << 2;
6222 // Whether this type is the same as T.
6225 Channel_type::is_identical(const Channel_type* t,
6226 bool errors_are_identical) const
6228 if (!Type::are_identical(this->element_type(), t->element_type(),
6229 errors_are_identical, NULL))
6231 return (this->may_send_ == t->may_send_
6232 && this->may_receive_ == t->may_receive_);
6235 // Return the tree for a channel type. A channel is a pointer to a
6236 // __go_channel struct. The __go_channel struct is defined in
6237 // libgo/runtime/channel.h.
6240 Channel_type::do_get_backend(Gogo* gogo)
6242 static Btype* backend_channel_type;
6243 if (backend_channel_type == NULL)
6245 std::vector<Backend::Btyped_identifier> bfields;
6246 Btype* bt = gogo->backend()->struct_type(bfields);
6247 bt = gogo->backend()->named_type("__go_channel", bt,
6248 Linemap::predeclared_location());
6249 backend_channel_type = gogo->backend()->pointer_type(bt);
6251 return backend_channel_type;
6254 // Build a type descriptor for a channel type.
6257 Channel_type::make_chan_type_descriptor_type()
6262 Type* tdt = Type::make_type_descriptor_type();
6263 Type* ptdt = Type::make_type_descriptor_ptr_type();
6265 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6268 Type::make_builtin_struct_type(3,
6271 "dir", uintptr_type);
6273 ret = Type::make_builtin_named_type("ChanType", sf);
6279 // Build a type descriptor for a map type.
6282 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6284 Location bloc = Linemap::predeclared_location();
6286 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
6288 const Struct_field_list* fields = ctdt->struct_type()->fields();
6290 Expression_list* vals = new Expression_list();
6293 Struct_field_list::const_iterator p = fields->begin();
6294 go_assert(p->is_field_name("commonType"));
6295 vals->push_back(this->type_descriptor_constructor(gogo,
6296 RUNTIME_TYPE_KIND_CHAN,
6300 go_assert(p->is_field_name("elem"));
6301 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
6304 go_assert(p->is_field_name("dir"));
6305 // These bits must match the ones in libgo/runtime/go-type.h.
6307 if (this->may_receive_)
6309 if (this->may_send_)
6312 mpz_init_set_ui(iv, val);
6313 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
6317 go_assert(p == fields->end());
6319 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
6322 // Reflection string.
6325 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
6327 if (!this->may_send_)
6329 ret->append("chan");
6330 if (!this->may_receive_)
6332 ret->push_back(' ');
6333 this->append_reflection(this->element_type_, gogo, ret);
6339 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6341 ret->push_back('C');
6342 this->append_mangled_name(this->element_type_, gogo, ret);
6343 if (this->may_send_)
6344 ret->push_back('s');
6345 if (this->may_receive_)
6346 ret->push_back('r');
6347 ret->push_back('e');
6353 Channel_type::do_export(Export* exp) const
6355 exp->write_c_string("chan ");
6356 if (this->may_send_ && !this->may_receive_)
6357 exp->write_c_string("-< ");
6358 else if (this->may_receive_ && !this->may_send_)
6359 exp->write_c_string("<- ");
6360 exp->write_type(this->element_type_);
6366 Channel_type::do_import(Import* imp)
6368 imp->require_c_string("chan ");
6372 if (imp->match_c_string("-< "))
6376 may_receive = false;
6378 else if (imp->match_c_string("<- "))
6390 Type* element_type = imp->read_type();
6392 return Type::make_channel_type(may_send, may_receive, element_type);
6395 // Make a new channel type.
6398 Type::make_channel_type(bool send, bool receive, Type* element_type)
6400 return new Channel_type(send, receive, element_type);
6403 // Class Interface_type.
6408 Interface_type::do_traverse(Traverse* traverse)
6410 Typed_identifier_list* methods = (this->methods_are_finalized_
6411 ? this->all_methods_
6412 : this->parse_methods_);
6413 if (methods == NULL)
6414 return TRAVERSE_CONTINUE;
6415 return methods->traverse(traverse);
6418 // Finalize the methods. This handles interface inheritance.
6421 Interface_type::finalize_methods()
6423 if (this->methods_are_finalized_)
6425 this->methods_are_finalized_ = true;
6426 if (this->parse_methods_ == NULL)
6429 this->all_methods_ = new Typed_identifier_list();
6430 this->all_methods_->reserve(this->parse_methods_->size());
6431 Typed_identifier_list inherit;
6432 for (Typed_identifier_list::const_iterator pm =
6433 this->parse_methods_->begin();
6434 pm != this->parse_methods_->end();
6437 const Typed_identifier* p = &*pm;
6438 if (p->name().empty())
6439 inherit.push_back(*p);
6440 else if (this->find_method(p->name()) == NULL)
6441 this->all_methods_->push_back(*p);
6443 error_at(p->location(), "duplicate method %qs",
6444 Gogo::message_name(p->name()).c_str());
6447 std::vector<Named_type*> seen;
6448 seen.reserve(inherit.size());
6449 bool issued_recursive_error = false;
6450 while (!inherit.empty())
6452 Type* t = inherit.back().type();
6453 Location tl = inherit.back().location();
6456 Interface_type* it = t->interface_type();
6460 error_at(tl, "interface contains embedded non-interface");
6465 if (!issued_recursive_error)
6467 error_at(tl, "invalid recursive interface");
6468 issued_recursive_error = true;
6473 Named_type* nt = t->named_type();
6474 if (nt != NULL && it->parse_methods_ != NULL)
6476 std::vector<Named_type*>::const_iterator q;
6477 for (q = seen.begin(); q != seen.end(); ++q)
6481 error_at(tl, "inherited interface loop");
6485 if (q != seen.end())
6490 const Typed_identifier_list* imethods = it->parse_methods_;
6491 if (imethods == NULL)
6493 for (Typed_identifier_list::const_iterator q = imethods->begin();
6494 q != imethods->end();
6497 if (q->name().empty())
6498 inherit.push_back(*q);
6499 else if (this->find_method(q->name()) == NULL)
6500 this->all_methods_->push_back(Typed_identifier(q->name(),
6503 error_at(tl, "inherited method %qs is ambiguous",
6504 Gogo::message_name(q->name()).c_str());
6508 if (!this->all_methods_->empty())
6509 this->all_methods_->sort_by_name();
6512 delete this->all_methods_;
6513 this->all_methods_ = NULL;
6517 // Return the method NAME, or NULL.
6519 const Typed_identifier*
6520 Interface_type::find_method(const std::string& name) const
6522 go_assert(this->methods_are_finalized_);
6523 if (this->all_methods_ == NULL)
6525 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6526 p != this->all_methods_->end();
6528 if (p->name() == name)
6533 // Return the method index.
6536 Interface_type::method_index(const std::string& name) const
6538 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
6540 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6541 p != this->all_methods_->end();
6543 if (p->name() == name)
6548 // Return whether NAME is an unexported method, for better error
6552 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
6554 go_assert(this->methods_are_finalized_);
6555 if (this->all_methods_ == NULL)
6557 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6558 p != this->all_methods_->end();
6561 const std::string& method_name(p->name());
6562 if (Gogo::is_hidden_name(method_name)
6563 && name == Gogo::unpack_hidden_name(method_name)
6564 && gogo->pack_hidden_name(name, false) != method_name)
6570 // Whether this type is identical with T.
6573 Interface_type::is_identical(const Interface_type* t,
6574 bool errors_are_identical) const
6576 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
6578 // We require the same methods with the same types. The methods
6579 // have already been sorted.
6580 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
6581 return this->all_methods_ == t->all_methods_;
6583 if (this->assume_identical(this, t) || t->assume_identical(t, this))
6586 Assume_identical* hold_ai = this->assume_identical_;
6587 Assume_identical ai;
6591 this->assume_identical_ = &ai;
6593 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
6594 Typed_identifier_list::const_iterator p2;
6595 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
6597 if (p1 == this->all_methods_->end())
6599 if (p1->name() != p2->name()
6600 || !Type::are_identical(p1->type(), p2->type(),
6601 errors_are_identical, NULL))
6605 this->assume_identical_ = hold_ai;
6607 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
6610 // Return true if T1 and T2 are assumed to be identical during a type
6614 Interface_type::assume_identical(const Interface_type* t1,
6615 const Interface_type* t2) const
6617 for (Assume_identical* p = this->assume_identical_;
6620 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
6625 // Whether we can assign the interface type T to this type. The types
6626 // are known to not be identical. An interface assignment is only
6627 // permitted if T is known to implement all methods in THIS.
6628 // Otherwise a type guard is required.
6631 Interface_type::is_compatible_for_assign(const Interface_type* t,
6632 std::string* reason) const
6634 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
6635 if (this->all_methods_ == NULL)
6637 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6638 p != this->all_methods_->end();
6641 const Typed_identifier* m = t->find_method(p->name());
6647 snprintf(buf, sizeof buf,
6648 _("need explicit conversion; missing method %s%s%s"),
6649 open_quote, Gogo::message_name(p->name()).c_str(),
6651 reason->assign(buf);
6656 std::string subreason;
6657 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
6661 std::string n = Gogo::message_name(p->name());
6662 size_t len = 100 + n.length() + subreason.length();
6663 char* buf = new char[len];
6664 if (subreason.empty())
6665 snprintf(buf, len, _("incompatible type for method %s%s%s"),
6666 open_quote, n.c_str(), close_quote);
6669 _("incompatible type for method %s%s%s (%s)"),
6670 open_quote, n.c_str(), close_quote,
6672 reason->assign(buf);
6685 Interface_type::do_hash_for_method(Gogo*) const
6687 go_assert(this->methods_are_finalized_);
6688 unsigned int ret = 0;
6689 if (this->all_methods_ != NULL)
6691 for (Typed_identifier_list::const_iterator p =
6692 this->all_methods_->begin();
6693 p != this->all_methods_->end();
6696 ret = Type::hash_string(p->name(), ret);
6697 // We don't use the method type in the hash, to avoid
6698 // infinite recursion if an interface method uses a type
6699 // which is an interface which inherits from the interface
6701 // type T interface { F() interface {T}}
6708 // Return true if T implements the interface. If it does not, and
6709 // REASON is not NULL, set *REASON to a useful error message.
6712 Interface_type::implements_interface(const Type* t, std::string* reason) const
6714 go_assert(this->methods_are_finalized_);
6715 if (this->all_methods_ == NULL)
6718 bool is_pointer = false;
6719 const Named_type* nt = t->named_type();
6720 const Struct_type* st = t->struct_type();
6721 // If we start with a named type, we don't dereference it to find
6725 const Type* pt = t->points_to();
6728 // If T is a pointer to a named type, then we need to look at
6729 // the type to which it points.
6731 nt = pt->named_type();
6732 st = pt->struct_type();
6736 // If we have a named type, get the methods from it rather than from
6741 // Only named and struct types have methods.
6742 if (nt == NULL && st == NULL)
6746 if (t->points_to() != NULL
6747 && t->points_to()->interface_type() != NULL)
6748 reason->assign(_("pointer to interface type has no methods"));
6750 reason->assign(_("type has no methods"));
6755 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
6759 if (t->points_to() != NULL
6760 && t->points_to()->interface_type() != NULL)
6761 reason->assign(_("pointer to interface type has no methods"));
6763 reason->assign(_("type has no methods"));
6768 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6769 p != this->all_methods_->end();
6772 bool is_ambiguous = false;
6773 Method* m = (nt != NULL
6774 ? nt->method_function(p->name(), &is_ambiguous)
6775 : st->method_function(p->name(), &is_ambiguous));
6780 std::string n = Gogo::message_name(p->name());
6781 size_t len = n.length() + 100;
6782 char* buf = new char[len];
6784 snprintf(buf, len, _("ambiguous method %s%s%s"),
6785 open_quote, n.c_str(), close_quote);
6787 snprintf(buf, len, _("missing method %s%s%s"),
6788 open_quote, n.c_str(), close_quote);
6789 reason->assign(buf);
6795 Function_type *p_fn_type = p->type()->function_type();
6796 Function_type* m_fn_type = m->type()->function_type();
6797 go_assert(p_fn_type != NULL && m_fn_type != NULL);
6798 std::string subreason;
6799 if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
6803 std::string n = Gogo::message_name(p->name());
6804 size_t len = 100 + n.length() + subreason.length();
6805 char* buf = new char[len];
6806 if (subreason.empty())
6807 snprintf(buf, len, _("incompatible type for method %s%s%s"),
6808 open_quote, n.c_str(), close_quote);
6811 _("incompatible type for method %s%s%s (%s)"),
6812 open_quote, n.c_str(), close_quote,
6814 reason->assign(buf);
6820 if (!is_pointer && !m->is_value_method())
6824 std::string n = Gogo::message_name(p->name());
6825 size_t len = 100 + n.length();
6826 char* buf = new char[len];
6827 snprintf(buf, len, _("method %s%s%s requires a pointer"),
6828 open_quote, n.c_str(), close_quote);
6829 reason->assign(buf);
6839 // Return the backend representation of the empty interface type. We
6840 // use the same struct for all empty interfaces.
6843 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
6845 static Btype* empty_interface_type;
6846 if (empty_interface_type == NULL)
6848 std::vector<Backend::Btyped_identifier> bfields(2);
6850 Location bloc = Linemap::predeclared_location();
6852 Type* pdt = Type::make_type_descriptor_ptr_type();
6853 bfields[0].name = "__type_descriptor";
6854 bfields[0].btype = pdt->get_backend(gogo);
6855 bfields[0].location = bloc;
6857 Type* vt = Type::make_pointer_type(Type::make_void_type());
6858 bfields[1].name = "__object";
6859 bfields[1].btype = vt->get_backend(gogo);
6860 bfields[1].location = bloc;
6862 empty_interface_type = gogo->backend()->struct_type(bfields);
6864 return empty_interface_type;
6867 // Return the fields of a non-empty interface type. This is not
6868 // declared in types.h so that types.h doesn't have to #include
6872 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
6873 bool use_placeholder,
6874 std::vector<Backend::Btyped_identifier>* bfields)
6876 Location loc = type->location();
6878 std::vector<Backend::Btyped_identifier> mfields(type->methods()->size() + 1);
6880 Type* pdt = Type::make_type_descriptor_ptr_type();
6881 mfields[0].name = "__type_descriptor";
6882 mfields[0].btype = pdt->get_backend(gogo);
6883 mfields[0].location = loc;
6885 std::string last_name = "";
6887 for (Typed_identifier_list::const_iterator p = type->methods()->begin();
6888 p != type->methods()->end();
6891 // The type of the method in Go only includes the parameters.
6892 // The actual method also has a receiver, which is always a
6893 // pointer. We need to add that pointer type here in order to
6894 // generate the correct type for the backend.
6895 Function_type* ft = p->type()->function_type();
6896 go_assert(ft->receiver() == NULL);
6898 const Typed_identifier_list* params = ft->parameters();
6899 Typed_identifier_list* mparams = new Typed_identifier_list();
6901 mparams->reserve(params->size() + 1);
6902 Type* vt = Type::make_pointer_type(Type::make_void_type());
6903 mparams->push_back(Typed_identifier("", vt, ft->location()));
6906 for (Typed_identifier_list::const_iterator pp = params->begin();
6907 pp != params->end();
6909 mparams->push_back(*pp);
6912 Typed_identifier_list* mresults = (ft->results() == NULL
6914 : ft->results()->copy());
6915 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
6918 mfields[i].name = Gogo::unpack_hidden_name(p->name());
6919 mfields[i].btype = (use_placeholder
6920 ? mft->get_backend_placeholder(gogo)
6921 : mft->get_backend(gogo));
6922 mfields[i].location = loc;
6923 // Sanity check: the names should be sorted.
6924 go_assert(p->name() > last_name);
6925 last_name = p->name();
6928 Btype* methods = gogo->backend()->struct_type(mfields);
6932 (*bfields)[0].name = "__methods";
6933 (*bfields)[0].btype = gogo->backend()->pointer_type(methods);
6934 (*bfields)[0].location = loc;
6936 Type* vt = Type::make_pointer_type(Type::make_void_type());
6937 (*bfields)[1].name = "__object";
6938 (*bfields)[1].btype = vt->get_backend(gogo);
6939 (*bfields)[1].location = Linemap::predeclared_location();
6942 // Return a tree for an interface type. An interface is a pointer to
6943 // a struct. The struct has three fields. The first field is a
6944 // pointer to the type descriptor for the dynamic type of the object.
6945 // The second field is a pointer to a table of methods for the
6946 // interface to be used with the object. The third field is the value
6947 // of the object itself.
6950 Interface_type::do_get_backend(Gogo* gogo)
6952 if (this->is_empty())
6953 return Interface_type::get_backend_empty_interface_type(gogo);
6956 if (this->interface_btype_ != NULL)
6957 return this->interface_btype_;
6958 this->interface_btype_ =
6959 gogo->backend()->placeholder_struct_type("", this->location_);
6960 std::vector<Backend::Btyped_identifier> bfields;
6961 get_backend_interface_fields(gogo, this, false, &bfields);
6962 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
6964 this->interface_btype_ = gogo->backend()->error_type();
6965 return this->interface_btype_;
6969 // Finish the backend representation of the methods.
6972 Interface_type::finish_backend_methods(Gogo* gogo)
6974 if (!this->interface_type()->is_empty())
6976 const Typed_identifier_list* methods = this->methods();
6977 if (methods != NULL)
6979 for (Typed_identifier_list::const_iterator p = methods->begin();
6980 p != methods->end();
6982 p->type()->get_backend(gogo);
6987 // The type of an interface type descriptor.
6990 Interface_type::make_interface_type_descriptor_type()
6995 Type* tdt = Type::make_type_descriptor_type();
6996 Type* ptdt = Type::make_type_descriptor_ptr_type();
6998 Type* string_type = Type::lookup_string_type();
6999 Type* pointer_string_type = Type::make_pointer_type(string_type);
7002 Type::make_builtin_struct_type(3,
7003 "name", pointer_string_type,
7004 "pkgPath", pointer_string_type,
7007 Type* nsm = Type::make_builtin_named_type("imethod", sm);
7009 Type* slice_nsm = Type::make_array_type(nsm, NULL);
7011 Struct_type* s = Type::make_builtin_struct_type(2,
7013 "methods", slice_nsm);
7015 ret = Type::make_builtin_named_type("InterfaceType", s);
7021 // Build a type descriptor for an interface type.
7024 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7026 Location bloc = Linemap::predeclared_location();
7028 Type* itdt = Interface_type::make_interface_type_descriptor_type();
7030 const Struct_field_list* ifields = itdt->struct_type()->fields();
7032 Expression_list* ivals = new Expression_list();
7035 Struct_field_list::const_iterator pif = ifields->begin();
7036 go_assert(pif->is_field_name("commonType"));
7037 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
7038 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
7042 go_assert(pif->is_field_name("methods"));
7044 Expression_list* methods = new Expression_list();
7045 if (this->all_methods_ != NULL)
7047 Type* elemtype = pif->type()->array_type()->element_type();
7049 methods->reserve(this->all_methods_->size());
7050 for (Typed_identifier_list::const_iterator pm =
7051 this->all_methods_->begin();
7052 pm != this->all_methods_->end();
7055 const Struct_field_list* mfields = elemtype->struct_type()->fields();
7057 Expression_list* mvals = new Expression_list();
7060 Struct_field_list::const_iterator pmf = mfields->begin();
7061 go_assert(pmf->is_field_name("name"));
7062 std::string s = Gogo::unpack_hidden_name(pm->name());
7063 Expression* e = Expression::make_string(s, bloc);
7064 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7067 go_assert(pmf->is_field_name("pkgPath"));
7068 if (!Gogo::is_hidden_name(pm->name()))
7069 mvals->push_back(Expression::make_nil(bloc));
7072 s = Gogo::hidden_name_prefix(pm->name());
7073 e = Expression::make_string(s, bloc);
7074 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7078 go_assert(pmf->is_field_name("typ"));
7079 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
7082 go_assert(pmf == mfields->end());
7084 e = Expression::make_struct_composite_literal(elemtype, mvals,
7086 methods->push_back(e);
7090 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
7094 go_assert(pif == ifields->end());
7096 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
7099 // Reflection string.
7102 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
7104 ret->append("interface {");
7105 const Typed_identifier_list* methods = this->parse_methods_;
7106 if (methods != NULL)
7108 ret->push_back(' ');
7109 for (Typed_identifier_list::const_iterator p = methods->begin();
7110 p != methods->end();
7113 if (p != methods->begin())
7115 if (p->name().empty())
7116 this->append_reflection(p->type(), gogo, ret);
7119 if (!Gogo::is_hidden_name(p->name()))
7120 ret->append(p->name());
7123 // This matches what the gc compiler does.
7124 std::string prefix = Gogo::hidden_name_prefix(p->name());
7125 ret->append(prefix.substr(prefix.find('.') + 1));
7126 ret->push_back('.');
7127 ret->append(Gogo::unpack_hidden_name(p->name()));
7129 std::string sub = p->type()->reflection(gogo);
7130 go_assert(sub.compare(0, 4, "func") == 0);
7131 sub = sub.substr(4);
7135 ret->push_back(' ');
7143 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7145 go_assert(this->methods_are_finalized_);
7147 ret->push_back('I');
7149 const Typed_identifier_list* methods = this->all_methods_;
7150 if (methods != NULL && !this->seen_)
7153 for (Typed_identifier_list::const_iterator p = methods->begin();
7154 p != methods->end();
7157 if (!p->name().empty())
7159 std::string n = Gogo::unpack_hidden_name(p->name());
7161 snprintf(buf, sizeof buf, "%u_",
7162 static_cast<unsigned int>(n.length()));
7166 this->append_mangled_name(p->type(), gogo, ret);
7168 this->seen_ = false;
7171 ret->push_back('e');
7177 Interface_type::do_export(Export* exp) const
7179 exp->write_c_string("interface { ");
7181 const Typed_identifier_list* methods = this->parse_methods_;
7182 if (methods != NULL)
7184 for (Typed_identifier_list::const_iterator pm = methods->begin();
7185 pm != methods->end();
7188 if (pm->name().empty())
7190 exp->write_c_string("? ");
7191 exp->write_type(pm->type());
7195 exp->write_string(pm->name());
7196 exp->write_c_string(" (");
7198 const Function_type* fntype = pm->type()->function_type();
7201 const Typed_identifier_list* parameters = fntype->parameters();
7202 if (parameters != NULL)
7204 bool is_varargs = fntype->is_varargs();
7205 for (Typed_identifier_list::const_iterator pp =
7206 parameters->begin();
7207 pp != parameters->end();
7213 exp->write_c_string(", ");
7214 exp->write_name(pp->name());
7215 exp->write_c_string(" ");
7216 if (!is_varargs || pp + 1 != parameters->end())
7217 exp->write_type(pp->type());
7220 exp->write_c_string("...");
7221 Type *pptype = pp->type();
7222 exp->write_type(pptype->array_type()->element_type());
7227 exp->write_c_string(")");
7229 const Typed_identifier_list* results = fntype->results();
7230 if (results != NULL)
7232 exp->write_c_string(" ");
7233 if (results->size() == 1 && results->begin()->name().empty())
7234 exp->write_type(results->begin()->type());
7238 exp->write_c_string("(");
7239 for (Typed_identifier_list::const_iterator p =
7241 p != results->end();
7247 exp->write_c_string(", ");
7248 exp->write_name(p->name());
7249 exp->write_c_string(" ");
7250 exp->write_type(p->type());
7252 exp->write_c_string(")");
7257 exp->write_c_string("; ");
7261 exp->write_c_string("}");
7264 // Import an interface type.
7267 Interface_type::do_import(Import* imp)
7269 imp->require_c_string("interface { ");
7271 Typed_identifier_list* methods = new Typed_identifier_list;
7272 while (imp->peek_char() != '}')
7274 std::string name = imp->read_identifier();
7278 imp->require_c_string(" ");
7279 Type* t = imp->read_type();
7280 methods->push_back(Typed_identifier("", t, imp->location()));
7281 imp->require_c_string("; ");
7285 imp->require_c_string(" (");
7287 Typed_identifier_list* parameters;
7288 bool is_varargs = false;
7289 if (imp->peek_char() == ')')
7293 parameters = new Typed_identifier_list;
7296 std::string name = imp->read_name();
7297 imp->require_c_string(" ");
7299 if (imp->match_c_string("..."))
7305 Type* ptype = imp->read_type();
7307 ptype = Type::make_array_type(ptype, NULL);
7308 parameters->push_back(Typed_identifier(name, ptype,
7310 if (imp->peek_char() != ',')
7312 go_assert(!is_varargs);
7313 imp->require_c_string(", ");
7316 imp->require_c_string(")");
7318 Typed_identifier_list* results;
7319 if (imp->peek_char() != ' ')
7323 results = new Typed_identifier_list;
7325 if (imp->peek_char() != '(')
7327 Type* rtype = imp->read_type();
7328 results->push_back(Typed_identifier("", rtype, imp->location()));
7335 std::string name = imp->read_name();
7336 imp->require_c_string(" ");
7337 Type* rtype = imp->read_type();
7338 results->push_back(Typed_identifier(name, rtype,
7340 if (imp->peek_char() != ',')
7342 imp->require_c_string(", ");
7344 imp->require_c_string(")");
7348 Function_type* fntype = Type::make_function_type(NULL, parameters,
7352 fntype->set_is_varargs();
7353 methods->push_back(Typed_identifier(name, fntype, imp->location()));
7355 imp->require_c_string("; ");
7358 imp->require_c_string("}");
7360 if (methods->empty())
7366 return Type::make_interface_type(methods, imp->location());
7369 // Make an interface type.
7372 Type::make_interface_type(Typed_identifier_list* methods,
7375 return new Interface_type(methods, location);
7378 // Make an empty interface type.
7381 Type::make_empty_interface_type(Location location)
7383 Interface_type* ret = new Interface_type(NULL, location);
7384 ret->finalize_methods();
7390 // Bind a method to an object.
7393 Method::bind_method(Expression* expr, Location location) const
7395 if (this->stub_ == NULL)
7397 // When there is no stub object, the binding is determined by
7399 return this->do_bind_method(expr, location);
7401 return Expression::make_bound_method(expr, this->stub_, location);
7404 // Return the named object associated with a method. This may only be
7405 // called after methods are finalized.
7408 Method::named_object() const
7410 if (this->stub_ != NULL)
7412 return this->do_named_object();
7415 // Class Named_method.
7417 // The type of the method.
7420 Named_method::do_type() const
7422 if (this->named_object_->is_function())
7423 return this->named_object_->func_value()->type();
7424 else if (this->named_object_->is_function_declaration())
7425 return this->named_object_->func_declaration_value()->type();
7430 // Return the location of the method receiver.
7433 Named_method::do_receiver_location() const
7435 return this->do_type()->receiver()->location();
7438 // Bind a method to an object.
7441 Named_method::do_bind_method(Expression* expr, Location location) const
7443 Named_object* no = this->named_object_;
7444 Bound_method_expression* bme = Expression::make_bound_method(expr, no,
7446 // If this is not a local method, and it does not use a stub, then
7447 // the real method expects a different type. We need to cast the
7449 if (this->depth() > 0 && !this->needs_stub_method())
7451 Function_type* ftype = this->do_type();
7452 go_assert(ftype->is_method());
7453 Type* frtype = ftype->receiver()->type();
7454 bme->set_first_argument_type(frtype);
7459 // Class Interface_method.
7461 // Bind a method to an object.
7464 Interface_method::do_bind_method(Expression* expr,
7465 Location location) const
7467 return Expression::make_interface_field_reference(expr, this->name_,
7473 // Insert a new method. Return true if it was inserted, false
7477 Methods::insert(const std::string& name, Method* m)
7479 std::pair<Method_map::iterator, bool> ins =
7480 this->methods_.insert(std::make_pair(name, m));
7485 Method* old_method = ins.first->second;
7486 if (m->depth() < old_method->depth())
7489 ins.first->second = m;
7494 if (m->depth() == old_method->depth())
7495 old_method->set_is_ambiguous();
7501 // Return the number of unambiguous methods.
7504 Methods::count() const
7507 for (Method_map::const_iterator p = this->methods_.begin();
7508 p != this->methods_.end();
7510 if (!p->second->is_ambiguous())
7515 // Class Named_type.
7517 // Return the name of the type.
7520 Named_type::name() const
7522 return this->named_object_->name();
7525 // Return the name of the type to use in an error message.
7528 Named_type::message_name() const
7530 return this->named_object_->message_name();
7533 // Whether this is an alias. There are currently only two aliases so
7534 // we just recognize them by name.
7537 Named_type::is_alias() const
7539 if (!this->is_builtin())
7541 const std::string& name(this->name());
7542 return name == "byte" || name == "rune";
7545 // Return the base type for this type. We have to be careful about
7546 // circular type definitions, which are invalid but may be seen here.
7549 Named_type::named_base()
7554 Type* ret = this->type_->base();
7555 this->seen_ = false;
7560 Named_type::named_base() const
7565 const Type* ret = this->type_->base();
7566 this->seen_ = false;
7570 // Return whether this is an error type. We have to be careful about
7571 // circular type definitions, which are invalid but may be seen here.
7574 Named_type::is_named_error_type() const
7579 bool ret = this->type_->is_error_type();
7580 this->seen_ = false;
7584 // Whether this type is comparable. We have to be careful about
7585 // circular type definitions.
7588 Named_type::named_type_is_comparable(std::string* reason) const
7593 bool ret = Type::are_compatible_for_comparison(true, this->type_,
7594 this->type_, reason);
7595 this->seen_ = false;
7599 // Add a method to this type.
7602 Named_type::add_method(const std::string& name, Function* function)
7604 if (this->local_methods_ == NULL)
7605 this->local_methods_ = new Bindings(NULL);
7606 return this->local_methods_->add_function(name, NULL, function);
7609 // Add a method declaration to this type.
7612 Named_type::add_method_declaration(const std::string& name, Package* package,
7613 Function_type* type,
7616 if (this->local_methods_ == NULL)
7617 this->local_methods_ = new Bindings(NULL);
7618 return this->local_methods_->add_function_declaration(name, package, type,
7622 // Add an existing method to this type.
7625 Named_type::add_existing_method(Named_object* no)
7627 if (this->local_methods_ == NULL)
7628 this->local_methods_ = new Bindings(NULL);
7629 this->local_methods_->add_named_object(no);
7632 // Look for a local method NAME, and returns its named object, or NULL
7636 Named_type::find_local_method(const std::string& name) const
7638 if (this->local_methods_ == NULL)
7640 return this->local_methods_->lookup(name);
7643 // Return whether NAME is an unexported field or method, for better
7647 Named_type::is_unexported_local_method(Gogo* gogo,
7648 const std::string& name) const
7650 Bindings* methods = this->local_methods_;
7651 if (methods != NULL)
7653 for (Bindings::const_declarations_iterator p =
7654 methods->begin_declarations();
7655 p != methods->end_declarations();
7658 if (Gogo::is_hidden_name(p->first)
7659 && name == Gogo::unpack_hidden_name(p->first)
7660 && gogo->pack_hidden_name(name, false) != p->first)
7667 // Build the complete list of methods for this type, which means
7668 // recursively including all methods for anonymous fields. Create all
7672 Named_type::finalize_methods(Gogo* gogo)
7674 if (this->all_methods_ != NULL)
7677 if (this->local_methods_ != NULL
7678 && (this->points_to() != NULL || this->interface_type() != NULL))
7680 const Bindings* lm = this->local_methods_;
7681 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
7682 p != lm->end_declarations();
7684 error_at(p->second->location(),
7685 "invalid pointer or interface receiver type");
7686 delete this->local_methods_;
7687 this->local_methods_ = NULL;
7691 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
7694 // Return the method NAME, or NULL if there isn't one or if it is
7695 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
7699 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
7701 return Type::method_function(this->all_methods_, name, is_ambiguous);
7704 // Return a pointer to the interface method table for this type for
7705 // the interface INTERFACE. IS_POINTER is true if this is for a
7709 Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface,
7712 go_assert(!interface->is_empty());
7714 Interface_method_tables** pimt = (is_pointer
7715 ? &this->interface_method_tables_
7716 : &this->pointer_interface_method_tables_);
7719 *pimt = new Interface_method_tables(5);
7721 std::pair<const Interface_type*, tree> val(interface, NULL_TREE);
7722 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
7726 // This is a new entry in the hash table.
7727 go_assert(ins.first->second == NULL_TREE);
7728 ins.first->second = gogo->interface_method_table_for_type(interface,
7733 tree decl = ins.first->second;
7734 if (decl == error_mark_node)
7735 return error_mark_node;
7736 go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL);
7737 return build_fold_addr_expr(decl);
7740 // Return whether a named type has any hidden fields.
7743 Named_type::named_type_has_hidden_fields(std::string* reason) const
7748 bool ret = this->type_->has_hidden_fields(this, reason);
7749 this->seen_ = false;
7753 // Look for a use of a complete type within another type. This is
7754 // used to check that we don't try to use a type within itself.
7756 class Find_type_use : public Traverse
7759 Find_type_use(Named_type* find_type)
7760 : Traverse(traverse_types),
7761 find_type_(find_type), found_(false)
7764 // Whether we found the type.
7767 { return this->found_; }
7774 // The type we are looking for.
7775 Named_type* find_type_;
7776 // Whether we found the type.
7780 // Check for FIND_TYPE in TYPE.
7783 Find_type_use::type(Type* type)
7785 if (type->named_type() != NULL && this->find_type_ == type->named_type())
7787 this->found_ = true;
7788 return TRAVERSE_EXIT;
7791 // It's OK if we see a reference to the type in any type which is
7792 // essentially a pointer: a pointer, a slice, a function, a map, or
7794 if (type->points_to() != NULL
7795 || type->is_slice_type()
7796 || type->function_type() != NULL
7797 || type->map_type() != NULL
7798 || type->channel_type() != NULL)
7799 return TRAVERSE_SKIP_COMPONENTS;
7801 // For an interface, a reference to the type in a method type should
7802 // be ignored, but we have to consider direct inheritance. When
7803 // this is called, there may be cases of direct inheritance
7804 // represented as a method with no name.
7805 if (type->interface_type() != NULL)
7807 const Typed_identifier_list* methods = type->interface_type()->methods();
7808 if (methods != NULL)
7810 for (Typed_identifier_list::const_iterator p = methods->begin();
7811 p != methods->end();
7814 if (p->name().empty())
7816 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
7817 return TRAVERSE_EXIT;
7821 return TRAVERSE_SKIP_COMPONENTS;
7824 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
7825 // to convert TYPE to the backend representation before we convert
7827 if (type->named_type() != NULL)
7829 switch (type->base()->classification())
7831 case Type::TYPE_ERROR:
7832 case Type::TYPE_BOOLEAN:
7833 case Type::TYPE_INTEGER:
7834 case Type::TYPE_FLOAT:
7835 case Type::TYPE_COMPLEX:
7836 case Type::TYPE_STRING:
7837 case Type::TYPE_NIL:
7840 case Type::TYPE_ARRAY:
7841 case Type::TYPE_STRUCT:
7842 this->find_type_->add_dependency(type->named_type());
7845 case Type::TYPE_NAMED:
7846 case Type::TYPE_FORWARD:
7847 go_assert(saw_errors());
7850 case Type::TYPE_VOID:
7851 case Type::TYPE_SINK:
7852 case Type::TYPE_FUNCTION:
7853 case Type::TYPE_POINTER:
7854 case Type::TYPE_CALL_MULTIPLE_RESULT:
7855 case Type::TYPE_MAP:
7856 case Type::TYPE_CHANNEL:
7857 case Type::TYPE_INTERFACE:
7863 return TRAVERSE_CONTINUE;
7866 // Verify that a named type does not refer to itself.
7869 Named_type::do_verify()
7871 Find_type_use find(this);
7872 Type::traverse(this->type_, &find);
7875 error_at(this->location_, "invalid recursive type %qs",
7876 this->message_name().c_str());
7877 this->is_error_ = true;
7881 // Check whether any of the local methods overloads an existing
7882 // struct field or interface method. We don't need to check the
7883 // list of methods against itself: that is handled by the Bindings
7885 if (this->local_methods_ != NULL)
7887 Struct_type* st = this->type_->struct_type();
7888 bool found_dup = false;
7891 for (Bindings::const_declarations_iterator p =
7892 this->local_methods_->begin_declarations();
7893 p != this->local_methods_->end_declarations();
7896 const std::string& name(p->first);
7897 if (st != NULL && st->find_local_field(name, NULL) != NULL)
7899 error_at(p->second->location(),
7900 "method %qs redeclares struct field name",
7901 Gogo::message_name(name).c_str());
7913 // Return whether this type is or contains a pointer.
7916 Named_type::do_has_pointer() const
7921 bool ret = this->type_->has_pointer();
7922 this->seen_ = false;
7926 // Return whether comparisons for this type can use the identity
7930 Named_type::do_compare_is_identity(Gogo* gogo) const
7932 // We don't use this->seen_ here because compare_is_identity may
7933 // call base() later, and that will mess up if seen_ is set here.
7934 if (this->seen_in_compare_is_identity_)
7936 this->seen_in_compare_is_identity_ = true;
7937 bool ret = this->type_->compare_is_identity(gogo);
7938 this->seen_in_compare_is_identity_ = false;
7942 // Return a hash code. This is used for method lookup. We simply
7943 // hash on the name itself.
7946 Named_type::do_hash_for_method(Gogo* gogo) const
7948 if (this->is_alias())
7949 return this->type_->named_type()->do_hash_for_method(gogo);
7951 const std::string& name(this->named_object()->name());
7952 unsigned int ret = Type::hash_string(name, 0);
7954 // GOGO will be NULL here when called from Type_hash_identical.
7955 // That is OK because that is only used for internal hash tables
7956 // where we are going to be comparing named types for equality. In
7957 // other cases, which are cases where the runtime is going to
7958 // compare hash codes to see if the types are the same, we need to
7959 // include the package prefix and name in the hash.
7960 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
7962 const Package* package = this->named_object()->package();
7963 if (package == NULL)
7965 ret = Type::hash_string(gogo->unique_prefix(), ret);
7966 ret = Type::hash_string(gogo->package_name(), ret);
7970 ret = Type::hash_string(package->unique_prefix(), ret);
7971 ret = Type::hash_string(package->name(), ret);
7978 // Convert a named type to the backend representation. In order to
7979 // get dependencies right, we fill in a dummy structure for this type,
7980 // then convert all the dependencies, then complete this type. When
7981 // this function is complete, the size of the type is known.
7984 Named_type::convert(Gogo* gogo)
7986 if (this->is_error_ || this->is_converted_)
7989 this->create_placeholder(gogo);
7991 // Convert all the dependencies. If they refer indirectly back to
7992 // this type, they will pick up the intermediate tree we just
7994 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
7995 p != this->dependencies_.end();
7997 (*p)->convert(gogo);
7999 // Complete this type.
8000 Btype* bt = this->named_btype_;
8001 Type* base = this->type_->base();
8002 switch (base->classification())
8019 // The size of these types is already correct. We don't worry
8020 // about filling them in until later, when we also track
8021 // circular references.
8026 std::vector<Backend::Btyped_identifier> bfields;
8027 get_backend_struct_fields(gogo, base->struct_type()->fields(),
8029 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8030 bt = gogo->backend()->error_type();
8035 // Slice types were completed in create_placeholder.
8036 if (!base->is_slice_type())
8038 Btype* bet = base->array_type()->get_backend_element(gogo, true);
8039 Bexpression* blen = base->array_type()->get_backend_length(gogo);
8040 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
8041 bt = gogo->backend()->error_type();
8045 case TYPE_INTERFACE:
8046 // Interface types were completed in create_placeholder.
8054 case TYPE_CALL_MULTIPLE_RESULT:
8060 this->named_btype_ = bt;
8061 this->is_converted_ = true;
8062 this->is_placeholder_ = false;
8065 // Create the placeholder for a named type. This is the first step in
8066 // converting to the backend representation.
8069 Named_type::create_placeholder(Gogo* gogo)
8071 if (this->is_error_)
8072 this->named_btype_ = gogo->backend()->error_type();
8074 if (this->named_btype_ != NULL)
8077 // Create the structure for this type. Note that because we call
8078 // base() here, we don't attempt to represent a named type defined
8079 // as another named type. Instead both named types will point to
8080 // different base representations.
8081 Type* base = this->type_->base();
8083 bool set_name = true;
8084 switch (base->classification())
8087 this->is_error_ = true;
8088 this->named_btype_ = gogo->backend()->error_type();
8098 // These are simple basic types, we can just create them
8100 bt = Type::get_named_base_btype(gogo, base);
8105 // All maps and channels have the same backend representation.
8106 bt = Type::get_named_base_btype(gogo, base);
8112 bool for_function = base->classification() == TYPE_FUNCTION;
8113 bt = gogo->backend()->placeholder_pointer_type(this->name(),
8121 bt = gogo->backend()->placeholder_struct_type(this->name(),
8123 this->is_placeholder_ = true;
8128 if (base->is_slice_type())
8129 bt = gogo->backend()->placeholder_struct_type(this->name(),
8133 bt = gogo->backend()->placeholder_array_type(this->name(),
8135 this->is_placeholder_ = true;
8140 case TYPE_INTERFACE:
8141 if (base->interface_type()->is_empty())
8142 bt = Interface_type::get_backend_empty_interface_type(gogo);
8145 bt = gogo->backend()->placeholder_struct_type(this->name(),
8153 case TYPE_CALL_MULTIPLE_RESULT:
8160 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
8162 this->named_btype_ = bt;
8164 if (base->is_slice_type())
8166 // We do not record slices as dependencies of other types,
8167 // because we can fill them in completely here with the final
8169 std::vector<Backend::Btyped_identifier> bfields;
8170 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
8171 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8172 this->named_btype_ = gogo->backend()->error_type();
8174 else if (base->interface_type() != NULL
8175 && !base->interface_type()->is_empty())
8177 // We do not record interfaces as dependencies of other types,
8178 // because we can fill them in completely here with the final
8180 std::vector<Backend::Btyped_identifier> bfields;
8181 get_backend_interface_fields(gogo, base->interface_type(), true,
8183 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8184 this->named_btype_ = gogo->backend()->error_type();
8188 // Get a tree for a named type.
8191 Named_type::do_get_backend(Gogo* gogo)
8193 if (this->is_error_)
8194 return gogo->backend()->error_type();
8196 Btype* bt = this->named_btype_;
8198 if (!gogo->named_types_are_converted())
8200 // We have not completed converting named types. NAMED_BTYPE_
8201 // is a placeholder and we shouldn't do anything further.
8205 // We don't build dependencies for types whose sizes do not
8206 // change or are not relevant, so we may see them here while
8207 // converting types.
8208 this->create_placeholder(gogo);
8209 bt = this->named_btype_;
8210 go_assert(bt != NULL);
8214 // We are not converting types. This should only be called if the
8215 // type has already been converted.
8216 if (!this->is_converted_)
8218 go_assert(saw_errors());
8219 return gogo->backend()->error_type();
8222 go_assert(bt != NULL);
8224 // Complete the tree.
8225 Type* base = this->type_->base();
8227 switch (base->classification())
8230 return gogo->backend()->error_type();
8244 if (!this->seen_in_get_backend_)
8246 this->seen_in_get_backend_ = true;
8247 base->struct_type()->finish_backend_fields(gogo);
8248 this->seen_in_get_backend_ = false;
8253 if (!this->seen_in_get_backend_)
8255 this->seen_in_get_backend_ = true;
8256 base->array_type()->finish_backend_element(gogo);
8257 this->seen_in_get_backend_ = false;
8261 case TYPE_INTERFACE:
8262 if (!this->seen_in_get_backend_)
8264 this->seen_in_get_backend_ = true;
8265 base->interface_type()->finish_backend_methods(gogo);
8266 this->seen_in_get_backend_ = false;
8271 // Don't build a circular data structure. GENERIC can't handle
8273 if (this->seen_in_get_backend_)
8275 this->is_circular_ = true;
8276 return gogo->backend()->circular_pointer_type(bt, true);
8278 this->seen_in_get_backend_ = true;
8279 bt1 = Type::get_named_base_btype(gogo, base);
8280 this->seen_in_get_backend_ = false;
8281 if (this->is_circular_)
8282 bt1 = gogo->backend()->circular_pointer_type(bt, true);
8283 if (!gogo->backend()->set_placeholder_function_type(bt, bt1))
8284 bt = gogo->backend()->error_type();
8288 // Don't build a circular data structure. GENERIC can't handle
8290 if (this->seen_in_get_backend_)
8292 this->is_circular_ = true;
8293 return gogo->backend()->circular_pointer_type(bt, false);
8295 this->seen_in_get_backend_ = true;
8296 bt1 = Type::get_named_base_btype(gogo, base);
8297 this->seen_in_get_backend_ = false;
8298 if (this->is_circular_)
8299 bt1 = gogo->backend()->circular_pointer_type(bt, false);
8300 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
8301 bt = gogo->backend()->error_type();
8306 case TYPE_CALL_MULTIPLE_RESULT:
8315 // Build a type descriptor for a named type.
8318 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8320 if (name == NULL && this->is_alias())
8321 return this->type_->type_descriptor(gogo, this->type_);
8323 // If NAME is not NULL, then we don't really want the type
8324 // descriptor for this type; we want the descriptor for the
8325 // underlying type, giving it the name NAME.
8326 return this->named_type_descriptor(gogo, this->type_,
8327 name == NULL ? this : name);
8330 // Add to the reflection string. This is used mostly for the name of
8331 // the type used in a type descriptor, not for actual reflection
8335 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
8337 if (this->is_alias())
8339 this->append_reflection(this->type_, gogo, ret);
8342 if (!this->is_builtin())
8344 const Package* package = this->named_object_->package();
8345 if (package != NULL)
8346 ret->append(package->name());
8348 ret->append(gogo->package_name());
8349 ret->push_back('.');
8351 if (this->in_function_ != NULL)
8353 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
8354 ret->push_back('$');
8356 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
8359 // Get the mangled name.
8362 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8364 if (this->is_alias())
8366 this->append_mangled_name(this->type_, gogo, ret);
8369 Named_object* no = this->named_object_;
8371 if (this->is_builtin())
8372 go_assert(this->in_function_ == NULL);
8375 const std::string& unique_prefix(no->package() == NULL
8376 ? gogo->unique_prefix()
8377 : no->package()->unique_prefix());
8378 const std::string& package_name(no->package() == NULL
8379 ? gogo->package_name()
8380 : no->package()->name());
8381 name = unique_prefix;
8382 name.append(1, '.');
8383 name.append(package_name);
8384 name.append(1, '.');
8385 if (this->in_function_ != NULL)
8387 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
8388 name.append(1, '$');
8391 name.append(Gogo::unpack_hidden_name(no->name()));
8393 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
8398 // Export the type. This is called to export a global type.
8401 Named_type::export_named_type(Export* exp, const std::string&) const
8403 // We don't need to write the name of the type here, because it will
8404 // be written by Export::write_type anyhow.
8405 exp->write_c_string("type ");
8406 exp->write_type(this);
8407 exp->write_c_string(";\n");
8410 // Import a named type.
8413 Named_type::import_named_type(Import* imp, Named_type** ptype)
8415 imp->require_c_string("type ");
8416 Type *type = imp->read_type();
8417 *ptype = type->named_type();
8418 go_assert(*ptype != NULL);
8419 imp->require_c_string(";\n");
8422 // Export the type when it is referenced by another type. In this
8423 // case Export::export_type will already have issued the name.
8426 Named_type::do_export(Export* exp) const
8428 exp->write_type(this->type_);
8430 // To save space, we only export the methods directly attached to
8432 Bindings* methods = this->local_methods_;
8433 if (methods == NULL)
8436 exp->write_c_string("\n");
8437 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
8438 p != methods->end_definitions();
8441 exp->write_c_string(" ");
8442 (*p)->export_named_object(exp);
8445 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
8446 p != methods->end_declarations();
8449 if (p->second->is_function_declaration())
8451 exp->write_c_string(" ");
8452 p->second->export_named_object(exp);
8457 // Make a named type.
8460 Type::make_named_type(Named_object* named_object, Type* type,
8463 return new Named_type(named_object, type, location);
8466 // Finalize the methods for TYPE. It will be a named type or a struct
8467 // type. This sets *ALL_METHODS to the list of methods, and builds
8468 // all required stubs.
8471 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
8472 Methods** all_methods)
8474 *all_methods = NULL;
8475 Types_seen types_seen;
8476 Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen,
8478 Type::build_stub_methods(gogo, type, *all_methods, location);
8481 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
8482 // build up the struct field indexes as we go. DEPTH is the depth of
8483 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
8484 // adding these methods for an anonymous field with pointer type.
8485 // NEEDS_STUB_METHOD is true if we need to use a stub method which
8486 // calls the real method. TYPES_SEEN is used to avoid infinite
8490 Type::add_methods_for_type(const Type* type,
8491 const Method::Field_indexes* field_indexes,
8493 bool is_embedded_pointer,
8494 bool needs_stub_method,
8495 Types_seen* types_seen,
8498 // Pointer types may not have methods.
8499 if (type->points_to() != NULL)
8502 const Named_type* nt = type->named_type();
8505 std::pair<Types_seen::iterator, bool> ins = types_seen->insert(nt);
8511 Type::add_local_methods_for_type(nt, field_indexes, depth,
8512 is_embedded_pointer, needs_stub_method,
8515 Type::add_embedded_methods_for_type(type, field_indexes, depth,
8516 is_embedded_pointer, needs_stub_method,
8517 types_seen, methods);
8519 // If we are called with depth > 0, then we are looking at an
8520 // anonymous field of a struct. If such a field has interface type,
8521 // then we need to add the interface methods. We don't want to add
8522 // them when depth == 0, because we will already handle them
8523 // following the usual rules for an interface type.
8525 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
8528 // Add the local methods for the named type NT to *METHODS. The
8529 // parameters are as for add_methods_to_type.
8532 Type::add_local_methods_for_type(const Named_type* nt,
8533 const Method::Field_indexes* field_indexes,
8535 bool is_embedded_pointer,
8536 bool needs_stub_method,
8539 const Bindings* local_methods = nt->local_methods();
8540 if (local_methods == NULL)
8543 if (*methods == NULL)
8544 *methods = new Methods();
8546 for (Bindings::const_declarations_iterator p =
8547 local_methods->begin_declarations();
8548 p != local_methods->end_declarations();
8551 Named_object* no = p->second;
8552 bool is_value_method = (is_embedded_pointer
8553 || !Type::method_expects_pointer(no));
8554 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
8556 || (depth > 0 && is_value_method)));
8557 if (!(*methods)->insert(no->name(), m))
8562 // Add the embedded methods for TYPE to *METHODS. These are the
8563 // methods attached to anonymous fields. The parameters are as for
8564 // add_methods_to_type.
8567 Type::add_embedded_methods_for_type(const Type* type,
8568 const Method::Field_indexes* field_indexes,
8570 bool is_embedded_pointer,
8571 bool needs_stub_method,
8572 Types_seen* types_seen,
8575 // Look for anonymous fields in TYPE. TYPE has fields if it is a
8577 const Struct_type* st = type->struct_type();
8581 const Struct_field_list* fields = st->fields();
8586 for (Struct_field_list::const_iterator pf = fields->begin();
8587 pf != fields->end();
8590 if (!pf->is_anonymous())
8593 Type* ftype = pf->type();
8594 bool is_pointer = false;
8595 if (ftype->points_to() != NULL)
8597 ftype = ftype->points_to();
8600 Named_type* fnt = ftype->named_type();
8603 // This is an error, but it will be diagnosed elsewhere.
8607 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
8608 sub_field_indexes->next = field_indexes;
8609 sub_field_indexes->field_index = i;
8611 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
8612 (is_embedded_pointer || is_pointer),
8621 // If TYPE is an interface type, then add its method to *METHODS.
8622 // This is for interface methods attached to an anonymous field. The
8623 // parameters are as for add_methods_for_type.
8626 Type::add_interface_methods_for_type(const Type* type,
8627 const Method::Field_indexes* field_indexes,
8631 const Interface_type* it = type->interface_type();
8635 const Typed_identifier_list* imethods = it->methods();
8636 if (imethods == NULL)
8639 if (*methods == NULL)
8640 *methods = new Methods();
8642 for (Typed_identifier_list::const_iterator pm = imethods->begin();
8643 pm != imethods->end();
8646 Function_type* fntype = pm->type()->function_type();
8649 // This is an error, but it should be reported elsewhere
8650 // when we look at the methods for IT.
8653 go_assert(!fntype->is_method());
8654 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
8655 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
8656 field_indexes, depth);
8657 if (!(*methods)->insert(pm->name(), m))
8662 // Build stub methods for TYPE as needed. METHODS is the set of
8663 // methods for the type. A stub method may be needed when a type
8664 // inherits a method from an anonymous field. When we need the
8665 // address of the method, as in a type descriptor, we need to build a
8666 // little stub which does the required field dereferences and jumps to
8667 // the real method. LOCATION is the location of the type definition.
8670 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
8673 if (methods == NULL)
8675 for (Methods::const_iterator p = methods->begin();
8676 p != methods->end();
8679 Method* m = p->second;
8680 if (m->is_ambiguous() || !m->needs_stub_method())
8683 const std::string& name(p->first);
8685 // Build a stub method.
8687 const Function_type* fntype = m->type();
8689 static unsigned int counter;
8691 snprintf(buf, sizeof buf, "$this%u", counter);
8694 Type* receiver_type = const_cast<Type*>(type);
8695 if (!m->is_value_method())
8696 receiver_type = Type::make_pointer_type(receiver_type);
8697 Location receiver_location = m->receiver_location();
8698 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
8701 const Typed_identifier_list* fnparams = fntype->parameters();
8702 Typed_identifier_list* stub_params;
8703 if (fnparams == NULL || fnparams->empty())
8707 // We give each stub parameter a unique name.
8708 stub_params = new Typed_identifier_list();
8709 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
8710 pp != fnparams->end();
8714 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
8715 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
8721 const Typed_identifier_list* fnresults = fntype->results();
8722 Typed_identifier_list* stub_results;
8723 if (fnresults == NULL || fnresults->empty())
8724 stub_results = NULL;
8727 // We create the result parameters without any names, since
8728 // we won't refer to them.
8729 stub_results = new Typed_identifier_list();
8730 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
8731 pr != fnresults->end();
8733 stub_results->push_back(Typed_identifier("", pr->type(),
8737 Function_type* stub_type = Type::make_function_type(receiver,
8740 fntype->location());
8741 if (fntype->is_varargs())
8742 stub_type->set_is_varargs();
8744 // We only create the function in the package which creates the
8746 const Package* package;
8747 if (type->named_type() == NULL)
8750 package = type->named_type()->named_object()->package();
8752 if (package != NULL)
8753 stub = Named_object::make_function_declaration(name, package,
8754 stub_type, location);
8757 stub = gogo->start_function(name, stub_type, false,
8758 fntype->location());
8759 Type::build_one_stub_method(gogo, m, buf, stub_params,
8760 fntype->is_varargs(), location);
8761 gogo->finish_function(fntype->location());
8764 m->set_stub_object(stub);
8768 // Build a stub method which adjusts the receiver as required to call
8769 // METHOD. RECEIVER_NAME is the name we used for the receiver.
8770 // PARAMS is the list of function parameters.
8773 Type::build_one_stub_method(Gogo* gogo, Method* method,
8774 const char* receiver_name,
8775 const Typed_identifier_list* params,
8779 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
8780 go_assert(receiver_object != NULL);
8782 Expression* expr = Expression::make_var_reference(receiver_object, location);
8783 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
8784 if (expr->type()->points_to() == NULL)
8785 expr = Expression::make_unary(OPERATOR_AND, expr, location);
8787 Expression_list* arguments;
8788 if (params == NULL || params->empty())
8792 arguments = new Expression_list();
8793 for (Typed_identifier_list::const_iterator p = params->begin();
8797 Named_object* param = gogo->lookup(p->name(), NULL);
8798 go_assert(param != NULL);
8799 Expression* param_ref = Expression::make_var_reference(param,
8801 arguments->push_back(param_ref);
8805 Expression* func = method->bind_method(expr, location);
8806 go_assert(func != NULL);
8807 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
8809 call->set_hidden_fields_are_ok();
8810 size_t count = call->result_count();
8812 gogo->add_statement(Statement::make_statement(call, true));
8815 Expression_list* retvals = new Expression_list();
8817 retvals->push_back(call);
8820 for (size_t i = 0; i < count; ++i)
8821 retvals->push_back(Expression::make_call_result(call, i));
8823 Return_statement* retstat = Statement::make_return_statement(retvals,
8826 // We can return values with hidden fields from a stub. This is
8827 // necessary if the method is itself hidden.
8828 retstat->set_hidden_fields_are_ok();
8830 gogo->add_statement(retstat);
8834 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
8835 // in reverse order.
8838 Type::apply_field_indexes(Expression* expr,
8839 const Method::Field_indexes* field_indexes,
8842 if (field_indexes == NULL)
8844 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
8845 Struct_type* stype = expr->type()->deref()->struct_type();
8846 go_assert(stype != NULL
8847 && field_indexes->field_index < stype->field_count());
8848 if (expr->type()->struct_type() == NULL)
8850 go_assert(expr->type()->points_to() != NULL);
8851 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
8852 go_assert(expr->type()->struct_type() == stype);
8854 return Expression::make_field_reference(expr, field_indexes->field_index,
8858 // Return whether NO is a method for which the receiver is a pointer.
8861 Type::method_expects_pointer(const Named_object* no)
8863 const Function_type *fntype;
8864 if (no->is_function())
8865 fntype = no->func_value()->type();
8866 else if (no->is_function_declaration())
8867 fntype = no->func_declaration_value()->type();
8870 return fntype->receiver()->type()->points_to() != NULL;
8873 // Given a set of methods for a type, METHODS, return the method NAME,
8874 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
8875 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
8876 // but is ambiguous (and return NULL).
8879 Type::method_function(const Methods* methods, const std::string& name,
8882 if (is_ambiguous != NULL)
8883 *is_ambiguous = false;
8884 if (methods == NULL)
8886 Methods::const_iterator p = methods->find(name);
8887 if (p == methods->end())
8889 Method* m = p->second;
8890 if (m->is_ambiguous())
8892 if (is_ambiguous != NULL)
8893 *is_ambiguous = true;
8899 // Look for field or method NAME for TYPE. Return an Expression for
8900 // the field or method bound to EXPR. If there is no such field or
8901 // method, give an appropriate error and return an error expression.
8904 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
8905 const std::string& name,
8908 if (type->deref()->is_error_type())
8909 return Expression::make_error(location);
8911 const Named_type* nt = type->deref()->named_type();
8912 const Struct_type* st = type->deref()->struct_type();
8913 const Interface_type* it = type->interface_type();
8915 // If this is a pointer to a pointer, then it is possible that the
8916 // pointed-to type has methods.
8917 bool dereferenced = false;
8921 && type->points_to() != NULL
8922 && type->points_to()->points_to() != NULL)
8924 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
8925 type = type->points_to();
8926 if (type->deref()->is_error_type())
8927 return Expression::make_error(location);
8928 nt = type->points_to()->named_type();
8929 st = type->points_to()->struct_type();
8930 dereferenced = true;
8933 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
8934 || expr->is_addressable());
8935 std::vector<const Named_type*> seen;
8936 bool is_method = false;
8937 bool found_pointer_method = false;
8940 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
8941 &seen, NULL, &is_method,
8942 &found_pointer_method, &ambig1, &ambig2))
8947 go_assert(st != NULL);
8948 if (type->struct_type() == NULL)
8950 go_assert(type->points_to() != NULL);
8951 expr = Expression::make_unary(OPERATOR_MULT, expr,
8953 go_assert(expr->type()->struct_type() == st);
8955 ret = st->field_reference(expr, name, location);
8957 else if (it != NULL && it->find_method(name) != NULL)
8958 ret = Expression::make_interface_field_reference(expr, name,
8964 m = nt->method_function(name, NULL);
8965 else if (st != NULL)
8966 m = st->method_function(name, NULL);
8969 go_assert(m != NULL);
8970 if (dereferenced && m->is_value_method())
8973 "calling value method requires explicit dereference");
8974 return Expression::make_error(location);
8976 if (!m->is_value_method() && expr->type()->points_to() == NULL)
8977 expr = Expression::make_unary(OPERATOR_AND, expr, location);
8978 ret = m->bind_method(expr, location);
8980 go_assert(ret != NULL);
8985 if (!ambig1.empty())
8986 error_at(location, "%qs is ambiguous via %qs and %qs",
8987 Gogo::message_name(name).c_str(), ambig1.c_str(),
8989 else if (found_pointer_method)
8990 error_at(location, "method requires a pointer");
8991 else if (nt == NULL && st == NULL && it == NULL)
8993 ("reference to field %qs in object which "
8994 "has no fields or methods"),
8995 Gogo::message_name(name).c_str());
8999 if (!Gogo::is_hidden_name(name))
9000 is_unexported = false;
9003 std::string unpacked = Gogo::unpack_hidden_name(name);
9005 is_unexported = Type::is_unexported_field_or_method(gogo, type,
9010 error_at(location, "reference to unexported field or method %qs",
9011 Gogo::message_name(name).c_str());
9013 error_at(location, "reference to undefined field or method %qs",
9014 Gogo::message_name(name).c_str());
9016 return Expression::make_error(location);
9020 // Look in TYPE for a field or method named NAME, return true if one
9021 // is found. This looks through embedded anonymous fields and handles
9022 // ambiguity. If a method is found, sets *IS_METHOD to true;
9023 // otherwise, if a field is found, set it to false. If
9024 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
9025 // whose address can not be taken. SEEN is used to avoid infinite
9026 // recursion on invalid types.
9028 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
9029 // method we couldn't use because it requires a pointer. LEVEL is
9030 // used for recursive calls, and can be NULL for a non-recursive call.
9031 // When this function returns false because it finds that the name is
9032 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
9033 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
9034 // will be unchanged.
9036 // This function just returns whether or not there is a field or
9037 // method, and whether it is a field or method. It doesn't build an
9038 // expression to refer to it. If it is a method, we then look in the
9039 // list of all methods for the type. If it is a field, the search has
9040 // to be done again, looking only for fields, and building up the
9041 // expression as we go.
9044 Type::find_field_or_method(const Type* type,
9045 const std::string& name,
9046 bool receiver_can_be_pointer,
9047 std::vector<const Named_type*>* seen,
9050 bool* found_pointer_method,
9051 std::string* ambig1,
9052 std::string* ambig2)
9054 // Named types can have locally defined methods.
9055 const Named_type* nt = type->named_type();
9056 if (nt == NULL && type->points_to() != NULL)
9057 nt = type->points_to()->named_type();
9060 Named_object* no = nt->find_local_method(name);
9063 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
9069 // Record that we have found a pointer method in order to
9070 // give a better error message if we don't find anything
9072 *found_pointer_method = true;
9075 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9081 // We've already seen this type when searching for methods.
9087 // Interface types can have methods.
9088 const Interface_type* it = type->interface_type();
9089 if (it != NULL && it->find_method(name) != NULL)
9095 // Struct types can have fields. They can also inherit fields and
9096 // methods from anonymous fields.
9097 const Struct_type* st = type->deref()->struct_type();
9100 const Struct_field_list* fields = st->fields();
9105 seen->push_back(nt);
9107 int found_level = 0;
9108 bool found_is_method = false;
9109 std::string found_ambig1;
9110 std::string found_ambig2;
9111 const Struct_field* found_parent = NULL;
9112 for (Struct_field_list::const_iterator pf = fields->begin();
9113 pf != fields->end();
9116 if (pf->is_field_name(name))
9124 if (!pf->is_anonymous())
9127 if (pf->type()->deref()->is_error_type()
9128 || pf->type()->deref()->is_undefined())
9131 Named_type* fnt = pf->type()->named_type();
9133 fnt = pf->type()->deref()->named_type();
9134 go_assert(fnt != NULL);
9136 int sublevel = level == NULL ? 1 : *level + 1;
9138 std::string subambig1;
9139 std::string subambig2;
9140 bool subfound = Type::find_field_or_method(fnt,
9142 receiver_can_be_pointer,
9146 found_pointer_method,
9151 if (!subambig1.empty())
9153 // The name was found via this field, but is ambiguous.
9154 // if the ambiguity is lower or at the same level as
9155 // anything else we have already found, then we want to
9156 // pass the ambiguity back to the caller.
9157 if (found_level == 0 || sublevel <= found_level)
9159 found_ambig1 = (Gogo::message_name(pf->field_name())
9161 found_ambig2 = (Gogo::message_name(pf->field_name())
9163 found_level = sublevel;
9169 // The name was found via this field. Use the level to see
9170 // if we want to use this one, or whether it introduces an
9172 if (found_level == 0 || sublevel < found_level)
9174 found_level = sublevel;
9175 found_is_method = sub_is_method;
9176 found_ambig1.clear();
9177 found_ambig2.clear();
9178 found_parent = &*pf;
9180 else if (sublevel > found_level)
9182 else if (found_ambig1.empty())
9184 // We found an ambiguity.
9185 go_assert(found_parent != NULL);
9186 found_ambig1 = Gogo::message_name(found_parent->field_name());
9187 found_ambig2 = Gogo::message_name(pf->field_name());
9191 // We found an ambiguity, but we already know of one.
9192 // Just report the earlier one.
9197 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
9198 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
9199 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
9200 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
9205 if (found_level == 0)
9207 else if (!found_ambig1.empty())
9209 go_assert(!found_ambig1.empty());
9210 ambig1->assign(found_ambig1);
9211 ambig2->assign(found_ambig2);
9213 *level = found_level;
9219 *level = found_level;
9220 *is_method = found_is_method;
9225 // Return whether NAME is an unexported field or method for TYPE.
9228 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
9229 const std::string& name,
9230 std::vector<const Named_type*>* seen)
9232 const Named_type* nt = type->named_type();
9234 nt = type->deref()->named_type();
9237 if (nt->is_unexported_local_method(gogo, name))
9240 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9246 // We've already seen this type.
9252 const Interface_type* it = type->interface_type();
9253 if (it != NULL && it->is_unexported_method(gogo, name))
9256 type = type->deref();
9258 const Struct_type* st = type->struct_type();
9259 if (st != NULL && st->is_unexported_local_field(gogo, name))
9265 const Struct_field_list* fields = st->fields();
9270 seen->push_back(nt);
9272 for (Struct_field_list::const_iterator pf = fields->begin();
9273 pf != fields->end();
9276 if (pf->is_anonymous()
9277 && !pf->type()->deref()->is_error_type()
9278 && !pf->type()->deref()->is_undefined())
9280 Named_type* subtype = pf->type()->named_type();
9281 if (subtype == NULL)
9282 subtype = pf->type()->deref()->named_type();
9283 if (subtype == NULL)
9285 // This is an error, but it will be diagnosed elsewhere.
9288 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
9303 // Class Forward_declaration.
9305 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
9306 : Type(TYPE_FORWARD),
9307 named_object_(named_object->resolve()), warned_(false)
9309 go_assert(this->named_object_->is_unknown()
9310 || this->named_object_->is_type_declaration());
9313 // Return the named object.
9316 Forward_declaration_type::named_object()
9318 return this->named_object_->resolve();
9322 Forward_declaration_type::named_object() const
9324 return this->named_object_->resolve();
9327 // Return the name of the forward declared type.
9330 Forward_declaration_type::name() const
9332 return this->named_object()->name();
9335 // Warn about a use of a type which has been declared but not defined.
9338 Forward_declaration_type::warn() const
9340 Named_object* no = this->named_object_->resolve();
9341 if (no->is_unknown())
9343 // The name was not defined anywhere.
9346 error_at(this->named_object_->location(),
9347 "use of undefined type %qs",
9348 no->message_name().c_str());
9349 this->warned_ = true;
9352 else if (no->is_type_declaration())
9354 // The name was seen as a type, but the type was never defined.
9355 if (no->type_declaration_value()->using_type())
9357 error_at(this->named_object_->location(),
9358 "use of undefined type %qs",
9359 no->message_name().c_str());
9360 this->warned_ = true;
9365 // The name was defined, but not as a type.
9368 error_at(this->named_object_->location(), "expected type");
9369 this->warned_ = true;
9374 // Get the base type of a declaration. This gives an error if the
9375 // type has not yet been defined.
9378 Forward_declaration_type::real_type()
9380 if (this->is_defined())
9381 return this->named_object()->type_value();
9385 return Type::make_error_type();
9390 Forward_declaration_type::real_type() const
9392 if (this->is_defined())
9393 return this->named_object()->type_value();
9397 return Type::make_error_type();
9401 // Return whether the base type is defined.
9404 Forward_declaration_type::is_defined() const
9406 return this->named_object()->is_type();
9409 // Add a method. This is used when methods are defined before the
9413 Forward_declaration_type::add_method(const std::string& name,
9416 Named_object* no = this->named_object();
9417 if (no->is_unknown())
9418 no->declare_as_type();
9419 return no->type_declaration_value()->add_method(name, function);
9422 // Add a method declaration. This is used when methods are declared
9426 Forward_declaration_type::add_method_declaration(const std::string& name,
9428 Function_type* type,
9431 Named_object* no = this->named_object();
9432 if (no->is_unknown())
9433 no->declare_as_type();
9434 Type_declaration* td = no->type_declaration_value();
9435 return td->add_method_declaration(name, package, type, location);
9441 Forward_declaration_type::do_traverse(Traverse* traverse)
9443 if (this->is_defined()
9444 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
9445 return TRAVERSE_EXIT;
9446 return TRAVERSE_CONTINUE;
9449 // Get the backend representation for the type.
9452 Forward_declaration_type::do_get_backend(Gogo* gogo)
9454 if (this->is_defined())
9455 return Type::get_named_base_btype(gogo, this->real_type());
9458 return gogo->backend()->error_type();
9460 // We represent an undefined type as a struct with no fields. That
9461 // should work fine for the backend, since the same case can arise
9463 std::vector<Backend::Btyped_identifier> fields;
9464 Btype* bt = gogo->backend()->struct_type(fields);
9465 return gogo->backend()->named_type(this->name(), bt,
9466 this->named_object()->location());
9469 // Build a type descriptor for a forwarded type.
9472 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9474 Location ploc = Linemap::predeclared_location();
9475 if (!this->is_defined())
9476 return Expression::make_error(ploc);
9479 Type* t = this->real_type();
9481 return this->named_type_descriptor(gogo, t, name);
9483 return Expression::make_type_descriptor(t, ploc);
9487 // The reflection string.
9490 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
9492 this->append_reflection(this->real_type(), gogo, ret);
9495 // The mangled name.
9498 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
9500 if (this->is_defined())
9501 this->append_mangled_name(this->real_type(), gogo, ret);
9504 const Named_object* no = this->named_object();
9506 if (no->package() == NULL)
9507 name = gogo->package_name();
9509 name = no->package()->name();
9511 name += Gogo::unpack_hidden_name(no->name());
9513 snprintf(buf, sizeof buf, "N%u_",
9514 static_cast<unsigned int>(name.length()));
9520 // Export a forward declaration. This can happen when a defined type
9521 // refers to a type which is only declared (and is presumably defined
9522 // in some other file in the same package).
9525 Forward_declaration_type::do_export(Export*) const
9527 // If there is a base type, that should be exported instead of this.
9528 go_assert(!this->is_defined());
9530 // We don't output anything.
9533 // Make a forward declaration.
9536 Type::make_forward_declaration(Named_object* named_object)
9538 return new Forward_declaration_type(named_object);
9541 // Class Typed_identifier_list.
9543 // Sort the entries by name.
9545 struct Typed_identifier_list_sort
9549 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
9550 { return t1.name() < t2.name(); }
9554 Typed_identifier_list::sort_by_name()
9556 std::sort(this->entries_.begin(), this->entries_.end(),
9557 Typed_identifier_list_sort());
9563 Typed_identifier_list::traverse(Traverse* traverse)
9565 for (Typed_identifier_list::const_iterator p = this->begin();
9569 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
9570 return TRAVERSE_EXIT;
9572 return TRAVERSE_CONTINUE;
9577 Typed_identifier_list*
9578 Typed_identifier_list::copy() const
9580 Typed_identifier_list* ret = new Typed_identifier_list();
9581 for (Typed_identifier_list::const_iterator p = this->begin();
9584 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));