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.
625 if (rhs != NULL && !rhs->is_undefined())
627 if (rhs->is_void_type())
630 *reason = "non-value used as value";
633 if (rhs->is_call_multiple_result_type())
636 reason->assign(_("multiple value function call in "
637 "single value context"));
642 if (lhs != NULL && !lhs->is_undefined())
644 // Any value may be assigned to the blank identifier.
645 if (lhs->is_sink_type())
648 // All fields of a struct must be exported, or the assignment
649 // must be in the same package.
650 if (check_hidden_fields && rhs != NULL && !rhs->is_undefined())
652 if (lhs->has_hidden_fields(NULL, reason)
653 || rhs->has_hidden_fields(NULL, reason))
658 // Identical types are assignable.
659 if (Type::are_identical(lhs, rhs, true, reason))
662 // The types are assignable if they have identical underlying types
663 // and either LHS or RHS is not a named type.
664 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
665 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
666 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
669 // The types are assignable if LHS is an interface type and RHS
670 // implements the required methods.
671 const Interface_type* lhs_interface_type = lhs->interface_type();
672 if (lhs_interface_type != NULL)
674 if (lhs_interface_type->implements_interface(rhs, reason))
676 const Interface_type* rhs_interface_type = rhs->interface_type();
677 if (rhs_interface_type != NULL
678 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
683 // The type are assignable if RHS is a bidirectional channel type,
684 // LHS is a channel type, they have identical element types, and
685 // either LHS or RHS is not a named type.
686 if (lhs->channel_type() != NULL
687 && rhs->channel_type() != NULL
688 && rhs->channel_type()->may_send()
689 && rhs->channel_type()->may_receive()
690 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
691 && Type::are_identical(lhs->channel_type()->element_type(),
692 rhs->channel_type()->element_type(),
697 // The nil type may be assigned to a pointer, function, slice, map,
698 // channel, or interface type.
699 if (rhs->is_nil_type()
700 && (lhs->points_to() != NULL
701 || lhs->function_type() != NULL
702 || lhs->is_slice_type()
703 || lhs->map_type() != NULL
704 || lhs->channel_type() != NULL
705 || lhs->interface_type() != NULL))
708 // An untyped numeric constant may be assigned to a numeric type if
709 // it is representable in that type.
710 if ((rhs->is_abstract()
711 && (rhs->integer_type() != NULL
712 || rhs->float_type() != NULL
713 || rhs->complex_type() != NULL))
714 && (lhs->integer_type() != NULL
715 || lhs->float_type() != NULL
716 || lhs->complex_type() != NULL))
719 // Give some better error messages.
720 if (reason != NULL && reason->empty())
722 if (rhs->interface_type() != NULL)
723 reason->assign(_("need explicit conversion"));
724 else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
726 size_t len = (lhs->named_type()->name().length()
727 + rhs->named_type()->name().length()
729 char* buf = new char[len];
730 snprintf(buf, len, _("cannot use type %s as type %s"),
731 rhs->named_type()->message_name().c_str(),
732 lhs->named_type()->message_name().c_str());
741 // Return true if a value with type RHS may be assigned to a variable
742 // with type LHS. If REASON is not NULL, set *REASON to the reason
743 // the types are not assignable.
746 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
748 return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
751 // Like are_assignable but don't check for hidden fields.
754 Type::are_assignable_hidden_ok(const Type* lhs, const Type* rhs,
757 return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
760 // Return true if a value with type RHS may be converted to type LHS.
761 // If REASON is not NULL, set *REASON to the reason the types are not
765 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
767 // The types are convertible if they are assignable.
768 if (Type::are_assignable(lhs, rhs, reason))
771 // The types are convertible if they have identical underlying
773 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
774 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
777 // The types are convertible if they are both unnamed pointer types
778 // and their pointer base types have identical underlying types.
779 if (lhs->named_type() == NULL
780 && rhs->named_type() == NULL
781 && lhs->points_to() != NULL
782 && rhs->points_to() != NULL
783 && (lhs->points_to()->named_type() != NULL
784 || rhs->points_to()->named_type() != NULL)
785 && Type::are_identical(lhs->points_to()->base(),
786 rhs->points_to()->base(),
791 // Integer and floating point types are convertible to each other.
792 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
793 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
796 // Complex types are convertible to each other.
797 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
800 // An integer, or []byte, or []rune, may be converted to a string.
801 if (lhs->is_string_type())
803 if (rhs->integer_type() != NULL)
805 if (rhs->is_slice_type())
807 const Type* e = rhs->array_type()->element_type()->forwarded();
808 if (e->integer_type() != NULL
809 && (e->integer_type()->is_byte()
810 || e->integer_type()->is_rune()))
815 // A string may be converted to []byte or []rune.
816 if (rhs->is_string_type() && lhs->is_slice_type())
818 const Type* e = lhs->array_type()->element_type()->forwarded();
819 if (e->integer_type() != NULL
820 && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
824 // An unsafe.Pointer type may be converted to any pointer type or to
825 // uintptr, and vice-versa.
826 if (lhs->is_unsafe_pointer_type()
827 && (rhs->points_to() != NULL
828 || (rhs->integer_type() != NULL
829 && rhs->forwarded() == Type::lookup_integer_type("uintptr"))))
831 if (rhs->is_unsafe_pointer_type()
832 && (lhs->points_to() != NULL
833 || (lhs->integer_type() != NULL
834 && lhs->forwarded() == Type::lookup_integer_type("uintptr"))))
837 // Give a better error message.
841 *reason = "invalid type conversion";
844 std::string s = "invalid type conversion (";
854 // Return whether this type has any hidden fields. This is only a
855 // possibility for a few types.
858 Type::has_hidden_fields(const Named_type* within, std::string* reason) const
860 switch (this->forwarded()->classification_)
863 return this->named_type()->named_type_has_hidden_fields(reason);
865 return this->struct_type()->struct_has_hidden_fields(within, reason);
867 return this->array_type()->array_has_hidden_fields(within, reason);
873 // Return a hash code for the type to be used for method lookup.
876 Type::hash_for_method(Gogo* gogo) const
878 unsigned int ret = 0;
879 if (this->classification_ != TYPE_FORWARD)
880 ret += this->classification_;
881 return ret + this->do_hash_for_method(gogo);
884 // Default implementation of do_hash_for_method. This is appropriate
885 // for types with no subfields.
888 Type::do_hash_for_method(Gogo*) const
893 // Return a hash code for a string, given a starting hash.
896 Type::hash_string(const std::string& s, unsigned int h)
898 const char* p = s.data();
899 size_t len = s.length();
900 for (; len > 0; --len)
908 // A hash table mapping unnamed types to the backend representation of
911 Type::Type_btypes Type::type_btypes;
913 // Return a tree representing this type.
916 Type::get_backend(Gogo* gogo)
918 if (this->btype_ != NULL)
920 if (this->btype_is_placeholder_ && gogo->named_types_are_converted())
921 this->finish_backend(gogo);
925 if (this->forward_declaration_type() != NULL
926 || this->named_type() != NULL)
927 return this->get_btype_without_hash(gogo);
929 if (this->is_error_type())
930 return gogo->backend()->error_type();
932 // To avoid confusing the backend, translate all identical Go types
933 // to the same backend representation. We use a hash table to do
934 // that. There is no need to use the hash table for named types, as
935 // named types are only identical to themselves.
937 std::pair<Type*, Btype*> val(this, NULL);
938 std::pair<Type_btypes::iterator, bool> ins =
939 Type::type_btypes.insert(val);
940 if (!ins.second && ins.first->second != NULL)
942 if (gogo != NULL && gogo->named_types_are_converted())
943 this->btype_ = ins.first->second;
944 return ins.first->second;
947 Btype* bt = this->get_btype_without_hash(gogo);
949 if (ins.first->second == NULL)
950 ins.first->second = bt;
953 // We have already created a backend representation for this
954 // type. This can happen when an unnamed type is defined using
955 // a named type which in turns uses an identical unnamed type.
956 // Use the tree we created earlier and ignore the one we just
958 bt = ins.first->second;
959 if (gogo == NULL || !gogo->named_types_are_converted())
967 // Return the backend representation for a type without looking in the
968 // hash table for identical types. This is used for named types,
969 // since a named type is never identical to any other type.
972 Type::get_btype_without_hash(Gogo* gogo)
974 if (this->btype_ == NULL)
976 Btype* bt = this->do_get_backend(gogo);
978 // For a recursive function or pointer type, we will temporarily
979 // return a circular pointer type during the recursion. We
980 // don't want to record that for a forwarding type, as it may
982 if (this->forward_declaration_type() != NULL
983 && gogo->backend()->is_circular_pointer_type(bt))
986 if (gogo == NULL || !gogo->named_types_are_converted())
994 // Get the backend representation of a type without forcing the
995 // creation of the backend representation of all supporting types.
996 // This will return a backend type that has the correct size but may
997 // be incomplete. E.g., a pointer will just be a placeholder pointer,
998 // and will not contain the final representation of the type to which
999 // it points. This is used while converting all named types to the
1000 // backend representation, to avoid problems with indirect references
1001 // to types which are not yet complete. When this is called, the
1002 // sizes of all direct references (e.g., a struct field) should be
1003 // known, but the sizes of indirect references (e.g., the type to
1004 // which a pointer points) may not.
1007 Type::get_backend_placeholder(Gogo* gogo)
1009 if (gogo->named_types_are_converted())
1010 return this->get_backend(gogo);
1011 if (this->btype_ != NULL)
1012 return this->btype_;
1015 switch (this->classification_)
1025 // These are simple types that can just be created directly.
1026 return this->get_backend(gogo);
1030 Location loc = this->function_type()->location();
1031 bt = gogo->backend()->placeholder_pointer_type("", loc, true);
1037 Location loc = Linemap::unknown_location();
1038 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1043 // We don't have to make the struct itself be a placeholder. We
1044 // are promised that we know the sizes of the struct fields.
1045 // But we may have to use a placeholder for any particular
1048 std::vector<Backend::Btyped_identifier> bfields;
1049 get_backend_struct_fields(gogo, this->struct_type()->fields(),
1051 bt = gogo->backend()->struct_type(bfields);
1056 if (this->is_slice_type())
1058 std::vector<Backend::Btyped_identifier> bfields;
1059 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1060 bt = gogo->backend()->struct_type(bfields);
1064 Btype* element = this->array_type()->get_backend_element(gogo, true);
1065 Bexpression* len = this->array_type()->get_backend_length(gogo);
1066 bt = gogo->backend()->array_type(element, len);
1072 // All maps and channels have the same backend representation.
1073 return this->get_backend(gogo);
1075 case TYPE_INTERFACE:
1076 if (this->interface_type()->is_empty())
1077 return Interface_type::get_backend_empty_interface_type(gogo);
1080 std::vector<Backend::Btyped_identifier> bfields;
1081 get_backend_interface_fields(gogo, this->interface_type(), true,
1083 bt = gogo->backend()->struct_type(bfields);
1089 // Named types keep track of their own dependencies and manage
1090 // their own placeholders.
1091 return this->get_backend(gogo);
1094 case TYPE_CALL_MULTIPLE_RESULT:
1100 this->btype_is_placeholder_ = true;
1104 // Complete the backend representation. This is called for a type
1105 // using a placeholder type.
1108 Type::finish_backend(Gogo* gogo)
1110 go_assert(this->btype_ != NULL);
1111 if (!this->btype_is_placeholder_)
1114 switch (this->classification_)
1128 Btype* bt = this->do_get_backend(gogo);
1129 if (!gogo->backend()->set_placeholder_function_type(this->btype_, bt))
1130 go_assert(saw_errors());
1136 Btype* bt = this->do_get_backend(gogo);
1137 if (!gogo->backend()->set_placeholder_pointer_type(this->btype_, bt))
1138 go_assert(saw_errors());
1143 // The struct type itself is done, but we have to make sure that
1144 // all the field types are converted.
1145 this->struct_type()->finish_backend_fields(gogo);
1149 // The array type itself is done, but make sure the element type
1151 this->array_type()->finish_backend_element(gogo);
1158 case TYPE_INTERFACE:
1159 // The interface type itself is done, but make sure the method
1160 // types are converted.
1161 this->interface_type()->finish_backend_methods(gogo);
1169 case TYPE_CALL_MULTIPLE_RESULT:
1174 this->btype_is_placeholder_ = false;
1177 // Return a pointer to the type descriptor for this type.
1180 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1182 Type* t = this->forwarded();
1183 if (t->named_type() != NULL && t->named_type()->is_alias())
1184 t = t->named_type()->real_type();
1185 if (t->type_descriptor_var_ == NULL)
1187 t->make_type_descriptor_var(gogo);
1188 go_assert(t->type_descriptor_var_ != NULL);
1190 tree var_tree = var_to_tree(t->type_descriptor_var_);
1191 if (var_tree == error_mark_node)
1192 return error_mark_node;
1193 return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
1196 // A mapping from unnamed types to type descriptor variables.
1198 Type::Type_descriptor_vars Type::type_descriptor_vars;
1200 // Build the type descriptor for this type.
1203 Type::make_type_descriptor_var(Gogo* gogo)
1205 go_assert(this->type_descriptor_var_ == NULL);
1207 Named_type* nt = this->named_type();
1209 // We can have multiple instances of unnamed types, but we only want
1210 // to emit the type descriptor once. We use a hash table. This is
1211 // not necessary for named types, as they are unique, and we store
1212 // the type descriptor in the type itself.
1213 Bvariable** phash = NULL;
1216 Bvariable* bvnull = NULL;
1217 std::pair<Type_descriptor_vars::iterator, bool> ins =
1218 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1221 // We've already build a type descriptor for this type.
1222 this->type_descriptor_var_ = ins.first->second;
1225 phash = &ins.first->second;
1228 std::string var_name = this->type_descriptor_var_name(gogo, nt);
1230 // Build the contents of the type descriptor.
1231 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1233 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1235 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1237 const Package* dummy;
1238 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1240 this->type_descriptor_var_ =
1241 gogo->backend()->immutable_struct_reference(var_name,
1245 *phash = this->type_descriptor_var_;
1249 // See if this type descriptor can appear in multiple packages.
1250 bool is_common = false;
1253 // We create the descriptor for a builtin type whenever we need
1255 is_common = nt->is_builtin();
1259 // This is an unnamed type. The descriptor could be defined in
1260 // any package where it is needed, and the linker will pick one
1261 // descriptor to keep.
1265 // We are going to build the type descriptor in this package. We
1266 // must create the variable before we convert the initializer to the
1267 // backend representation, because the initializer may refer to the
1268 // type descriptor of this type. By setting type_descriptor_var_ we
1269 // ensure that type_descriptor_pointer will work if called while
1270 // converting INITIALIZER.
1272 this->type_descriptor_var_ =
1273 gogo->backend()->immutable_struct(var_name, is_common, initializer_btype,
1276 *phash = this->type_descriptor_var_;
1278 Translate_context context(gogo, NULL, NULL, NULL);
1279 context.set_is_const();
1280 Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
1282 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1283 var_name, is_common,
1284 initializer_btype, loc,
1288 // Return the name of the type descriptor variable. If NT is not
1289 // NULL, use it to get the name. Otherwise this is an unnamed type.
1292 Type::type_descriptor_var_name(Gogo* gogo, Named_type* nt)
1295 return "__go_td_" + this->mangled_name(gogo);
1297 Named_object* no = nt->named_object();
1298 const Named_object* in_function = nt->in_function();
1299 std::string ret = "__go_tdn_";
1300 if (nt->is_builtin())
1301 go_assert(in_function == NULL);
1304 const std::string& pkgpath(no->package() == NULL
1305 ? gogo->pkgpath_symbol()
1306 : no->package()->pkgpath_symbol());
1307 ret.append(pkgpath);
1309 if (in_function != NULL)
1311 ret.append(Gogo::unpack_hidden_name(in_function->name()));
1316 // FIXME: This adds in pkgpath twice for hidden symbols, which is
1318 const std::string& name(no->name());
1319 if (!Gogo::is_hidden_name(name))
1324 ret.append(Gogo::pkgpath_for_symbol(Gogo::hidden_name_pkgpath(name)));
1326 ret.append(Gogo::unpack_hidden_name(name));
1332 // Return true if this type descriptor is defined in a different
1333 // package. If this returns true it sets *PACKAGE to the package.
1336 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1337 const Package** package)
1341 if (nt->named_object()->package() != NULL)
1343 // This is a named type defined in a different package. The
1344 // type descriptor should be defined in that package.
1345 *package = nt->named_object()->package();
1351 if (this->points_to() != NULL
1352 && this->points_to()->named_type() != NULL
1353 && this->points_to()->named_type()->named_object()->package() != NULL)
1355 // This is an unnamed pointer to a named type defined in a
1356 // different package. The descriptor should be defined in
1358 *package = this->points_to()->named_type()->named_object()->package();
1365 // Return a composite literal for a type descriptor.
1368 Type::type_descriptor(Gogo* gogo, Type* type)
1370 return type->do_type_descriptor(gogo, NULL);
1373 // Return a composite literal for a type descriptor with a name.
1376 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1378 go_assert(name != NULL && type->named_type() != name);
1379 return type->do_type_descriptor(gogo, name);
1382 // Make a builtin struct type from a list of fields. The fields are
1383 // pairs of a name and a type.
1386 Type::make_builtin_struct_type(int nfields, ...)
1389 va_start(ap, nfields);
1391 Location bloc = Linemap::predeclared_location();
1392 Struct_field_list* sfl = new Struct_field_list();
1393 for (int i = 0; i < nfields; i++)
1395 const char* field_name = va_arg(ap, const char *);
1396 Type* type = va_arg(ap, Type*);
1397 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1402 return Type::make_struct_type(sfl, bloc);
1405 // A list of builtin named types.
1407 std::vector<Named_type*> Type::named_builtin_types;
1409 // Make a builtin named type.
1412 Type::make_builtin_named_type(const char* name, Type* type)
1414 Location bloc = Linemap::predeclared_location();
1415 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1416 Named_type* ret = no->type_value();
1417 Type::named_builtin_types.push_back(ret);
1421 // Convert the named builtin types.
1424 Type::convert_builtin_named_types(Gogo* gogo)
1426 for (std::vector<Named_type*>::const_iterator p =
1427 Type::named_builtin_types.begin();
1428 p != Type::named_builtin_types.end();
1431 bool r = (*p)->verify();
1433 (*p)->convert(gogo);
1437 // Return the type of a type descriptor. We should really tie this to
1438 // runtime.Type rather than copying it. This must match commonType in
1439 // libgo/go/runtime/type.go.
1442 Type::make_type_descriptor_type()
1447 Location bloc = Linemap::predeclared_location();
1449 Type* uint8_type = Type::lookup_integer_type("uint8");
1450 Type* uint32_type = Type::lookup_integer_type("uint32");
1451 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1452 Type* string_type = Type::lookup_string_type();
1453 Type* pointer_string_type = Type::make_pointer_type(string_type);
1455 // This is an unnamed version of unsafe.Pointer. Perhaps we
1456 // should use the named version instead, although that would
1457 // require us to create the unsafe package if it has not been
1458 // imported. It probably doesn't matter.
1459 Type* void_type = Type::make_void_type();
1460 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1462 // Forward declaration for the type descriptor type.
1463 Named_object* named_type_descriptor_type =
1464 Named_object::make_type_declaration("commonType", NULL, bloc);
1465 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1466 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1468 // The type of a method on a concrete type.
1469 Struct_type* method_type =
1470 Type::make_builtin_struct_type(5,
1471 "name", pointer_string_type,
1472 "pkgPath", pointer_string_type,
1473 "mtyp", pointer_type_descriptor_type,
1474 "typ", pointer_type_descriptor_type,
1475 "tfn", unsafe_pointer_type);
1476 Named_type* named_method_type =
1477 Type::make_builtin_named_type("method", method_type);
1479 // Information for types with a name or methods.
1480 Type* slice_named_method_type =
1481 Type::make_array_type(named_method_type, NULL);
1482 Struct_type* uncommon_type =
1483 Type::make_builtin_struct_type(3,
1484 "name", pointer_string_type,
1485 "pkgPath", pointer_string_type,
1486 "methods", slice_named_method_type);
1487 Named_type* named_uncommon_type =
1488 Type::make_builtin_named_type("uncommonType", uncommon_type);
1490 Type* pointer_uncommon_type =
1491 Type::make_pointer_type(named_uncommon_type);
1493 // The type descriptor type.
1495 Typed_identifier_list* params = new Typed_identifier_list();
1496 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1497 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1499 Typed_identifier_list* results = new Typed_identifier_list();
1500 results->push_back(Typed_identifier("", uintptr_type, bloc));
1502 Type* hashfn_type = Type::make_function_type(NULL, params, results, bloc);
1504 params = new Typed_identifier_list();
1505 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1506 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1507 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1509 results = new Typed_identifier_list();
1510 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1512 Type* equalfn_type = Type::make_function_type(NULL, params, results,
1515 Struct_type* type_descriptor_type =
1516 Type::make_builtin_struct_type(10,
1518 "align", uint8_type,
1519 "fieldAlign", uint8_type,
1520 "size", uintptr_type,
1521 "hash", uint32_type,
1522 "hashfn", hashfn_type,
1523 "equalfn", equalfn_type,
1524 "string", pointer_string_type,
1525 "", pointer_uncommon_type,
1527 pointer_type_descriptor_type);
1529 Named_type* named = Type::make_builtin_named_type("commonType",
1530 type_descriptor_type);
1532 named_type_descriptor_type->set_type_value(named);
1540 // Make the type of a pointer to a type descriptor as represented in
1544 Type::make_type_descriptor_ptr_type()
1548 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1552 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1553 // hash code for this type and which compare whether two values of
1554 // this type are equal. If NAME is not NULL it is the name of this
1555 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1556 // functions, for convenience; they may be NULL.
1559 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1560 Function_type* equal_fntype, Named_object** hash_fn,
1561 Named_object** equal_fn)
1563 if (hash_fntype == NULL || equal_fntype == NULL)
1565 Location bloc = Linemap::predeclared_location();
1567 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1568 Type* void_type = Type::make_void_type();
1569 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1571 if (hash_fntype == NULL)
1573 Typed_identifier_list* params = new Typed_identifier_list();
1574 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1576 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1578 Typed_identifier_list* results = new Typed_identifier_list();
1579 results->push_back(Typed_identifier("", uintptr_type, bloc));
1581 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1583 if (equal_fntype == NULL)
1585 Typed_identifier_list* params = new Typed_identifier_list();
1586 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1588 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1590 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1592 Typed_identifier_list* results = new Typed_identifier_list();
1593 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1596 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1600 const char* hash_fnname;
1601 const char* equal_fnname;
1602 if (this->compare_is_identity(gogo))
1604 hash_fnname = "__go_type_hash_identity";
1605 equal_fnname = "__go_type_equal_identity";
1607 else if (!this->is_comparable())
1609 hash_fnname = "__go_type_hash_error";
1610 equal_fnname = "__go_type_equal_error";
1614 switch (this->base()->classification())
1616 case Type::TYPE_ERROR:
1617 case Type::TYPE_VOID:
1618 case Type::TYPE_NIL:
1619 case Type::TYPE_FUNCTION:
1620 case Type::TYPE_MAP:
1621 // For these types is_comparable should have returned false.
1624 case Type::TYPE_BOOLEAN:
1625 case Type::TYPE_INTEGER:
1626 case Type::TYPE_POINTER:
1627 case Type::TYPE_CHANNEL:
1628 // For these types compare_is_identity should have returned true.
1631 case Type::TYPE_FLOAT:
1632 hash_fnname = "__go_type_hash_float";
1633 equal_fnname = "__go_type_equal_float";
1636 case Type::TYPE_COMPLEX:
1637 hash_fnname = "__go_type_hash_complex";
1638 equal_fnname = "__go_type_equal_complex";
1641 case Type::TYPE_STRING:
1642 hash_fnname = "__go_type_hash_string";
1643 equal_fnname = "__go_type_equal_string";
1646 case Type::TYPE_STRUCT:
1648 // This is a struct which can not be compared using a
1649 // simple identity function. We need to build a function
1651 this->specific_type_functions(gogo, name, hash_fntype,
1652 equal_fntype, hash_fn, equal_fn);
1656 case Type::TYPE_ARRAY:
1657 if (this->is_slice_type())
1659 // Type::is_compatible_for_comparison should have
1665 // This is an array which can not be compared using a
1666 // simple identity function. We need to build a
1667 // function for comparison.
1668 this->specific_type_functions(gogo, name, hash_fntype,
1669 equal_fntype, hash_fn, equal_fn);
1674 case Type::TYPE_INTERFACE:
1675 if (this->interface_type()->is_empty())
1677 hash_fnname = "__go_type_hash_empty_interface";
1678 equal_fnname = "__go_type_equal_empty_interface";
1682 hash_fnname = "__go_type_hash_interface";
1683 equal_fnname = "__go_type_equal_interface";
1687 case Type::TYPE_NAMED:
1688 case Type::TYPE_FORWARD:
1697 Location bloc = Linemap::predeclared_location();
1698 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1700 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1701 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1702 equal_fntype, bloc);
1703 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1706 // A hash table mapping types to the specific hash functions.
1708 Type::Type_functions Type::type_functions_table;
1710 // Handle a type function which is specific to a type: a struct or
1711 // array which can not use an identity comparison.
1714 Type::specific_type_functions(Gogo* gogo, Named_type* name,
1715 Function_type* hash_fntype,
1716 Function_type* equal_fntype,
1717 Named_object** hash_fn,
1718 Named_object** equal_fn)
1720 Hash_equal_fn fnull(NULL, NULL);
1721 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1722 std::pair<Type_functions::iterator, bool> ins =
1723 Type::type_functions_table.insert(val);
1726 // We already have functions for this type
1727 *hash_fn = ins.first->second.first;
1728 *equal_fn = ins.first->second.second;
1732 std::string base_name;
1735 // Mangled names can have '.' if they happen to refer to named
1736 // types in some way. That's fine if this is simply a named
1737 // type, but otherwise it will confuse the code that builds
1738 // function identifiers. Remove '.' when necessary.
1739 base_name = this->mangled_name(gogo);
1741 while ((i = base_name.find('.')) != std::string::npos)
1743 base_name = gogo->pack_hidden_name(base_name, false);
1747 // This name is already hidden or not as appropriate.
1748 base_name = name->name();
1749 const Named_object* in_function = name->in_function();
1750 if (in_function != NULL)
1751 base_name += '$' + Gogo::unpack_hidden_name(in_function->name());
1753 std::string hash_name = base_name + "$hash";
1754 std::string equal_name = base_name + "$equal";
1756 Location bloc = Linemap::predeclared_location();
1758 const Package* package = NULL;
1759 bool is_defined_elsewhere =
1760 this->type_descriptor_defined_elsewhere(name, &package);
1761 if (is_defined_elsewhere)
1763 *hash_fn = Named_object::make_function_declaration(hash_name, package,
1765 *equal_fn = Named_object::make_function_declaration(equal_name, package,
1766 equal_fntype, bloc);
1770 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
1771 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
1775 ins.first->second.first = *hash_fn;
1776 ins.first->second.second = *equal_fn;
1778 if (!is_defined_elsewhere)
1780 if (gogo->in_global_scope())
1781 this->write_specific_type_functions(gogo, name, hash_name, hash_fntype,
1782 equal_name, equal_fntype);
1784 gogo->queue_specific_type_function(this, name, hash_name, hash_fntype,
1785 equal_name, equal_fntype);
1789 // Write the hash and equality functions for a type which needs to be
1790 // written specially.
1793 Type::write_specific_type_functions(Gogo* gogo, Named_type* name,
1794 const std::string& hash_name,
1795 Function_type* hash_fntype,
1796 const std::string& equal_name,
1797 Function_type* equal_fntype)
1799 Location bloc = Linemap::predeclared_location();
1801 if (gogo->specific_type_functions_are_written())
1803 go_assert(saw_errors());
1807 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
1809 gogo->start_block(bloc);
1811 if (this->struct_type() != NULL)
1812 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
1814 else if (this->array_type() != NULL)
1815 this->array_type()->write_hash_function(gogo, name, hash_fntype,
1820 Block* b = gogo->finish_block(bloc);
1821 gogo->add_block(b, bloc);
1822 gogo->lower_block(hash_fn, b);
1823 gogo->finish_function(bloc);
1825 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
1827 gogo->start_block(bloc);
1829 if (this->struct_type() != NULL)
1830 this->struct_type()->write_equal_function(gogo, name);
1831 else if (this->array_type() != NULL)
1832 this->array_type()->write_equal_function(gogo, name);
1836 b = gogo->finish_block(bloc);
1837 gogo->add_block(b, bloc);
1838 gogo->lower_block(equal_fn, b);
1839 gogo->finish_function(bloc);
1842 // Return a composite literal for the type descriptor for a plain type
1843 // of kind RUNTIME_TYPE_KIND named NAME.
1846 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
1847 Named_type* name, const Methods* methods,
1848 bool only_value_methods)
1850 Location bloc = Linemap::predeclared_location();
1852 Type* td_type = Type::make_type_descriptor_type();
1853 const Struct_field_list* fields = td_type->struct_type()->fields();
1855 Expression_list* vals = new Expression_list();
1858 if (!this->has_pointer())
1859 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
1860 Struct_field_list::const_iterator p = fields->begin();
1861 go_assert(p->is_field_name("Kind"));
1863 mpz_init_set_ui(iv, runtime_type_kind);
1864 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1867 go_assert(p->is_field_name("align"));
1868 Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT;
1869 vals->push_back(Expression::make_type_info(this, type_info));
1872 go_assert(p->is_field_name("fieldAlign"));
1873 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
1874 vals->push_back(Expression::make_type_info(this, type_info));
1877 go_assert(p->is_field_name("size"));
1878 type_info = Expression::TYPE_INFO_SIZE;
1879 vals->push_back(Expression::make_type_info(this, type_info));
1882 go_assert(p->is_field_name("hash"));
1885 h = name->hash_for_method(gogo);
1887 h = this->hash_for_method(gogo);
1889 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1892 go_assert(p->is_field_name("hashfn"));
1893 Function_type* hash_fntype = p->type()->function_type();
1896 go_assert(p->is_field_name("equalfn"));
1897 Function_type* equal_fntype = p->type()->function_type();
1899 Named_object* hash_fn;
1900 Named_object* equal_fn;
1901 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
1903 vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
1904 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
1907 go_assert(p->is_field_name("string"));
1908 Expression* s = Expression::make_string((name != NULL
1909 ? name->reflection(gogo)
1910 : this->reflection(gogo)),
1912 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1915 go_assert(p->is_field_name("uncommonType"));
1916 if (name == NULL && methods == NULL)
1917 vals->push_back(Expression::make_nil(bloc));
1920 if (methods == NULL)
1921 methods = name->methods();
1922 vals->push_back(this->uncommon_type_constructor(gogo,
1925 only_value_methods));
1929 go_assert(p->is_field_name("ptrToThis"));
1931 vals->push_back(Expression::make_nil(bloc));
1934 Type* pt = Type::make_pointer_type(name);
1935 vals->push_back(Expression::make_type_descriptor(pt, bloc));
1939 go_assert(p == fields->end());
1943 return Expression::make_struct_composite_literal(td_type, vals, bloc);
1946 // Return a composite literal for the uncommon type information for
1947 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
1948 // struct. If name is not NULL, it is the name of the type. If
1949 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
1950 // is true if only value methods should be included. At least one of
1951 // NAME and METHODS must not be NULL.
1954 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
1955 Named_type* name, const Methods* methods,
1956 bool only_value_methods) const
1958 Location bloc = Linemap::predeclared_location();
1960 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
1962 Expression_list* vals = new Expression_list();
1965 Struct_field_list::const_iterator p = fields->begin();
1966 go_assert(p->is_field_name("name"));
1969 go_assert(p->is_field_name("pkgPath"));
1973 vals->push_back(Expression::make_nil(bloc));
1974 vals->push_back(Expression::make_nil(bloc));
1978 Named_object* no = name->named_object();
1979 std::string n = Gogo::unpack_hidden_name(no->name());
1980 Expression* s = Expression::make_string(n, bloc);
1981 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1983 if (name->is_builtin())
1984 vals->push_back(Expression::make_nil(bloc));
1987 const Package* package = no->package();
1988 const std::string& pkgpath(package == NULL
1990 : package->pkgpath());
1992 if (name->in_function() != NULL)
1995 n.append(Gogo::unpack_hidden_name(name->in_function()->name()));
1997 s = Expression::make_string(n, bloc);
1998 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2003 go_assert(p->is_field_name("methods"));
2004 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
2005 only_value_methods));
2008 go_assert(p == fields->end());
2010 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
2012 return Expression::make_unary(OPERATOR_AND, r, bloc);
2015 // Sort methods by name.
2021 operator()(const std::pair<std::string, const Method*>& m1,
2022 const std::pair<std::string, const Method*>& m2) const
2023 { return m1.first < m2.first; }
2026 // Return a composite literal for the type method table for this type.
2027 // METHODS_TYPE is the type of the table, and is a slice type.
2028 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
2029 // then only value methods are used.
2032 Type::methods_constructor(Gogo* gogo, Type* methods_type,
2033 const Methods* methods,
2034 bool only_value_methods) const
2036 Location bloc = Linemap::predeclared_location();
2038 std::vector<std::pair<std::string, const Method*> > smethods;
2039 if (methods != NULL)
2041 smethods.reserve(methods->count());
2042 for (Methods::const_iterator p = methods->begin();
2043 p != methods->end();
2046 if (p->second->is_ambiguous())
2048 if (only_value_methods && !p->second->is_value_method())
2050 smethods.push_back(std::make_pair(p->first, p->second));
2054 if (smethods.empty())
2055 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
2057 std::sort(smethods.begin(), smethods.end(), Sort_methods());
2059 Type* method_type = methods_type->array_type()->element_type();
2061 Expression_list* vals = new Expression_list();
2062 vals->reserve(smethods.size());
2063 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
2065 p != smethods.end();
2067 vals->push_back(this->method_constructor(gogo, method_type, p->first,
2068 p->second, only_value_methods));
2070 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
2073 // Return a composite literal for a single method. METHOD_TYPE is the
2074 // type of the entry. METHOD_NAME is the name of the method and M is
2075 // the method information.
2078 Type::method_constructor(Gogo*, Type* method_type,
2079 const std::string& method_name,
2081 bool only_value_methods) const
2083 Location bloc = Linemap::predeclared_location();
2085 const Struct_field_list* fields = method_type->struct_type()->fields();
2087 Expression_list* vals = new Expression_list();
2090 Struct_field_list::const_iterator p = fields->begin();
2091 go_assert(p->is_field_name("name"));
2092 const std::string n = Gogo::unpack_hidden_name(method_name);
2093 Expression* s = Expression::make_string(n, bloc);
2094 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2097 go_assert(p->is_field_name("pkgPath"));
2098 if (!Gogo::is_hidden_name(method_name))
2099 vals->push_back(Expression::make_nil(bloc));
2102 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
2104 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2107 Named_object* no = (m->needs_stub_method()
2109 : m->named_object());
2111 Function_type* mtype;
2112 if (no->is_function())
2113 mtype = no->func_value()->type();
2115 mtype = no->func_declaration_value()->type();
2116 go_assert(mtype->is_method());
2117 Type* nonmethod_type = mtype->copy_without_receiver();
2120 go_assert(p->is_field_name("mtyp"));
2121 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
2124 go_assert(p->is_field_name("typ"));
2125 if (!only_value_methods && m->is_value_method())
2127 // This is a value method on a pointer type. Change the type of
2128 // the method to use a pointer receiver. The implementation
2129 // always uses a pointer receiver anyhow.
2130 Type* rtype = mtype->receiver()->type();
2131 Type* prtype = Type::make_pointer_type(rtype);
2132 Typed_identifier* receiver =
2133 new Typed_identifier(mtype->receiver()->name(), prtype,
2134 mtype->receiver()->location());
2135 mtype = Type::make_function_type(receiver,
2136 (mtype->parameters() == NULL
2138 : mtype->parameters()->copy()),
2139 (mtype->results() == NULL
2141 : mtype->results()->copy()),
2144 vals->push_back(Expression::make_type_descriptor(mtype, bloc));
2147 go_assert(p->is_field_name("tfn"));
2148 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
2151 go_assert(p == fields->end());
2153 return Expression::make_struct_composite_literal(method_type, vals, bloc);
2156 // Return a composite literal for the type descriptor of a plain type.
2157 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
2158 // NULL, it is the name to use as well as the list of methods.
2161 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
2164 return this->type_descriptor_constructor(gogo, runtime_type_kind,
2168 // Return the type reflection string for this type.
2171 Type::reflection(Gogo* gogo) const
2175 // The do_reflection virtual function should set RET to the
2176 // reflection string.
2177 this->do_reflection(gogo, &ret);
2182 // Return a mangled name for the type.
2185 Type::mangled_name(Gogo* gogo) const
2189 // The do_mangled_name virtual function should set RET to the
2190 // mangled name. For a composite type it should append a code for
2191 // the composition and then call do_mangled_name on the components.
2192 this->do_mangled_name(gogo, &ret);
2197 // Return whether the backend size of the type is known.
2200 Type::is_backend_type_size_known(Gogo* gogo)
2202 switch (this->classification_)
2216 case TYPE_INTERFACE:
2221 const Struct_field_list* fields = this->struct_type()->fields();
2222 for (Struct_field_list::const_iterator pf = fields->begin();
2223 pf != fields->end();
2225 if (!pf->type()->is_backend_type_size_known(gogo))
2232 const Array_type* at = this->array_type();
2233 if (at->length() == NULL)
2237 Numeric_constant nc;
2238 if (!at->length()->numeric_constant_value(&nc))
2241 if (!nc.to_int(&ival))
2244 return at->element_type()->is_backend_type_size_known(gogo);
2249 // Begin converting this type to the backend representation.
2250 // This will create a placeholder if necessary.
2251 this->get_backend(gogo);
2252 return this->named_type()->is_named_backend_type_size_known();
2256 Forward_declaration_type* fdt = this->forward_declaration_type();
2257 return fdt->real_type()->is_backend_type_size_known(gogo);
2261 case TYPE_CALL_MULTIPLE_RESULT:
2269 // If the size of the type can be determined, set *PSIZE to the size
2270 // in bytes and return true. Otherwise, return false. This queries
2274 Type::backend_type_size(Gogo* gogo, unsigned int *psize)
2276 if (!this->is_backend_type_size_known(gogo))
2278 Btype* bt = this->get_backend_placeholder(gogo);
2279 size_t size = gogo->backend()->type_size(bt);
2280 *psize = static_cast<unsigned int>(size);
2286 // If the alignment of the type can be determined, set *PALIGN to
2287 // the alignment in bytes and return true. Otherwise, return false.
2290 Type::backend_type_align(Gogo* gogo, unsigned int *palign)
2292 if (!this->is_backend_type_size_known(gogo))
2294 Btype* bt = this->get_backend_placeholder(gogo);
2295 size_t align = gogo->backend()->type_alignment(bt);
2296 *palign = static_cast<unsigned int>(align);
2297 if (*palign != align)
2302 // Like backend_type_align, but return the alignment when used as a
2306 Type::backend_type_field_align(Gogo* gogo, unsigned int *palign)
2308 if (!this->is_backend_type_size_known(gogo))
2310 Btype* bt = this->get_backend_placeholder(gogo);
2311 size_t a = gogo->backend()->type_field_alignment(bt);
2312 *palign = static_cast<unsigned int>(a);
2318 // Default function to export a type.
2321 Type::do_export(Export*) const
2329 Type::import_type(Import* imp)
2331 if (imp->match_c_string("("))
2332 return Function_type::do_import(imp);
2333 else if (imp->match_c_string("*"))
2334 return Pointer_type::do_import(imp);
2335 else if (imp->match_c_string("struct "))
2336 return Struct_type::do_import(imp);
2337 else if (imp->match_c_string("["))
2338 return Array_type::do_import(imp);
2339 else if (imp->match_c_string("map "))
2340 return Map_type::do_import(imp);
2341 else if (imp->match_c_string("chan "))
2342 return Channel_type::do_import(imp);
2343 else if (imp->match_c_string("interface"))
2344 return Interface_type::do_import(imp);
2347 error_at(imp->location(), "import error: expected type");
2348 return Type::make_error_type();
2352 // A type used to indicate a parsing error. This exists to simplify
2353 // later error detection.
2355 class Error_type : public Type
2364 do_compare_is_identity(Gogo*) const
2368 do_get_backend(Gogo* gogo)
2369 { return gogo->backend()->error_type(); }
2372 do_type_descriptor(Gogo*, Named_type*)
2373 { return Expression::make_error(Linemap::predeclared_location()); }
2376 do_reflection(Gogo*, std::string*) const
2377 { go_assert(saw_errors()); }
2380 do_mangled_name(Gogo*, std::string* ret) const
2381 { ret->push_back('E'); }
2385 Type::make_error_type()
2387 static Error_type singleton_error_type;
2388 return &singleton_error_type;
2393 class Void_type : public Type
2402 do_compare_is_identity(Gogo*) const
2406 do_get_backend(Gogo* gogo)
2407 { return gogo->backend()->void_type(); }
2410 do_type_descriptor(Gogo*, Named_type*)
2411 { go_unreachable(); }
2414 do_reflection(Gogo*, std::string*) const
2418 do_mangled_name(Gogo*, std::string* ret) const
2419 { ret->push_back('v'); }
2423 Type::make_void_type()
2425 static Void_type singleton_void_type;
2426 return &singleton_void_type;
2429 // The boolean type.
2431 class Boolean_type : public Type
2435 : Type(TYPE_BOOLEAN)
2440 do_compare_is_identity(Gogo*) const
2444 do_get_backend(Gogo* gogo)
2445 { return gogo->backend()->bool_type(); }
2448 do_type_descriptor(Gogo*, Named_type* name);
2450 // We should not be asked for the reflection string of a basic type.
2452 do_reflection(Gogo*, std::string* ret) const
2453 { ret->append("bool"); }
2456 do_mangled_name(Gogo*, std::string* ret) const
2457 { ret->push_back('b'); }
2460 // Make the type descriptor.
2463 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2466 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
2469 Named_object* no = gogo->lookup_global("bool");
2470 go_assert(no != NULL);
2471 return Type::type_descriptor(gogo, no->type_value());
2476 Type::make_boolean_type()
2478 static Boolean_type boolean_type;
2479 return &boolean_type;
2482 // The named type "bool".
2484 static Named_type* named_bool_type;
2486 // Get the named type "bool".
2489 Type::lookup_bool_type()
2491 return named_bool_type;
2494 // Make the named type "bool".
2497 Type::make_named_bool_type()
2499 Type* bool_type = Type::make_boolean_type();
2500 Named_object* named_object =
2501 Named_object::make_type("bool", NULL, bool_type,
2502 Linemap::predeclared_location());
2503 Named_type* named_type = named_object->type_value();
2504 named_bool_type = named_type;
2508 // Class Integer_type.
2510 Integer_type::Named_integer_types Integer_type::named_integer_types;
2512 // Create a new integer type. Non-abstract integer types always have
2516 Integer_type::create_integer_type(const char* name, bool is_unsigned,
2517 int bits, int runtime_type_kind)
2519 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
2521 std::string sname(name);
2522 Named_object* named_object =
2523 Named_object::make_type(sname, NULL, integer_type,
2524 Linemap::predeclared_location());
2525 Named_type* named_type = named_object->type_value();
2526 std::pair<Named_integer_types::iterator, bool> ins =
2527 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
2528 go_assert(ins.second);
2532 // Look up an existing integer type.
2535 Integer_type::lookup_integer_type(const char* name)
2537 Named_integer_types::const_iterator p =
2538 Integer_type::named_integer_types.find(name);
2539 go_assert(p != Integer_type::named_integer_types.end());
2543 // Create a new abstract integer type.
2546 Integer_type::create_abstract_integer_type()
2548 static Integer_type* abstract_type;
2549 if (abstract_type == NULL)
2550 abstract_type = new Integer_type(true, false, INT_TYPE_SIZE,
2551 RUNTIME_TYPE_KIND_INT);
2552 return abstract_type;
2555 // Create a new abstract character type.
2558 Integer_type::create_abstract_character_type()
2560 static Integer_type* abstract_type;
2561 if (abstract_type == NULL)
2563 abstract_type = new Integer_type(true, false, 32,
2564 RUNTIME_TYPE_KIND_INT32);
2565 abstract_type->set_is_rune();
2567 return abstract_type;
2570 // Integer type compatibility.
2573 Integer_type::is_identical(const Integer_type* t) const
2575 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
2577 return this->is_abstract_ == t->is_abstract_;
2583 Integer_type::do_hash_for_method(Gogo*) const
2585 return ((this->bits_ << 4)
2586 + ((this->is_unsigned_ ? 1 : 0) << 8)
2587 + ((this->is_abstract_ ? 1 : 0) << 9));
2590 // Convert an Integer_type to the backend representation.
2593 Integer_type::do_get_backend(Gogo* gogo)
2595 if (this->is_abstract_)
2597 go_assert(saw_errors());
2598 return gogo->backend()->error_type();
2600 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
2603 // The type descriptor for an integer type. Integer types are always
2607 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2609 go_assert(name != NULL || saw_errors());
2610 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2613 // We should not be asked for the reflection string of a basic type.
2616 Integer_type::do_reflection(Gogo*, std::string*) const
2618 go_assert(saw_errors());
2624 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
2627 snprintf(buf, sizeof buf, "i%s%s%de",
2628 this->is_abstract_ ? "a" : "",
2629 this->is_unsigned_ ? "u" : "",
2634 // Make an integer type.
2637 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
2638 int runtime_type_kind)
2640 return Integer_type::create_integer_type(name, is_unsigned, bits,
2644 // Make an abstract integer type.
2647 Type::make_abstract_integer_type()
2649 return Integer_type::create_abstract_integer_type();
2652 // Make an abstract character type.
2655 Type::make_abstract_character_type()
2657 return Integer_type::create_abstract_character_type();
2660 // Look up an integer type.
2663 Type::lookup_integer_type(const char* name)
2665 return Integer_type::lookup_integer_type(name);
2668 // Class Float_type.
2670 Float_type::Named_float_types Float_type::named_float_types;
2672 // Create a new float type. Non-abstract float types always have
2676 Float_type::create_float_type(const char* name, int bits,
2677 int runtime_type_kind)
2679 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
2680 std::string sname(name);
2681 Named_object* named_object =
2682 Named_object::make_type(sname, NULL, float_type,
2683 Linemap::predeclared_location());
2684 Named_type* named_type = named_object->type_value();
2685 std::pair<Named_float_types::iterator, bool> ins =
2686 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
2687 go_assert(ins.second);
2691 // Look up an existing float type.
2694 Float_type::lookup_float_type(const char* name)
2696 Named_float_types::const_iterator p =
2697 Float_type::named_float_types.find(name);
2698 go_assert(p != Float_type::named_float_types.end());
2702 // Create a new abstract float type.
2705 Float_type::create_abstract_float_type()
2707 static Float_type* abstract_type;
2708 if (abstract_type == NULL)
2709 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
2710 return abstract_type;
2713 // Whether this type is identical with T.
2716 Float_type::is_identical(const Float_type* t) const
2718 if (this->bits_ != t->bits_)
2720 return this->is_abstract_ == t->is_abstract_;
2726 Float_type::do_hash_for_method(Gogo*) const
2728 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2731 // Convert to the backend representation.
2734 Float_type::do_get_backend(Gogo* gogo)
2736 return gogo->backend()->float_type(this->bits_);
2739 // The type descriptor for a float type. Float types are always named.
2742 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2744 go_assert(name != NULL || saw_errors());
2745 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2748 // We should not be asked for the reflection string of a basic type.
2751 Float_type::do_reflection(Gogo*, std::string*) const
2753 go_assert(saw_errors());
2759 Float_type::do_mangled_name(Gogo*, std::string* ret) const
2762 snprintf(buf, sizeof buf, "f%s%de",
2763 this->is_abstract_ ? "a" : "",
2768 // Make a floating point type.
2771 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
2773 return Float_type::create_float_type(name, bits, runtime_type_kind);
2776 // Make an abstract float type.
2779 Type::make_abstract_float_type()
2781 return Float_type::create_abstract_float_type();
2784 // Look up a float type.
2787 Type::lookup_float_type(const char* name)
2789 return Float_type::lookup_float_type(name);
2792 // Class Complex_type.
2794 Complex_type::Named_complex_types Complex_type::named_complex_types;
2796 // Create a new complex type. Non-abstract complex types always have
2800 Complex_type::create_complex_type(const char* name, int bits,
2801 int runtime_type_kind)
2803 Complex_type* complex_type = new Complex_type(false, bits,
2805 std::string sname(name);
2806 Named_object* named_object =
2807 Named_object::make_type(sname, NULL, complex_type,
2808 Linemap::predeclared_location());
2809 Named_type* named_type = named_object->type_value();
2810 std::pair<Named_complex_types::iterator, bool> ins =
2811 Complex_type::named_complex_types.insert(std::make_pair(sname,
2813 go_assert(ins.second);
2817 // Look up an existing complex type.
2820 Complex_type::lookup_complex_type(const char* name)
2822 Named_complex_types::const_iterator p =
2823 Complex_type::named_complex_types.find(name);
2824 go_assert(p != Complex_type::named_complex_types.end());
2828 // Create a new abstract complex type.
2831 Complex_type::create_abstract_complex_type()
2833 static Complex_type* abstract_type;
2834 if (abstract_type == NULL)
2835 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
2836 return abstract_type;
2839 // Whether this type is identical with T.
2842 Complex_type::is_identical(const Complex_type *t) const
2844 if (this->bits_ != t->bits_)
2846 return this->is_abstract_ == t->is_abstract_;
2852 Complex_type::do_hash_for_method(Gogo*) const
2854 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2857 // Convert to the backend representation.
2860 Complex_type::do_get_backend(Gogo* gogo)
2862 return gogo->backend()->complex_type(this->bits_);
2865 // The type descriptor for a complex type. Complex types are always
2869 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2871 go_assert(name != NULL || saw_errors());
2872 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2875 // We should not be asked for the reflection string of a basic type.
2878 Complex_type::do_reflection(Gogo*, std::string*) const
2880 go_assert(saw_errors());
2886 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
2889 snprintf(buf, sizeof buf, "c%s%de",
2890 this->is_abstract_ ? "a" : "",
2895 // Make a complex type.
2898 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
2900 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
2903 // Make an abstract complex type.
2906 Type::make_abstract_complex_type()
2908 return Complex_type::create_abstract_complex_type();
2911 // Look up a complex type.
2914 Type::lookup_complex_type(const char* name)
2916 return Complex_type::lookup_complex_type(name);
2919 // Class String_type.
2921 // Convert String_type to the backend representation. A string is a
2922 // struct with two fields: a pointer to the characters and a length.
2925 String_type::do_get_backend(Gogo* gogo)
2927 static Btype* backend_string_type;
2928 if (backend_string_type == NULL)
2930 std::vector<Backend::Btyped_identifier> fields(2);
2932 Type* b = gogo->lookup_global("byte")->type_value();
2933 Type* pb = Type::make_pointer_type(b);
2935 // We aren't going to get back to this field to finish the
2936 // backend representation, so force it to be finished now.
2937 if (!gogo->named_types_are_converted())
2939 pb->get_backend_placeholder(gogo);
2940 pb->finish_backend(gogo);
2943 fields[0].name = "__data";
2944 fields[0].btype = pb->get_backend(gogo);
2945 fields[0].location = Linemap::predeclared_location();
2947 Type* int_type = Type::lookup_integer_type("int");
2948 fields[1].name = "__length";
2949 fields[1].btype = int_type->get_backend(gogo);
2950 fields[1].location = fields[0].location;
2952 backend_string_type = gogo->backend()->struct_type(fields);
2954 return backend_string_type;
2957 // Return a tree for the length of STRING.
2960 String_type::length_tree(Gogo*, tree string)
2962 tree string_type = TREE_TYPE(string);
2963 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2964 tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type));
2965 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)),
2967 return fold_build3(COMPONENT_REF, integer_type_node, string,
2968 length_field, NULL_TREE);
2971 // Return a tree for a pointer to the bytes of STRING.
2974 String_type::bytes_tree(Gogo*, tree string)
2976 tree string_type = TREE_TYPE(string);
2977 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2978 tree bytes_field = TYPE_FIELDS(string_type);
2979 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)),
2981 return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string,
2982 bytes_field, NULL_TREE);
2985 // The type descriptor for the string type.
2988 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2991 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
2994 Named_object* no = gogo->lookup_global("string");
2995 go_assert(no != NULL);
2996 return Type::type_descriptor(gogo, no->type_value());
3000 // We should not be asked for the reflection string of a basic type.
3003 String_type::do_reflection(Gogo*, std::string* ret) const
3005 ret->append("string");
3008 // Mangled name of a string type.
3011 String_type::do_mangled_name(Gogo*, std::string* ret) const
3013 ret->push_back('z');
3016 // Make a string type.
3019 Type::make_string_type()
3021 static String_type string_type;
3022 return &string_type;
3025 // The named type "string".
3027 static Named_type* named_string_type;
3029 // Get the named type "string".
3032 Type::lookup_string_type()
3034 return named_string_type;
3037 // Make the named type string.
3040 Type::make_named_string_type()
3042 Type* string_type = Type::make_string_type();
3043 Named_object* named_object =
3044 Named_object::make_type("string", NULL, string_type,
3045 Linemap::predeclared_location());
3046 Named_type* named_type = named_object->type_value();
3047 named_string_type = named_type;
3051 // The sink type. This is the type of the blank identifier _. Any
3052 // type may be assigned to it.
3054 class Sink_type : public Type
3063 do_compare_is_identity(Gogo*) const
3067 do_get_backend(Gogo*)
3068 { go_unreachable(); }
3071 do_type_descriptor(Gogo*, Named_type*)
3072 { go_unreachable(); }
3075 do_reflection(Gogo*, std::string*) const
3076 { go_unreachable(); }
3079 do_mangled_name(Gogo*, std::string*) const
3080 { go_unreachable(); }
3083 // Make the sink type.
3086 Type::make_sink_type()
3088 static Sink_type sink_type;
3092 // Class Function_type.
3097 Function_type::do_traverse(Traverse* traverse)
3099 if (this->receiver_ != NULL
3100 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
3101 return TRAVERSE_EXIT;
3102 if (this->parameters_ != NULL
3103 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
3104 return TRAVERSE_EXIT;
3105 if (this->results_ != NULL
3106 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
3107 return TRAVERSE_EXIT;
3108 return TRAVERSE_CONTINUE;
3111 // Returns whether T is a valid redeclaration of this type. If this
3112 // returns false, and REASON is not NULL, *REASON may be set to a
3113 // brief explanation of why it returned false.
3116 Function_type::is_valid_redeclaration(const Function_type* t,
3117 std::string* reason) const
3119 if (!this->is_identical(t, false, true, reason))
3122 // A redeclaration of a function is required to use the same names
3123 // for the receiver and parameters.
3124 if (this->receiver() != NULL
3125 && this->receiver()->name() != t->receiver()->name())
3128 *reason = "receiver name changed";
3132 const Typed_identifier_list* parms1 = this->parameters();
3133 const Typed_identifier_list* parms2 = t->parameters();
3136 Typed_identifier_list::const_iterator p1 = parms1->begin();
3137 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3138 p2 != parms2->end();
3141 if (p1->name() != p2->name())
3144 *reason = "parameter name changed";
3148 // This is called at parse time, so we may have unknown
3150 Type* t1 = p1->type()->forwarded();
3151 Type* t2 = p2->type()->forwarded();
3153 && t1->forward_declaration_type() != NULL
3154 && (t2->forward_declaration_type() == NULL
3155 || (t1->forward_declaration_type()->named_object()
3156 != t2->forward_declaration_type()->named_object())))
3161 const Typed_identifier_list* results1 = this->results();
3162 const Typed_identifier_list* results2 = t->results();
3163 if (results1 != NULL)
3165 Typed_identifier_list::const_iterator res1 = results1->begin();
3166 for (Typed_identifier_list::const_iterator res2 = results2->begin();
3167 res2 != results2->end();
3170 if (res1->name() != res2->name())
3173 *reason = "result name changed";
3177 // This is called at parse time, so we may have unknown
3179 Type* t1 = res1->type()->forwarded();
3180 Type* t2 = res2->type()->forwarded();
3182 && t1->forward_declaration_type() != NULL
3183 && (t2->forward_declaration_type() == NULL
3184 || (t1->forward_declaration_type()->named_object()
3185 != t2->forward_declaration_type()->named_object())))
3193 // Check whether T is the same as this type.
3196 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
3197 bool errors_are_identical,
3198 std::string* reason) const
3200 if (!ignore_receiver)
3202 const Typed_identifier* r1 = this->receiver();
3203 const Typed_identifier* r2 = t->receiver();
3204 if ((r1 != NULL) != (r2 != NULL))
3207 *reason = _("different receiver types");
3212 if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
3215 if (reason != NULL && !reason->empty())
3216 *reason = "receiver: " + *reason;
3222 const Typed_identifier_list* parms1 = this->parameters();
3223 const Typed_identifier_list* parms2 = t->parameters();
3224 if ((parms1 != NULL) != (parms2 != NULL))
3227 *reason = _("different number of parameters");
3232 Typed_identifier_list::const_iterator p1 = parms1->begin();
3233 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3234 p2 != parms2->end();
3237 if (p1 == parms1->end())
3240 *reason = _("different number of parameters");
3244 if (!Type::are_identical(p1->type(), p2->type(),
3245 errors_are_identical, NULL))
3248 *reason = _("different parameter types");
3252 if (p1 != parms1->end())
3255 *reason = _("different number of parameters");
3260 if (this->is_varargs() != t->is_varargs())
3263 *reason = _("different varargs");
3267 const Typed_identifier_list* results1 = this->results();
3268 const Typed_identifier_list* results2 = t->results();
3269 if ((results1 != NULL) != (results2 != NULL))
3272 *reason = _("different number of results");
3275 if (results1 != NULL)
3277 Typed_identifier_list::const_iterator res1 = results1->begin();
3278 for (Typed_identifier_list::const_iterator res2 = results2->begin();
3279 res2 != results2->end();
3282 if (res1 == results1->end())
3285 *reason = _("different number of results");
3289 if (!Type::are_identical(res1->type(), res2->type(),
3290 errors_are_identical, NULL))
3293 *reason = _("different result types");
3297 if (res1 != results1->end())
3300 *reason = _("different number of results");
3311 Function_type::do_hash_for_method(Gogo* gogo) const
3313 unsigned int ret = 0;
3314 // We ignore the receiver type for hash codes, because we need to
3315 // get the same hash code for a method in an interface and a method
3316 // declared for a type. The former will not have a receiver.
3317 if (this->parameters_ != NULL)
3320 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3321 p != this->parameters_->end();
3323 ret += p->type()->hash_for_method(gogo) << shift;
3325 if (this->results_ != NULL)
3328 for (Typed_identifier_list::const_iterator p = this->results_->begin();
3329 p != this->results_->end();
3331 ret += p->type()->hash_for_method(gogo) << shift;
3333 if (this->is_varargs_)
3339 // Get the backend representation for a function type.
3342 Function_type::do_get_backend(Gogo* gogo)
3344 Backend::Btyped_identifier breceiver;
3345 if (this->receiver_ != NULL)
3347 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
3349 // We always pass the address of the receiver parameter, in
3350 // order to make interface calls work with unknown types.
3351 Type* rtype = this->receiver_->type();
3352 if (rtype->points_to() == NULL)
3353 rtype = Type::make_pointer_type(rtype);
3354 breceiver.btype = rtype->get_backend(gogo);
3355 breceiver.location = this->receiver_->location();
3358 std::vector<Backend::Btyped_identifier> bparameters;
3359 if (this->parameters_ != NULL)
3361 bparameters.resize(this->parameters_->size());
3363 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3364 p != this->parameters_->end();
3367 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
3368 bparameters[i].btype = p->type()->get_backend(gogo);
3369 bparameters[i].location = p->location();
3371 go_assert(i == bparameters.size());
3374 std::vector<Backend::Btyped_identifier> bresults;
3375 if (this->results_ != NULL)
3377 bresults.resize(this->results_->size());
3379 for (Typed_identifier_list::const_iterator p = this->results_->begin();
3380 p != this->results_->end();
3383 bresults[i].name = Gogo::unpack_hidden_name(p->name());
3384 bresults[i].btype = p->type()->get_backend(gogo);
3385 bresults[i].location = p->location();
3387 go_assert(i == bresults.size());
3390 return gogo->backend()->function_type(breceiver, bparameters, bresults,
3394 // The type of a function type descriptor.
3397 Function_type::make_function_type_descriptor_type()
3402 Type* tdt = Type::make_type_descriptor_type();
3403 Type* ptdt = Type::make_type_descriptor_ptr_type();
3405 Type* bool_type = Type::lookup_bool_type();
3407 Type* slice_type = Type::make_array_type(ptdt, NULL);
3409 Struct_type* s = Type::make_builtin_struct_type(4,
3411 "dotdotdot", bool_type,
3415 ret = Type::make_builtin_named_type("FuncType", s);
3421 // The type descriptor for a function type.
3424 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3426 Location bloc = Linemap::predeclared_location();
3428 Type* ftdt = Function_type::make_function_type_descriptor_type();
3430 const Struct_field_list* fields = ftdt->struct_type()->fields();
3432 Expression_list* vals = new Expression_list();
3435 Struct_field_list::const_iterator p = fields->begin();
3436 go_assert(p->is_field_name("commonType"));
3437 vals->push_back(this->type_descriptor_constructor(gogo,
3438 RUNTIME_TYPE_KIND_FUNC,
3442 go_assert(p->is_field_name("dotdotdot"));
3443 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
3446 go_assert(p->is_field_name("in"));
3447 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
3448 this->parameters()));
3451 go_assert(p->is_field_name("out"));
3452 vals->push_back(this->type_descriptor_params(p->type(), NULL,
3456 go_assert(p == fields->end());
3458 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
3461 // Return a composite literal for the parameters or results of a type
3465 Function_type::type_descriptor_params(Type* params_type,
3466 const Typed_identifier* receiver,
3467 const Typed_identifier_list* params)
3469 Location bloc = Linemap::predeclared_location();
3471 if (receiver == NULL && params == NULL)
3472 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
3474 Expression_list* vals = new Expression_list();
3475 vals->reserve((params == NULL ? 0 : params->size())
3476 + (receiver != NULL ? 1 : 0));
3478 if (receiver != NULL)
3479 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
3483 for (Typed_identifier_list::const_iterator p = params->begin();
3486 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
3489 return Expression::make_slice_composite_literal(params_type, vals, bloc);
3492 // The reflection string.
3495 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
3497 // FIXME: Turn this off until we straighten out the type of the
3498 // struct field used in a go statement which calls a method.
3499 // go_assert(this->receiver_ == NULL);
3501 ret->append("func");
3503 if (this->receiver_ != NULL)
3505 ret->push_back('(');
3506 this->append_reflection(this->receiver_->type(), gogo, ret);
3507 ret->push_back(')');
3510 ret->push_back('(');
3511 const Typed_identifier_list* params = this->parameters();
3514 bool is_varargs = this->is_varargs_;
3515 for (Typed_identifier_list::const_iterator p = params->begin();
3519 if (p != params->begin())
3521 if (!is_varargs || p + 1 != params->end())
3522 this->append_reflection(p->type(), gogo, ret);
3526 this->append_reflection(p->type()->array_type()->element_type(),
3531 ret->push_back(')');
3533 const Typed_identifier_list* results = this->results();
3534 if (results != NULL && !results->empty())
3536 if (results->size() == 1)
3537 ret->push_back(' ');
3540 for (Typed_identifier_list::const_iterator p = results->begin();
3541 p != results->end();
3544 if (p != results->begin())
3546 this->append_reflection(p->type(), gogo, ret);
3548 if (results->size() > 1)
3549 ret->push_back(')');
3556 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3558 ret->push_back('F');
3560 if (this->receiver_ != NULL)
3562 ret->push_back('m');
3563 this->append_mangled_name(this->receiver_->type(), gogo, ret);
3566 const Typed_identifier_list* params = this->parameters();
3569 ret->push_back('p');
3570 for (Typed_identifier_list::const_iterator p = params->begin();
3573 this->append_mangled_name(p->type(), gogo, ret);
3574 if (this->is_varargs_)
3575 ret->push_back('V');
3576 ret->push_back('e');
3579 const Typed_identifier_list* results = this->results();
3580 if (results != NULL)
3582 ret->push_back('r');
3583 for (Typed_identifier_list::const_iterator p = results->begin();
3584 p != results->end();
3586 this->append_mangled_name(p->type(), gogo, ret);
3587 ret->push_back('e');
3590 ret->push_back('e');
3593 // Export a function type.
3596 Function_type::do_export(Export* exp) const
3598 // We don't write out the receiver. The only function types which
3599 // should have a receiver are the ones associated with explicitly
3600 // defined methods. For those the receiver type is written out by
3601 // Function::export_func.
3603 exp->write_c_string("(");
3605 if (this->parameters_ != NULL)
3607 bool is_varargs = this->is_varargs_;
3608 for (Typed_identifier_list::const_iterator p =
3609 this->parameters_->begin();
3610 p != this->parameters_->end();
3616 exp->write_c_string(", ");
3617 exp->write_name(p->name());
3618 exp->write_c_string(" ");
3619 if (!is_varargs || p + 1 != this->parameters_->end())
3620 exp->write_type(p->type());
3623 exp->write_c_string("...");
3624 exp->write_type(p->type()->array_type()->element_type());
3628 exp->write_c_string(")");
3630 const Typed_identifier_list* results = this->results_;
3631 if (results != NULL)
3633 exp->write_c_string(" ");
3634 if (results->size() == 1 && results->begin()->name().empty())
3635 exp->write_type(results->begin()->type());
3639 exp->write_c_string("(");
3640 for (Typed_identifier_list::const_iterator p = results->begin();
3641 p != results->end();
3647 exp->write_c_string(", ");
3648 exp->write_name(p->name());
3649 exp->write_c_string(" ");
3650 exp->write_type(p->type());
3652 exp->write_c_string(")");
3657 // Import a function type.
3660 Function_type::do_import(Import* imp)
3662 imp->require_c_string("(");
3663 Typed_identifier_list* parameters;
3664 bool is_varargs = false;
3665 if (imp->peek_char() == ')')
3669 parameters = new Typed_identifier_list();
3672 std::string name = imp->read_name();
3673 imp->require_c_string(" ");
3675 if (imp->match_c_string("..."))
3681 Type* ptype = imp->read_type();
3683 ptype = Type::make_array_type(ptype, NULL);
3684 parameters->push_back(Typed_identifier(name, ptype,
3686 if (imp->peek_char() != ',')
3688 go_assert(!is_varargs);
3689 imp->require_c_string(", ");
3692 imp->require_c_string(")");
3694 Typed_identifier_list* results;
3695 if (imp->peek_char() != ' ')
3700 results = new Typed_identifier_list;
3701 if (imp->peek_char() != '(')
3703 Type* rtype = imp->read_type();
3704 results->push_back(Typed_identifier("", rtype, imp->location()));
3711 std::string name = imp->read_name();
3712 imp->require_c_string(" ");
3713 Type* rtype = imp->read_type();
3714 results->push_back(Typed_identifier(name, rtype,
3716 if (imp->peek_char() != ',')
3718 imp->require_c_string(", ");
3720 imp->require_c_string(")");
3724 Function_type* ret = Type::make_function_type(NULL, parameters, results,
3727 ret->set_is_varargs();
3731 // Make a copy of a function type without a receiver.
3734 Function_type::copy_without_receiver() const
3736 go_assert(this->is_method());
3737 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
3740 if (this->is_varargs())
3741 ret->set_is_varargs();
3742 if (this->is_builtin())
3743 ret->set_is_builtin();
3747 // Make a copy of a function type with a receiver.
3750 Function_type::copy_with_receiver(Type* receiver_type) const
3752 go_assert(!this->is_method());
3753 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
3755 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
3758 if (this->is_varargs_)
3759 ret->set_is_varargs();
3763 // Make a function type.
3766 Type::make_function_type(Typed_identifier* receiver,
3767 Typed_identifier_list* parameters,
3768 Typed_identifier_list* results,
3771 return new Function_type(receiver, parameters, results, location);
3774 // Class Pointer_type.
3779 Pointer_type::do_traverse(Traverse* traverse)
3781 return Type::traverse(this->to_type_, traverse);
3787 Pointer_type::do_hash_for_method(Gogo* gogo) const
3789 return this->to_type_->hash_for_method(gogo) << 4;
3792 // Get the backend representation for a pointer type.
3795 Pointer_type::do_get_backend(Gogo* gogo)
3797 Btype* to_btype = this->to_type_->get_backend(gogo);
3798 return gogo->backend()->pointer_type(to_btype);
3801 // The type of a pointer type descriptor.
3804 Pointer_type::make_pointer_type_descriptor_type()
3809 Type* tdt = Type::make_type_descriptor_type();
3810 Type* ptdt = Type::make_type_descriptor_ptr_type();
3812 Struct_type* s = Type::make_builtin_struct_type(2,
3816 ret = Type::make_builtin_named_type("PtrType", s);
3822 // The type descriptor for a pointer type.
3825 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3827 if (this->is_unsafe_pointer_type())
3829 go_assert(name != NULL);
3830 return this->plain_type_descriptor(gogo,
3831 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
3836 Location bloc = Linemap::predeclared_location();
3838 const Methods* methods;
3839 Type* deref = this->points_to();
3840 if (deref->named_type() != NULL)
3841 methods = deref->named_type()->methods();
3842 else if (deref->struct_type() != NULL)
3843 methods = deref->struct_type()->methods();
3847 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
3849 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
3851 Expression_list* vals = new Expression_list();
3854 Struct_field_list::const_iterator p = fields->begin();
3855 go_assert(p->is_field_name("commonType"));
3856 vals->push_back(this->type_descriptor_constructor(gogo,
3857 RUNTIME_TYPE_KIND_PTR,
3858 name, methods, false));
3861 go_assert(p->is_field_name("elem"));
3862 vals->push_back(Expression::make_type_descriptor(deref, bloc));
3864 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
3868 // Reflection string.
3871 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
3873 ret->push_back('*');
3874 this->append_reflection(this->to_type_, gogo, ret);
3880 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3882 ret->push_back('p');
3883 this->append_mangled_name(this->to_type_, gogo, ret);
3889 Pointer_type::do_export(Export* exp) const
3891 exp->write_c_string("*");
3892 if (this->is_unsafe_pointer_type())
3893 exp->write_c_string("any");
3895 exp->write_type(this->to_type_);
3901 Pointer_type::do_import(Import* imp)
3903 imp->require_c_string("*");
3904 if (imp->match_c_string("any"))
3907 return Type::make_pointer_type(Type::make_void_type());
3909 Type* to = imp->read_type();
3910 return Type::make_pointer_type(to);
3913 // Make a pointer type.
3916 Type::make_pointer_type(Type* to_type)
3918 typedef Unordered_map(Type*, Pointer_type*) Hashtable;
3919 static Hashtable pointer_types;
3920 Hashtable::const_iterator p = pointer_types.find(to_type);
3921 if (p != pointer_types.end())
3923 Pointer_type* ret = new Pointer_type(to_type);
3924 pointer_types[to_type] = ret;
3928 // The nil type. We use a special type for nil because it is not the
3929 // same as any other type. In C term nil has type void*, but there is
3930 // no such type in Go.
3932 class Nil_type : public Type
3941 do_compare_is_identity(Gogo*) const
3945 do_get_backend(Gogo* gogo)
3946 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
3949 do_type_descriptor(Gogo*, Named_type*)
3950 { go_unreachable(); }
3953 do_reflection(Gogo*, std::string*) const
3954 { go_unreachable(); }
3957 do_mangled_name(Gogo*, std::string* ret) const
3958 { ret->push_back('n'); }
3961 // Make the nil type.
3964 Type::make_nil_type()
3966 static Nil_type singleton_nil_type;
3967 return &singleton_nil_type;
3970 // The type of a function call which returns multiple values. This is
3971 // really a struct, but we don't want to confuse a function call which
3972 // returns a struct with a function call which returns multiple
3975 class Call_multiple_result_type : public Type
3978 Call_multiple_result_type(Call_expression* call)
3979 : Type(TYPE_CALL_MULTIPLE_RESULT),
3985 do_has_pointer() const
3987 go_assert(saw_errors());
3992 do_compare_is_identity(Gogo*) const
3996 do_get_backend(Gogo* gogo)
3998 go_assert(saw_errors());
3999 return gogo->backend()->error_type();
4003 do_type_descriptor(Gogo*, Named_type*)
4005 go_assert(saw_errors());
4006 return Expression::make_error(Linemap::unknown_location());
4010 do_reflection(Gogo*, std::string*) const
4011 { go_assert(saw_errors()); }
4014 do_mangled_name(Gogo*, std::string*) const
4015 { go_assert(saw_errors()); }
4018 // The expression being called.
4019 Call_expression* call_;
4022 // Make a call result type.
4025 Type::make_call_multiple_result_type(Call_expression* call)
4027 return new Call_multiple_result_type(call);
4030 // Class Struct_field.
4032 // Get the name of a field.
4035 Struct_field::field_name() const
4037 const std::string& name(this->typed_identifier_.name());
4042 // This is called during parsing, before anything is lowered, so
4043 // we have to be pretty careful to avoid dereferencing an
4044 // unknown type name.
4045 Type* t = this->typed_identifier_.type();
4047 if (t->classification() == Type::TYPE_POINTER)
4050 Pointer_type* ptype = static_cast<Pointer_type*>(t);
4051 dt = ptype->points_to();
4053 if (dt->forward_declaration_type() != NULL)
4054 return dt->forward_declaration_type()->name();
4055 else if (dt->named_type() != NULL)
4056 return dt->named_type()->name();
4057 else if (t->is_error_type() || dt->is_error_type())
4059 static const std::string error_string = "*error*";
4060 return error_string;
4064 // Avoid crashing in the erroneous case where T is named but
4067 if (t->forward_declaration_type() != NULL)
4068 return t->forward_declaration_type()->name();
4069 else if (t->named_type() != NULL)
4070 return t->named_type()->name();
4077 // Return whether this field is named NAME.
4080 Struct_field::is_field_name(const std::string& name) const
4082 const std::string& me(this->typed_identifier_.name());
4087 Type* t = this->typed_identifier_.type();
4088 if (t->points_to() != NULL)
4090 Named_type* nt = t->named_type();
4091 if (nt != NULL && nt->name() == name)
4094 // This is a horrible hack caused by the fact that we don't pack
4095 // the names of builtin types. FIXME.
4098 && nt->name() == Gogo::unpack_hidden_name(name))
4105 // Class Struct_type.
4110 Struct_type::do_traverse(Traverse* traverse)
4112 Struct_field_list* fields = this->fields_;
4115 for (Struct_field_list::iterator p = fields->begin();
4119 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
4120 return TRAVERSE_EXIT;
4123 return TRAVERSE_CONTINUE;
4126 // Verify that the struct type is complete and valid.
4129 Struct_type::do_verify()
4131 Struct_field_list* fields = this->fields_;
4134 for (Struct_field_list::iterator p = fields->begin();
4138 Type* t = p->type();
4139 if (t->is_undefined())
4141 error_at(p->location(), "struct field type is incomplete");
4142 p->set_type(Type::make_error_type());
4144 else if (p->is_anonymous())
4146 if (t->named_type() != NULL && t->points_to() != NULL)
4148 error_at(p->location(), "embedded type may not be a pointer");
4149 p->set_type(Type::make_error_type());
4151 else if (t->points_to() != NULL
4152 && t->points_to()->interface_type() != NULL)
4154 error_at(p->location(),
4155 "embedded type may not be pointer to interface");
4156 p->set_type(Type::make_error_type());
4163 // Whether this contains a pointer.
4166 Struct_type::do_has_pointer() const
4168 const Struct_field_list* fields = this->fields();
4171 for (Struct_field_list::const_iterator p = fields->begin();
4175 if (p->type()->has_pointer())
4181 // Whether this type is identical to T.
4184 Struct_type::is_identical(const Struct_type* t,
4185 bool errors_are_identical) const
4187 const Struct_field_list* fields1 = this->fields();
4188 const Struct_field_list* fields2 = t->fields();
4189 if (fields1 == NULL || fields2 == NULL)
4190 return fields1 == fields2;
4191 Struct_field_list::const_iterator pf2 = fields2->begin();
4192 for (Struct_field_list::const_iterator pf1 = fields1->begin();
4193 pf1 != fields1->end();
4196 if (pf2 == fields2->end())
4198 if (pf1->field_name() != pf2->field_name())
4200 if (pf1->is_anonymous() != pf2->is_anonymous()
4201 || !Type::are_identical(pf1->type(), pf2->type(),
4202 errors_are_identical, NULL))
4204 if (!pf1->has_tag())
4211 if (!pf2->has_tag())
4213 if (pf1->tag() != pf2->tag())
4217 if (pf2 != fields2->end())
4222 // Whether this struct type has any hidden fields.
4225 Struct_type::struct_has_hidden_fields(const Named_type* within,
4226 std::string* reason) const
4228 const Struct_field_list* fields = this->fields();
4231 const Package* within_package = (within == NULL
4233 : within->named_object()->package());
4234 for (Struct_field_list::const_iterator pf = fields->begin();
4235 pf != fields->end();
4238 if (within_package != NULL
4239 && !pf->is_anonymous()
4240 && Gogo::is_hidden_name(pf->field_name()))
4244 std::string within_name = within->named_object()->message_name();
4245 std::string name = Gogo::message_name(pf->field_name());
4246 size_t bufsize = 200 + within_name.length() + name.length();
4247 char* buf = new char[bufsize];
4248 snprintf(buf, bufsize,
4249 _("implicit assignment of %s%s%s hidden field %s%s%s"),
4250 open_quote, within_name.c_str(), close_quote,
4251 open_quote, name.c_str(), close_quote);
4252 reason->assign(buf);
4258 if (pf->type()->has_hidden_fields(within, reason))
4265 // Whether comparisons of this struct type are simple identity
4269 Struct_type::do_compare_is_identity(Gogo* gogo) const
4271 const Struct_field_list* fields = this->fields_;
4274 unsigned int offset = 0;
4275 for (Struct_field_list::const_iterator pf = fields->begin();
4276 pf != fields->end();
4279 if (!pf->type()->compare_is_identity(gogo))
4282 unsigned int field_align;
4283 if (!pf->type()->backend_type_align(gogo, &field_align))
4285 if ((offset & (field_align - 1)) != 0)
4287 // This struct has padding. We don't guarantee that that
4288 // padding is zero-initialized for a stack variable, so we
4289 // can't use memcmp to compare struct values.
4293 unsigned int field_size;
4294 if (!pf->type()->backend_type_size(gogo, &field_size))
4296 offset += field_size;
4301 // Build identity and hash functions for this struct.
4306 Struct_type::do_hash_for_method(Gogo* gogo) const
4308 unsigned int ret = 0;
4309 if (this->fields() != NULL)
4311 for (Struct_field_list::const_iterator pf = this->fields()->begin();
4312 pf != this->fields()->end();
4314 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
4319 // Find the local field NAME.
4322 Struct_type::find_local_field(const std::string& name,
4323 unsigned int *pindex) const
4325 const Struct_field_list* fields = this->fields_;
4329 for (Struct_field_list::const_iterator pf = fields->begin();
4330 pf != fields->end();
4333 if (pf->is_field_name(name))
4343 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
4345 Field_reference_expression*
4346 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
4347 Location location) const
4350 return this->field_reference_depth(struct_expr, name, location, NULL,
4354 // Return an expression for a field, along with the depth at which it
4357 Field_reference_expression*
4358 Struct_type::field_reference_depth(Expression* struct_expr,
4359 const std::string& name,
4361 Saw_named_type* saw,
4362 unsigned int* depth) const
4364 const Struct_field_list* fields = this->fields_;
4368 // Look for a field with this name.
4370 for (Struct_field_list::const_iterator pf = fields->begin();
4371 pf != fields->end();
4374 if (pf->is_field_name(name))
4377 return Expression::make_field_reference(struct_expr, i, location);
4381 // Look for an anonymous field which contains a field with this
4383 unsigned int found_depth = 0;
4384 Field_reference_expression* ret = NULL;
4386 for (Struct_field_list::const_iterator pf = fields->begin();
4387 pf != fields->end();
4390 if (!pf->is_anonymous())
4393 Struct_type* st = pf->type()->deref()->struct_type();
4397 Saw_named_type* hold_saw = saw;
4398 Saw_named_type saw_here;
4399 Named_type* nt = pf->type()->named_type();
4401 nt = pf->type()->deref()->named_type();
4405 for (q = saw; q != NULL; q = q->next)
4409 // If this is an error, it will be reported
4416 saw_here.next = saw;
4421 // Look for a reference using a NULL struct expression. If we
4422 // find one, fill in the struct expression with a reference to
4424 unsigned int subdepth;
4425 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
4435 if (ret == NULL || subdepth < found_depth)
4440 found_depth = subdepth;
4441 Expression* here = Expression::make_field_reference(struct_expr, i,
4443 if (pf->type()->points_to() != NULL)
4444 here = Expression::make_unary(OPERATOR_MULT, here, location);
4445 while (sub->expr() != NULL)
4447 sub = sub->expr()->deref()->field_reference_expression();
4448 go_assert(sub != NULL);
4450 sub->set_struct_expression(here);
4452 else if (subdepth > found_depth)
4456 // We do not handle ambiguity here--it should be handled by
4457 // Type::bind_field_or_method.
4465 *depth = found_depth + 1;
4470 // Return the total number of fields, including embedded fields.
4473 Struct_type::total_field_count() const
4475 if (this->fields_ == NULL)
4477 unsigned int ret = 0;
4478 for (Struct_field_list::const_iterator pf = this->fields_->begin();
4479 pf != this->fields_->end();
4482 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
4485 ret += pf->type()->struct_type()->total_field_count();
4490 // Return whether NAME is an unexported field, for better error reporting.
4493 Struct_type::is_unexported_local_field(Gogo* gogo,
4494 const std::string& name) const
4496 const Struct_field_list* fields = this->fields_;
4499 for (Struct_field_list::const_iterator pf = fields->begin();
4500 pf != fields->end();
4503 const std::string& field_name(pf->field_name());
4504 if (Gogo::is_hidden_name(field_name)
4505 && name == Gogo::unpack_hidden_name(field_name)
4506 && gogo->pack_hidden_name(name, false) != field_name)
4513 // Finalize the methods of an unnamed struct.
4516 Struct_type::finalize_methods(Gogo* gogo)
4518 if (this->all_methods_ != NULL)
4520 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
4523 // Return the method NAME, or NULL if there isn't one or if it is
4524 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
4528 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
4530 return Type::method_function(this->all_methods_, name, is_ambiguous);
4533 // Convert struct fields to the backend representation. This is not
4534 // declared in types.h so that types.h doesn't have to #include
4538 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
4539 bool use_placeholder,
4540 std::vector<Backend::Btyped_identifier>* bfields)
4542 bfields->resize(fields->size());
4544 for (Struct_field_list::const_iterator p = fields->begin();
4548 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
4549 (*bfields)[i].btype = (use_placeholder
4550 ? p->type()->get_backend_placeholder(gogo)
4551 : p->type()->get_backend(gogo));
4552 (*bfields)[i].location = p->location();
4554 go_assert(i == fields->size());
4557 // Get the tree for a struct type.
4560 Struct_type::do_get_backend(Gogo* gogo)
4562 std::vector<Backend::Btyped_identifier> bfields;
4563 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
4564 return gogo->backend()->struct_type(bfields);
4567 // Finish the backend representation of the fields of a struct.
4570 Struct_type::finish_backend_fields(Gogo* gogo)
4572 const Struct_field_list* fields = this->fields_;
4575 for (Struct_field_list::const_iterator p = fields->begin();
4578 p->type()->get_backend(gogo);
4582 // The type of a struct type descriptor.
4585 Struct_type::make_struct_type_descriptor_type()
4590 Type* tdt = Type::make_type_descriptor_type();
4591 Type* ptdt = Type::make_type_descriptor_ptr_type();
4593 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4594 Type* string_type = Type::lookup_string_type();
4595 Type* pointer_string_type = Type::make_pointer_type(string_type);
4598 Type::make_builtin_struct_type(5,
4599 "name", pointer_string_type,
4600 "pkgPath", pointer_string_type,
4602 "tag", pointer_string_type,
4603 "offset", uintptr_type);
4604 Type* nsf = Type::make_builtin_named_type("structField", sf);
4606 Type* slice_type = Type::make_array_type(nsf, NULL);
4608 Struct_type* s = Type::make_builtin_struct_type(2,
4610 "fields", slice_type);
4612 ret = Type::make_builtin_named_type("StructType", s);
4618 // Build a type descriptor for a struct type.
4621 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4623 Location bloc = Linemap::predeclared_location();
4625 Type* stdt = Struct_type::make_struct_type_descriptor_type();
4627 const Struct_field_list* fields = stdt->struct_type()->fields();
4629 Expression_list* vals = new Expression_list();
4632 const Methods* methods = this->methods();
4633 // A named struct should not have methods--the methods should attach
4634 // to the named type.
4635 go_assert(methods == NULL || name == NULL);
4637 Struct_field_list::const_iterator ps = fields->begin();
4638 go_assert(ps->is_field_name("commonType"));
4639 vals->push_back(this->type_descriptor_constructor(gogo,
4640 RUNTIME_TYPE_KIND_STRUCT,
4641 name, methods, true));
4644 go_assert(ps->is_field_name("fields"));
4646 Expression_list* elements = new Expression_list();
4647 elements->reserve(this->fields_->size());
4648 Type* element_type = ps->type()->array_type()->element_type();
4649 for (Struct_field_list::const_iterator pf = this->fields_->begin();
4650 pf != this->fields_->end();
4653 const Struct_field_list* f = element_type->struct_type()->fields();
4655 Expression_list* fvals = new Expression_list();
4658 Struct_field_list::const_iterator q = f->begin();
4659 go_assert(q->is_field_name("name"));
4660 if (pf->is_anonymous())
4661 fvals->push_back(Expression::make_nil(bloc));
4664 std::string n = Gogo::unpack_hidden_name(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("pkgPath"));
4671 if (!Gogo::is_hidden_name(pf->field_name()))
4672 fvals->push_back(Expression::make_nil(bloc));
4675 std::string n = Gogo::hidden_name_pkgpath(pf->field_name());
4676 Expression* s = Expression::make_string(n, bloc);
4677 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4681 go_assert(q->is_field_name("typ"));
4682 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
4685 go_assert(q->is_field_name("tag"));
4687 fvals->push_back(Expression::make_nil(bloc));
4690 Expression* s = Expression::make_string(pf->tag(), bloc);
4691 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4695 go_assert(q->is_field_name("offset"));
4696 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
4698 Expression* v = Expression::make_struct_composite_literal(element_type,
4700 elements->push_back(v);
4703 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
4706 return Expression::make_struct_composite_literal(stdt, vals, bloc);
4709 // Write the hash function for a struct which can not use the identity
4713 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
4714 Function_type* hash_fntype,
4715 Function_type* equal_fntype)
4717 Location bloc = Linemap::predeclared_location();
4719 // The pointer to the struct that we are going to hash. This is an
4720 // argument to the hash function we are implementing here.
4721 Named_object* key_arg = gogo->lookup("key", NULL);
4722 go_assert(key_arg != NULL);
4723 Type* key_arg_type = key_arg->var_value()->type();
4725 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4729 mpz_init_set_ui(ival, 0);
4730 Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
4733 // Make a temporary to hold the return value, initialized to 0.
4734 Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
4736 gogo->add_statement(retval);
4738 // Make a temporary to hold the key as a uintptr.
4739 Expression* ref = Expression::make_var_reference(key_arg, bloc);
4740 ref = Expression::make_cast(uintptr_type, ref, bloc);
4741 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
4743 gogo->add_statement(key);
4745 // Loop over the struct fields.
4747 const Struct_field_list* fields = this->fields_;
4748 for (Struct_field_list::const_iterator pf = fields->begin();
4749 pf != fields->end();
4756 // Multiply retval by 33.
4757 mpz_init_set_ui(ival, 33);
4758 Expression* i33 = Expression::make_integer(&ival, uintptr_type,
4762 ref = Expression::make_temporary_reference(retval, bloc);
4763 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ,
4765 gogo->add_statement(s);
4768 // Get a pointer to the value of this field.
4769 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
4770 ref = Expression::make_temporary_reference(key, bloc);
4771 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
4773 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
4775 // Get the size of this field.
4776 Expression* size = Expression::make_type_info(pf->type(),
4777 Expression::TYPE_INFO_SIZE);
4779 // Get the hash function to use for the type of this field.
4780 Named_object* hash_fn;
4781 Named_object* equal_fn;
4782 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
4783 equal_fntype, &hash_fn, &equal_fn);
4785 // Call the hash function for the field.
4786 Expression_list* args = new Expression_list();
4787 args->push_back(subkey);
4788 args->push_back(size);
4789 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
4790 Expression* call = Expression::make_call(func, args, false, bloc);
4792 // Add the field's hash value to retval.
4793 Temporary_reference_expression* tref =
4794 Expression::make_temporary_reference(retval, bloc);
4795 tref->set_is_lvalue();
4796 Statement* s = Statement::make_assignment_operation(OPERATOR_PLUSEQ,
4798 gogo->add_statement(s);
4801 // Return retval to the caller of the hash function.
4802 Expression_list* vals = new Expression_list();
4803 ref = Expression::make_temporary_reference(retval, bloc);
4804 vals->push_back(ref);
4805 Statement* s = Statement::make_return_statement(vals, bloc);
4806 gogo->add_statement(s);
4809 // Write the equality function for a struct which can not use the
4810 // identity function.
4813 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
4815 Location bloc = Linemap::predeclared_location();
4817 // The pointers to the structs we are going to compare.
4818 Named_object* key1_arg = gogo->lookup("key1", NULL);
4819 Named_object* key2_arg = gogo->lookup("key2", NULL);
4820 go_assert(key1_arg != NULL && key2_arg != NULL);
4822 // Build temporaries with the right types.
4823 Type* pt = Type::make_pointer_type(name != NULL
4824 ? static_cast<Type*>(name)
4825 : static_cast<Type*>(this));
4827 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
4828 ref = Expression::make_unsafe_cast(pt, ref, bloc);
4829 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
4830 gogo->add_statement(p1);
4832 ref = Expression::make_var_reference(key2_arg, bloc);
4833 ref = Expression::make_unsafe_cast(pt, ref, bloc);
4834 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
4835 gogo->add_statement(p2);
4837 const Struct_field_list* fields = this->fields_;
4838 unsigned int field_index = 0;
4839 for (Struct_field_list::const_iterator pf = fields->begin();
4840 pf != fields->end();
4841 ++pf, ++field_index)
4843 // Compare one field in both P1 and P2.
4844 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
4845 f1 = Expression::make_unary(OPERATOR_MULT, f1, bloc);
4846 f1 = Expression::make_field_reference(f1, field_index, bloc);
4848 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
4849 f2 = Expression::make_unary(OPERATOR_MULT, f2, bloc);
4850 f2 = Expression::make_field_reference(f2, field_index, bloc);
4852 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
4854 // If the values are not equal, return false.
4855 gogo->start_block(bloc);
4856 Expression_list* vals = new Expression_list();
4857 vals->push_back(Expression::make_boolean(false, bloc));
4858 Statement* s = Statement::make_return_statement(vals, bloc);
4859 gogo->add_statement(s);
4860 Block* then_block = gogo->finish_block(bloc);
4862 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
4863 gogo->add_statement(s);
4866 // All the fields are equal, so return true.
4867 Expression_list* vals = new Expression_list();
4868 vals->push_back(Expression::make_boolean(true, bloc));
4869 Statement* s = Statement::make_return_statement(vals, bloc);
4870 gogo->add_statement(s);
4873 // Reflection string.
4876 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
4878 ret->append("struct { ");
4880 for (Struct_field_list::const_iterator p = this->fields_->begin();
4881 p != this->fields_->end();
4884 if (p != this->fields_->begin())
4886 if (p->is_anonymous())
4887 ret->push_back('?');
4889 ret->append(Gogo::unpack_hidden_name(p->field_name()));
4890 ret->push_back(' ');
4891 this->append_reflection(p->type(), gogo, ret);
4895 const std::string& tag(p->tag());
4897 for (std::string::const_iterator p = tag.begin();
4902 ret->append("\\x00");
4903 else if (*p == '\n')
4905 else if (*p == '\t')
4908 ret->append("\\\"");
4909 else if (*p == '\\')
4910 ret->append("\\\\");
4914 ret->push_back('"');
4924 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4926 ret->push_back('S');
4928 const Struct_field_list* fields = this->fields_;
4931 for (Struct_field_list::const_iterator p = fields->begin();
4935 if (p->is_anonymous())
4939 std::string n = Gogo::unpack_hidden_name(p->field_name());
4941 snprintf(buf, sizeof buf, "%u_",
4942 static_cast<unsigned int>(n.length()));
4946 this->append_mangled_name(p->type(), gogo, ret);
4949 const std::string& tag(p->tag());
4951 for (std::string::const_iterator p = tag.begin();
4955 if (ISALNUM(*p) || *p == '_')
4960 snprintf(buf, sizeof buf, ".%x.",
4961 static_cast<unsigned int>(*p));
4966 snprintf(buf, sizeof buf, "T%u_",
4967 static_cast<unsigned int>(out.length()));
4974 ret->push_back('e');
4977 // If the offset of field INDEX in the backend implementation can be
4978 // determined, set *POFFSET to the offset in bytes and return true.
4979 // Otherwise, return false.
4982 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
4983 unsigned int* poffset)
4985 if (!this->is_backend_type_size_known(gogo))
4987 Btype* bt = this->get_backend_placeholder(gogo);
4988 size_t offset = gogo->backend()->type_field_offset(bt, index);
4989 *poffset = static_cast<unsigned int>(offset);
4990 if (*poffset != offset)
4998 Struct_type::do_export(Export* exp) const
5000 exp->write_c_string("struct { ");
5001 const Struct_field_list* fields = this->fields_;
5002 go_assert(fields != NULL);
5003 for (Struct_field_list::const_iterator p = fields->begin();
5007 if (p->is_anonymous())
5008 exp->write_string("? ");
5011 exp->write_string(p->field_name());
5012 exp->write_c_string(" ");
5014 exp->write_type(p->type());
5018 exp->write_c_string(" ");
5020 Expression::make_string(p->tag(), Linemap::predeclared_location());
5021 expr->export_expression(exp);
5025 exp->write_c_string("; ");
5027 exp->write_c_string("}");
5033 Struct_type::do_import(Import* imp)
5035 imp->require_c_string("struct { ");
5036 Struct_field_list* fields = new Struct_field_list;
5037 if (imp->peek_char() != '}')
5042 if (imp->match_c_string("? "))
5046 name = imp->read_identifier();
5047 imp->require_c_string(" ");
5049 Type* ftype = imp->read_type();
5051 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
5053 if (imp->peek_char() == ' ')
5056 Expression* expr = Expression::import_expression(imp);
5057 String_expression* sexpr = expr->string_expression();
5058 go_assert(sexpr != NULL);
5059 sf.set_tag(sexpr->val());
5063 imp->require_c_string("; ");
5064 fields->push_back(sf);
5065 if (imp->peek_char() == '}')
5069 imp->require_c_string("}");
5071 return Type::make_struct_type(fields, imp->location());
5074 // Make a struct type.
5077 Type::make_struct_type(Struct_field_list* fields,
5080 return new Struct_type(fields, location);
5083 // Class Array_type.
5085 // Whether two array types are identical.
5088 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
5090 if (!Type::are_identical(this->element_type(), t->element_type(),
5091 errors_are_identical, NULL))
5094 Expression* l1 = this->length();
5095 Expression* l2 = t->length();
5097 // Slices of the same element type are identical.
5098 if (l1 == NULL && l2 == NULL)
5101 // Arrays of the same element type are identical if they have the
5103 if (l1 != NULL && l2 != NULL)
5108 // Try to determine the lengths. If we can't, assume the arrays
5109 // are not identical.
5111 Numeric_constant nc1, nc2;
5112 if (l1->numeric_constant_value(&nc1)
5113 && l2->numeric_constant_value(&nc2))
5116 if (nc1.to_int(&v1))
5119 if (nc2.to_int(&v2))
5121 ret = mpz_cmp(v1, v2) == 0;
5130 // Otherwise the arrays are not identical.
5137 Array_type::do_traverse(Traverse* traverse)
5139 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
5140 return TRAVERSE_EXIT;
5141 if (this->length_ != NULL
5142 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
5143 return TRAVERSE_EXIT;
5144 return TRAVERSE_CONTINUE;
5147 // Check that the length is valid.
5150 Array_type::verify_length()
5152 if (this->length_ == NULL)
5155 Type_context context(Type::lookup_integer_type("int"), false);
5156 this->length_->determine_type(&context);
5158 if (!this->length_->is_constant())
5160 error_at(this->length_->location(), "array bound is not constant");
5164 Numeric_constant nc;
5165 if (!this->length_->numeric_constant_value(&nc))
5167 if (this->length_->type()->integer_type() != NULL
5168 || this->length_->type()->float_type() != NULL)
5169 error_at(this->length_->location(), "array bound is not constant");
5171 error_at(this->length_->location(), "array bound is not numeric");
5176 switch (nc.to_unsigned_long(&val))
5178 case Numeric_constant::NC_UL_VALID:
5180 case Numeric_constant::NC_UL_NOTINT:
5181 error_at(this->length_->location(), "array bound truncated to integer");
5183 case Numeric_constant::NC_UL_NEGATIVE:
5184 error_at(this->length_->location(), "negative array bound");
5186 case Numeric_constant::NC_UL_BIG:
5187 error_at(this->length_->location(), "array bound overflows");
5193 Type* int_type = Type::lookup_integer_type("int");
5194 unsigned int tbits = int_type->integer_type()->bits();
5195 if (sizeof(val) <= tbits * 8
5196 && val >> (tbits - 1) != 0)
5198 error_at(this->length_->location(), "array bound overflows");
5208 Array_type::do_verify()
5210 if (!this->verify_length())
5211 this->length_ = Expression::make_error(this->length_->location());
5215 // Whether we can use memcmp to compare this array.
5218 Array_type::do_compare_is_identity(Gogo* gogo) const
5220 if (this->length_ == NULL)
5223 // Check for [...], which indicates that this is not a real type.
5224 if (this->length_->is_nil_expression())
5227 if (!this->element_type_->compare_is_identity(gogo))
5230 // If there is any padding, then we can't use memcmp.
5233 if (!this->element_type_->backend_type_size(gogo, &size)
5234 || !this->element_type_->backend_type_align(gogo, &align))
5236 if ((size & (align - 1)) != 0)
5242 // Array type hash code.
5245 Array_type::do_hash_for_method(Gogo* gogo) const
5247 // There is no very convenient way to get a hash code for the
5249 return this->element_type_->hash_for_method(gogo) + 1;
5252 // Write the hash function for an array which can not use the identify
5256 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
5257 Function_type* hash_fntype,
5258 Function_type* equal_fntype)
5260 Location bloc = Linemap::predeclared_location();
5262 // The pointer to the array that we are going to hash. This is an
5263 // argument to the hash function we are implementing here.
5264 Named_object* key_arg = gogo->lookup("key", NULL);
5265 go_assert(key_arg != NULL);
5266 Type* key_arg_type = key_arg->var_value()->type();
5268 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5272 mpz_init_set_ui(ival, 0);
5273 Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
5276 // Make a temporary to hold the return value, initialized to 0.
5277 Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
5279 gogo->add_statement(retval);
5281 // Make a temporary to hold the key as a uintptr.
5282 Expression* ref = Expression::make_var_reference(key_arg, bloc);
5283 ref = Expression::make_cast(uintptr_type, ref, bloc);
5284 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
5286 gogo->add_statement(key);
5288 // Loop over the array elements.
5290 Type* int_type = Type::lookup_integer_type("int");
5291 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
5292 gogo->add_statement(index);
5294 Expression* iref = Expression::make_temporary_reference(index, bloc);
5295 Expression* aref = Expression::make_var_reference(key_arg, bloc);
5296 Type* pt = Type::make_pointer_type(name != NULL
5297 ? static_cast<Type*>(name)
5298 : static_cast<Type*>(this));
5299 aref = Expression::make_cast(pt, aref, bloc);
5300 For_range_statement* for_range = Statement::make_for_range_statement(iref,
5305 gogo->start_block(bloc);
5307 // Multiply retval by 33.
5308 mpz_init_set_ui(ival, 33);
5309 Expression* i33 = Expression::make_integer(&ival, uintptr_type, bloc);
5312 ref = Expression::make_temporary_reference(retval, bloc);
5313 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ, ref,
5315 gogo->add_statement(s);
5317 // Get the hash function for the element type.
5318 Named_object* hash_fn;
5319 Named_object* equal_fn;
5320 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
5321 hash_fntype, equal_fntype, &hash_fn,
5324 // Get a pointer to this element in the loop.
5325 Expression* subkey = Expression::make_temporary_reference(key, bloc);
5326 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
5328 // Get the size of each element.
5329 Expression* ele_size = Expression::make_type_info(this->element_type_,
5330 Expression::TYPE_INFO_SIZE);
5332 // Get the hash of this element.
5333 Expression_list* args = new Expression_list();
5334 args->push_back(subkey);
5335 args->push_back(ele_size);
5336 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
5337 Expression* call = Expression::make_call(func, args, false, bloc);
5339 // Add the element's hash value to retval.
5340 Temporary_reference_expression* tref =
5341 Expression::make_temporary_reference(retval, bloc);
5342 tref->set_is_lvalue();
5343 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, call, bloc);
5344 gogo->add_statement(s);
5346 // Increase the element pointer.
5347 tref = Expression::make_temporary_reference(key, bloc);
5348 tref->set_is_lvalue();
5349 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
5352 Block* statements = gogo->finish_block(bloc);
5354 for_range->add_statements(statements);
5355 gogo->add_statement(for_range);
5357 // Return retval to the caller of the hash function.
5358 Expression_list* vals = new Expression_list();
5359 ref = Expression::make_temporary_reference(retval, bloc);
5360 vals->push_back(ref);
5361 s = Statement::make_return_statement(vals, bloc);
5362 gogo->add_statement(s);
5365 // Write the equality function for an array which can not use the
5366 // identity function.
5369 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
5371 Location bloc = Linemap::predeclared_location();
5373 // The pointers to the arrays we are going to compare.
5374 Named_object* key1_arg = gogo->lookup("key1", NULL);
5375 Named_object* key2_arg = gogo->lookup("key2", NULL);
5376 go_assert(key1_arg != NULL && key2_arg != NULL);
5378 // Build temporaries for the keys with the right types.
5379 Type* pt = Type::make_pointer_type(name != NULL
5380 ? static_cast<Type*>(name)
5381 : static_cast<Type*>(this));
5383 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
5384 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5385 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
5386 gogo->add_statement(p1);
5388 ref = Expression::make_var_reference(key2_arg, bloc);
5389 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5390 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
5391 gogo->add_statement(p2);
5393 // Loop over the array elements.
5395 Type* int_type = Type::lookup_integer_type("int");
5396 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
5397 gogo->add_statement(index);
5399 Expression* iref = Expression::make_temporary_reference(index, bloc);
5400 Expression* aref = Expression::make_temporary_reference(p1, bloc);
5401 For_range_statement* for_range = Statement::make_for_range_statement(iref,
5406 gogo->start_block(bloc);
5408 // Compare element in P1 and P2.
5409 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
5410 e1 = Expression::make_unary(OPERATOR_MULT, e1, bloc);
5411 ref = Expression::make_temporary_reference(index, bloc);
5412 e1 = Expression::make_array_index(e1, ref, NULL, bloc);
5414 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
5415 e2 = Expression::make_unary(OPERATOR_MULT, e2, bloc);
5416 ref = Expression::make_temporary_reference(index, bloc);
5417 e2 = Expression::make_array_index(e2, ref, NULL, bloc);
5419 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
5421 // If the elements are not equal, return false.
5422 gogo->start_block(bloc);
5423 Expression_list* vals = new Expression_list();
5424 vals->push_back(Expression::make_boolean(false, bloc));
5425 Statement* s = Statement::make_return_statement(vals, bloc);
5426 gogo->add_statement(s);
5427 Block* then_block = gogo->finish_block(bloc);
5429 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
5430 gogo->add_statement(s);
5432 Block* statements = gogo->finish_block(bloc);
5434 for_range->add_statements(statements);
5435 gogo->add_statement(for_range);
5437 // All the elements are equal, so return true.
5438 vals = new Expression_list();
5439 vals->push_back(Expression::make_boolean(true, bloc));
5440 s = Statement::make_return_statement(vals, bloc);
5441 gogo->add_statement(s);
5444 // Get a tree for the length of a fixed array. The length may be
5445 // computed using a function call, so we must only evaluate it once.
5448 Array_type::get_length_tree(Gogo* gogo)
5450 go_assert(this->length_ != NULL);
5451 if (this->length_tree_ == NULL_TREE)
5453 Numeric_constant nc;
5455 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
5457 if (mpz_sgn(val) < 0)
5459 this->length_tree_ = error_mark_node;
5460 return this->length_tree_;
5462 Type* t = nc.type();
5464 t = Type::lookup_integer_type("int");
5465 else if (t->is_abstract())
5466 t = t->make_non_abstract_type();
5467 tree tt = type_to_tree(t->get_backend(gogo));
5468 this->length_tree_ = Expression::integer_constant_tree(val, tt);
5473 // Make up a translation context for the array length
5474 // expression. FIXME: This won't work in general.
5475 Translate_context context(gogo, NULL, NULL, NULL);
5476 tree len = this->length_->get_tree(&context);
5477 if (len != error_mark_node)
5479 len = convert_to_integer(integer_type_node, len);
5480 len = save_expr(len);
5482 this->length_tree_ = len;
5485 return this->length_tree_;
5488 // Get the backend representation of the fields of a slice. This is
5489 // not declared in types.h so that types.h doesn't have to #include
5492 // We use int for the count and capacity fields. This matches 6g.
5493 // The language more or less assumes that we can't allocate space of a
5494 // size which does not fit in int.
5497 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
5498 std::vector<Backend::Btyped_identifier>* bfields)
5502 Type* pet = Type::make_pointer_type(type->element_type());
5503 Btype* pbet = (use_placeholder
5504 ? pet->get_backend_placeholder(gogo)
5505 : pet->get_backend(gogo));
5506 Location ploc = Linemap::predeclared_location();
5508 Backend::Btyped_identifier* p = &(*bfields)[0];
5509 p->name = "__values";
5513 Type* int_type = Type::lookup_integer_type("int");
5516 p->name = "__count";
5517 p->btype = int_type->get_backend(gogo);
5521 p->name = "__capacity";
5522 p->btype = int_type->get_backend(gogo);
5526 // Get a tree for the type of this array. A fixed array is simply
5527 // represented as ARRAY_TYPE with the appropriate index--i.e., it is
5528 // just like an array in C. An open array is a struct with three
5529 // fields: a data pointer, the length, and the capacity.
5532 Array_type::do_get_backend(Gogo* gogo)
5534 if (this->length_ == NULL)
5536 std::vector<Backend::Btyped_identifier> bfields;
5537 get_backend_slice_fields(gogo, this, false, &bfields);
5538 return gogo->backend()->struct_type(bfields);
5542 Btype* element = this->get_backend_element(gogo, false);
5543 Bexpression* len = this->get_backend_length(gogo);
5544 return gogo->backend()->array_type(element, len);
5548 // Return the backend representation of the element type.
5551 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
5553 if (use_placeholder)
5554 return this->element_type_->get_backend_placeholder(gogo);
5556 return this->element_type_->get_backend(gogo);
5559 // Return the backend representation of the length.
5562 Array_type::get_backend_length(Gogo* gogo)
5564 return tree_to_expr(this->get_length_tree(gogo));
5567 // Finish backend representation of the array.
5570 Array_type::finish_backend_element(Gogo* gogo)
5572 Type* et = this->array_type()->element_type();
5573 et->get_backend(gogo);
5574 if (this->is_slice_type())
5576 // This relies on the fact that we always use the same
5577 // structure for a pointer to any given type.
5578 Type* pet = Type::make_pointer_type(et);
5579 pet->get_backend(gogo);
5583 // Return a tree for a pointer to the values in ARRAY.
5586 Array_type::value_pointer_tree(Gogo*, tree array) const
5589 if (this->length() != NULL)
5592 ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))),
5593 build_fold_addr_expr(array));
5598 tree field = TYPE_FIELDS(TREE_TYPE(array));
5599 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
5601 ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field,
5604 if (TREE_CONSTANT(array))
5605 TREE_CONSTANT(ret) = 1;
5609 // Return a tree for the length of the array ARRAY which has this
5613 Array_type::length_tree(Gogo* gogo, tree array)
5615 if (this->length_ != NULL)
5617 if (TREE_CODE(array) == SAVE_EXPR)
5618 return fold_convert(integer_type_node, this->get_length_tree(gogo));
5620 return omit_one_operand(integer_type_node,
5621 this->get_length_tree(gogo), array);
5624 // This is an open array. We need to read the length field.
5626 tree type = TREE_TYPE(array);
5627 go_assert(TREE_CODE(type) == RECORD_TYPE);
5629 tree field = DECL_CHAIN(TYPE_FIELDS(type));
5630 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
5632 tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
5633 if (TREE_CONSTANT(array))
5634 TREE_CONSTANT(ret) = 1;
5638 // Return a tree for the capacity of the array ARRAY which has this
5642 Array_type::capacity_tree(Gogo* gogo, tree array)
5644 if (this->length_ != NULL)
5645 return omit_one_operand(integer_type_node, this->get_length_tree(gogo),
5648 // This is an open array. We need to read the capacity field.
5650 tree type = TREE_TYPE(array);
5651 go_assert(TREE_CODE(type) == RECORD_TYPE);
5653 tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type)));
5654 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
5656 return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
5662 Array_type::do_export(Export* exp) const
5664 exp->write_c_string("[");
5665 if (this->length_ != NULL)
5666 this->length_->export_expression(exp);
5667 exp->write_c_string("] ");
5668 exp->write_type(this->element_type_);
5674 Array_type::do_import(Import* imp)
5676 imp->require_c_string("[");
5678 if (imp->peek_char() == ']')
5681 length = Expression::import_expression(imp);
5682 imp->require_c_string("] ");
5683 Type* element_type = imp->read_type();
5684 return Type::make_array_type(element_type, length);
5687 // The type of an array type descriptor.
5690 Array_type::make_array_type_descriptor_type()
5695 Type* tdt = Type::make_type_descriptor_type();
5696 Type* ptdt = Type::make_type_descriptor_ptr_type();
5698 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5701 Type::make_builtin_struct_type(4,
5705 "len", uintptr_type);
5707 ret = Type::make_builtin_named_type("ArrayType", sf);
5713 // The type of an slice type descriptor.
5716 Array_type::make_slice_type_descriptor_type()
5721 Type* tdt = Type::make_type_descriptor_type();
5722 Type* ptdt = Type::make_type_descriptor_ptr_type();
5725 Type::make_builtin_struct_type(2,
5729 ret = Type::make_builtin_named_type("SliceType", sf);
5735 // Build a type descriptor for an array/slice type.
5738 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5740 if (this->length_ != NULL)
5741 return this->array_type_descriptor(gogo, name);
5743 return this->slice_type_descriptor(gogo, name);
5746 // Build a type descriptor for an array type.
5749 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
5751 Location bloc = Linemap::predeclared_location();
5753 Type* atdt = Array_type::make_array_type_descriptor_type();
5755 const Struct_field_list* fields = atdt->struct_type()->fields();
5757 Expression_list* vals = new Expression_list();
5760 Struct_field_list::const_iterator p = fields->begin();
5761 go_assert(p->is_field_name("commonType"));
5762 vals->push_back(this->type_descriptor_constructor(gogo,
5763 RUNTIME_TYPE_KIND_ARRAY,
5767 go_assert(p->is_field_name("elem"));
5768 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5771 go_assert(p->is_field_name("slice"));
5772 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
5773 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
5776 go_assert(p->is_field_name("len"));
5777 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
5780 go_assert(p == fields->end());
5782 return Expression::make_struct_composite_literal(atdt, vals, bloc);
5785 // Build a type descriptor for a slice type.
5788 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
5790 Location bloc = Linemap::predeclared_location();
5792 Type* stdt = Array_type::make_slice_type_descriptor_type();
5794 const Struct_field_list* fields = stdt->struct_type()->fields();
5796 Expression_list* vals = new Expression_list();
5799 Struct_field_list::const_iterator p = fields->begin();
5800 go_assert(p->is_field_name("commonType"));
5801 vals->push_back(this->type_descriptor_constructor(gogo,
5802 RUNTIME_TYPE_KIND_SLICE,
5806 go_assert(p->is_field_name("elem"));
5807 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5810 go_assert(p == fields->end());
5812 return Expression::make_struct_composite_literal(stdt, vals, bloc);
5815 // Reflection string.
5818 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
5820 ret->push_back('[');
5821 if (this->length_ != NULL)
5823 Numeric_constant nc;
5825 if (!this->length_->numeric_constant_value(&nc)
5826 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
5827 error_at(this->length_->location(), "invalid array length");
5831 snprintf(buf, sizeof buf, "%lu", val);
5835 ret->push_back(']');
5837 this->append_reflection(this->element_type_, gogo, ret);
5843 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5845 ret->push_back('A');
5846 this->append_mangled_name(this->element_type_, gogo, ret);
5847 if (this->length_ != NULL)
5849 Numeric_constant nc;
5851 if (!this->length_->numeric_constant_value(&nc)
5852 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
5853 error_at(this->length_->location(), "invalid array length");
5857 snprintf(buf, sizeof buf, "%lu", val);
5861 ret->push_back('e');
5864 // Make an array type.
5867 Type::make_array_type(Type* element_type, Expression* length)
5869 return new Array_type(element_type, length);
5877 Map_type::do_traverse(Traverse* traverse)
5879 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
5880 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
5881 return TRAVERSE_EXIT;
5882 return TRAVERSE_CONTINUE;
5885 // Check that the map type is OK.
5888 Map_type::do_verify()
5890 // The runtime support uses "map[void]void".
5891 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
5892 error_at(this->location_, "invalid map key type");
5896 // Whether two map types are identical.
5899 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
5901 return (Type::are_identical(this->key_type(), t->key_type(),
5902 errors_are_identical, NULL)
5903 && Type::are_identical(this->val_type(), t->val_type(),
5904 errors_are_identical, NULL));
5910 Map_type::do_hash_for_method(Gogo* gogo) const
5912 return (this->key_type_->hash_for_method(gogo)
5913 + this->val_type_->hash_for_method(gogo)
5917 // Get the backend representation for a map type. A map type is
5918 // represented as a pointer to a struct. The struct is __go_map in
5922 Map_type::do_get_backend(Gogo* gogo)
5924 static Btype* backend_map_type;
5925 if (backend_map_type == NULL)
5927 std::vector<Backend::Btyped_identifier> bfields(4);
5929 Location bloc = Linemap::predeclared_location();
5931 Type* pdt = Type::make_type_descriptor_ptr_type();
5932 bfields[0].name = "__descriptor";
5933 bfields[0].btype = pdt->get_backend(gogo);
5934 bfields[0].location = bloc;
5936 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5937 bfields[1].name = "__element_count";
5938 bfields[1].btype = uintptr_type->get_backend(gogo);
5939 bfields[1].location = bloc;
5941 bfields[2].name = "__bucket_count";
5942 bfields[2].btype = bfields[1].btype;
5943 bfields[2].location = bloc;
5945 Btype* bvt = gogo->backend()->void_type();
5946 Btype* bpvt = gogo->backend()->pointer_type(bvt);
5947 Btype* bppvt = gogo->backend()->pointer_type(bpvt);
5948 bfields[3].name = "__buckets";
5949 bfields[3].btype = bppvt;
5950 bfields[3].location = bloc;
5952 Btype *bt = gogo->backend()->struct_type(bfields);
5953 bt = gogo->backend()->named_type("__go_map", bt, bloc);
5954 backend_map_type = gogo->backend()->pointer_type(bt);
5956 return backend_map_type;
5959 // The type of a map type descriptor.
5962 Map_type::make_map_type_descriptor_type()
5967 Type* tdt = Type::make_type_descriptor_type();
5968 Type* ptdt = Type::make_type_descriptor_ptr_type();
5971 Type::make_builtin_struct_type(3,
5976 ret = Type::make_builtin_named_type("MapType", sf);
5982 // Build a type descriptor for a map type.
5985 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5987 Location bloc = Linemap::predeclared_location();
5989 Type* mtdt = Map_type::make_map_type_descriptor_type();
5991 const Struct_field_list* fields = mtdt->struct_type()->fields();
5993 Expression_list* vals = new Expression_list();
5996 Struct_field_list::const_iterator p = fields->begin();
5997 go_assert(p->is_field_name("commonType"));
5998 vals->push_back(this->type_descriptor_constructor(gogo,
5999 RUNTIME_TYPE_KIND_MAP,
6003 go_assert(p->is_field_name("key"));
6004 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
6007 go_assert(p->is_field_name("elem"));
6008 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
6011 go_assert(p == fields->end());
6013 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
6016 // A mapping from map types to map descriptors.
6018 Map_type::Map_descriptors Map_type::map_descriptors;
6020 // Build a map descriptor for this type. Return a pointer to it.
6023 Map_type::map_descriptor_pointer(Gogo* gogo, Location location)
6025 Bvariable* bvar = this->map_descriptor(gogo);
6026 tree var_tree = var_to_tree(bvar);
6027 if (var_tree == error_mark_node)
6028 return error_mark_node;
6029 return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
6032 // Build a map descriptor for this type.
6035 Map_type::map_descriptor(Gogo* gogo)
6037 std::pair<Map_type*, Bvariable*> val(this, NULL);
6038 std::pair<Map_type::Map_descriptors::iterator, bool> ins =
6039 Map_type::map_descriptors.insert(val);
6041 return ins.first->second;
6043 Type* key_type = this->key_type_;
6044 Type* val_type = this->val_type_;
6046 // The map entry type is a struct with three fields. Build that
6047 // struct so that we can get the offsets of the key and value within
6048 // a map entry. The first field should technically be a pointer to
6049 // this type itself, but since we only care about field offsets we
6050 // just use pointer to bool.
6051 Type* pbool = Type::make_pointer_type(Type::make_boolean_type());
6052 Struct_type* map_entry_type =
6053 Type::make_builtin_struct_type(3,
6058 Type* map_descriptor_type = Map_type::make_map_descriptor_type();
6060 const Struct_field_list* fields =
6061 map_descriptor_type->struct_type()->fields();
6063 Expression_list* vals = new Expression_list();
6066 Location bloc = Linemap::predeclared_location();
6068 Struct_field_list::const_iterator p = fields->begin();
6070 go_assert(p->is_field_name("__map_descriptor"));
6071 vals->push_back(Expression::make_type_descriptor(this, bloc));
6074 go_assert(p->is_field_name("__entry_size"));
6075 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
6076 vals->push_back(Expression::make_type_info(map_entry_type, type_info));
6078 Struct_field_list::const_iterator pf = map_entry_type->fields()->begin();
6080 go_assert(pf->is_field_name("__key"));
6083 go_assert(p->is_field_name("__key_offset"));
6084 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6087 go_assert(pf->is_field_name("__val"));
6090 go_assert(p->is_field_name("__val_offset"));
6091 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6094 go_assert(p == fields->end());
6096 Expression* initializer =
6097 Expression::make_struct_composite_literal(map_descriptor_type, vals, bloc);
6099 std::string mangled_name = "__go_map_" + this->mangled_name(gogo);
6100 Btype* map_descriptor_btype = map_descriptor_type->get_backend(gogo);
6101 Bvariable* bvar = gogo->backend()->immutable_struct(mangled_name, true,
6102 map_descriptor_btype,
6105 Translate_context context(gogo, NULL, NULL, NULL);
6106 context.set_is_const();
6107 Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
6109 gogo->backend()->immutable_struct_set_init(bvar, mangled_name, true,
6110 map_descriptor_btype, bloc,
6113 ins.first->second = bvar;
6117 // Build the type of a map descriptor. This must match the struct
6118 // __go_map_descriptor in libgo/runtime/map.h.
6121 Map_type::make_map_descriptor_type()
6126 Type* ptdt = Type::make_type_descriptor_ptr_type();
6127 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6129 Type::make_builtin_struct_type(4,
6130 "__map_descriptor", ptdt,
6131 "__entry_size", uintptr_type,
6132 "__key_offset", uintptr_type,
6133 "__val_offset", uintptr_type);
6134 ret = Type::make_builtin_named_type("__go_map_descriptor", sf);
6139 // Reflection string for a map.
6142 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
6144 ret->append("map[");
6145 this->append_reflection(this->key_type_, gogo, ret);
6147 this->append_reflection(this->val_type_, gogo, ret);
6150 // Mangled name for a map.
6153 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6155 ret->push_back('M');
6156 this->append_mangled_name(this->key_type_, gogo, ret);
6158 this->append_mangled_name(this->val_type_, gogo, ret);
6161 // Export a map type.
6164 Map_type::do_export(Export* exp) const
6166 exp->write_c_string("map [");
6167 exp->write_type(this->key_type_);
6168 exp->write_c_string("] ");
6169 exp->write_type(this->val_type_);
6172 // Import a map type.
6175 Map_type::do_import(Import* imp)
6177 imp->require_c_string("map [");
6178 Type* key_type = imp->read_type();
6179 imp->require_c_string("] ");
6180 Type* val_type = imp->read_type();
6181 return Type::make_map_type(key_type, val_type, imp->location());
6187 Type::make_map_type(Type* key_type, Type* val_type, Location location)
6189 return new Map_type(key_type, val_type, location);
6192 // Class Channel_type.
6197 Channel_type::do_hash_for_method(Gogo* gogo) const
6199 unsigned int ret = 0;
6200 if (this->may_send_)
6202 if (this->may_receive_)
6204 if (this->element_type_ != NULL)
6205 ret += this->element_type_->hash_for_method(gogo) << 2;
6209 // Whether this type is the same as T.
6212 Channel_type::is_identical(const Channel_type* t,
6213 bool errors_are_identical) const
6215 if (!Type::are_identical(this->element_type(), t->element_type(),
6216 errors_are_identical, NULL))
6218 return (this->may_send_ == t->may_send_
6219 && this->may_receive_ == t->may_receive_);
6222 // Return the tree for a channel type. A channel is a pointer to a
6223 // __go_channel struct. The __go_channel struct is defined in
6224 // libgo/runtime/channel.h.
6227 Channel_type::do_get_backend(Gogo* gogo)
6229 static Btype* backend_channel_type;
6230 if (backend_channel_type == NULL)
6232 std::vector<Backend::Btyped_identifier> bfields;
6233 Btype* bt = gogo->backend()->struct_type(bfields);
6234 bt = gogo->backend()->named_type("__go_channel", bt,
6235 Linemap::predeclared_location());
6236 backend_channel_type = gogo->backend()->pointer_type(bt);
6238 return backend_channel_type;
6241 // Build a type descriptor for a channel type.
6244 Channel_type::make_chan_type_descriptor_type()
6249 Type* tdt = Type::make_type_descriptor_type();
6250 Type* ptdt = Type::make_type_descriptor_ptr_type();
6252 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6255 Type::make_builtin_struct_type(3,
6258 "dir", uintptr_type);
6260 ret = Type::make_builtin_named_type("ChanType", sf);
6266 // Build a type descriptor for a map type.
6269 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6271 Location bloc = Linemap::predeclared_location();
6273 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
6275 const Struct_field_list* fields = ctdt->struct_type()->fields();
6277 Expression_list* vals = new Expression_list();
6280 Struct_field_list::const_iterator p = fields->begin();
6281 go_assert(p->is_field_name("commonType"));
6282 vals->push_back(this->type_descriptor_constructor(gogo,
6283 RUNTIME_TYPE_KIND_CHAN,
6287 go_assert(p->is_field_name("elem"));
6288 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
6291 go_assert(p->is_field_name("dir"));
6292 // These bits must match the ones in libgo/runtime/go-type.h.
6294 if (this->may_receive_)
6296 if (this->may_send_)
6299 mpz_init_set_ui(iv, val);
6300 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
6304 go_assert(p == fields->end());
6306 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
6309 // Reflection string.
6312 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
6314 if (!this->may_send_)
6316 ret->append("chan");
6317 if (!this->may_receive_)
6319 ret->push_back(' ');
6320 this->append_reflection(this->element_type_, gogo, ret);
6326 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6328 ret->push_back('C');
6329 this->append_mangled_name(this->element_type_, gogo, ret);
6330 if (this->may_send_)
6331 ret->push_back('s');
6332 if (this->may_receive_)
6333 ret->push_back('r');
6334 ret->push_back('e');
6340 Channel_type::do_export(Export* exp) const
6342 exp->write_c_string("chan ");
6343 if (this->may_send_ && !this->may_receive_)
6344 exp->write_c_string("-< ");
6345 else if (this->may_receive_ && !this->may_send_)
6346 exp->write_c_string("<- ");
6347 exp->write_type(this->element_type_);
6353 Channel_type::do_import(Import* imp)
6355 imp->require_c_string("chan ");
6359 if (imp->match_c_string("-< "))
6363 may_receive = false;
6365 else if (imp->match_c_string("<- "))
6377 Type* element_type = imp->read_type();
6379 return Type::make_channel_type(may_send, may_receive, element_type);
6382 // Make a new channel type.
6385 Type::make_channel_type(bool send, bool receive, Type* element_type)
6387 return new Channel_type(send, receive, element_type);
6390 // Class Interface_type.
6395 Interface_type::do_traverse(Traverse* traverse)
6397 Typed_identifier_list* methods = (this->methods_are_finalized_
6398 ? this->all_methods_
6399 : this->parse_methods_);
6400 if (methods == NULL)
6401 return TRAVERSE_CONTINUE;
6402 return methods->traverse(traverse);
6405 // Finalize the methods. This handles interface inheritance.
6408 Interface_type::finalize_methods()
6410 if (this->methods_are_finalized_)
6412 this->methods_are_finalized_ = true;
6413 if (this->parse_methods_ == NULL)
6416 this->all_methods_ = new Typed_identifier_list();
6417 this->all_methods_->reserve(this->parse_methods_->size());
6418 Typed_identifier_list inherit;
6419 for (Typed_identifier_list::const_iterator pm =
6420 this->parse_methods_->begin();
6421 pm != this->parse_methods_->end();
6424 const Typed_identifier* p = &*pm;
6425 if (p->name().empty())
6426 inherit.push_back(*p);
6427 else if (this->find_method(p->name()) == NULL)
6428 this->all_methods_->push_back(*p);
6430 error_at(p->location(), "duplicate method %qs",
6431 Gogo::message_name(p->name()).c_str());
6434 std::vector<Named_type*> seen;
6435 seen.reserve(inherit.size());
6436 bool issued_recursive_error = false;
6437 while (!inherit.empty())
6439 Type* t = inherit.back().type();
6440 Location tl = inherit.back().location();
6443 Interface_type* it = t->interface_type();
6447 error_at(tl, "interface contains embedded non-interface");
6452 if (!issued_recursive_error)
6454 error_at(tl, "invalid recursive interface");
6455 issued_recursive_error = true;
6460 Named_type* nt = t->named_type();
6461 if (nt != NULL && it->parse_methods_ != NULL)
6463 std::vector<Named_type*>::const_iterator q;
6464 for (q = seen.begin(); q != seen.end(); ++q)
6468 error_at(tl, "inherited interface loop");
6472 if (q != seen.end())
6477 const Typed_identifier_list* imethods = it->parse_methods_;
6478 if (imethods == NULL)
6480 for (Typed_identifier_list::const_iterator q = imethods->begin();
6481 q != imethods->end();
6484 if (q->name().empty())
6485 inherit.push_back(*q);
6486 else if (this->find_method(q->name()) == NULL)
6487 this->all_methods_->push_back(Typed_identifier(q->name(),
6490 error_at(tl, "inherited method %qs is ambiguous",
6491 Gogo::message_name(q->name()).c_str());
6495 if (!this->all_methods_->empty())
6496 this->all_methods_->sort_by_name();
6499 delete this->all_methods_;
6500 this->all_methods_ = NULL;
6504 // Return the method NAME, or NULL.
6506 const Typed_identifier*
6507 Interface_type::find_method(const std::string& name) const
6509 go_assert(this->methods_are_finalized_);
6510 if (this->all_methods_ == NULL)
6512 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6513 p != this->all_methods_->end();
6515 if (p->name() == name)
6520 // Return the method index.
6523 Interface_type::method_index(const std::string& name) const
6525 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
6527 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6528 p != this->all_methods_->end();
6530 if (p->name() == name)
6535 // Return whether NAME is an unexported method, for better error
6539 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
6541 go_assert(this->methods_are_finalized_);
6542 if (this->all_methods_ == NULL)
6544 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6545 p != this->all_methods_->end();
6548 const std::string& method_name(p->name());
6549 if (Gogo::is_hidden_name(method_name)
6550 && name == Gogo::unpack_hidden_name(method_name)
6551 && gogo->pack_hidden_name(name, false) != method_name)
6557 // Whether this type is identical with T.
6560 Interface_type::is_identical(const Interface_type* t,
6561 bool errors_are_identical) const
6563 // If methods have not been finalized, then we are asking whether
6564 // func redeclarations are the same. This is an error, so for
6565 // simplicity we say they are never the same.
6566 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
6569 // We require the same methods with the same types. The methods
6570 // have already been sorted.
6571 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
6572 return this->all_methods_ == t->all_methods_;
6574 if (this->assume_identical(this, t) || t->assume_identical(t, this))
6577 Assume_identical* hold_ai = this->assume_identical_;
6578 Assume_identical ai;
6582 this->assume_identical_ = &ai;
6584 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
6585 Typed_identifier_list::const_iterator p2;
6586 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
6588 if (p1 == this->all_methods_->end())
6590 if (p1->name() != p2->name()
6591 || !Type::are_identical(p1->type(), p2->type(),
6592 errors_are_identical, NULL))
6596 this->assume_identical_ = hold_ai;
6598 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
6601 // Return true if T1 and T2 are assumed to be identical during a type
6605 Interface_type::assume_identical(const Interface_type* t1,
6606 const Interface_type* t2) const
6608 for (Assume_identical* p = this->assume_identical_;
6611 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
6616 // Whether we can assign the interface type T to this type. The types
6617 // are known to not be identical. An interface assignment is only
6618 // permitted if T is known to implement all methods in THIS.
6619 // Otherwise a type guard is required.
6622 Interface_type::is_compatible_for_assign(const Interface_type* t,
6623 std::string* reason) const
6625 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
6626 if (this->all_methods_ == NULL)
6628 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6629 p != this->all_methods_->end();
6632 const Typed_identifier* m = t->find_method(p->name());
6638 snprintf(buf, sizeof buf,
6639 _("need explicit conversion; missing method %s%s%s"),
6640 open_quote, Gogo::message_name(p->name()).c_str(),
6642 reason->assign(buf);
6647 std::string subreason;
6648 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
6652 std::string n = Gogo::message_name(p->name());
6653 size_t len = 100 + n.length() + subreason.length();
6654 char* buf = new char[len];
6655 if (subreason.empty())
6656 snprintf(buf, len, _("incompatible type for method %s%s%s"),
6657 open_quote, n.c_str(), close_quote);
6660 _("incompatible type for method %s%s%s (%s)"),
6661 open_quote, n.c_str(), close_quote,
6663 reason->assign(buf);
6676 Interface_type::do_hash_for_method(Gogo*) const
6678 go_assert(this->methods_are_finalized_);
6679 unsigned int ret = 0;
6680 if (this->all_methods_ != NULL)
6682 for (Typed_identifier_list::const_iterator p =
6683 this->all_methods_->begin();
6684 p != this->all_methods_->end();
6687 ret = Type::hash_string(p->name(), ret);
6688 // We don't use the method type in the hash, to avoid
6689 // infinite recursion if an interface method uses a type
6690 // which is an interface which inherits from the interface
6692 // type T interface { F() interface {T}}
6699 // Return true if T implements the interface. If it does not, and
6700 // REASON is not NULL, set *REASON to a useful error message.
6703 Interface_type::implements_interface(const Type* t, std::string* reason) const
6705 go_assert(this->methods_are_finalized_);
6706 if (this->all_methods_ == NULL)
6709 bool is_pointer = false;
6710 const Named_type* nt = t->named_type();
6711 const Struct_type* st = t->struct_type();
6712 // If we start with a named type, we don't dereference it to find
6716 const Type* pt = t->points_to();
6719 // If T is a pointer to a named type, then we need to look at
6720 // the type to which it points.
6722 nt = pt->named_type();
6723 st = pt->struct_type();
6727 // If we have a named type, get the methods from it rather than from
6732 // Only named and struct types have methods.
6733 if (nt == NULL && st == NULL)
6737 if (t->points_to() != NULL
6738 && t->points_to()->interface_type() != NULL)
6739 reason->assign(_("pointer to interface type has no methods"));
6741 reason->assign(_("type has no methods"));
6746 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
6750 if (t->points_to() != NULL
6751 && t->points_to()->interface_type() != NULL)
6752 reason->assign(_("pointer to interface type has no methods"));
6754 reason->assign(_("type has no methods"));
6759 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6760 p != this->all_methods_->end();
6763 bool is_ambiguous = false;
6764 Method* m = (nt != NULL
6765 ? nt->method_function(p->name(), &is_ambiguous)
6766 : st->method_function(p->name(), &is_ambiguous));
6771 std::string n = Gogo::message_name(p->name());
6772 size_t len = n.length() + 100;
6773 char* buf = new char[len];
6775 snprintf(buf, len, _("ambiguous method %s%s%s"),
6776 open_quote, n.c_str(), close_quote);
6778 snprintf(buf, len, _("missing method %s%s%s"),
6779 open_quote, n.c_str(), close_quote);
6780 reason->assign(buf);
6786 Function_type *p_fn_type = p->type()->function_type();
6787 Function_type* m_fn_type = m->type()->function_type();
6788 go_assert(p_fn_type != NULL && m_fn_type != NULL);
6789 std::string subreason;
6790 if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
6794 std::string n = Gogo::message_name(p->name());
6795 size_t len = 100 + n.length() + subreason.length();
6796 char* buf = new char[len];
6797 if (subreason.empty())
6798 snprintf(buf, len, _("incompatible type for method %s%s%s"),
6799 open_quote, n.c_str(), close_quote);
6802 _("incompatible type for method %s%s%s (%s)"),
6803 open_quote, n.c_str(), close_quote,
6805 reason->assign(buf);
6811 if (!is_pointer && !m->is_value_method())
6815 std::string n = Gogo::message_name(p->name());
6816 size_t len = 100 + n.length();
6817 char* buf = new char[len];
6818 snprintf(buf, len, _("method %s%s%s requires a pointer"),
6819 open_quote, n.c_str(), close_quote);
6820 reason->assign(buf);
6830 // Return the backend representation of the empty interface type. We
6831 // use the same struct for all empty interfaces.
6834 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
6836 static Btype* empty_interface_type;
6837 if (empty_interface_type == NULL)
6839 std::vector<Backend::Btyped_identifier> bfields(2);
6841 Location bloc = Linemap::predeclared_location();
6843 Type* pdt = Type::make_type_descriptor_ptr_type();
6844 bfields[0].name = "__type_descriptor";
6845 bfields[0].btype = pdt->get_backend(gogo);
6846 bfields[0].location = bloc;
6848 Type* vt = Type::make_pointer_type(Type::make_void_type());
6849 bfields[1].name = "__object";
6850 bfields[1].btype = vt->get_backend(gogo);
6851 bfields[1].location = bloc;
6853 empty_interface_type = gogo->backend()->struct_type(bfields);
6855 return empty_interface_type;
6858 // Return the fields of a non-empty interface type. This is not
6859 // declared in types.h so that types.h doesn't have to #include
6863 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
6864 bool use_placeholder,
6865 std::vector<Backend::Btyped_identifier>* bfields)
6867 Location loc = type->location();
6869 std::vector<Backend::Btyped_identifier> mfields(type->methods()->size() + 1);
6871 Type* pdt = Type::make_type_descriptor_ptr_type();
6872 mfields[0].name = "__type_descriptor";
6873 mfields[0].btype = pdt->get_backend(gogo);
6874 mfields[0].location = loc;
6876 std::string last_name = "";
6878 for (Typed_identifier_list::const_iterator p = type->methods()->begin();
6879 p != type->methods()->end();
6882 // The type of the method in Go only includes the parameters.
6883 // The actual method also has a receiver, which is always a
6884 // pointer. We need to add that pointer type here in order to
6885 // generate the correct type for the backend.
6886 Function_type* ft = p->type()->function_type();
6887 go_assert(ft->receiver() == NULL);
6889 const Typed_identifier_list* params = ft->parameters();
6890 Typed_identifier_list* mparams = new Typed_identifier_list();
6892 mparams->reserve(params->size() + 1);
6893 Type* vt = Type::make_pointer_type(Type::make_void_type());
6894 mparams->push_back(Typed_identifier("", vt, ft->location()));
6897 for (Typed_identifier_list::const_iterator pp = params->begin();
6898 pp != params->end();
6900 mparams->push_back(*pp);
6903 Typed_identifier_list* mresults = (ft->results() == NULL
6905 : ft->results()->copy());
6906 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
6909 mfields[i].name = Gogo::unpack_hidden_name(p->name());
6910 mfields[i].btype = (use_placeholder
6911 ? mft->get_backend_placeholder(gogo)
6912 : mft->get_backend(gogo));
6913 mfields[i].location = loc;
6914 // Sanity check: the names should be sorted.
6915 go_assert(p->name() > last_name);
6916 last_name = p->name();
6919 Btype* methods = gogo->backend()->struct_type(mfields);
6923 (*bfields)[0].name = "__methods";
6924 (*bfields)[0].btype = gogo->backend()->pointer_type(methods);
6925 (*bfields)[0].location = loc;
6927 Type* vt = Type::make_pointer_type(Type::make_void_type());
6928 (*bfields)[1].name = "__object";
6929 (*bfields)[1].btype = vt->get_backend(gogo);
6930 (*bfields)[1].location = Linemap::predeclared_location();
6933 // Return a tree for an interface type. An interface is a pointer to
6934 // a struct. The struct has three fields. The first field is a
6935 // pointer to the type descriptor for the dynamic type of the object.
6936 // The second field is a pointer to a table of methods for the
6937 // interface to be used with the object. The third field is the value
6938 // of the object itself.
6941 Interface_type::do_get_backend(Gogo* gogo)
6943 if (this->is_empty())
6944 return Interface_type::get_backend_empty_interface_type(gogo);
6947 if (this->interface_btype_ != NULL)
6948 return this->interface_btype_;
6949 this->interface_btype_ =
6950 gogo->backend()->placeholder_struct_type("", this->location_);
6951 std::vector<Backend::Btyped_identifier> bfields;
6952 get_backend_interface_fields(gogo, this, false, &bfields);
6953 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
6955 this->interface_btype_ = gogo->backend()->error_type();
6956 return this->interface_btype_;
6960 // Finish the backend representation of the methods.
6963 Interface_type::finish_backend_methods(Gogo* gogo)
6965 if (!this->interface_type()->is_empty())
6967 const Typed_identifier_list* methods = this->methods();
6968 if (methods != NULL)
6970 for (Typed_identifier_list::const_iterator p = methods->begin();
6971 p != methods->end();
6973 p->type()->get_backend(gogo);
6978 // The type of an interface type descriptor.
6981 Interface_type::make_interface_type_descriptor_type()
6986 Type* tdt = Type::make_type_descriptor_type();
6987 Type* ptdt = Type::make_type_descriptor_ptr_type();
6989 Type* string_type = Type::lookup_string_type();
6990 Type* pointer_string_type = Type::make_pointer_type(string_type);
6993 Type::make_builtin_struct_type(3,
6994 "name", pointer_string_type,
6995 "pkgPath", pointer_string_type,
6998 Type* nsm = Type::make_builtin_named_type("imethod", sm);
7000 Type* slice_nsm = Type::make_array_type(nsm, NULL);
7002 Struct_type* s = Type::make_builtin_struct_type(2,
7004 "methods", slice_nsm);
7006 ret = Type::make_builtin_named_type("InterfaceType", s);
7012 // Build a type descriptor for an interface type.
7015 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7017 Location bloc = Linemap::predeclared_location();
7019 Type* itdt = Interface_type::make_interface_type_descriptor_type();
7021 const Struct_field_list* ifields = itdt->struct_type()->fields();
7023 Expression_list* ivals = new Expression_list();
7026 Struct_field_list::const_iterator pif = ifields->begin();
7027 go_assert(pif->is_field_name("commonType"));
7028 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
7029 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
7033 go_assert(pif->is_field_name("methods"));
7035 Expression_list* methods = new Expression_list();
7036 if (this->all_methods_ != NULL)
7038 Type* elemtype = pif->type()->array_type()->element_type();
7040 methods->reserve(this->all_methods_->size());
7041 for (Typed_identifier_list::const_iterator pm =
7042 this->all_methods_->begin();
7043 pm != this->all_methods_->end();
7046 const Struct_field_list* mfields = elemtype->struct_type()->fields();
7048 Expression_list* mvals = new Expression_list();
7051 Struct_field_list::const_iterator pmf = mfields->begin();
7052 go_assert(pmf->is_field_name("name"));
7053 std::string s = Gogo::unpack_hidden_name(pm->name());
7054 Expression* e = Expression::make_string(s, bloc);
7055 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7058 go_assert(pmf->is_field_name("pkgPath"));
7059 if (!Gogo::is_hidden_name(pm->name()))
7060 mvals->push_back(Expression::make_nil(bloc));
7063 s = Gogo::hidden_name_pkgpath(pm->name());
7064 e = Expression::make_string(s, bloc);
7065 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7069 go_assert(pmf->is_field_name("typ"));
7070 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
7073 go_assert(pmf == mfields->end());
7075 e = Expression::make_struct_composite_literal(elemtype, mvals,
7077 methods->push_back(e);
7081 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
7085 go_assert(pif == ifields->end());
7087 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
7090 // Reflection string.
7093 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
7095 ret->append("interface {");
7096 const Typed_identifier_list* methods = this->parse_methods_;
7097 if (methods != NULL)
7099 ret->push_back(' ');
7100 for (Typed_identifier_list::const_iterator p = methods->begin();
7101 p != methods->end();
7104 if (p != methods->begin())
7106 if (p->name().empty())
7107 this->append_reflection(p->type(), gogo, ret);
7110 if (!Gogo::is_hidden_name(p->name()))
7111 ret->append(p->name());
7112 else if (gogo->pkgpath_from_option())
7113 ret->append(p->name().substr(1));
7116 // If no -fgo-pkgpath option, backward compatibility
7117 // for how this used to work before -fgo-pkgpath was
7119 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
7120 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
7121 ret->push_back('.');
7122 ret->append(Gogo::unpack_hidden_name(p->name()));
7124 std::string sub = p->type()->reflection(gogo);
7125 go_assert(sub.compare(0, 4, "func") == 0);
7126 sub = sub.substr(4);
7130 ret->push_back(' ');
7138 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7140 go_assert(this->methods_are_finalized_);
7142 ret->push_back('I');
7144 const Typed_identifier_list* methods = this->all_methods_;
7145 if (methods != NULL && !this->seen_)
7148 for (Typed_identifier_list::const_iterator p = methods->begin();
7149 p != methods->end();
7152 if (!p->name().empty())
7154 std::string n = Gogo::unpack_hidden_name(p->name());
7156 snprintf(buf, sizeof buf, "%u_",
7157 static_cast<unsigned int>(n.length()));
7161 this->append_mangled_name(p->type(), gogo, ret);
7163 this->seen_ = false;
7166 ret->push_back('e');
7172 Interface_type::do_export(Export* exp) const
7174 exp->write_c_string("interface { ");
7176 const Typed_identifier_list* methods = this->parse_methods_;
7177 if (methods != NULL)
7179 for (Typed_identifier_list::const_iterator pm = methods->begin();
7180 pm != methods->end();
7183 if (pm->name().empty())
7185 exp->write_c_string("? ");
7186 exp->write_type(pm->type());
7190 exp->write_string(pm->name());
7191 exp->write_c_string(" (");
7193 const Function_type* fntype = pm->type()->function_type();
7196 const Typed_identifier_list* parameters = fntype->parameters();
7197 if (parameters != NULL)
7199 bool is_varargs = fntype->is_varargs();
7200 for (Typed_identifier_list::const_iterator pp =
7201 parameters->begin();
7202 pp != parameters->end();
7208 exp->write_c_string(", ");
7209 exp->write_name(pp->name());
7210 exp->write_c_string(" ");
7211 if (!is_varargs || pp + 1 != parameters->end())
7212 exp->write_type(pp->type());
7215 exp->write_c_string("...");
7216 Type *pptype = pp->type();
7217 exp->write_type(pptype->array_type()->element_type());
7222 exp->write_c_string(")");
7224 const Typed_identifier_list* results = fntype->results();
7225 if (results != NULL)
7227 exp->write_c_string(" ");
7228 if (results->size() == 1 && results->begin()->name().empty())
7229 exp->write_type(results->begin()->type());
7233 exp->write_c_string("(");
7234 for (Typed_identifier_list::const_iterator p =
7236 p != results->end();
7242 exp->write_c_string(", ");
7243 exp->write_name(p->name());
7244 exp->write_c_string(" ");
7245 exp->write_type(p->type());
7247 exp->write_c_string(")");
7252 exp->write_c_string("; ");
7256 exp->write_c_string("}");
7259 // Import an interface type.
7262 Interface_type::do_import(Import* imp)
7264 imp->require_c_string("interface { ");
7266 Typed_identifier_list* methods = new Typed_identifier_list;
7267 while (imp->peek_char() != '}')
7269 std::string name = imp->read_identifier();
7273 imp->require_c_string(" ");
7274 Type* t = imp->read_type();
7275 methods->push_back(Typed_identifier("", t, imp->location()));
7276 imp->require_c_string("; ");
7280 imp->require_c_string(" (");
7282 Typed_identifier_list* parameters;
7283 bool is_varargs = false;
7284 if (imp->peek_char() == ')')
7288 parameters = new Typed_identifier_list;
7291 std::string name = imp->read_name();
7292 imp->require_c_string(" ");
7294 if (imp->match_c_string("..."))
7300 Type* ptype = imp->read_type();
7302 ptype = Type::make_array_type(ptype, NULL);
7303 parameters->push_back(Typed_identifier(name, ptype,
7305 if (imp->peek_char() != ',')
7307 go_assert(!is_varargs);
7308 imp->require_c_string(", ");
7311 imp->require_c_string(")");
7313 Typed_identifier_list* results;
7314 if (imp->peek_char() != ' ')
7318 results = new Typed_identifier_list;
7320 if (imp->peek_char() != '(')
7322 Type* rtype = imp->read_type();
7323 results->push_back(Typed_identifier("", rtype, imp->location()));
7330 std::string name = imp->read_name();
7331 imp->require_c_string(" ");
7332 Type* rtype = imp->read_type();
7333 results->push_back(Typed_identifier(name, rtype,
7335 if (imp->peek_char() != ',')
7337 imp->require_c_string(", ");
7339 imp->require_c_string(")");
7343 Function_type* fntype = Type::make_function_type(NULL, parameters,
7347 fntype->set_is_varargs();
7348 methods->push_back(Typed_identifier(name, fntype, imp->location()));
7350 imp->require_c_string("; ");
7353 imp->require_c_string("}");
7355 if (methods->empty())
7361 return Type::make_interface_type(methods, imp->location());
7364 // Make an interface type.
7367 Type::make_interface_type(Typed_identifier_list* methods,
7370 return new Interface_type(methods, location);
7373 // Make an empty interface type.
7376 Type::make_empty_interface_type(Location location)
7378 Interface_type* ret = new Interface_type(NULL, location);
7379 ret->finalize_methods();
7385 // Bind a method to an object.
7388 Method::bind_method(Expression* expr, Location location) const
7390 if (this->stub_ == NULL)
7392 // When there is no stub object, the binding is determined by
7394 return this->do_bind_method(expr, location);
7396 return Expression::make_bound_method(expr, this->stub_, location);
7399 // Return the named object associated with a method. This may only be
7400 // called after methods are finalized.
7403 Method::named_object() const
7405 if (this->stub_ != NULL)
7407 return this->do_named_object();
7410 // Class Named_method.
7412 // The type of the method.
7415 Named_method::do_type() const
7417 if (this->named_object_->is_function())
7418 return this->named_object_->func_value()->type();
7419 else if (this->named_object_->is_function_declaration())
7420 return this->named_object_->func_declaration_value()->type();
7425 // Return the location of the method receiver.
7428 Named_method::do_receiver_location() const
7430 return this->do_type()->receiver()->location();
7433 // Bind a method to an object.
7436 Named_method::do_bind_method(Expression* expr, Location location) const
7438 Named_object* no = this->named_object_;
7439 Bound_method_expression* bme = Expression::make_bound_method(expr, no,
7441 // If this is not a local method, and it does not use a stub, then
7442 // the real method expects a different type. We need to cast the
7444 if (this->depth() > 0 && !this->needs_stub_method())
7446 Function_type* ftype = this->do_type();
7447 go_assert(ftype->is_method());
7448 Type* frtype = ftype->receiver()->type();
7449 bme->set_first_argument_type(frtype);
7454 // Class Interface_method.
7456 // Bind a method to an object.
7459 Interface_method::do_bind_method(Expression* expr,
7460 Location location) const
7462 return Expression::make_interface_field_reference(expr, this->name_,
7468 // Insert a new method. Return true if it was inserted, false
7472 Methods::insert(const std::string& name, Method* m)
7474 std::pair<Method_map::iterator, bool> ins =
7475 this->methods_.insert(std::make_pair(name, m));
7480 Method* old_method = ins.first->second;
7481 if (m->depth() < old_method->depth())
7484 ins.first->second = m;
7489 if (m->depth() == old_method->depth())
7490 old_method->set_is_ambiguous();
7496 // Return the number of unambiguous methods.
7499 Methods::count() const
7502 for (Method_map::const_iterator p = this->methods_.begin();
7503 p != this->methods_.end();
7505 if (!p->second->is_ambiguous())
7510 // Class Named_type.
7512 // Return the name of the type.
7515 Named_type::name() const
7517 return this->named_object_->name();
7520 // Return the name of the type to use in an error message.
7523 Named_type::message_name() const
7525 return this->named_object_->message_name();
7528 // Whether this is an alias. There are currently only two aliases so
7529 // we just recognize them by name.
7532 Named_type::is_alias() const
7534 if (!this->is_builtin())
7536 const std::string& name(this->name());
7537 return name == "byte" || name == "rune";
7540 // Return the base type for this type. We have to be careful about
7541 // circular type definitions, which are invalid but may be seen here.
7544 Named_type::named_base()
7549 Type* ret = this->type_->base();
7550 this->seen_ = false;
7555 Named_type::named_base() const
7560 const Type* ret = this->type_->base();
7561 this->seen_ = false;
7565 // Return whether this is an error type. We have to be careful about
7566 // circular type definitions, which are invalid but may be seen here.
7569 Named_type::is_named_error_type() const
7574 bool ret = this->type_->is_error_type();
7575 this->seen_ = false;
7579 // Whether this type is comparable. We have to be careful about
7580 // circular type definitions.
7583 Named_type::named_type_is_comparable(std::string* reason) const
7588 bool ret = Type::are_compatible_for_comparison(true, this->type_,
7589 this->type_, reason);
7590 this->seen_ = false;
7594 // Add a method to this type.
7597 Named_type::add_method(const std::string& name, Function* function)
7599 if (this->local_methods_ == NULL)
7600 this->local_methods_ = new Bindings(NULL);
7601 return this->local_methods_->add_function(name, NULL, function);
7604 // Add a method declaration to this type.
7607 Named_type::add_method_declaration(const std::string& name, Package* package,
7608 Function_type* type,
7611 if (this->local_methods_ == NULL)
7612 this->local_methods_ = new Bindings(NULL);
7613 return this->local_methods_->add_function_declaration(name, package, type,
7617 // Add an existing method to this type.
7620 Named_type::add_existing_method(Named_object* no)
7622 if (this->local_methods_ == NULL)
7623 this->local_methods_ = new Bindings(NULL);
7624 this->local_methods_->add_named_object(no);
7627 // Look for a local method NAME, and returns its named object, or NULL
7631 Named_type::find_local_method(const std::string& name) const
7633 if (this->local_methods_ == NULL)
7635 return this->local_methods_->lookup(name);
7638 // Return whether NAME is an unexported field or method, for better
7642 Named_type::is_unexported_local_method(Gogo* gogo,
7643 const std::string& name) const
7645 Bindings* methods = this->local_methods_;
7646 if (methods != NULL)
7648 for (Bindings::const_declarations_iterator p =
7649 methods->begin_declarations();
7650 p != methods->end_declarations();
7653 if (Gogo::is_hidden_name(p->first)
7654 && name == Gogo::unpack_hidden_name(p->first)
7655 && gogo->pack_hidden_name(name, false) != p->first)
7662 // Build the complete list of methods for this type, which means
7663 // recursively including all methods for anonymous fields. Create all
7667 Named_type::finalize_methods(Gogo* gogo)
7669 if (this->all_methods_ != NULL)
7672 if (this->local_methods_ != NULL
7673 && (this->points_to() != NULL || this->interface_type() != NULL))
7675 const Bindings* lm = this->local_methods_;
7676 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
7677 p != lm->end_declarations();
7679 error_at(p->second->location(),
7680 "invalid pointer or interface receiver type");
7681 delete this->local_methods_;
7682 this->local_methods_ = NULL;
7686 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
7689 // Return the method NAME, or NULL if there isn't one or if it is
7690 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
7694 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
7696 return Type::method_function(this->all_methods_, name, is_ambiguous);
7699 // Return a pointer to the interface method table for this type for
7700 // the interface INTERFACE. IS_POINTER is true if this is for a
7704 Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface,
7707 go_assert(!interface->is_empty());
7709 Interface_method_tables** pimt = (is_pointer
7710 ? &this->interface_method_tables_
7711 : &this->pointer_interface_method_tables_);
7714 *pimt = new Interface_method_tables(5);
7716 std::pair<const Interface_type*, tree> val(interface, NULL_TREE);
7717 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
7721 // This is a new entry in the hash table.
7722 go_assert(ins.first->second == NULL_TREE);
7723 ins.first->second = gogo->interface_method_table_for_type(interface,
7728 tree decl = ins.first->second;
7729 if (decl == error_mark_node)
7730 return error_mark_node;
7731 go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL);
7732 return build_fold_addr_expr(decl);
7735 // Return whether a named type has any hidden fields.
7738 Named_type::named_type_has_hidden_fields(std::string* reason) const
7743 bool ret = this->type_->has_hidden_fields(this, reason);
7744 this->seen_ = false;
7748 // Look for a use of a complete type within another type. This is
7749 // used to check that we don't try to use a type within itself.
7751 class Find_type_use : public Traverse
7754 Find_type_use(Named_type* find_type)
7755 : Traverse(traverse_types),
7756 find_type_(find_type), found_(false)
7759 // Whether we found the type.
7762 { return this->found_; }
7769 // The type we are looking for.
7770 Named_type* find_type_;
7771 // Whether we found the type.
7775 // Check for FIND_TYPE in TYPE.
7778 Find_type_use::type(Type* type)
7780 if (type->named_type() != NULL && this->find_type_ == type->named_type())
7782 this->found_ = true;
7783 return TRAVERSE_EXIT;
7786 // It's OK if we see a reference to the type in any type which is
7787 // essentially a pointer: a pointer, a slice, a function, a map, or
7789 if (type->points_to() != NULL
7790 || type->is_slice_type()
7791 || type->function_type() != NULL
7792 || type->map_type() != NULL
7793 || type->channel_type() != NULL)
7794 return TRAVERSE_SKIP_COMPONENTS;
7796 // For an interface, a reference to the type in a method type should
7797 // be ignored, but we have to consider direct inheritance. When
7798 // this is called, there may be cases of direct inheritance
7799 // represented as a method with no name.
7800 if (type->interface_type() != NULL)
7802 const Typed_identifier_list* methods = type->interface_type()->methods();
7803 if (methods != NULL)
7805 for (Typed_identifier_list::const_iterator p = methods->begin();
7806 p != methods->end();
7809 if (p->name().empty())
7811 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
7812 return TRAVERSE_EXIT;
7816 return TRAVERSE_SKIP_COMPONENTS;
7819 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
7820 // to convert TYPE to the backend representation before we convert
7822 if (type->named_type() != NULL)
7824 switch (type->base()->classification())
7826 case Type::TYPE_ERROR:
7827 case Type::TYPE_BOOLEAN:
7828 case Type::TYPE_INTEGER:
7829 case Type::TYPE_FLOAT:
7830 case Type::TYPE_COMPLEX:
7831 case Type::TYPE_STRING:
7832 case Type::TYPE_NIL:
7835 case Type::TYPE_ARRAY:
7836 case Type::TYPE_STRUCT:
7837 this->find_type_->add_dependency(type->named_type());
7840 case Type::TYPE_NAMED:
7841 case Type::TYPE_FORWARD:
7842 go_assert(saw_errors());
7845 case Type::TYPE_VOID:
7846 case Type::TYPE_SINK:
7847 case Type::TYPE_FUNCTION:
7848 case Type::TYPE_POINTER:
7849 case Type::TYPE_CALL_MULTIPLE_RESULT:
7850 case Type::TYPE_MAP:
7851 case Type::TYPE_CHANNEL:
7852 case Type::TYPE_INTERFACE:
7858 return TRAVERSE_CONTINUE;
7861 // Verify that a named type does not refer to itself.
7864 Named_type::do_verify()
7866 if (this->is_verified_)
7868 this->is_verified_ = true;
7870 Find_type_use find(this);
7871 Type::traverse(this->type_, &find);
7874 error_at(this->location_, "invalid recursive type %qs",
7875 this->message_name().c_str());
7876 this->is_error_ = true;
7880 // Check whether any of the local methods overloads an existing
7881 // struct field or interface method. We don't need to check the
7882 // list of methods against itself: that is handled by the Bindings
7884 if (this->local_methods_ != NULL)
7886 Struct_type* st = this->type_->struct_type();
7889 for (Bindings::const_declarations_iterator p =
7890 this->local_methods_->begin_declarations();
7891 p != this->local_methods_->end_declarations();
7894 const std::string& name(p->first);
7895 if (st != NULL && st->find_local_field(name, NULL) != NULL)
7897 error_at(p->second->location(),
7898 "method %qs redeclares struct field name",
7899 Gogo::message_name(name).c_str());
7908 // Return whether this type is or contains a pointer.
7911 Named_type::do_has_pointer() const
7916 bool ret = this->type_->has_pointer();
7917 this->seen_ = false;
7921 // Return whether comparisons for this type can use the identity
7925 Named_type::do_compare_is_identity(Gogo* gogo) const
7927 // We don't use this->seen_ here because compare_is_identity may
7928 // call base() later, and that will mess up if seen_ is set here.
7929 if (this->seen_in_compare_is_identity_)
7931 this->seen_in_compare_is_identity_ = true;
7932 bool ret = this->type_->compare_is_identity(gogo);
7933 this->seen_in_compare_is_identity_ = false;
7937 // Return a hash code. This is used for method lookup. We simply
7938 // hash on the name itself.
7941 Named_type::do_hash_for_method(Gogo* gogo) const
7943 if (this->is_alias())
7944 return this->type_->named_type()->do_hash_for_method(gogo);
7946 const std::string& name(this->named_object()->name());
7947 unsigned int ret = Type::hash_string(name, 0);
7949 // GOGO will be NULL here when called from Type_hash_identical.
7950 // That is OK because that is only used for internal hash tables
7951 // where we are going to be comparing named types for equality. In
7952 // other cases, which are cases where the runtime is going to
7953 // compare hash codes to see if the types are the same, we need to
7954 // include the pkgpath in the hash.
7955 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
7957 const Package* package = this->named_object()->package();
7958 if (package == NULL)
7959 ret = Type::hash_string(gogo->pkgpath(), ret);
7961 ret = Type::hash_string(package->pkgpath(), ret);
7967 // Convert a named type to the backend representation. In order to
7968 // get dependencies right, we fill in a dummy structure for this type,
7969 // then convert all the dependencies, then complete this type. When
7970 // this function is complete, the size of the type is known.
7973 Named_type::convert(Gogo* gogo)
7975 if (this->is_error_ || this->is_converted_)
7978 this->create_placeholder(gogo);
7980 // If we are called to turn unsafe.Sizeof into a constant, we may
7981 // not have verified the type yet. We have to make sure it is
7982 // verified, since that sets the list of dependencies.
7985 // Convert all the dependencies. If they refer indirectly back to
7986 // this type, they will pick up the intermediate tree we just
7988 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
7989 p != this->dependencies_.end();
7991 (*p)->convert(gogo);
7993 // Complete this type.
7994 Btype* bt = this->named_btype_;
7995 Type* base = this->type_->base();
7996 switch (base->classification())
8013 // The size of these types is already correct. We don't worry
8014 // about filling them in until later, when we also track
8015 // circular references.
8020 std::vector<Backend::Btyped_identifier> bfields;
8021 get_backend_struct_fields(gogo, base->struct_type()->fields(),
8023 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8024 bt = gogo->backend()->error_type();
8029 // Slice types were completed in create_placeholder.
8030 if (!base->is_slice_type())
8032 Btype* bet = base->array_type()->get_backend_element(gogo, true);
8033 Bexpression* blen = base->array_type()->get_backend_length(gogo);
8034 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
8035 bt = gogo->backend()->error_type();
8039 case TYPE_INTERFACE:
8040 // Interface types were completed in create_placeholder.
8048 case TYPE_CALL_MULTIPLE_RESULT:
8054 this->named_btype_ = bt;
8055 this->is_converted_ = true;
8056 this->is_placeholder_ = false;
8059 // Create the placeholder for a named type. This is the first step in
8060 // converting to the backend representation.
8063 Named_type::create_placeholder(Gogo* gogo)
8065 if (this->is_error_)
8066 this->named_btype_ = gogo->backend()->error_type();
8068 if (this->named_btype_ != NULL)
8071 // Create the structure for this type. Note that because we call
8072 // base() here, we don't attempt to represent a named type defined
8073 // as another named type. Instead both named types will point to
8074 // different base representations.
8075 Type* base = this->type_->base();
8077 bool set_name = true;
8078 switch (base->classification())
8081 this->is_error_ = true;
8082 this->named_btype_ = gogo->backend()->error_type();
8092 // These are simple basic types, we can just create them
8094 bt = Type::get_named_base_btype(gogo, base);
8099 // All maps and channels have the same backend representation.
8100 bt = Type::get_named_base_btype(gogo, base);
8106 bool for_function = base->classification() == TYPE_FUNCTION;
8107 bt = gogo->backend()->placeholder_pointer_type(this->name(),
8115 bt = gogo->backend()->placeholder_struct_type(this->name(),
8117 this->is_placeholder_ = true;
8122 if (base->is_slice_type())
8123 bt = gogo->backend()->placeholder_struct_type(this->name(),
8127 bt = gogo->backend()->placeholder_array_type(this->name(),
8129 this->is_placeholder_ = true;
8134 case TYPE_INTERFACE:
8135 if (base->interface_type()->is_empty())
8136 bt = Interface_type::get_backend_empty_interface_type(gogo);
8139 bt = gogo->backend()->placeholder_struct_type(this->name(),
8147 case TYPE_CALL_MULTIPLE_RESULT:
8154 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
8156 this->named_btype_ = bt;
8158 if (base->is_slice_type())
8160 // We do not record slices as dependencies of other types,
8161 // because we can fill them in completely here with the final
8163 std::vector<Backend::Btyped_identifier> bfields;
8164 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
8165 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8166 this->named_btype_ = gogo->backend()->error_type();
8168 else if (base->interface_type() != NULL
8169 && !base->interface_type()->is_empty())
8171 // We do not record interfaces as dependencies of other types,
8172 // because we can fill them in completely here with the final
8174 std::vector<Backend::Btyped_identifier> bfields;
8175 get_backend_interface_fields(gogo, base->interface_type(), true,
8177 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8178 this->named_btype_ = gogo->backend()->error_type();
8182 // Get a tree for a named type.
8185 Named_type::do_get_backend(Gogo* gogo)
8187 if (this->is_error_)
8188 return gogo->backend()->error_type();
8190 Btype* bt = this->named_btype_;
8192 if (!gogo->named_types_are_converted())
8194 // We have not completed converting named types. NAMED_BTYPE_
8195 // is a placeholder and we shouldn't do anything further.
8199 // We don't build dependencies for types whose sizes do not
8200 // change or are not relevant, so we may see them here while
8201 // converting types.
8202 this->create_placeholder(gogo);
8203 bt = this->named_btype_;
8204 go_assert(bt != NULL);
8208 // We are not converting types. This should only be called if the
8209 // type has already been converted.
8210 if (!this->is_converted_)
8212 go_assert(saw_errors());
8213 return gogo->backend()->error_type();
8216 go_assert(bt != NULL);
8218 // Complete the tree.
8219 Type* base = this->type_->base();
8221 switch (base->classification())
8224 return gogo->backend()->error_type();
8238 if (!this->seen_in_get_backend_)
8240 this->seen_in_get_backend_ = true;
8241 base->struct_type()->finish_backend_fields(gogo);
8242 this->seen_in_get_backend_ = false;
8247 if (!this->seen_in_get_backend_)
8249 this->seen_in_get_backend_ = true;
8250 base->array_type()->finish_backend_element(gogo);
8251 this->seen_in_get_backend_ = false;
8255 case TYPE_INTERFACE:
8256 if (!this->seen_in_get_backend_)
8258 this->seen_in_get_backend_ = true;
8259 base->interface_type()->finish_backend_methods(gogo);
8260 this->seen_in_get_backend_ = false;
8265 // Don't build a circular data structure. GENERIC can't handle
8267 if (this->seen_in_get_backend_)
8269 this->is_circular_ = true;
8270 return gogo->backend()->circular_pointer_type(bt, true);
8272 this->seen_in_get_backend_ = true;
8273 bt1 = Type::get_named_base_btype(gogo, base);
8274 this->seen_in_get_backend_ = false;
8275 if (this->is_circular_)
8276 bt1 = gogo->backend()->circular_pointer_type(bt, true);
8277 if (!gogo->backend()->set_placeholder_function_type(bt, bt1))
8278 bt = gogo->backend()->error_type();
8282 // Don't build a circular data structure. GENERIC can't handle
8284 if (this->seen_in_get_backend_)
8286 this->is_circular_ = true;
8287 return gogo->backend()->circular_pointer_type(bt, false);
8289 this->seen_in_get_backend_ = true;
8290 bt1 = Type::get_named_base_btype(gogo, base);
8291 this->seen_in_get_backend_ = false;
8292 if (this->is_circular_)
8293 bt1 = gogo->backend()->circular_pointer_type(bt, false);
8294 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
8295 bt = gogo->backend()->error_type();
8300 case TYPE_CALL_MULTIPLE_RESULT:
8309 // Build a type descriptor for a named type.
8312 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8314 if (name == NULL && this->is_alias())
8315 return this->type_->type_descriptor(gogo, this->type_);
8317 // If NAME is not NULL, then we don't really want the type
8318 // descriptor for this type; we want the descriptor for the
8319 // underlying type, giving it the name NAME.
8320 return this->named_type_descriptor(gogo, this->type_,
8321 name == NULL ? this : name);
8324 // Add to the reflection string. This is used mostly for the name of
8325 // the type used in a type descriptor, not for actual reflection
8329 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
8331 if (this->is_alias())
8333 this->append_reflection(this->type_, gogo, ret);
8336 if (!this->is_builtin())
8338 // We handle -fgo-prefix and -fgo-pkgpath differently here for
8339 // compatibility with how the compiler worked before
8340 // -fgo-pkgpath was introduced.
8341 const Package* package = this->named_object_->package();
8342 if (gogo->pkgpath_from_option())
8343 ret->append(package != NULL ? package->pkgpath() : gogo->pkgpath());
8345 ret->append(package != NULL
8346 ? package->package_name()
8347 : gogo->package_name());
8348 ret->push_back('.');
8350 if (this->in_function_ != NULL)
8352 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
8353 ret->push_back('$');
8355 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
8358 // Get the mangled name.
8361 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8363 if (this->is_alias())
8365 this->append_mangled_name(this->type_, gogo, ret);
8368 Named_object* no = this->named_object_;
8370 if (this->is_builtin())
8371 go_assert(this->in_function_ == NULL);
8374 const std::string& pkgpath(no->package() == NULL
8375 ? gogo->pkgpath_symbol()
8376 : no->package()->pkgpath_symbol());
8378 name.append(1, '.');
8379 if (this->in_function_ != NULL)
8381 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
8382 name.append(1, '$');
8385 name.append(Gogo::unpack_hidden_name(no->name()));
8387 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
8392 // Export the type. This is called to export a global type.
8395 Named_type::export_named_type(Export* exp, const std::string&) const
8397 // We don't need to write the name of the type here, because it will
8398 // be written by Export::write_type anyhow.
8399 exp->write_c_string("type ");
8400 exp->write_type(this);
8401 exp->write_c_string(";\n");
8404 // Import a named type.
8407 Named_type::import_named_type(Import* imp, Named_type** ptype)
8409 imp->require_c_string("type ");
8410 Type *type = imp->read_type();
8411 *ptype = type->named_type();
8412 go_assert(*ptype != NULL);
8413 imp->require_c_string(";\n");
8416 // Export the type when it is referenced by another type. In this
8417 // case Export::export_type will already have issued the name.
8420 Named_type::do_export(Export* exp) const
8422 exp->write_type(this->type_);
8424 // To save space, we only export the methods directly attached to
8426 Bindings* methods = this->local_methods_;
8427 if (methods == NULL)
8430 exp->write_c_string("\n");
8431 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
8432 p != methods->end_definitions();
8435 exp->write_c_string(" ");
8436 (*p)->export_named_object(exp);
8439 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
8440 p != methods->end_declarations();
8443 if (p->second->is_function_declaration())
8445 exp->write_c_string(" ");
8446 p->second->export_named_object(exp);
8451 // Make a named type.
8454 Type::make_named_type(Named_object* named_object, Type* type,
8457 return new Named_type(named_object, type, location);
8460 // Finalize the methods for TYPE. It will be a named type or a struct
8461 // type. This sets *ALL_METHODS to the list of methods, and builds
8462 // all required stubs.
8465 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
8466 Methods** all_methods)
8468 *all_methods = NULL;
8469 Types_seen types_seen;
8470 Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen,
8472 Type::build_stub_methods(gogo, type, *all_methods, location);
8475 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
8476 // build up the struct field indexes as we go. DEPTH is the depth of
8477 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
8478 // adding these methods for an anonymous field with pointer type.
8479 // NEEDS_STUB_METHOD is true if we need to use a stub method which
8480 // calls the real method. TYPES_SEEN is used to avoid infinite
8484 Type::add_methods_for_type(const Type* type,
8485 const Method::Field_indexes* field_indexes,
8487 bool is_embedded_pointer,
8488 bool needs_stub_method,
8489 Types_seen* types_seen,
8492 // Pointer types may not have methods.
8493 if (type->points_to() != NULL)
8496 const Named_type* nt = type->named_type();
8499 std::pair<Types_seen::iterator, bool> ins = types_seen->insert(nt);
8505 Type::add_local_methods_for_type(nt, field_indexes, depth,
8506 is_embedded_pointer, needs_stub_method,
8509 Type::add_embedded_methods_for_type(type, field_indexes, depth,
8510 is_embedded_pointer, needs_stub_method,
8511 types_seen, methods);
8513 // If we are called with depth > 0, then we are looking at an
8514 // anonymous field of a struct. If such a field has interface type,
8515 // then we need to add the interface methods. We don't want to add
8516 // them when depth == 0, because we will already handle them
8517 // following the usual rules for an interface type.
8519 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
8522 // Add the local methods for the named type NT to *METHODS. The
8523 // parameters are as for add_methods_to_type.
8526 Type::add_local_methods_for_type(const Named_type* nt,
8527 const Method::Field_indexes* field_indexes,
8529 bool is_embedded_pointer,
8530 bool needs_stub_method,
8533 const Bindings* local_methods = nt->local_methods();
8534 if (local_methods == NULL)
8537 if (*methods == NULL)
8538 *methods = new Methods();
8540 for (Bindings::const_declarations_iterator p =
8541 local_methods->begin_declarations();
8542 p != local_methods->end_declarations();
8545 Named_object* no = p->second;
8546 bool is_value_method = (is_embedded_pointer
8547 || !Type::method_expects_pointer(no));
8548 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
8550 || (depth > 0 && is_value_method)));
8551 if (!(*methods)->insert(no->name(), m))
8556 // Add the embedded methods for TYPE to *METHODS. These are the
8557 // methods attached to anonymous fields. The parameters are as for
8558 // add_methods_to_type.
8561 Type::add_embedded_methods_for_type(const Type* type,
8562 const Method::Field_indexes* field_indexes,
8564 bool is_embedded_pointer,
8565 bool needs_stub_method,
8566 Types_seen* types_seen,
8569 // Look for anonymous fields in TYPE. TYPE has fields if it is a
8571 const Struct_type* st = type->struct_type();
8575 const Struct_field_list* fields = st->fields();
8580 for (Struct_field_list::const_iterator pf = fields->begin();
8581 pf != fields->end();
8584 if (!pf->is_anonymous())
8587 Type* ftype = pf->type();
8588 bool is_pointer = false;
8589 if (ftype->points_to() != NULL)
8591 ftype = ftype->points_to();
8594 Named_type* fnt = ftype->named_type();
8597 // This is an error, but it will be diagnosed elsewhere.
8601 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
8602 sub_field_indexes->next = field_indexes;
8603 sub_field_indexes->field_index = i;
8605 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
8606 (is_embedded_pointer || is_pointer),
8615 // If TYPE is an interface type, then add its method to *METHODS.
8616 // This is for interface methods attached to an anonymous field. The
8617 // parameters are as for add_methods_for_type.
8620 Type::add_interface_methods_for_type(const Type* type,
8621 const Method::Field_indexes* field_indexes,
8625 const Interface_type* it = type->interface_type();
8629 const Typed_identifier_list* imethods = it->methods();
8630 if (imethods == NULL)
8633 if (*methods == NULL)
8634 *methods = new Methods();
8636 for (Typed_identifier_list::const_iterator pm = imethods->begin();
8637 pm != imethods->end();
8640 Function_type* fntype = pm->type()->function_type();
8643 // This is an error, but it should be reported elsewhere
8644 // when we look at the methods for IT.
8647 go_assert(!fntype->is_method());
8648 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
8649 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
8650 field_indexes, depth);
8651 if (!(*methods)->insert(pm->name(), m))
8656 // Build stub methods for TYPE as needed. METHODS is the set of
8657 // methods for the type. A stub method may be needed when a type
8658 // inherits a method from an anonymous field. When we need the
8659 // address of the method, as in a type descriptor, we need to build a
8660 // little stub which does the required field dereferences and jumps to
8661 // the real method. LOCATION is the location of the type definition.
8664 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
8667 if (methods == NULL)
8669 for (Methods::const_iterator p = methods->begin();
8670 p != methods->end();
8673 Method* m = p->second;
8674 if (m->is_ambiguous() || !m->needs_stub_method())
8677 const std::string& name(p->first);
8679 // Build a stub method.
8681 const Function_type* fntype = m->type();
8683 static unsigned int counter;
8685 snprintf(buf, sizeof buf, "$this%u", counter);
8688 Type* receiver_type = const_cast<Type*>(type);
8689 if (!m->is_value_method())
8690 receiver_type = Type::make_pointer_type(receiver_type);
8691 Location receiver_location = m->receiver_location();
8692 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
8695 const Typed_identifier_list* fnparams = fntype->parameters();
8696 Typed_identifier_list* stub_params;
8697 if (fnparams == NULL || fnparams->empty())
8701 // We give each stub parameter a unique name.
8702 stub_params = new Typed_identifier_list();
8703 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
8704 pp != fnparams->end();
8708 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
8709 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
8715 const Typed_identifier_list* fnresults = fntype->results();
8716 Typed_identifier_list* stub_results;
8717 if (fnresults == NULL || fnresults->empty())
8718 stub_results = NULL;
8721 // We create the result parameters without any names, since
8722 // we won't refer to them.
8723 stub_results = new Typed_identifier_list();
8724 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
8725 pr != fnresults->end();
8727 stub_results->push_back(Typed_identifier("", pr->type(),
8731 Function_type* stub_type = Type::make_function_type(receiver,
8734 fntype->location());
8735 if (fntype->is_varargs())
8736 stub_type->set_is_varargs();
8738 // We only create the function in the package which creates the
8740 const Package* package;
8741 if (type->named_type() == NULL)
8744 package = type->named_type()->named_object()->package();
8746 if (package != NULL)
8747 stub = Named_object::make_function_declaration(name, package,
8748 stub_type, location);
8751 stub = gogo->start_function(name, stub_type, false,
8752 fntype->location());
8753 Type::build_one_stub_method(gogo, m, buf, stub_params,
8754 fntype->is_varargs(), location);
8755 gogo->finish_function(fntype->location());
8758 m->set_stub_object(stub);
8762 // Build a stub method which adjusts the receiver as required to call
8763 // METHOD. RECEIVER_NAME is the name we used for the receiver.
8764 // PARAMS is the list of function parameters.
8767 Type::build_one_stub_method(Gogo* gogo, Method* method,
8768 const char* receiver_name,
8769 const Typed_identifier_list* params,
8773 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
8774 go_assert(receiver_object != NULL);
8776 Expression* expr = Expression::make_var_reference(receiver_object, location);
8777 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
8778 if (expr->type()->points_to() == NULL)
8779 expr = Expression::make_unary(OPERATOR_AND, expr, location);
8781 Expression_list* arguments;
8782 if (params == NULL || params->empty())
8786 arguments = new Expression_list();
8787 for (Typed_identifier_list::const_iterator p = params->begin();
8791 Named_object* param = gogo->lookup(p->name(), NULL);
8792 go_assert(param != NULL);
8793 Expression* param_ref = Expression::make_var_reference(param,
8795 arguments->push_back(param_ref);
8799 Expression* func = method->bind_method(expr, location);
8800 go_assert(func != NULL);
8801 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
8803 call->set_hidden_fields_are_ok();
8804 size_t count = call->result_count();
8806 gogo->add_statement(Statement::make_statement(call, true));
8809 Expression_list* retvals = new Expression_list();
8811 retvals->push_back(call);
8814 for (size_t i = 0; i < count; ++i)
8815 retvals->push_back(Expression::make_call_result(call, i));
8817 Return_statement* retstat = Statement::make_return_statement(retvals,
8820 // We can return values with hidden fields from a stub. This is
8821 // necessary if the method is itself hidden.
8822 retstat->set_hidden_fields_are_ok();
8824 gogo->add_statement(retstat);
8828 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
8829 // in reverse order.
8832 Type::apply_field_indexes(Expression* expr,
8833 const Method::Field_indexes* field_indexes,
8836 if (field_indexes == NULL)
8838 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
8839 Struct_type* stype = expr->type()->deref()->struct_type();
8840 go_assert(stype != NULL
8841 && field_indexes->field_index < stype->field_count());
8842 if (expr->type()->struct_type() == NULL)
8844 go_assert(expr->type()->points_to() != NULL);
8845 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
8846 go_assert(expr->type()->struct_type() == stype);
8848 return Expression::make_field_reference(expr, field_indexes->field_index,
8852 // Return whether NO is a method for which the receiver is a pointer.
8855 Type::method_expects_pointer(const Named_object* no)
8857 const Function_type *fntype;
8858 if (no->is_function())
8859 fntype = no->func_value()->type();
8860 else if (no->is_function_declaration())
8861 fntype = no->func_declaration_value()->type();
8864 return fntype->receiver()->type()->points_to() != NULL;
8867 // Given a set of methods for a type, METHODS, return the method NAME,
8868 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
8869 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
8870 // but is ambiguous (and return NULL).
8873 Type::method_function(const Methods* methods, const std::string& name,
8876 if (is_ambiguous != NULL)
8877 *is_ambiguous = false;
8878 if (methods == NULL)
8880 Methods::const_iterator p = methods->find(name);
8881 if (p == methods->end())
8883 Method* m = p->second;
8884 if (m->is_ambiguous())
8886 if (is_ambiguous != NULL)
8887 *is_ambiguous = true;
8893 // Look for field or method NAME for TYPE. Return an Expression for
8894 // the field or method bound to EXPR. If there is no such field or
8895 // method, give an appropriate error and return an error expression.
8898 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
8899 const std::string& name,
8902 if (type->deref()->is_error_type())
8903 return Expression::make_error(location);
8905 const Named_type* nt = type->deref()->named_type();
8906 const Struct_type* st = type->deref()->struct_type();
8907 const Interface_type* it = type->interface_type();
8909 // If this is a pointer to a pointer, then it is possible that the
8910 // pointed-to type has methods.
8911 bool dereferenced = false;
8915 && type->points_to() != NULL
8916 && type->points_to()->points_to() != NULL)
8918 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
8919 type = type->points_to();
8920 if (type->deref()->is_error_type())
8921 return Expression::make_error(location);
8922 nt = type->points_to()->named_type();
8923 st = type->points_to()->struct_type();
8924 dereferenced = true;
8927 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
8928 || expr->is_addressable());
8929 std::vector<const Named_type*> seen;
8930 bool is_method = false;
8931 bool found_pointer_method = false;
8934 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
8935 &seen, NULL, &is_method,
8936 &found_pointer_method, &ambig1, &ambig2))
8941 go_assert(st != NULL);
8942 if (type->struct_type() == NULL)
8944 go_assert(type->points_to() != NULL);
8945 expr = Expression::make_unary(OPERATOR_MULT, expr,
8947 go_assert(expr->type()->struct_type() == st);
8949 ret = st->field_reference(expr, name, location);
8951 else if (it != NULL && it->find_method(name) != NULL)
8952 ret = Expression::make_interface_field_reference(expr, name,
8958 m = nt->method_function(name, NULL);
8959 else if (st != NULL)
8960 m = st->method_function(name, NULL);
8963 go_assert(m != NULL);
8964 if (dereferenced && m->is_value_method())
8967 "calling value method requires explicit dereference");
8968 return Expression::make_error(location);
8970 if (!m->is_value_method() && expr->type()->points_to() == NULL)
8971 expr = Expression::make_unary(OPERATOR_AND, expr, location);
8972 ret = m->bind_method(expr, location);
8974 go_assert(ret != NULL);
8979 if (!ambig1.empty())
8980 error_at(location, "%qs is ambiguous via %qs and %qs",
8981 Gogo::message_name(name).c_str(), ambig1.c_str(),
8983 else if (found_pointer_method)
8984 error_at(location, "method requires a pointer");
8985 else if (nt == NULL && st == NULL && it == NULL)
8987 ("reference to field %qs in object which "
8988 "has no fields or methods"),
8989 Gogo::message_name(name).c_str());
8993 if (!Gogo::is_hidden_name(name))
8994 is_unexported = false;
8997 std::string unpacked = Gogo::unpack_hidden_name(name);
8999 is_unexported = Type::is_unexported_field_or_method(gogo, type,
9004 error_at(location, "reference to unexported field or method %qs",
9005 Gogo::message_name(name).c_str());
9007 error_at(location, "reference to undefined field or method %qs",
9008 Gogo::message_name(name).c_str());
9010 return Expression::make_error(location);
9014 // Look in TYPE for a field or method named NAME, return true if one
9015 // is found. This looks through embedded anonymous fields and handles
9016 // ambiguity. If a method is found, sets *IS_METHOD to true;
9017 // otherwise, if a field is found, set it to false. If
9018 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
9019 // whose address can not be taken. SEEN is used to avoid infinite
9020 // recursion on invalid types.
9022 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
9023 // method we couldn't use because it requires a pointer. LEVEL is
9024 // used for recursive calls, and can be NULL for a non-recursive call.
9025 // When this function returns false because it finds that the name is
9026 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
9027 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
9028 // will be unchanged.
9030 // This function just returns whether or not there is a field or
9031 // method, and whether it is a field or method. It doesn't build an
9032 // expression to refer to it. If it is a method, we then look in the
9033 // list of all methods for the type. If it is a field, the search has
9034 // to be done again, looking only for fields, and building up the
9035 // expression as we go.
9038 Type::find_field_or_method(const Type* type,
9039 const std::string& name,
9040 bool receiver_can_be_pointer,
9041 std::vector<const Named_type*>* seen,
9044 bool* found_pointer_method,
9045 std::string* ambig1,
9046 std::string* ambig2)
9048 // Named types can have locally defined methods.
9049 const Named_type* nt = type->named_type();
9050 if (nt == NULL && type->points_to() != NULL)
9051 nt = type->points_to()->named_type();
9054 Named_object* no = nt->find_local_method(name);
9057 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
9063 // Record that we have found a pointer method in order to
9064 // give a better error message if we don't find anything
9066 *found_pointer_method = true;
9069 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9075 // We've already seen this type when searching for methods.
9081 // Interface types can have methods.
9082 const Interface_type* it = type->interface_type();
9083 if (it != NULL && it->find_method(name) != NULL)
9089 // Struct types can have fields. They can also inherit fields and
9090 // methods from anonymous fields.
9091 const Struct_type* st = type->deref()->struct_type();
9094 const Struct_field_list* fields = st->fields();
9099 seen->push_back(nt);
9101 int found_level = 0;
9102 bool found_is_method = false;
9103 std::string found_ambig1;
9104 std::string found_ambig2;
9105 const Struct_field* found_parent = NULL;
9106 for (Struct_field_list::const_iterator pf = fields->begin();
9107 pf != fields->end();
9110 if (pf->is_field_name(name))
9118 if (!pf->is_anonymous())
9121 if (pf->type()->deref()->is_error_type()
9122 || pf->type()->deref()->is_undefined())
9125 Named_type* fnt = pf->type()->named_type();
9127 fnt = pf->type()->deref()->named_type();
9128 go_assert(fnt != NULL);
9130 int sublevel = level == NULL ? 1 : *level + 1;
9132 std::string subambig1;
9133 std::string subambig2;
9134 bool subfound = Type::find_field_or_method(fnt,
9136 receiver_can_be_pointer,
9140 found_pointer_method,
9145 if (!subambig1.empty())
9147 // The name was found via this field, but is ambiguous.
9148 // if the ambiguity is lower or at the same level as
9149 // anything else we have already found, then we want to
9150 // pass the ambiguity back to the caller.
9151 if (found_level == 0 || sublevel <= found_level)
9153 found_ambig1 = (Gogo::message_name(pf->field_name())
9155 found_ambig2 = (Gogo::message_name(pf->field_name())
9157 found_level = sublevel;
9163 // The name was found via this field. Use the level to see
9164 // if we want to use this one, or whether it introduces an
9166 if (found_level == 0 || sublevel < found_level)
9168 found_level = sublevel;
9169 found_is_method = sub_is_method;
9170 found_ambig1.clear();
9171 found_ambig2.clear();
9172 found_parent = &*pf;
9174 else if (sublevel > found_level)
9176 else if (found_ambig1.empty())
9178 // We found an ambiguity.
9179 go_assert(found_parent != NULL);
9180 found_ambig1 = Gogo::message_name(found_parent->field_name());
9181 found_ambig2 = Gogo::message_name(pf->field_name());
9185 // We found an ambiguity, but we already know of one.
9186 // Just report the earlier one.
9191 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
9192 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
9193 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
9194 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
9199 if (found_level == 0)
9201 else if (!found_ambig1.empty())
9203 go_assert(!found_ambig1.empty());
9204 ambig1->assign(found_ambig1);
9205 ambig2->assign(found_ambig2);
9207 *level = found_level;
9213 *level = found_level;
9214 *is_method = found_is_method;
9219 // Return whether NAME is an unexported field or method for TYPE.
9222 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
9223 const std::string& name,
9224 std::vector<const Named_type*>* seen)
9226 const Named_type* nt = type->named_type();
9228 nt = type->deref()->named_type();
9231 if (nt->is_unexported_local_method(gogo, name))
9234 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9240 // We've already seen this type.
9246 const Interface_type* it = type->interface_type();
9247 if (it != NULL && it->is_unexported_method(gogo, name))
9250 type = type->deref();
9252 const Struct_type* st = type->struct_type();
9253 if (st != NULL && st->is_unexported_local_field(gogo, name))
9259 const Struct_field_list* fields = st->fields();
9264 seen->push_back(nt);
9266 for (Struct_field_list::const_iterator pf = fields->begin();
9267 pf != fields->end();
9270 if (pf->is_anonymous()
9271 && !pf->type()->deref()->is_error_type()
9272 && !pf->type()->deref()->is_undefined())
9274 Named_type* subtype = pf->type()->named_type();
9275 if (subtype == NULL)
9276 subtype = pf->type()->deref()->named_type();
9277 if (subtype == NULL)
9279 // This is an error, but it will be diagnosed elsewhere.
9282 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
9297 // Class Forward_declaration.
9299 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
9300 : Type(TYPE_FORWARD),
9301 named_object_(named_object->resolve()), warned_(false)
9303 go_assert(this->named_object_->is_unknown()
9304 || this->named_object_->is_type_declaration());
9307 // Return the named object.
9310 Forward_declaration_type::named_object()
9312 return this->named_object_->resolve();
9316 Forward_declaration_type::named_object() const
9318 return this->named_object_->resolve();
9321 // Return the name of the forward declared type.
9324 Forward_declaration_type::name() const
9326 return this->named_object()->name();
9329 // Warn about a use of a type which has been declared but not defined.
9332 Forward_declaration_type::warn() const
9334 Named_object* no = this->named_object_->resolve();
9335 if (no->is_unknown())
9337 // The name was not defined anywhere.
9340 error_at(this->named_object_->location(),
9341 "use of undefined type %qs",
9342 no->message_name().c_str());
9343 this->warned_ = true;
9346 else if (no->is_type_declaration())
9348 // The name was seen as a type, but the type was never defined.
9349 if (no->type_declaration_value()->using_type())
9351 error_at(this->named_object_->location(),
9352 "use of undefined type %qs",
9353 no->message_name().c_str());
9354 this->warned_ = true;
9359 // The name was defined, but not as a type.
9362 error_at(this->named_object_->location(), "expected type");
9363 this->warned_ = true;
9368 // Get the base type of a declaration. This gives an error if the
9369 // type has not yet been defined.
9372 Forward_declaration_type::real_type()
9374 if (this->is_defined())
9375 return this->named_object()->type_value();
9379 return Type::make_error_type();
9384 Forward_declaration_type::real_type() const
9386 if (this->is_defined())
9387 return this->named_object()->type_value();
9391 return Type::make_error_type();
9395 // Return whether the base type is defined.
9398 Forward_declaration_type::is_defined() const
9400 return this->named_object()->is_type();
9403 // Add a method. This is used when methods are defined before the
9407 Forward_declaration_type::add_method(const std::string& name,
9410 Named_object* no = this->named_object();
9411 if (no->is_unknown())
9412 no->declare_as_type();
9413 return no->type_declaration_value()->add_method(name, function);
9416 // Add a method declaration. This is used when methods are declared
9420 Forward_declaration_type::add_method_declaration(const std::string& name,
9422 Function_type* type,
9425 Named_object* no = this->named_object();
9426 if (no->is_unknown())
9427 no->declare_as_type();
9428 Type_declaration* td = no->type_declaration_value();
9429 return td->add_method_declaration(name, package, type, location);
9435 Forward_declaration_type::do_traverse(Traverse* traverse)
9437 if (this->is_defined()
9438 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
9439 return TRAVERSE_EXIT;
9440 return TRAVERSE_CONTINUE;
9443 // Get the backend representation for the type.
9446 Forward_declaration_type::do_get_backend(Gogo* gogo)
9448 if (this->is_defined())
9449 return Type::get_named_base_btype(gogo, this->real_type());
9452 return gogo->backend()->error_type();
9454 // We represent an undefined type as a struct with no fields. That
9455 // should work fine for the backend, since the same case can arise
9457 std::vector<Backend::Btyped_identifier> fields;
9458 Btype* bt = gogo->backend()->struct_type(fields);
9459 return gogo->backend()->named_type(this->name(), bt,
9460 this->named_object()->location());
9463 // Build a type descriptor for a forwarded type.
9466 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9468 Location ploc = Linemap::predeclared_location();
9469 if (!this->is_defined())
9470 return Expression::make_error(ploc);
9473 Type* t = this->real_type();
9475 return this->named_type_descriptor(gogo, t, name);
9477 return Expression::make_type_descriptor(t, ploc);
9481 // The reflection string.
9484 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
9486 this->append_reflection(this->real_type(), gogo, ret);
9489 // The mangled name.
9492 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
9494 if (this->is_defined())
9495 this->append_mangled_name(this->real_type(), gogo, ret);
9498 const Named_object* no = this->named_object();
9500 if (no->package() == NULL)
9501 name = gogo->pkgpath_symbol();
9503 name = no->package()->pkgpath_symbol();
9505 name += Gogo::unpack_hidden_name(no->name());
9507 snprintf(buf, sizeof buf, "N%u_",
9508 static_cast<unsigned int>(name.length()));
9514 // Export a forward declaration. This can happen when a defined type
9515 // refers to a type which is only declared (and is presumably defined
9516 // in some other file in the same package).
9519 Forward_declaration_type::do_export(Export*) const
9521 // If there is a base type, that should be exported instead of this.
9522 go_assert(!this->is_defined());
9524 // We don't output anything.
9527 // Make a forward declaration.
9530 Type::make_forward_declaration(Named_object* named_object)
9532 return new Forward_declaration_type(named_object);
9535 // Class Typed_identifier_list.
9537 // Sort the entries by name.
9539 struct Typed_identifier_list_sort
9543 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
9544 { return t1.name() < t2.name(); }
9548 Typed_identifier_list::sort_by_name()
9550 std::sort(this->entries_.begin(), this->entries_.end(),
9551 Typed_identifier_list_sort());
9557 Typed_identifier_list::traverse(Traverse* traverse)
9559 for (Typed_identifier_list::const_iterator p = this->begin();
9563 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
9564 return TRAVERSE_EXIT;
9566 return TRAVERSE_CONTINUE;
9571 Typed_identifier_list*
9572 Typed_identifier_list::copy() const
9574 Typed_identifier_list* ret = new Typed_identifier_list();
9575 for (Typed_identifier_list::const_iterator p = this->begin();
9578 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));