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& unique_prefix(no->package() == NULL
1305 ? gogo->unique_prefix()
1306 : no->package()->unique_prefix());
1307 const std::string& package_name(no->package() == NULL
1308 ? gogo->package_name()
1309 : no->package()->name());
1310 ret.append(unique_prefix);
1312 ret.append(package_name);
1314 if (in_function != NULL)
1316 ret.append(Gogo::unpack_hidden_name(in_function->name()));
1320 ret.append(no->name());
1324 // Return true if this type descriptor is defined in a different
1325 // package. If this returns true it sets *PACKAGE to the package.
1328 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1329 const Package** package)
1333 if (nt->named_object()->package() != NULL)
1335 // This is a named type defined in a different package. The
1336 // type descriptor should be defined in that package.
1337 *package = nt->named_object()->package();
1343 if (this->points_to() != NULL
1344 && this->points_to()->named_type() != NULL
1345 && this->points_to()->named_type()->named_object()->package() != NULL)
1347 // This is an unnamed pointer to a named type defined in a
1348 // different package. The descriptor should be defined in
1350 *package = this->points_to()->named_type()->named_object()->package();
1357 // Return a composite literal for a type descriptor.
1360 Type::type_descriptor(Gogo* gogo, Type* type)
1362 return type->do_type_descriptor(gogo, NULL);
1365 // Return a composite literal for a type descriptor with a name.
1368 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1370 go_assert(name != NULL && type->named_type() != name);
1371 return type->do_type_descriptor(gogo, name);
1374 // Make a builtin struct type from a list of fields. The fields are
1375 // pairs of a name and a type.
1378 Type::make_builtin_struct_type(int nfields, ...)
1381 va_start(ap, nfields);
1383 Location bloc = Linemap::predeclared_location();
1384 Struct_field_list* sfl = new Struct_field_list();
1385 for (int i = 0; i < nfields; i++)
1387 const char* field_name = va_arg(ap, const char *);
1388 Type* type = va_arg(ap, Type*);
1389 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1394 return Type::make_struct_type(sfl, bloc);
1397 // A list of builtin named types.
1399 std::vector<Named_type*> Type::named_builtin_types;
1401 // Make a builtin named type.
1404 Type::make_builtin_named_type(const char* name, Type* type)
1406 Location bloc = Linemap::predeclared_location();
1407 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1408 Named_type* ret = no->type_value();
1409 Type::named_builtin_types.push_back(ret);
1413 // Convert the named builtin types.
1416 Type::convert_builtin_named_types(Gogo* gogo)
1418 for (std::vector<Named_type*>::const_iterator p =
1419 Type::named_builtin_types.begin();
1420 p != Type::named_builtin_types.end();
1423 bool r = (*p)->verify();
1425 (*p)->convert(gogo);
1429 // Return the type of a type descriptor. We should really tie this to
1430 // runtime.Type rather than copying it. This must match commonType in
1431 // libgo/go/runtime/type.go.
1434 Type::make_type_descriptor_type()
1439 Location bloc = Linemap::predeclared_location();
1441 Type* uint8_type = Type::lookup_integer_type("uint8");
1442 Type* uint32_type = Type::lookup_integer_type("uint32");
1443 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1444 Type* string_type = Type::lookup_string_type();
1445 Type* pointer_string_type = Type::make_pointer_type(string_type);
1447 // This is an unnamed version of unsafe.Pointer. Perhaps we
1448 // should use the named version instead, although that would
1449 // require us to create the unsafe package if it has not been
1450 // imported. It probably doesn't matter.
1451 Type* void_type = Type::make_void_type();
1452 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1454 // Forward declaration for the type descriptor type.
1455 Named_object* named_type_descriptor_type =
1456 Named_object::make_type_declaration("commonType", NULL, bloc);
1457 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1458 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1460 // The type of a method on a concrete type.
1461 Struct_type* method_type =
1462 Type::make_builtin_struct_type(5,
1463 "name", pointer_string_type,
1464 "pkgPath", pointer_string_type,
1465 "mtyp", pointer_type_descriptor_type,
1466 "typ", pointer_type_descriptor_type,
1467 "tfn", unsafe_pointer_type);
1468 Named_type* named_method_type =
1469 Type::make_builtin_named_type("method", method_type);
1471 // Information for types with a name or methods.
1472 Type* slice_named_method_type =
1473 Type::make_array_type(named_method_type, NULL);
1474 Struct_type* uncommon_type =
1475 Type::make_builtin_struct_type(3,
1476 "name", pointer_string_type,
1477 "pkgPath", pointer_string_type,
1478 "methods", slice_named_method_type);
1479 Named_type* named_uncommon_type =
1480 Type::make_builtin_named_type("uncommonType", uncommon_type);
1482 Type* pointer_uncommon_type =
1483 Type::make_pointer_type(named_uncommon_type);
1485 // The type descriptor type.
1487 Typed_identifier_list* params = new Typed_identifier_list();
1488 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1489 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1491 Typed_identifier_list* results = new Typed_identifier_list();
1492 results->push_back(Typed_identifier("", uintptr_type, bloc));
1494 Type* hashfn_type = Type::make_function_type(NULL, params, results, bloc);
1496 params = new Typed_identifier_list();
1497 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1498 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1499 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1501 results = new Typed_identifier_list();
1502 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1504 Type* equalfn_type = Type::make_function_type(NULL, params, results,
1507 Struct_type* type_descriptor_type =
1508 Type::make_builtin_struct_type(10,
1510 "align", uint8_type,
1511 "fieldAlign", uint8_type,
1512 "size", uintptr_type,
1513 "hash", uint32_type,
1514 "hashfn", hashfn_type,
1515 "equalfn", equalfn_type,
1516 "string", pointer_string_type,
1517 "", pointer_uncommon_type,
1519 pointer_type_descriptor_type);
1521 Named_type* named = Type::make_builtin_named_type("commonType",
1522 type_descriptor_type);
1524 named_type_descriptor_type->set_type_value(named);
1532 // Make the type of a pointer to a type descriptor as represented in
1536 Type::make_type_descriptor_ptr_type()
1540 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1544 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1545 // hash code for this type and which compare whether two values of
1546 // this type are equal. If NAME is not NULL it is the name of this
1547 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1548 // functions, for convenience; they may be NULL.
1551 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1552 Function_type* equal_fntype, Named_object** hash_fn,
1553 Named_object** equal_fn)
1555 if (hash_fntype == NULL || equal_fntype == NULL)
1557 Location bloc = Linemap::predeclared_location();
1559 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1560 Type* void_type = Type::make_void_type();
1561 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1563 if (hash_fntype == NULL)
1565 Typed_identifier_list* params = new Typed_identifier_list();
1566 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1568 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1570 Typed_identifier_list* results = new Typed_identifier_list();
1571 results->push_back(Typed_identifier("", uintptr_type, bloc));
1573 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1575 if (equal_fntype == NULL)
1577 Typed_identifier_list* params = new Typed_identifier_list();
1578 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1580 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1582 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1584 Typed_identifier_list* results = new Typed_identifier_list();
1585 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1588 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1592 const char* hash_fnname;
1593 const char* equal_fnname;
1594 if (this->compare_is_identity(gogo))
1596 hash_fnname = "__go_type_hash_identity";
1597 equal_fnname = "__go_type_equal_identity";
1599 else if (!this->is_comparable())
1601 hash_fnname = "__go_type_hash_error";
1602 equal_fnname = "__go_type_equal_error";
1606 switch (this->base()->classification())
1608 case Type::TYPE_ERROR:
1609 case Type::TYPE_VOID:
1610 case Type::TYPE_NIL:
1611 case Type::TYPE_FUNCTION:
1612 case Type::TYPE_MAP:
1613 // For these types is_comparable should have returned false.
1616 case Type::TYPE_BOOLEAN:
1617 case Type::TYPE_INTEGER:
1618 case Type::TYPE_POINTER:
1619 case Type::TYPE_CHANNEL:
1620 // For these types compare_is_identity should have returned true.
1623 case Type::TYPE_FLOAT:
1624 hash_fnname = "__go_type_hash_float";
1625 equal_fnname = "__go_type_equal_float";
1628 case Type::TYPE_COMPLEX:
1629 hash_fnname = "__go_type_hash_complex";
1630 equal_fnname = "__go_type_equal_complex";
1633 case Type::TYPE_STRING:
1634 hash_fnname = "__go_type_hash_string";
1635 equal_fnname = "__go_type_equal_string";
1638 case Type::TYPE_STRUCT:
1640 // This is a struct which can not be compared using a
1641 // simple identity function. We need to build a function
1643 this->specific_type_functions(gogo, name, hash_fntype,
1644 equal_fntype, hash_fn, equal_fn);
1648 case Type::TYPE_ARRAY:
1649 if (this->is_slice_type())
1651 // Type::is_compatible_for_comparison should have
1657 // This is an array which can not be compared using a
1658 // simple identity function. We need to build a
1659 // function for comparison.
1660 this->specific_type_functions(gogo, name, hash_fntype,
1661 equal_fntype, hash_fn, equal_fn);
1666 case Type::TYPE_INTERFACE:
1667 if (this->interface_type()->is_empty())
1669 hash_fnname = "__go_type_hash_empty_interface";
1670 equal_fnname = "__go_type_equal_empty_interface";
1674 hash_fnname = "__go_type_hash_interface";
1675 equal_fnname = "__go_type_equal_interface";
1679 case Type::TYPE_NAMED:
1680 case Type::TYPE_FORWARD:
1689 Location bloc = Linemap::predeclared_location();
1690 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1692 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1693 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1694 equal_fntype, bloc);
1695 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1698 // A hash table mapping types to the specific hash functions.
1700 Type::Type_functions Type::type_functions_table;
1702 // Handle a type function which is specific to a type: a struct or
1703 // array which can not use an identity comparison.
1706 Type::specific_type_functions(Gogo* gogo, Named_type* name,
1707 Function_type* hash_fntype,
1708 Function_type* equal_fntype,
1709 Named_object** hash_fn,
1710 Named_object** equal_fn)
1712 Hash_equal_fn fnull(NULL, NULL);
1713 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1714 std::pair<Type_functions::iterator, bool> ins =
1715 Type::type_functions_table.insert(val);
1718 // We already have functions for this type
1719 *hash_fn = ins.first->second.first;
1720 *equal_fn = ins.first->second.second;
1724 std::string base_name;
1727 // Mangled names can have '.' if they happen to refer to named
1728 // types in some way. That's fine if this is simply a named
1729 // type, but otherwise it will confuse the code that builds
1730 // function identifiers. Remove '.' when necessary.
1731 base_name = this->mangled_name(gogo);
1733 while ((i = base_name.find('.')) != std::string::npos)
1735 base_name = gogo->pack_hidden_name(base_name, false);
1739 // This name is already hidden or not as appropriate.
1740 base_name = name->name();
1741 const Named_object* in_function = name->in_function();
1742 if (in_function != NULL)
1743 base_name += '$' + in_function->name();
1745 std::string hash_name = base_name + "$hash";
1746 std::string equal_name = base_name + "$equal";
1748 Location bloc = Linemap::predeclared_location();
1750 const Package* package = NULL;
1751 bool is_defined_elsewhere =
1752 this->type_descriptor_defined_elsewhere(name, &package);
1753 if (is_defined_elsewhere)
1755 *hash_fn = Named_object::make_function_declaration(hash_name, package,
1757 *equal_fn = Named_object::make_function_declaration(equal_name, package,
1758 equal_fntype, bloc);
1762 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
1763 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
1767 ins.first->second.first = *hash_fn;
1768 ins.first->second.second = *equal_fn;
1770 if (!is_defined_elsewhere)
1772 if (gogo->in_global_scope())
1773 this->write_specific_type_functions(gogo, name, hash_name, hash_fntype,
1774 equal_name, equal_fntype);
1776 gogo->queue_specific_type_function(this, name, hash_name, hash_fntype,
1777 equal_name, equal_fntype);
1781 // Write the hash and equality functions for a type which needs to be
1782 // written specially.
1785 Type::write_specific_type_functions(Gogo* gogo, Named_type* name,
1786 const std::string& hash_name,
1787 Function_type* hash_fntype,
1788 const std::string& equal_name,
1789 Function_type* equal_fntype)
1791 Location bloc = Linemap::predeclared_location();
1793 if (gogo->specific_type_functions_are_written())
1795 go_assert(saw_errors());
1799 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
1801 gogo->start_block(bloc);
1803 if (this->struct_type() != NULL)
1804 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
1806 else if (this->array_type() != NULL)
1807 this->array_type()->write_hash_function(gogo, name, hash_fntype,
1812 Block* b = gogo->finish_block(bloc);
1813 gogo->add_block(b, bloc);
1814 gogo->lower_block(hash_fn, b);
1815 gogo->finish_function(bloc);
1817 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
1819 gogo->start_block(bloc);
1821 if (this->struct_type() != NULL)
1822 this->struct_type()->write_equal_function(gogo, name);
1823 else if (this->array_type() != NULL)
1824 this->array_type()->write_equal_function(gogo, name);
1828 b = gogo->finish_block(bloc);
1829 gogo->add_block(b, bloc);
1830 gogo->lower_block(equal_fn, b);
1831 gogo->finish_function(bloc);
1834 // Return a composite literal for the type descriptor for a plain type
1835 // of kind RUNTIME_TYPE_KIND named NAME.
1838 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
1839 Named_type* name, const Methods* methods,
1840 bool only_value_methods)
1842 Location bloc = Linemap::predeclared_location();
1844 Type* td_type = Type::make_type_descriptor_type();
1845 const Struct_field_list* fields = td_type->struct_type()->fields();
1847 Expression_list* vals = new Expression_list();
1850 if (!this->has_pointer())
1851 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
1852 Struct_field_list::const_iterator p = fields->begin();
1853 go_assert(p->is_field_name("Kind"));
1855 mpz_init_set_ui(iv, runtime_type_kind);
1856 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1859 go_assert(p->is_field_name("align"));
1860 Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT;
1861 vals->push_back(Expression::make_type_info(this, type_info));
1864 go_assert(p->is_field_name("fieldAlign"));
1865 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
1866 vals->push_back(Expression::make_type_info(this, type_info));
1869 go_assert(p->is_field_name("size"));
1870 type_info = Expression::TYPE_INFO_SIZE;
1871 vals->push_back(Expression::make_type_info(this, type_info));
1874 go_assert(p->is_field_name("hash"));
1877 h = name->hash_for_method(gogo);
1879 h = this->hash_for_method(gogo);
1881 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1884 go_assert(p->is_field_name("hashfn"));
1885 Function_type* hash_fntype = p->type()->function_type();
1888 go_assert(p->is_field_name("equalfn"));
1889 Function_type* equal_fntype = p->type()->function_type();
1891 Named_object* hash_fn;
1892 Named_object* equal_fn;
1893 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
1895 vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
1896 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
1899 go_assert(p->is_field_name("string"));
1900 Expression* s = Expression::make_string((name != NULL
1901 ? name->reflection(gogo)
1902 : this->reflection(gogo)),
1904 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1907 go_assert(p->is_field_name("uncommonType"));
1908 if (name == NULL && methods == NULL)
1909 vals->push_back(Expression::make_nil(bloc));
1912 if (methods == NULL)
1913 methods = name->methods();
1914 vals->push_back(this->uncommon_type_constructor(gogo,
1917 only_value_methods));
1921 go_assert(p->is_field_name("ptrToThis"));
1923 vals->push_back(Expression::make_nil(bloc));
1926 Type* pt = Type::make_pointer_type(name);
1927 vals->push_back(Expression::make_type_descriptor(pt, bloc));
1931 go_assert(p == fields->end());
1935 return Expression::make_struct_composite_literal(td_type, vals, bloc);
1938 // Return a composite literal for the uncommon type information for
1939 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
1940 // struct. If name is not NULL, it is the name of the type. If
1941 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
1942 // is true if only value methods should be included. At least one of
1943 // NAME and METHODS must not be NULL.
1946 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
1947 Named_type* name, const Methods* methods,
1948 bool only_value_methods) const
1950 Location bloc = Linemap::predeclared_location();
1952 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
1954 Expression_list* vals = new Expression_list();
1957 Struct_field_list::const_iterator p = fields->begin();
1958 go_assert(p->is_field_name("name"));
1961 go_assert(p->is_field_name("pkgPath"));
1965 vals->push_back(Expression::make_nil(bloc));
1966 vals->push_back(Expression::make_nil(bloc));
1970 Named_object* no = name->named_object();
1971 std::string n = Gogo::unpack_hidden_name(no->name());
1972 Expression* s = Expression::make_string(n, bloc);
1973 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1975 if (name->is_builtin())
1976 vals->push_back(Expression::make_nil(bloc));
1979 const Package* package = no->package();
1980 const std::string& unique_prefix(package == NULL
1981 ? gogo->unique_prefix()
1982 : package->unique_prefix());
1983 const std::string& package_name(package == NULL
1984 ? gogo->package_name()
1986 n.assign(unique_prefix);
1988 n.append(package_name);
1989 if (name->in_function() != NULL)
1992 n.append(Gogo::unpack_hidden_name(name->in_function()->name()));
1994 s = Expression::make_string(n, bloc);
1995 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2000 go_assert(p->is_field_name("methods"));
2001 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
2002 only_value_methods));
2005 go_assert(p == fields->end());
2007 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
2009 return Expression::make_unary(OPERATOR_AND, r, bloc);
2012 // Sort methods by name.
2018 operator()(const std::pair<std::string, const Method*>& m1,
2019 const std::pair<std::string, const Method*>& m2) const
2020 { return m1.first < m2.first; }
2023 // Return a composite literal for the type method table for this type.
2024 // METHODS_TYPE is the type of the table, and is a slice type.
2025 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
2026 // then only value methods are used.
2029 Type::methods_constructor(Gogo* gogo, Type* methods_type,
2030 const Methods* methods,
2031 bool only_value_methods) const
2033 Location bloc = Linemap::predeclared_location();
2035 std::vector<std::pair<std::string, const Method*> > smethods;
2036 if (methods != NULL)
2038 smethods.reserve(methods->count());
2039 for (Methods::const_iterator p = methods->begin();
2040 p != methods->end();
2043 if (p->second->is_ambiguous())
2045 if (only_value_methods && !p->second->is_value_method())
2047 smethods.push_back(std::make_pair(p->first, p->second));
2051 if (smethods.empty())
2052 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
2054 std::sort(smethods.begin(), smethods.end(), Sort_methods());
2056 Type* method_type = methods_type->array_type()->element_type();
2058 Expression_list* vals = new Expression_list();
2059 vals->reserve(smethods.size());
2060 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
2062 p != smethods.end();
2064 vals->push_back(this->method_constructor(gogo, method_type, p->first,
2065 p->second, only_value_methods));
2067 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
2070 // Return a composite literal for a single method. METHOD_TYPE is the
2071 // type of the entry. METHOD_NAME is the name of the method and M is
2072 // the method information.
2075 Type::method_constructor(Gogo*, Type* method_type,
2076 const std::string& method_name,
2078 bool only_value_methods) const
2080 Location bloc = Linemap::predeclared_location();
2082 const Struct_field_list* fields = method_type->struct_type()->fields();
2084 Expression_list* vals = new Expression_list();
2087 Struct_field_list::const_iterator p = fields->begin();
2088 go_assert(p->is_field_name("name"));
2089 const std::string n = Gogo::unpack_hidden_name(method_name);
2090 Expression* s = Expression::make_string(n, bloc);
2091 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2094 go_assert(p->is_field_name("pkgPath"));
2095 if (!Gogo::is_hidden_name(method_name))
2096 vals->push_back(Expression::make_nil(bloc));
2099 s = Expression::make_string(Gogo::hidden_name_prefix(method_name), bloc);
2100 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2103 Named_object* no = (m->needs_stub_method()
2105 : m->named_object());
2107 Function_type* mtype;
2108 if (no->is_function())
2109 mtype = no->func_value()->type();
2111 mtype = no->func_declaration_value()->type();
2112 go_assert(mtype->is_method());
2113 Type* nonmethod_type = mtype->copy_without_receiver();
2116 go_assert(p->is_field_name("mtyp"));
2117 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
2120 go_assert(p->is_field_name("typ"));
2121 if (!only_value_methods && m->is_value_method())
2123 // This is a value method on a pointer type. Change the type of
2124 // the method to use a pointer receiver. The implementation
2125 // always uses a pointer receiver anyhow.
2126 Type* rtype = mtype->receiver()->type();
2127 Type* prtype = Type::make_pointer_type(rtype);
2128 Typed_identifier* receiver =
2129 new Typed_identifier(mtype->receiver()->name(), prtype,
2130 mtype->receiver()->location());
2131 mtype = Type::make_function_type(receiver,
2132 (mtype->parameters() == NULL
2134 : mtype->parameters()->copy()),
2135 (mtype->results() == NULL
2137 : mtype->results()->copy()),
2140 vals->push_back(Expression::make_type_descriptor(mtype, bloc));
2143 go_assert(p->is_field_name("tfn"));
2144 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
2147 go_assert(p == fields->end());
2149 return Expression::make_struct_composite_literal(method_type, vals, bloc);
2152 // Return a composite literal for the type descriptor of a plain type.
2153 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
2154 // NULL, it is the name to use as well as the list of methods.
2157 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
2160 return this->type_descriptor_constructor(gogo, runtime_type_kind,
2164 // Return the type reflection string for this type.
2167 Type::reflection(Gogo* gogo) const
2171 // The do_reflection virtual function should set RET to the
2172 // reflection string.
2173 this->do_reflection(gogo, &ret);
2178 // Return a mangled name for the type.
2181 Type::mangled_name(Gogo* gogo) const
2185 // The do_mangled_name virtual function should set RET to the
2186 // mangled name. For a composite type it should append a code for
2187 // the composition and then call do_mangled_name on the components.
2188 this->do_mangled_name(gogo, &ret);
2193 // Return whether the backend size of the type is known.
2196 Type::is_backend_type_size_known(Gogo* gogo)
2198 switch (this->classification_)
2212 case TYPE_INTERFACE:
2217 const Struct_field_list* fields = this->struct_type()->fields();
2218 for (Struct_field_list::const_iterator pf = fields->begin();
2219 pf != fields->end();
2221 if (!pf->type()->is_backend_type_size_known(gogo))
2228 const Array_type* at = this->array_type();
2229 if (at->length() == NULL)
2236 bool length_known = at->length()->integer_constant_value(true,
2242 return at->element_type()->is_backend_type_size_known(gogo);
2247 // Begin converting this type to the backend representation.
2248 // This will create a placeholder if necessary.
2249 this->get_backend(gogo);
2250 return this->named_type()->is_named_backend_type_size_known();
2254 Forward_declaration_type* fdt = this->forward_declaration_type();
2255 return fdt->real_type()->is_backend_type_size_known(gogo);
2259 case TYPE_CALL_MULTIPLE_RESULT:
2267 // If the size of the type can be determined, set *PSIZE to the size
2268 // in bytes and return true. Otherwise, return false. This queries
2272 Type::backend_type_size(Gogo* gogo, unsigned int *psize)
2274 if (!this->is_backend_type_size_known(gogo))
2276 Btype* bt = this->get_backend_placeholder(gogo);
2277 size_t size = gogo->backend()->type_size(bt);
2278 *psize = static_cast<unsigned int>(size);
2284 // If the alignment of the type can be determined, set *PALIGN to
2285 // the alignment in bytes and return true. Otherwise, return false.
2288 Type::backend_type_align(Gogo* gogo, unsigned int *palign)
2290 if (!this->is_backend_type_size_known(gogo))
2292 Btype* bt = this->get_backend_placeholder(gogo);
2293 size_t align = gogo->backend()->type_alignment(bt);
2294 *palign = static_cast<unsigned int>(align);
2295 if (*palign != align)
2300 // Like backend_type_align, but return the alignment when used as a
2304 Type::backend_type_field_align(Gogo* gogo, unsigned int *palign)
2306 if (!this->is_backend_type_size_known(gogo))
2308 Btype* bt = this->get_backend_placeholder(gogo);
2309 size_t a = gogo->backend()->type_field_alignment(bt);
2310 *palign = static_cast<unsigned int>(a);
2316 // Default function to export a type.
2319 Type::do_export(Export*) const
2327 Type::import_type(Import* imp)
2329 if (imp->match_c_string("("))
2330 return Function_type::do_import(imp);
2331 else if (imp->match_c_string("*"))
2332 return Pointer_type::do_import(imp);
2333 else if (imp->match_c_string("struct "))
2334 return Struct_type::do_import(imp);
2335 else if (imp->match_c_string("["))
2336 return Array_type::do_import(imp);
2337 else if (imp->match_c_string("map "))
2338 return Map_type::do_import(imp);
2339 else if (imp->match_c_string("chan "))
2340 return Channel_type::do_import(imp);
2341 else if (imp->match_c_string("interface"))
2342 return Interface_type::do_import(imp);
2345 error_at(imp->location(), "import error: expected type");
2346 return Type::make_error_type();
2350 // A type used to indicate a parsing error. This exists to simplify
2351 // later error detection.
2353 class Error_type : public Type
2362 do_compare_is_identity(Gogo*) const
2366 do_get_backend(Gogo* gogo)
2367 { return gogo->backend()->error_type(); }
2370 do_type_descriptor(Gogo*, Named_type*)
2371 { return Expression::make_error(Linemap::predeclared_location()); }
2374 do_reflection(Gogo*, std::string*) const
2375 { go_assert(saw_errors()); }
2378 do_mangled_name(Gogo*, std::string* ret) const
2379 { ret->push_back('E'); }
2383 Type::make_error_type()
2385 static Error_type singleton_error_type;
2386 return &singleton_error_type;
2391 class Void_type : public Type
2400 do_compare_is_identity(Gogo*) const
2404 do_get_backend(Gogo* gogo)
2405 { return gogo->backend()->void_type(); }
2408 do_type_descriptor(Gogo*, Named_type*)
2409 { go_unreachable(); }
2412 do_reflection(Gogo*, std::string*) const
2416 do_mangled_name(Gogo*, std::string* ret) const
2417 { ret->push_back('v'); }
2421 Type::make_void_type()
2423 static Void_type singleton_void_type;
2424 return &singleton_void_type;
2427 // The boolean type.
2429 class Boolean_type : public Type
2433 : Type(TYPE_BOOLEAN)
2438 do_compare_is_identity(Gogo*) const
2442 do_get_backend(Gogo* gogo)
2443 { return gogo->backend()->bool_type(); }
2446 do_type_descriptor(Gogo*, Named_type* name);
2448 // We should not be asked for the reflection string of a basic type.
2450 do_reflection(Gogo*, std::string* ret) const
2451 { ret->append("bool"); }
2454 do_mangled_name(Gogo*, std::string* ret) const
2455 { ret->push_back('b'); }
2458 // Make the type descriptor.
2461 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2464 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
2467 Named_object* no = gogo->lookup_global("bool");
2468 go_assert(no != NULL);
2469 return Type::type_descriptor(gogo, no->type_value());
2474 Type::make_boolean_type()
2476 static Boolean_type boolean_type;
2477 return &boolean_type;
2480 // The named type "bool".
2482 static Named_type* named_bool_type;
2484 // Get the named type "bool".
2487 Type::lookup_bool_type()
2489 return named_bool_type;
2492 // Make the named type "bool".
2495 Type::make_named_bool_type()
2497 Type* bool_type = Type::make_boolean_type();
2498 Named_object* named_object =
2499 Named_object::make_type("bool", NULL, bool_type,
2500 Linemap::predeclared_location());
2501 Named_type* named_type = named_object->type_value();
2502 named_bool_type = named_type;
2506 // Class Integer_type.
2508 Integer_type::Named_integer_types Integer_type::named_integer_types;
2510 // Create a new integer type. Non-abstract integer types always have
2514 Integer_type::create_integer_type(const char* name, bool is_unsigned,
2515 int bits, int runtime_type_kind)
2517 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
2519 std::string sname(name);
2520 Named_object* named_object =
2521 Named_object::make_type(sname, NULL, integer_type,
2522 Linemap::predeclared_location());
2523 Named_type* named_type = named_object->type_value();
2524 std::pair<Named_integer_types::iterator, bool> ins =
2525 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
2526 go_assert(ins.second);
2530 // Look up an existing integer type.
2533 Integer_type::lookup_integer_type(const char* name)
2535 Named_integer_types::const_iterator p =
2536 Integer_type::named_integer_types.find(name);
2537 go_assert(p != Integer_type::named_integer_types.end());
2541 // Create a new abstract integer type.
2544 Integer_type::create_abstract_integer_type()
2546 static Integer_type* abstract_type;
2547 if (abstract_type == NULL)
2548 abstract_type = new Integer_type(true, false, INT_TYPE_SIZE,
2549 RUNTIME_TYPE_KIND_INT);
2550 return abstract_type;
2553 // Create a new abstract character type.
2556 Integer_type::create_abstract_character_type()
2558 static Integer_type* abstract_type;
2559 if (abstract_type == NULL)
2561 abstract_type = new Integer_type(true, false, 32,
2562 RUNTIME_TYPE_KIND_INT32);
2563 abstract_type->set_is_rune();
2565 return abstract_type;
2568 // Integer type compatibility.
2571 Integer_type::is_identical(const Integer_type* t) const
2573 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
2575 return this->is_abstract_ == t->is_abstract_;
2581 Integer_type::do_hash_for_method(Gogo*) const
2583 return ((this->bits_ << 4)
2584 + ((this->is_unsigned_ ? 1 : 0) << 8)
2585 + ((this->is_abstract_ ? 1 : 0) << 9));
2588 // Convert an Integer_type to the backend representation.
2591 Integer_type::do_get_backend(Gogo* gogo)
2593 if (this->is_abstract_)
2595 go_assert(saw_errors());
2596 return gogo->backend()->error_type();
2598 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
2601 // The type descriptor for an integer type. Integer types are always
2605 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2607 go_assert(name != NULL || saw_errors());
2608 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2611 // We should not be asked for the reflection string of a basic type.
2614 Integer_type::do_reflection(Gogo*, std::string*) const
2616 go_assert(saw_errors());
2622 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
2625 snprintf(buf, sizeof buf, "i%s%s%de",
2626 this->is_abstract_ ? "a" : "",
2627 this->is_unsigned_ ? "u" : "",
2632 // Make an integer type.
2635 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
2636 int runtime_type_kind)
2638 return Integer_type::create_integer_type(name, is_unsigned, bits,
2642 // Make an abstract integer type.
2645 Type::make_abstract_integer_type()
2647 return Integer_type::create_abstract_integer_type();
2650 // Make an abstract character type.
2653 Type::make_abstract_character_type()
2655 return Integer_type::create_abstract_character_type();
2658 // Look up an integer type.
2661 Type::lookup_integer_type(const char* name)
2663 return Integer_type::lookup_integer_type(name);
2666 // Class Float_type.
2668 Float_type::Named_float_types Float_type::named_float_types;
2670 // Create a new float type. Non-abstract float types always have
2674 Float_type::create_float_type(const char* name, int bits,
2675 int runtime_type_kind)
2677 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
2678 std::string sname(name);
2679 Named_object* named_object =
2680 Named_object::make_type(sname, NULL, float_type,
2681 Linemap::predeclared_location());
2682 Named_type* named_type = named_object->type_value();
2683 std::pair<Named_float_types::iterator, bool> ins =
2684 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
2685 go_assert(ins.second);
2689 // Look up an existing float type.
2692 Float_type::lookup_float_type(const char* name)
2694 Named_float_types::const_iterator p =
2695 Float_type::named_float_types.find(name);
2696 go_assert(p != Float_type::named_float_types.end());
2700 // Create a new abstract float type.
2703 Float_type::create_abstract_float_type()
2705 static Float_type* abstract_type;
2706 if (abstract_type == NULL)
2707 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
2708 return abstract_type;
2711 // Whether this type is identical with T.
2714 Float_type::is_identical(const Float_type* t) const
2716 if (this->bits_ != t->bits_)
2718 return this->is_abstract_ == t->is_abstract_;
2724 Float_type::do_hash_for_method(Gogo*) const
2726 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2729 // Convert to the backend representation.
2732 Float_type::do_get_backend(Gogo* gogo)
2734 return gogo->backend()->float_type(this->bits_);
2737 // The type descriptor for a float type. Float types are always named.
2740 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2742 go_assert(name != NULL || saw_errors());
2743 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2746 // We should not be asked for the reflection string of a basic type.
2749 Float_type::do_reflection(Gogo*, std::string*) const
2751 go_assert(saw_errors());
2757 Float_type::do_mangled_name(Gogo*, std::string* ret) const
2760 snprintf(buf, sizeof buf, "f%s%de",
2761 this->is_abstract_ ? "a" : "",
2766 // Make a floating point type.
2769 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
2771 return Float_type::create_float_type(name, bits, runtime_type_kind);
2774 // Make an abstract float type.
2777 Type::make_abstract_float_type()
2779 return Float_type::create_abstract_float_type();
2782 // Look up a float type.
2785 Type::lookup_float_type(const char* name)
2787 return Float_type::lookup_float_type(name);
2790 // Class Complex_type.
2792 Complex_type::Named_complex_types Complex_type::named_complex_types;
2794 // Create a new complex type. Non-abstract complex types always have
2798 Complex_type::create_complex_type(const char* name, int bits,
2799 int runtime_type_kind)
2801 Complex_type* complex_type = new Complex_type(false, bits,
2803 std::string sname(name);
2804 Named_object* named_object =
2805 Named_object::make_type(sname, NULL, complex_type,
2806 Linemap::predeclared_location());
2807 Named_type* named_type = named_object->type_value();
2808 std::pair<Named_complex_types::iterator, bool> ins =
2809 Complex_type::named_complex_types.insert(std::make_pair(sname,
2811 go_assert(ins.second);
2815 // Look up an existing complex type.
2818 Complex_type::lookup_complex_type(const char* name)
2820 Named_complex_types::const_iterator p =
2821 Complex_type::named_complex_types.find(name);
2822 go_assert(p != Complex_type::named_complex_types.end());
2826 // Create a new abstract complex type.
2829 Complex_type::create_abstract_complex_type()
2831 static Complex_type* abstract_type;
2832 if (abstract_type == NULL)
2833 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
2834 return abstract_type;
2837 // Whether this type is identical with T.
2840 Complex_type::is_identical(const Complex_type *t) const
2842 if (this->bits_ != t->bits_)
2844 return this->is_abstract_ == t->is_abstract_;
2850 Complex_type::do_hash_for_method(Gogo*) const
2852 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2855 // Convert to the backend representation.
2858 Complex_type::do_get_backend(Gogo* gogo)
2860 return gogo->backend()->complex_type(this->bits_);
2863 // The type descriptor for a complex type. Complex types are always
2867 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2869 go_assert(name != NULL || saw_errors());
2870 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2873 // We should not be asked for the reflection string of a basic type.
2876 Complex_type::do_reflection(Gogo*, std::string*) const
2878 go_assert(saw_errors());
2884 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
2887 snprintf(buf, sizeof buf, "c%s%de",
2888 this->is_abstract_ ? "a" : "",
2893 // Make a complex type.
2896 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
2898 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
2901 // Make an abstract complex type.
2904 Type::make_abstract_complex_type()
2906 return Complex_type::create_abstract_complex_type();
2909 // Look up a complex type.
2912 Type::lookup_complex_type(const char* name)
2914 return Complex_type::lookup_complex_type(name);
2917 // Class String_type.
2919 // Convert String_type to the backend representation. A string is a
2920 // struct with two fields: a pointer to the characters and a length.
2923 String_type::do_get_backend(Gogo* gogo)
2925 static Btype* backend_string_type;
2926 if (backend_string_type == NULL)
2928 std::vector<Backend::Btyped_identifier> fields(2);
2930 Type* b = gogo->lookup_global("byte")->type_value();
2931 Type* pb = Type::make_pointer_type(b);
2933 // We aren't going to get back to this field to finish the
2934 // backend representation, so force it to be finished now.
2935 if (!gogo->named_types_are_converted())
2937 pb->get_backend_placeholder(gogo);
2938 pb->finish_backend(gogo);
2941 fields[0].name = "__data";
2942 fields[0].btype = pb->get_backend(gogo);
2943 fields[0].location = Linemap::predeclared_location();
2945 Type* int_type = Type::lookup_integer_type("int");
2946 fields[1].name = "__length";
2947 fields[1].btype = int_type->get_backend(gogo);
2948 fields[1].location = fields[0].location;
2950 backend_string_type = gogo->backend()->struct_type(fields);
2952 return backend_string_type;
2955 // Return a tree for the length of STRING.
2958 String_type::length_tree(Gogo*, tree string)
2960 tree string_type = TREE_TYPE(string);
2961 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2962 tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type));
2963 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)),
2965 return fold_build3(COMPONENT_REF, integer_type_node, string,
2966 length_field, NULL_TREE);
2969 // Return a tree for a pointer to the bytes of STRING.
2972 String_type::bytes_tree(Gogo*, tree string)
2974 tree string_type = TREE_TYPE(string);
2975 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2976 tree bytes_field = TYPE_FIELDS(string_type);
2977 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)),
2979 return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string,
2980 bytes_field, NULL_TREE);
2983 // The type descriptor for the string type.
2986 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2989 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
2992 Named_object* no = gogo->lookup_global("string");
2993 go_assert(no != NULL);
2994 return Type::type_descriptor(gogo, no->type_value());
2998 // We should not be asked for the reflection string of a basic type.
3001 String_type::do_reflection(Gogo*, std::string* ret) const
3003 ret->append("string");
3006 // Mangled name of a string type.
3009 String_type::do_mangled_name(Gogo*, std::string* ret) const
3011 ret->push_back('z');
3014 // Make a string type.
3017 Type::make_string_type()
3019 static String_type string_type;
3020 return &string_type;
3023 // The named type "string".
3025 static Named_type* named_string_type;
3027 // Get the named type "string".
3030 Type::lookup_string_type()
3032 return named_string_type;
3035 // Make the named type string.
3038 Type::make_named_string_type()
3040 Type* string_type = Type::make_string_type();
3041 Named_object* named_object =
3042 Named_object::make_type("string", NULL, string_type,
3043 Linemap::predeclared_location());
3044 Named_type* named_type = named_object->type_value();
3045 named_string_type = named_type;
3049 // The sink type. This is the type of the blank identifier _. Any
3050 // type may be assigned to it.
3052 class Sink_type : public Type
3061 do_compare_is_identity(Gogo*) const
3065 do_get_backend(Gogo*)
3066 { go_unreachable(); }
3069 do_type_descriptor(Gogo*, Named_type*)
3070 { go_unreachable(); }
3073 do_reflection(Gogo*, std::string*) const
3074 { go_unreachable(); }
3077 do_mangled_name(Gogo*, std::string*) const
3078 { go_unreachable(); }
3081 // Make the sink type.
3084 Type::make_sink_type()
3086 static Sink_type sink_type;
3090 // Class Function_type.
3095 Function_type::do_traverse(Traverse* traverse)
3097 if (this->receiver_ != NULL
3098 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
3099 return TRAVERSE_EXIT;
3100 if (this->parameters_ != NULL
3101 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
3102 return TRAVERSE_EXIT;
3103 if (this->results_ != NULL
3104 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
3105 return TRAVERSE_EXIT;
3106 return TRAVERSE_CONTINUE;
3109 // Returns whether T is a valid redeclaration of this type. If this
3110 // returns false, and REASON is not NULL, *REASON may be set to a
3111 // brief explanation of why it returned false.
3114 Function_type::is_valid_redeclaration(const Function_type* t,
3115 std::string* reason) const
3117 if (!this->is_identical(t, false, true, reason))
3120 // A redeclaration of a function is required to use the same names
3121 // for the receiver and parameters.
3122 if (this->receiver() != NULL
3123 && this->receiver()->name() != t->receiver()->name())
3126 *reason = "receiver name changed";
3130 const Typed_identifier_list* parms1 = this->parameters();
3131 const Typed_identifier_list* parms2 = t->parameters();
3134 Typed_identifier_list::const_iterator p1 = parms1->begin();
3135 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3136 p2 != parms2->end();
3139 if (p1->name() != p2->name())
3142 *reason = "parameter name changed";
3146 // This is called at parse time, so we may have unknown
3148 Type* t1 = p1->type()->forwarded();
3149 Type* t2 = p2->type()->forwarded();
3151 && t1->forward_declaration_type() != NULL
3152 && (t2->forward_declaration_type() == NULL
3153 || (t1->forward_declaration_type()->named_object()
3154 != t2->forward_declaration_type()->named_object())))
3159 const Typed_identifier_list* results1 = this->results();
3160 const Typed_identifier_list* results2 = t->results();
3161 if (results1 != NULL)
3163 Typed_identifier_list::const_iterator res1 = results1->begin();
3164 for (Typed_identifier_list::const_iterator res2 = results2->begin();
3165 res2 != results2->end();
3168 if (res1->name() != res2->name())
3171 *reason = "result name changed";
3175 // This is called at parse time, so we may have unknown
3177 Type* t1 = res1->type()->forwarded();
3178 Type* t2 = res2->type()->forwarded();
3180 && t1->forward_declaration_type() != NULL
3181 && (t2->forward_declaration_type() == NULL
3182 || (t1->forward_declaration_type()->named_object()
3183 != t2->forward_declaration_type()->named_object())))
3191 // Check whether T is the same as this type.
3194 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
3195 bool errors_are_identical,
3196 std::string* reason) const
3198 if (!ignore_receiver)
3200 const Typed_identifier* r1 = this->receiver();
3201 const Typed_identifier* r2 = t->receiver();
3202 if ((r1 != NULL) != (r2 != NULL))
3205 *reason = _("different receiver types");
3210 if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
3213 if (reason != NULL && !reason->empty())
3214 *reason = "receiver: " + *reason;
3220 const Typed_identifier_list* parms1 = this->parameters();
3221 const Typed_identifier_list* parms2 = t->parameters();
3222 if ((parms1 != NULL) != (parms2 != NULL))
3225 *reason = _("different number of parameters");
3230 Typed_identifier_list::const_iterator p1 = parms1->begin();
3231 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3232 p2 != parms2->end();
3235 if (p1 == parms1->end())
3238 *reason = _("different number of parameters");
3242 if (!Type::are_identical(p1->type(), p2->type(),
3243 errors_are_identical, NULL))
3246 *reason = _("different parameter types");
3250 if (p1 != parms1->end())
3253 *reason = _("different number of parameters");
3258 if (this->is_varargs() != t->is_varargs())
3261 *reason = _("different varargs");
3265 const Typed_identifier_list* results1 = this->results();
3266 const Typed_identifier_list* results2 = t->results();
3267 if ((results1 != NULL) != (results2 != NULL))
3270 *reason = _("different number of results");
3273 if (results1 != NULL)
3275 Typed_identifier_list::const_iterator res1 = results1->begin();
3276 for (Typed_identifier_list::const_iterator res2 = results2->begin();
3277 res2 != results2->end();
3280 if (res1 == results1->end())
3283 *reason = _("different number of results");
3287 if (!Type::are_identical(res1->type(), res2->type(),
3288 errors_are_identical, NULL))
3291 *reason = _("different result types");
3295 if (res1 != results1->end())
3298 *reason = _("different number of results");
3309 Function_type::do_hash_for_method(Gogo* gogo) const
3311 unsigned int ret = 0;
3312 // We ignore the receiver type for hash codes, because we need to
3313 // get the same hash code for a method in an interface and a method
3314 // declared for a type. The former will not have a receiver.
3315 if (this->parameters_ != NULL)
3318 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3319 p != this->parameters_->end();
3321 ret += p->type()->hash_for_method(gogo) << shift;
3323 if (this->results_ != NULL)
3326 for (Typed_identifier_list::const_iterator p = this->results_->begin();
3327 p != this->results_->end();
3329 ret += p->type()->hash_for_method(gogo) << shift;
3331 if (this->is_varargs_)
3337 // Get the backend representation for a function type.
3340 Function_type::do_get_backend(Gogo* gogo)
3342 Backend::Btyped_identifier breceiver;
3343 if (this->receiver_ != NULL)
3345 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
3347 // We always pass the address of the receiver parameter, in
3348 // order to make interface calls work with unknown types.
3349 Type* rtype = this->receiver_->type();
3350 if (rtype->points_to() == NULL)
3351 rtype = Type::make_pointer_type(rtype);
3352 breceiver.btype = rtype->get_backend(gogo);
3353 breceiver.location = this->receiver_->location();
3356 std::vector<Backend::Btyped_identifier> bparameters;
3357 if (this->parameters_ != NULL)
3359 bparameters.resize(this->parameters_->size());
3361 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3362 p != this->parameters_->end();
3365 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
3366 bparameters[i].btype = p->type()->get_backend(gogo);
3367 bparameters[i].location = p->location();
3369 go_assert(i == bparameters.size());
3372 std::vector<Backend::Btyped_identifier> bresults;
3373 if (this->results_ != NULL)
3375 bresults.resize(this->results_->size());
3377 for (Typed_identifier_list::const_iterator p = this->results_->begin();
3378 p != this->results_->end();
3381 bresults[i].name = Gogo::unpack_hidden_name(p->name());
3382 bresults[i].btype = p->type()->get_backend(gogo);
3383 bresults[i].location = p->location();
3385 go_assert(i == bresults.size());
3388 return gogo->backend()->function_type(breceiver, bparameters, bresults,
3392 // The type of a function type descriptor.
3395 Function_type::make_function_type_descriptor_type()
3400 Type* tdt = Type::make_type_descriptor_type();
3401 Type* ptdt = Type::make_type_descriptor_ptr_type();
3403 Type* bool_type = Type::lookup_bool_type();
3405 Type* slice_type = Type::make_array_type(ptdt, NULL);
3407 Struct_type* s = Type::make_builtin_struct_type(4,
3409 "dotdotdot", bool_type,
3413 ret = Type::make_builtin_named_type("FuncType", s);
3419 // The type descriptor for a function type.
3422 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3424 Location bloc = Linemap::predeclared_location();
3426 Type* ftdt = Function_type::make_function_type_descriptor_type();
3428 const Struct_field_list* fields = ftdt->struct_type()->fields();
3430 Expression_list* vals = new Expression_list();
3433 Struct_field_list::const_iterator p = fields->begin();
3434 go_assert(p->is_field_name("commonType"));
3435 vals->push_back(this->type_descriptor_constructor(gogo,
3436 RUNTIME_TYPE_KIND_FUNC,
3440 go_assert(p->is_field_name("dotdotdot"));
3441 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
3444 go_assert(p->is_field_name("in"));
3445 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
3446 this->parameters()));
3449 go_assert(p->is_field_name("out"));
3450 vals->push_back(this->type_descriptor_params(p->type(), NULL,
3454 go_assert(p == fields->end());
3456 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
3459 // Return a composite literal for the parameters or results of a type
3463 Function_type::type_descriptor_params(Type* params_type,
3464 const Typed_identifier* receiver,
3465 const Typed_identifier_list* params)
3467 Location bloc = Linemap::predeclared_location();
3469 if (receiver == NULL && params == NULL)
3470 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
3472 Expression_list* vals = new Expression_list();
3473 vals->reserve((params == NULL ? 0 : params->size())
3474 + (receiver != NULL ? 1 : 0));
3476 if (receiver != NULL)
3477 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
3481 for (Typed_identifier_list::const_iterator p = params->begin();
3484 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
3487 return Expression::make_slice_composite_literal(params_type, vals, bloc);
3490 // The reflection string.
3493 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
3495 // FIXME: Turn this off until we straighten out the type of the
3496 // struct field used in a go statement which calls a method.
3497 // go_assert(this->receiver_ == NULL);
3499 ret->append("func");
3501 if (this->receiver_ != NULL)
3503 ret->push_back('(');
3504 this->append_reflection(this->receiver_->type(), gogo, ret);
3505 ret->push_back(')');
3508 ret->push_back('(');
3509 const Typed_identifier_list* params = this->parameters();
3512 bool is_varargs = this->is_varargs_;
3513 for (Typed_identifier_list::const_iterator p = params->begin();
3517 if (p != params->begin())
3519 if (!is_varargs || p + 1 != params->end())
3520 this->append_reflection(p->type(), gogo, ret);
3524 this->append_reflection(p->type()->array_type()->element_type(),
3529 ret->push_back(')');
3531 const Typed_identifier_list* results = this->results();
3532 if (results != NULL && !results->empty())
3534 if (results->size() == 1)
3535 ret->push_back(' ');
3538 for (Typed_identifier_list::const_iterator p = results->begin();
3539 p != results->end();
3542 if (p != results->begin())
3544 this->append_reflection(p->type(), gogo, ret);
3546 if (results->size() > 1)
3547 ret->push_back(')');
3554 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3556 ret->push_back('F');
3558 if (this->receiver_ != NULL)
3560 ret->push_back('m');
3561 this->append_mangled_name(this->receiver_->type(), gogo, ret);
3564 const Typed_identifier_list* params = this->parameters();
3567 ret->push_back('p');
3568 for (Typed_identifier_list::const_iterator p = params->begin();
3571 this->append_mangled_name(p->type(), gogo, ret);
3572 if (this->is_varargs_)
3573 ret->push_back('V');
3574 ret->push_back('e');
3577 const Typed_identifier_list* results = this->results();
3578 if (results != NULL)
3580 ret->push_back('r');
3581 for (Typed_identifier_list::const_iterator p = results->begin();
3582 p != results->end();
3584 this->append_mangled_name(p->type(), gogo, ret);
3585 ret->push_back('e');
3588 ret->push_back('e');
3591 // Export a function type.
3594 Function_type::do_export(Export* exp) const
3596 // We don't write out the receiver. The only function types which
3597 // should have a receiver are the ones associated with explicitly
3598 // defined methods. For those the receiver type is written out by
3599 // Function::export_func.
3601 exp->write_c_string("(");
3603 if (this->parameters_ != NULL)
3605 bool is_varargs = this->is_varargs_;
3606 for (Typed_identifier_list::const_iterator p =
3607 this->parameters_->begin();
3608 p != this->parameters_->end();
3614 exp->write_c_string(", ");
3615 exp->write_name(p->name());
3616 exp->write_c_string(" ");
3617 if (!is_varargs || p + 1 != this->parameters_->end())
3618 exp->write_type(p->type());
3621 exp->write_c_string("...");
3622 exp->write_type(p->type()->array_type()->element_type());
3626 exp->write_c_string(")");
3628 const Typed_identifier_list* results = this->results_;
3629 if (results != NULL)
3631 exp->write_c_string(" ");
3632 if (results->size() == 1 && results->begin()->name().empty())
3633 exp->write_type(results->begin()->type());
3637 exp->write_c_string("(");
3638 for (Typed_identifier_list::const_iterator p = results->begin();
3639 p != results->end();
3645 exp->write_c_string(", ");
3646 exp->write_name(p->name());
3647 exp->write_c_string(" ");
3648 exp->write_type(p->type());
3650 exp->write_c_string(")");
3655 // Import a function type.
3658 Function_type::do_import(Import* imp)
3660 imp->require_c_string("(");
3661 Typed_identifier_list* parameters;
3662 bool is_varargs = false;
3663 if (imp->peek_char() == ')')
3667 parameters = new Typed_identifier_list();
3670 std::string name = imp->read_name();
3671 imp->require_c_string(" ");
3673 if (imp->match_c_string("..."))
3679 Type* ptype = imp->read_type();
3681 ptype = Type::make_array_type(ptype, NULL);
3682 parameters->push_back(Typed_identifier(name, ptype,
3684 if (imp->peek_char() != ',')
3686 go_assert(!is_varargs);
3687 imp->require_c_string(", ");
3690 imp->require_c_string(")");
3692 Typed_identifier_list* results;
3693 if (imp->peek_char() != ' ')
3698 results = new Typed_identifier_list;
3699 if (imp->peek_char() != '(')
3701 Type* rtype = imp->read_type();
3702 results->push_back(Typed_identifier("", rtype, imp->location()));
3709 std::string name = imp->read_name();
3710 imp->require_c_string(" ");
3711 Type* rtype = imp->read_type();
3712 results->push_back(Typed_identifier(name, rtype,
3714 if (imp->peek_char() != ',')
3716 imp->require_c_string(", ");
3718 imp->require_c_string(")");
3722 Function_type* ret = Type::make_function_type(NULL, parameters, results,
3725 ret->set_is_varargs();
3729 // Make a copy of a function type without a receiver.
3732 Function_type::copy_without_receiver() const
3734 go_assert(this->is_method());
3735 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
3738 if (this->is_varargs())
3739 ret->set_is_varargs();
3740 if (this->is_builtin())
3741 ret->set_is_builtin();
3745 // Make a copy of a function type with a receiver.
3748 Function_type::copy_with_receiver(Type* receiver_type) const
3750 go_assert(!this->is_method());
3751 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
3753 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
3756 if (this->is_varargs_)
3757 ret->set_is_varargs();
3761 // Make a function type.
3764 Type::make_function_type(Typed_identifier* receiver,
3765 Typed_identifier_list* parameters,
3766 Typed_identifier_list* results,
3769 return new Function_type(receiver, parameters, results, location);
3772 // Class Pointer_type.
3777 Pointer_type::do_traverse(Traverse* traverse)
3779 return Type::traverse(this->to_type_, traverse);
3785 Pointer_type::do_hash_for_method(Gogo* gogo) const
3787 return this->to_type_->hash_for_method(gogo) << 4;
3790 // Get the backend representation for a pointer type.
3793 Pointer_type::do_get_backend(Gogo* gogo)
3795 Btype* to_btype = this->to_type_->get_backend(gogo);
3796 return gogo->backend()->pointer_type(to_btype);
3799 // The type of a pointer type descriptor.
3802 Pointer_type::make_pointer_type_descriptor_type()
3807 Type* tdt = Type::make_type_descriptor_type();
3808 Type* ptdt = Type::make_type_descriptor_ptr_type();
3810 Struct_type* s = Type::make_builtin_struct_type(2,
3814 ret = Type::make_builtin_named_type("PtrType", s);
3820 // The type descriptor for a pointer type.
3823 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3825 if (this->is_unsafe_pointer_type())
3827 go_assert(name != NULL);
3828 return this->plain_type_descriptor(gogo,
3829 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
3834 Location bloc = Linemap::predeclared_location();
3836 const Methods* methods;
3837 Type* deref = this->points_to();
3838 if (deref->named_type() != NULL)
3839 methods = deref->named_type()->methods();
3840 else if (deref->struct_type() != NULL)
3841 methods = deref->struct_type()->methods();
3845 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
3847 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
3849 Expression_list* vals = new Expression_list();
3852 Struct_field_list::const_iterator p = fields->begin();
3853 go_assert(p->is_field_name("commonType"));
3854 vals->push_back(this->type_descriptor_constructor(gogo,
3855 RUNTIME_TYPE_KIND_PTR,
3856 name, methods, false));
3859 go_assert(p->is_field_name("elem"));
3860 vals->push_back(Expression::make_type_descriptor(deref, bloc));
3862 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
3866 // Reflection string.
3869 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
3871 ret->push_back('*');
3872 this->append_reflection(this->to_type_, gogo, ret);
3878 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3880 ret->push_back('p');
3881 this->append_mangled_name(this->to_type_, gogo, ret);
3887 Pointer_type::do_export(Export* exp) const
3889 exp->write_c_string("*");
3890 if (this->is_unsafe_pointer_type())
3891 exp->write_c_string("any");
3893 exp->write_type(this->to_type_);
3899 Pointer_type::do_import(Import* imp)
3901 imp->require_c_string("*");
3902 if (imp->match_c_string("any"))
3905 return Type::make_pointer_type(Type::make_void_type());
3907 Type* to = imp->read_type();
3908 return Type::make_pointer_type(to);
3911 // Make a pointer type.
3914 Type::make_pointer_type(Type* to_type)
3916 typedef Unordered_map(Type*, Pointer_type*) Hashtable;
3917 static Hashtable pointer_types;
3918 Hashtable::const_iterator p = pointer_types.find(to_type);
3919 if (p != pointer_types.end())
3921 Pointer_type* ret = new Pointer_type(to_type);
3922 pointer_types[to_type] = ret;
3926 // The nil type. We use a special type for nil because it is not the
3927 // same as any other type. In C term nil has type void*, but there is
3928 // no such type in Go.
3930 class Nil_type : public Type
3939 do_compare_is_identity(Gogo*) const
3943 do_get_backend(Gogo* gogo)
3944 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
3947 do_type_descriptor(Gogo*, Named_type*)
3948 { go_unreachable(); }
3951 do_reflection(Gogo*, std::string*) const
3952 { go_unreachable(); }
3955 do_mangled_name(Gogo*, std::string* ret) const
3956 { ret->push_back('n'); }
3959 // Make the nil type.
3962 Type::make_nil_type()
3964 static Nil_type singleton_nil_type;
3965 return &singleton_nil_type;
3968 // The type of a function call which returns multiple values. This is
3969 // really a struct, but we don't want to confuse a function call which
3970 // returns a struct with a function call which returns multiple
3973 class Call_multiple_result_type : public Type
3976 Call_multiple_result_type(Call_expression* call)
3977 : Type(TYPE_CALL_MULTIPLE_RESULT),
3983 do_has_pointer() const
3985 go_assert(saw_errors());
3990 do_compare_is_identity(Gogo*) const
3994 do_get_backend(Gogo* gogo)
3996 go_assert(saw_errors());
3997 return gogo->backend()->error_type();
4001 do_type_descriptor(Gogo*, Named_type*)
4003 go_assert(saw_errors());
4004 return Expression::make_error(Linemap::unknown_location());
4008 do_reflection(Gogo*, std::string*) const
4009 { go_assert(saw_errors()); }
4012 do_mangled_name(Gogo*, std::string*) const
4013 { go_assert(saw_errors()); }
4016 // The expression being called.
4017 Call_expression* call_;
4020 // Make a call result type.
4023 Type::make_call_multiple_result_type(Call_expression* call)
4025 return new Call_multiple_result_type(call);
4028 // Class Struct_field.
4030 // Get the name of a field.
4033 Struct_field::field_name() const
4035 const std::string& name(this->typed_identifier_.name());
4040 // This is called during parsing, before anything is lowered, so
4041 // we have to be pretty careful to avoid dereferencing an
4042 // unknown type name.
4043 Type* t = this->typed_identifier_.type();
4045 if (t->classification() == Type::TYPE_POINTER)
4048 Pointer_type* ptype = static_cast<Pointer_type*>(t);
4049 dt = ptype->points_to();
4051 if (dt->forward_declaration_type() != NULL)
4052 return dt->forward_declaration_type()->name();
4053 else if (dt->named_type() != NULL)
4054 return dt->named_type()->name();
4055 else if (t->is_error_type() || dt->is_error_type())
4057 static const std::string error_string = "*error*";
4058 return error_string;
4062 // Avoid crashing in the erroneous case where T is named but
4065 if (t->forward_declaration_type() != NULL)
4066 return t->forward_declaration_type()->name();
4067 else if (t->named_type() != NULL)
4068 return t->named_type()->name();
4075 // Return whether this field is named NAME.
4078 Struct_field::is_field_name(const std::string& name) const
4080 const std::string& me(this->typed_identifier_.name());
4085 Type* t = this->typed_identifier_.type();
4086 if (t->points_to() != NULL)
4088 Named_type* nt = t->named_type();
4089 if (nt != NULL && nt->name() == name)
4092 // This is a horrible hack caused by the fact that we don't pack
4093 // the names of builtin types. FIXME.
4096 && nt->name() == Gogo::unpack_hidden_name(name))
4103 // Class Struct_type.
4108 Struct_type::do_traverse(Traverse* traverse)
4110 Struct_field_list* fields = this->fields_;
4113 for (Struct_field_list::iterator p = fields->begin();
4117 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
4118 return TRAVERSE_EXIT;
4121 return TRAVERSE_CONTINUE;
4124 // Verify that the struct type is complete and valid.
4127 Struct_type::do_verify()
4129 Struct_field_list* fields = this->fields_;
4132 for (Struct_field_list::iterator p = fields->begin();
4136 Type* t = p->type();
4137 if (t->is_undefined())
4139 error_at(p->location(), "struct field type is incomplete");
4140 p->set_type(Type::make_error_type());
4142 else if (p->is_anonymous())
4144 if (t->named_type() != NULL && t->points_to() != NULL)
4146 error_at(p->location(), "embedded type may not be a pointer");
4147 p->set_type(Type::make_error_type());
4149 else if (t->points_to() != NULL
4150 && t->points_to()->interface_type() != NULL)
4152 error_at(p->location(),
4153 "embedded type may not be pointer to interface");
4154 p->set_type(Type::make_error_type());
4161 // Whether this contains a pointer.
4164 Struct_type::do_has_pointer() const
4166 const Struct_field_list* fields = this->fields();
4169 for (Struct_field_list::const_iterator p = fields->begin();
4173 if (p->type()->has_pointer())
4179 // Whether this type is identical to T.
4182 Struct_type::is_identical(const Struct_type* t,
4183 bool errors_are_identical) const
4185 const Struct_field_list* fields1 = this->fields();
4186 const Struct_field_list* fields2 = t->fields();
4187 if (fields1 == NULL || fields2 == NULL)
4188 return fields1 == fields2;
4189 Struct_field_list::const_iterator pf2 = fields2->begin();
4190 for (Struct_field_list::const_iterator pf1 = fields1->begin();
4191 pf1 != fields1->end();
4194 if (pf2 == fields2->end())
4196 if (pf1->field_name() != pf2->field_name())
4198 if (pf1->is_anonymous() != pf2->is_anonymous()
4199 || !Type::are_identical(pf1->type(), pf2->type(),
4200 errors_are_identical, NULL))
4202 if (!pf1->has_tag())
4209 if (!pf2->has_tag())
4211 if (pf1->tag() != pf2->tag())
4215 if (pf2 != fields2->end())
4220 // Whether this struct type has any hidden fields.
4223 Struct_type::struct_has_hidden_fields(const Named_type* within,
4224 std::string* reason) const
4226 const Struct_field_list* fields = this->fields();
4229 const Package* within_package = (within == NULL
4231 : within->named_object()->package());
4232 for (Struct_field_list::const_iterator pf = fields->begin();
4233 pf != fields->end();
4236 if (within_package != NULL
4237 && !pf->is_anonymous()
4238 && Gogo::is_hidden_name(pf->field_name()))
4242 std::string within_name = within->named_object()->message_name();
4243 std::string name = Gogo::message_name(pf->field_name());
4244 size_t bufsize = 200 + within_name.length() + name.length();
4245 char* buf = new char[bufsize];
4246 snprintf(buf, bufsize,
4247 _("implicit assignment of %s%s%s hidden field %s%s%s"),
4248 open_quote, within_name.c_str(), close_quote,
4249 open_quote, name.c_str(), close_quote);
4250 reason->assign(buf);
4256 if (pf->type()->has_hidden_fields(within, reason))
4263 // Whether comparisons of this struct type are simple identity
4267 Struct_type::do_compare_is_identity(Gogo* gogo) const
4269 const Struct_field_list* fields = this->fields_;
4272 unsigned int offset = 0;
4273 for (Struct_field_list::const_iterator pf = fields->begin();
4274 pf != fields->end();
4277 if (!pf->type()->compare_is_identity(gogo))
4280 unsigned int field_align;
4281 if (!pf->type()->backend_type_align(gogo, &field_align))
4283 if ((offset & (field_align - 1)) != 0)
4285 // This struct has padding. We don't guarantee that that
4286 // padding is zero-initialized for a stack variable, so we
4287 // can't use memcmp to compare struct values.
4291 unsigned int field_size;
4292 if (!pf->type()->backend_type_size(gogo, &field_size))
4294 offset += field_size;
4299 // Build identity and hash functions for this struct.
4304 Struct_type::do_hash_for_method(Gogo* gogo) const
4306 unsigned int ret = 0;
4307 if (this->fields() != NULL)
4309 for (Struct_field_list::const_iterator pf = this->fields()->begin();
4310 pf != this->fields()->end();
4312 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
4317 // Find the local field NAME.
4320 Struct_type::find_local_field(const std::string& name,
4321 unsigned int *pindex) const
4323 const Struct_field_list* fields = this->fields_;
4327 for (Struct_field_list::const_iterator pf = fields->begin();
4328 pf != fields->end();
4331 if (pf->is_field_name(name))
4341 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
4343 Field_reference_expression*
4344 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
4345 Location location) const
4348 return this->field_reference_depth(struct_expr, name, location, NULL,
4352 // Return an expression for a field, along with the depth at which it
4355 Field_reference_expression*
4356 Struct_type::field_reference_depth(Expression* struct_expr,
4357 const std::string& name,
4359 Saw_named_type* saw,
4360 unsigned int* depth) const
4362 const Struct_field_list* fields = this->fields_;
4366 // Look for a field with this name.
4368 for (Struct_field_list::const_iterator pf = fields->begin();
4369 pf != fields->end();
4372 if (pf->is_field_name(name))
4375 return Expression::make_field_reference(struct_expr, i, location);
4379 // Look for an anonymous field which contains a field with this
4381 unsigned int found_depth = 0;
4382 Field_reference_expression* ret = NULL;
4384 for (Struct_field_list::const_iterator pf = fields->begin();
4385 pf != fields->end();
4388 if (!pf->is_anonymous())
4391 Struct_type* st = pf->type()->deref()->struct_type();
4395 Saw_named_type* hold_saw = saw;
4396 Saw_named_type saw_here;
4397 Named_type* nt = pf->type()->named_type();
4399 nt = pf->type()->deref()->named_type();
4403 for (q = saw; q != NULL; q = q->next)
4407 // If this is an error, it will be reported
4414 saw_here.next = saw;
4419 // Look for a reference using a NULL struct expression. If we
4420 // find one, fill in the struct expression with a reference to
4422 unsigned int subdepth;
4423 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
4433 if (ret == NULL || subdepth < found_depth)
4438 found_depth = subdepth;
4439 Expression* here = Expression::make_field_reference(struct_expr, i,
4441 if (pf->type()->points_to() != NULL)
4442 here = Expression::make_unary(OPERATOR_MULT, here, location);
4443 while (sub->expr() != NULL)
4445 sub = sub->expr()->deref()->field_reference_expression();
4446 go_assert(sub != NULL);
4448 sub->set_struct_expression(here);
4450 else if (subdepth > found_depth)
4454 // We do not handle ambiguity here--it should be handled by
4455 // Type::bind_field_or_method.
4463 *depth = found_depth + 1;
4468 // Return the total number of fields, including embedded fields.
4471 Struct_type::total_field_count() const
4473 if (this->fields_ == NULL)
4475 unsigned int ret = 0;
4476 for (Struct_field_list::const_iterator pf = this->fields_->begin();
4477 pf != this->fields_->end();
4480 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
4483 ret += pf->type()->struct_type()->total_field_count();
4488 // Return whether NAME is an unexported field, for better error reporting.
4491 Struct_type::is_unexported_local_field(Gogo* gogo,
4492 const std::string& name) const
4494 const Struct_field_list* fields = this->fields_;
4497 for (Struct_field_list::const_iterator pf = fields->begin();
4498 pf != fields->end();
4501 const std::string& field_name(pf->field_name());
4502 if (Gogo::is_hidden_name(field_name)
4503 && name == Gogo::unpack_hidden_name(field_name)
4504 && gogo->pack_hidden_name(name, false) != field_name)
4511 // Finalize the methods of an unnamed struct.
4514 Struct_type::finalize_methods(Gogo* gogo)
4516 if (this->all_methods_ != NULL)
4518 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
4521 // Return the method NAME, or NULL if there isn't one or if it is
4522 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
4526 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
4528 return Type::method_function(this->all_methods_, name, is_ambiguous);
4531 // Convert struct fields to the backend representation. This is not
4532 // declared in types.h so that types.h doesn't have to #include
4536 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
4537 bool use_placeholder,
4538 std::vector<Backend::Btyped_identifier>* bfields)
4540 bfields->resize(fields->size());
4542 for (Struct_field_list::const_iterator p = fields->begin();
4546 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
4547 (*bfields)[i].btype = (use_placeholder
4548 ? p->type()->get_backend_placeholder(gogo)
4549 : p->type()->get_backend(gogo));
4550 (*bfields)[i].location = p->location();
4552 go_assert(i == fields->size());
4555 // Get the tree for a struct type.
4558 Struct_type::do_get_backend(Gogo* gogo)
4560 std::vector<Backend::Btyped_identifier> bfields;
4561 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
4562 return gogo->backend()->struct_type(bfields);
4565 // Finish the backend representation of the fields of a struct.
4568 Struct_type::finish_backend_fields(Gogo* gogo)
4570 const Struct_field_list* fields = this->fields_;
4573 for (Struct_field_list::const_iterator p = fields->begin();
4576 p->type()->get_backend(gogo);
4580 // The type of a struct type descriptor.
4583 Struct_type::make_struct_type_descriptor_type()
4588 Type* tdt = Type::make_type_descriptor_type();
4589 Type* ptdt = Type::make_type_descriptor_ptr_type();
4591 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4592 Type* string_type = Type::lookup_string_type();
4593 Type* pointer_string_type = Type::make_pointer_type(string_type);
4596 Type::make_builtin_struct_type(5,
4597 "name", pointer_string_type,
4598 "pkgPath", pointer_string_type,
4600 "tag", pointer_string_type,
4601 "offset", uintptr_type);
4602 Type* nsf = Type::make_builtin_named_type("structField", sf);
4604 Type* slice_type = Type::make_array_type(nsf, NULL);
4606 Struct_type* s = Type::make_builtin_struct_type(2,
4608 "fields", slice_type);
4610 ret = Type::make_builtin_named_type("StructType", s);
4616 // Build a type descriptor for a struct type.
4619 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4621 Location bloc = Linemap::predeclared_location();
4623 Type* stdt = Struct_type::make_struct_type_descriptor_type();
4625 const Struct_field_list* fields = stdt->struct_type()->fields();
4627 Expression_list* vals = new Expression_list();
4630 const Methods* methods = this->methods();
4631 // A named struct should not have methods--the methods should attach
4632 // to the named type.
4633 go_assert(methods == NULL || name == NULL);
4635 Struct_field_list::const_iterator ps = fields->begin();
4636 go_assert(ps->is_field_name("commonType"));
4637 vals->push_back(this->type_descriptor_constructor(gogo,
4638 RUNTIME_TYPE_KIND_STRUCT,
4639 name, methods, true));
4642 go_assert(ps->is_field_name("fields"));
4644 Expression_list* elements = new Expression_list();
4645 elements->reserve(this->fields_->size());
4646 Type* element_type = ps->type()->array_type()->element_type();
4647 for (Struct_field_list::const_iterator pf = this->fields_->begin();
4648 pf != this->fields_->end();
4651 const Struct_field_list* f = element_type->struct_type()->fields();
4653 Expression_list* fvals = new Expression_list();
4656 Struct_field_list::const_iterator q = f->begin();
4657 go_assert(q->is_field_name("name"));
4658 if (pf->is_anonymous())
4659 fvals->push_back(Expression::make_nil(bloc));
4662 std::string n = Gogo::unpack_hidden_name(pf->field_name());
4663 Expression* s = Expression::make_string(n, bloc);
4664 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4668 go_assert(q->is_field_name("pkgPath"));
4669 if (!Gogo::is_hidden_name(pf->field_name()))
4670 fvals->push_back(Expression::make_nil(bloc));
4673 std::string n = Gogo::hidden_name_prefix(pf->field_name());
4674 Expression* s = Expression::make_string(n, bloc);
4675 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4679 go_assert(q->is_field_name("typ"));
4680 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
4683 go_assert(q->is_field_name("tag"));
4685 fvals->push_back(Expression::make_nil(bloc));
4688 Expression* s = Expression::make_string(pf->tag(), bloc);
4689 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4693 go_assert(q->is_field_name("offset"));
4694 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
4696 Expression* v = Expression::make_struct_composite_literal(element_type,
4698 elements->push_back(v);
4701 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
4704 return Expression::make_struct_composite_literal(stdt, vals, bloc);
4707 // Write the hash function for a struct which can not use the identity
4711 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
4712 Function_type* hash_fntype,
4713 Function_type* equal_fntype)
4715 Location bloc = Linemap::predeclared_location();
4717 // The pointer to the struct that we are going to hash. This is an
4718 // argument to the hash function we are implementing here.
4719 Named_object* key_arg = gogo->lookup("key", NULL);
4720 go_assert(key_arg != NULL);
4721 Type* key_arg_type = key_arg->var_value()->type();
4723 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4727 mpz_init_set_ui(ival, 0);
4728 Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
4731 // Make a temporary to hold the return value, initialized to 0.
4732 Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
4734 gogo->add_statement(retval);
4736 // Make a temporary to hold the key as a uintptr.
4737 Expression* ref = Expression::make_var_reference(key_arg, bloc);
4738 ref = Expression::make_cast(uintptr_type, ref, bloc);
4739 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
4741 gogo->add_statement(key);
4743 // Loop over the struct fields.
4745 const Struct_field_list* fields = this->fields_;
4746 for (Struct_field_list::const_iterator pf = fields->begin();
4747 pf != fields->end();
4754 // Multiply retval by 33.
4755 mpz_init_set_ui(ival, 33);
4756 Expression* i33 = Expression::make_integer(&ival, uintptr_type,
4760 ref = Expression::make_temporary_reference(retval, bloc);
4761 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ,
4763 gogo->add_statement(s);
4766 // Get a pointer to the value of this field.
4767 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
4768 ref = Expression::make_temporary_reference(key, bloc);
4769 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
4771 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
4773 // Get the size of this field.
4774 Expression* size = Expression::make_type_info(pf->type(),
4775 Expression::TYPE_INFO_SIZE);
4777 // Get the hash function to use for the type of this field.
4778 Named_object* hash_fn;
4779 Named_object* equal_fn;
4780 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
4781 equal_fntype, &hash_fn, &equal_fn);
4783 // Call the hash function for the field.
4784 Expression_list* args = new Expression_list();
4785 args->push_back(subkey);
4786 args->push_back(size);
4787 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
4788 Expression* call = Expression::make_call(func, args, false, bloc);
4790 // Add the field's hash value to retval.
4791 Temporary_reference_expression* tref =
4792 Expression::make_temporary_reference(retval, bloc);
4793 tref->set_is_lvalue();
4794 Statement* s = Statement::make_assignment_operation(OPERATOR_PLUSEQ,
4796 gogo->add_statement(s);
4799 // Return retval to the caller of the hash function.
4800 Expression_list* vals = new Expression_list();
4801 ref = Expression::make_temporary_reference(retval, bloc);
4802 vals->push_back(ref);
4803 Statement* s = Statement::make_return_statement(vals, bloc);
4804 gogo->add_statement(s);
4807 // Write the equality function for a struct which can not use the
4808 // identity function.
4811 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
4813 Location bloc = Linemap::predeclared_location();
4815 // The pointers to the structs we are going to compare.
4816 Named_object* key1_arg = gogo->lookup("key1", NULL);
4817 Named_object* key2_arg = gogo->lookup("key2", NULL);
4818 go_assert(key1_arg != NULL && key2_arg != NULL);
4820 // Build temporaries with the right types.
4821 Type* pt = Type::make_pointer_type(name != NULL
4822 ? static_cast<Type*>(name)
4823 : static_cast<Type*>(this));
4825 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
4826 ref = Expression::make_unsafe_cast(pt, ref, bloc);
4827 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
4828 gogo->add_statement(p1);
4830 ref = Expression::make_var_reference(key2_arg, bloc);
4831 ref = Expression::make_unsafe_cast(pt, ref, bloc);
4832 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
4833 gogo->add_statement(p2);
4835 const Struct_field_list* fields = this->fields_;
4836 unsigned int field_index = 0;
4837 for (Struct_field_list::const_iterator pf = fields->begin();
4838 pf != fields->end();
4839 ++pf, ++field_index)
4841 // Compare one field in both P1 and P2.
4842 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
4843 f1 = Expression::make_unary(OPERATOR_MULT, f1, bloc);
4844 f1 = Expression::make_field_reference(f1, field_index, bloc);
4846 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
4847 f2 = Expression::make_unary(OPERATOR_MULT, f2, bloc);
4848 f2 = Expression::make_field_reference(f2, field_index, bloc);
4850 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
4852 // If the values are not equal, return false.
4853 gogo->start_block(bloc);
4854 Expression_list* vals = new Expression_list();
4855 vals->push_back(Expression::make_boolean(false, bloc));
4856 Statement* s = Statement::make_return_statement(vals, bloc);
4857 gogo->add_statement(s);
4858 Block* then_block = gogo->finish_block(bloc);
4860 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
4861 gogo->add_statement(s);
4864 // All the fields are equal, so return true.
4865 Expression_list* vals = new Expression_list();
4866 vals->push_back(Expression::make_boolean(true, bloc));
4867 Statement* s = Statement::make_return_statement(vals, bloc);
4868 gogo->add_statement(s);
4871 // Reflection string.
4874 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
4876 ret->append("struct { ");
4878 for (Struct_field_list::const_iterator p = this->fields_->begin();
4879 p != this->fields_->end();
4882 if (p != this->fields_->begin())
4884 if (p->is_anonymous())
4885 ret->push_back('?');
4887 ret->append(Gogo::unpack_hidden_name(p->field_name()));
4888 ret->push_back(' ');
4889 this->append_reflection(p->type(), gogo, ret);
4893 const std::string& tag(p->tag());
4895 for (std::string::const_iterator p = tag.begin();
4900 ret->append("\\x00");
4901 else if (*p == '\n')
4903 else if (*p == '\t')
4906 ret->append("\\\"");
4907 else if (*p == '\\')
4908 ret->append("\\\\");
4912 ret->push_back('"');
4922 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4924 ret->push_back('S');
4926 const Struct_field_list* fields = this->fields_;
4929 for (Struct_field_list::const_iterator p = fields->begin();
4933 if (p->is_anonymous())
4937 std::string n = Gogo::unpack_hidden_name(p->field_name());
4939 snprintf(buf, sizeof buf, "%u_",
4940 static_cast<unsigned int>(n.length()));
4944 this->append_mangled_name(p->type(), gogo, ret);
4947 const std::string& tag(p->tag());
4949 for (std::string::const_iterator p = tag.begin();
4953 if (ISALNUM(*p) || *p == '_')
4958 snprintf(buf, sizeof buf, ".%x.",
4959 static_cast<unsigned int>(*p));
4964 snprintf(buf, sizeof buf, "T%u_",
4965 static_cast<unsigned int>(out.length()));
4972 ret->push_back('e');
4975 // If the offset of field INDEX in the backend implementation can be
4976 // determined, set *POFFSET to the offset in bytes and return true.
4977 // Otherwise, return false.
4980 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
4981 unsigned int* poffset)
4983 if (!this->is_backend_type_size_known(gogo))
4985 Btype* bt = this->get_backend_placeholder(gogo);
4986 size_t offset = gogo->backend()->type_field_offset(bt, index);
4987 *poffset = static_cast<unsigned int>(offset);
4988 if (*poffset != offset)
4996 Struct_type::do_export(Export* exp) const
4998 exp->write_c_string("struct { ");
4999 const Struct_field_list* fields = this->fields_;
5000 go_assert(fields != NULL);
5001 for (Struct_field_list::const_iterator p = fields->begin();
5005 if (p->is_anonymous())
5006 exp->write_string("? ");
5009 exp->write_string(p->field_name());
5010 exp->write_c_string(" ");
5012 exp->write_type(p->type());
5016 exp->write_c_string(" ");
5018 Expression::make_string(p->tag(), Linemap::predeclared_location());
5019 expr->export_expression(exp);
5023 exp->write_c_string("; ");
5025 exp->write_c_string("}");
5031 Struct_type::do_import(Import* imp)
5033 imp->require_c_string("struct { ");
5034 Struct_field_list* fields = new Struct_field_list;
5035 if (imp->peek_char() != '}')
5040 if (imp->match_c_string("? "))
5044 name = imp->read_identifier();
5045 imp->require_c_string(" ");
5047 Type* ftype = imp->read_type();
5049 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
5051 if (imp->peek_char() == ' ')
5054 Expression* expr = Expression::import_expression(imp);
5055 String_expression* sexpr = expr->string_expression();
5056 go_assert(sexpr != NULL);
5057 sf.set_tag(sexpr->val());
5061 imp->require_c_string("; ");
5062 fields->push_back(sf);
5063 if (imp->peek_char() == '}')
5067 imp->require_c_string("}");
5069 return Type::make_struct_type(fields, imp->location());
5072 // Make a struct type.
5075 Type::make_struct_type(Struct_field_list* fields,
5078 return new Struct_type(fields, location);
5081 // Class Array_type.
5083 // Whether two array types are identical.
5086 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
5088 if (!Type::are_identical(this->element_type(), t->element_type(),
5089 errors_are_identical, NULL))
5092 Expression* l1 = this->length();
5093 Expression* l2 = t->length();
5095 // Slices of the same element type are identical.
5096 if (l1 == NULL && l2 == NULL)
5099 // Arrays of the same element type are identical if they have the
5101 if (l1 != NULL && l2 != NULL)
5106 // Try to determine the lengths. If we can't, assume the arrays
5107 // are not identical.
5115 if (l1->integer_constant_value(true, v1, &type1)
5116 && l2->integer_constant_value(true, v2, &type2))
5117 ret = mpz_cmp(v1, v2) == 0;
5123 // Otherwise the arrays are not identical.
5130 Array_type::do_traverse(Traverse* traverse)
5132 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
5133 return TRAVERSE_EXIT;
5134 if (this->length_ != NULL
5135 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
5136 return TRAVERSE_EXIT;
5137 return TRAVERSE_CONTINUE;
5140 // Check that the length is valid.
5143 Array_type::verify_length()
5145 if (this->length_ == NULL)
5148 Type_context context(Type::lookup_integer_type("int"), false);
5149 this->length_->determine_type(&context);
5151 if (!this->length_->is_constant())
5153 error_at(this->length_->location(), "array bound is not constant");
5160 if (!this->length_->integer_constant_value(true, val, &vt))
5164 if (!this->length_->float_constant_value(fval, &vt))
5166 if (this->length_->type()->integer_type() != NULL
5167 || this->length_->type()->float_type() != NULL)
5168 error_at(this->length_->location(),
5169 "array bound is not constant");
5171 error_at(this->length_->location(),
5172 "array bound is not numeric");
5177 if (!mpfr_integer_p(fval))
5179 error_at(this->length_->location(),
5180 "array bound truncated to integer");
5186 mpfr_get_z(val, fval, GMP_RNDN);
5190 if (mpz_sgn(val) < 0)
5192 error_at(this->length_->location(), "negative array bound");
5197 Type* int_type = Type::lookup_integer_type("int");
5198 int tbits = int_type->integer_type()->bits();
5199 int vbits = mpz_sizeinbase(val, 2);
5200 if (vbits + 1 > tbits)
5202 error_at(this->length_->location(), "array bound overflows");
5215 Array_type::do_verify()
5217 if (!this->verify_length())
5218 this->length_ = Expression::make_error(this->length_->location());
5222 // Whether we can use memcmp to compare this array.
5225 Array_type::do_compare_is_identity(Gogo* gogo) const
5227 if (this->length_ == NULL)
5230 // Check for [...], which indicates that this is not a real type.
5231 if (this->length_->is_nil_expression())
5234 if (!this->element_type_->compare_is_identity(gogo))
5237 // If there is any padding, then we can't use memcmp.
5240 if (!this->element_type_->backend_type_size(gogo, &size)
5241 || !this->element_type_->backend_type_align(gogo, &align))
5243 if ((size & (align - 1)) != 0)
5249 // Array type hash code.
5252 Array_type::do_hash_for_method(Gogo* gogo) const
5254 // There is no very convenient way to get a hash code for the
5256 return this->element_type_->hash_for_method(gogo) + 1;
5259 // Write the hash function for an array which can not use the identify
5263 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
5264 Function_type* hash_fntype,
5265 Function_type* equal_fntype)
5267 Location bloc = Linemap::predeclared_location();
5269 // The pointer to the array that we are going to hash. This is an
5270 // argument to the hash function we are implementing here.
5271 Named_object* key_arg = gogo->lookup("key", NULL);
5272 go_assert(key_arg != NULL);
5273 Type* key_arg_type = key_arg->var_value()->type();
5275 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5279 mpz_init_set_ui(ival, 0);
5280 Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
5283 // Make a temporary to hold the return value, initialized to 0.
5284 Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
5286 gogo->add_statement(retval);
5288 // Make a temporary to hold the key as a uintptr.
5289 Expression* ref = Expression::make_var_reference(key_arg, bloc);
5290 ref = Expression::make_cast(uintptr_type, ref, bloc);
5291 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
5293 gogo->add_statement(key);
5295 // Loop over the array elements.
5297 Type* int_type = Type::lookup_integer_type("int");
5298 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
5299 gogo->add_statement(index);
5301 Expression* iref = Expression::make_temporary_reference(index, bloc);
5302 Expression* aref = Expression::make_var_reference(key_arg, bloc);
5303 Type* pt = Type::make_pointer_type(name != NULL
5304 ? static_cast<Type*>(name)
5305 : static_cast<Type*>(this));
5306 aref = Expression::make_cast(pt, aref, bloc);
5307 For_range_statement* for_range = Statement::make_for_range_statement(iref,
5312 gogo->start_block(bloc);
5314 // Multiply retval by 33.
5315 mpz_init_set_ui(ival, 33);
5316 Expression* i33 = Expression::make_integer(&ival, uintptr_type, bloc);
5319 ref = Expression::make_temporary_reference(retval, bloc);
5320 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ, ref,
5322 gogo->add_statement(s);
5324 // Get the hash function for the element type.
5325 Named_object* hash_fn;
5326 Named_object* equal_fn;
5327 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
5328 hash_fntype, equal_fntype, &hash_fn,
5331 // Get a pointer to this element in the loop.
5332 Expression* subkey = Expression::make_temporary_reference(key, bloc);
5333 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
5335 // Get the size of each element.
5336 Expression* ele_size = Expression::make_type_info(this->element_type_,
5337 Expression::TYPE_INFO_SIZE);
5339 // Get the hash of this element.
5340 Expression_list* args = new Expression_list();
5341 args->push_back(subkey);
5342 args->push_back(ele_size);
5343 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
5344 Expression* call = Expression::make_call(func, args, false, bloc);
5346 // Add the element's hash value to retval.
5347 Temporary_reference_expression* tref =
5348 Expression::make_temporary_reference(retval, bloc);
5349 tref->set_is_lvalue();
5350 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, call, bloc);
5351 gogo->add_statement(s);
5353 // Increase the element pointer.
5354 tref = Expression::make_temporary_reference(key, bloc);
5355 tref->set_is_lvalue();
5356 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
5359 Block* statements = gogo->finish_block(bloc);
5361 for_range->add_statements(statements);
5362 gogo->add_statement(for_range);
5364 // Return retval to the caller of the hash function.
5365 Expression_list* vals = new Expression_list();
5366 ref = Expression::make_temporary_reference(retval, bloc);
5367 vals->push_back(ref);
5368 s = Statement::make_return_statement(vals, bloc);
5369 gogo->add_statement(s);
5372 // Write the equality function for an array which can not use the
5373 // identity function.
5376 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
5378 Location bloc = Linemap::predeclared_location();
5380 // The pointers to the arrays we are going to compare.
5381 Named_object* key1_arg = gogo->lookup("key1", NULL);
5382 Named_object* key2_arg = gogo->lookup("key2", NULL);
5383 go_assert(key1_arg != NULL && key2_arg != NULL);
5385 // Build temporaries for the keys with the right types.
5386 Type* pt = Type::make_pointer_type(name != NULL
5387 ? static_cast<Type*>(name)
5388 : static_cast<Type*>(this));
5390 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
5391 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5392 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
5393 gogo->add_statement(p1);
5395 ref = Expression::make_var_reference(key2_arg, bloc);
5396 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5397 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
5398 gogo->add_statement(p2);
5400 // Loop over the array elements.
5402 Type* int_type = Type::lookup_integer_type("int");
5403 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
5404 gogo->add_statement(index);
5406 Expression* iref = Expression::make_temporary_reference(index, bloc);
5407 Expression* aref = Expression::make_temporary_reference(p1, bloc);
5408 For_range_statement* for_range = Statement::make_for_range_statement(iref,
5413 gogo->start_block(bloc);
5415 // Compare element in P1 and P2.
5416 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
5417 e1 = Expression::make_unary(OPERATOR_MULT, e1, bloc);
5418 ref = Expression::make_temporary_reference(index, bloc);
5419 e1 = Expression::make_array_index(e1, ref, NULL, bloc);
5421 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
5422 e2 = Expression::make_unary(OPERATOR_MULT, e2, bloc);
5423 ref = Expression::make_temporary_reference(index, bloc);
5424 e2 = Expression::make_array_index(e2, ref, NULL, bloc);
5426 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
5428 // If the elements are not equal, return false.
5429 gogo->start_block(bloc);
5430 Expression_list* vals = new Expression_list();
5431 vals->push_back(Expression::make_boolean(false, bloc));
5432 Statement* s = Statement::make_return_statement(vals, bloc);
5433 gogo->add_statement(s);
5434 Block* then_block = gogo->finish_block(bloc);
5436 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
5437 gogo->add_statement(s);
5439 Block* statements = gogo->finish_block(bloc);
5441 for_range->add_statements(statements);
5442 gogo->add_statement(for_range);
5444 // All the elements are equal, so return true.
5445 vals = new Expression_list();
5446 vals->push_back(Expression::make_boolean(true, bloc));
5447 s = Statement::make_return_statement(vals, bloc);
5448 gogo->add_statement(s);
5451 // Get a tree for the length of a fixed array. The length may be
5452 // computed using a function call, so we must only evaluate it once.
5455 Array_type::get_length_tree(Gogo* gogo)
5457 go_assert(this->length_ != NULL);
5458 if (this->length_tree_ == NULL_TREE)
5463 if (this->length_->integer_constant_value(true, val, &t))
5466 t = Type::lookup_integer_type("int");
5467 else if (t->is_abstract())
5468 t = t->make_non_abstract_type();
5469 tree tt = type_to_tree(t->get_backend(gogo));
5470 this->length_tree_ = Expression::integer_constant_tree(val, tt);
5477 // Make up a translation context for the array length
5478 // expression. FIXME: This won't work in general.
5479 Translate_context context(gogo, NULL, NULL, NULL);
5480 tree len = this->length_->get_tree(&context);
5481 if (len != error_mark_node)
5483 len = convert_to_integer(integer_type_node, len);
5484 len = save_expr(len);
5486 this->length_tree_ = len;
5489 return this->length_tree_;
5492 // Get the backend representation of the fields of a slice. This is
5493 // not declared in types.h so that types.h doesn't have to #include
5496 // We use int for the count and capacity fields. This matches 6g.
5497 // The language more or less assumes that we can't allocate space of a
5498 // size which does not fit in int.
5501 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
5502 std::vector<Backend::Btyped_identifier>* bfields)
5506 Type* pet = Type::make_pointer_type(type->element_type());
5507 Btype* pbet = (use_placeholder
5508 ? pet->get_backend_placeholder(gogo)
5509 : pet->get_backend(gogo));
5510 Location ploc = Linemap::predeclared_location();
5512 Backend::Btyped_identifier* p = &(*bfields)[0];
5513 p->name = "__values";
5517 Type* int_type = Type::lookup_integer_type("int");
5520 p->name = "__count";
5521 p->btype = int_type->get_backend(gogo);
5525 p->name = "__capacity";
5526 p->btype = int_type->get_backend(gogo);
5530 // Get a tree for the type of this array. A fixed array is simply
5531 // represented as ARRAY_TYPE with the appropriate index--i.e., it is
5532 // just like an array in C. An open array is a struct with three
5533 // fields: a data pointer, the length, and the capacity.
5536 Array_type::do_get_backend(Gogo* gogo)
5538 if (this->length_ == NULL)
5540 std::vector<Backend::Btyped_identifier> bfields;
5541 get_backend_slice_fields(gogo, this, false, &bfields);
5542 return gogo->backend()->struct_type(bfields);
5546 Btype* element = this->get_backend_element(gogo, false);
5547 Bexpression* len = this->get_backend_length(gogo);
5548 return gogo->backend()->array_type(element, len);
5552 // Return the backend representation of the element type.
5555 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
5557 if (use_placeholder)
5558 return this->element_type_->get_backend_placeholder(gogo);
5560 return this->element_type_->get_backend(gogo);
5563 // Return the backend representation of the length.
5566 Array_type::get_backend_length(Gogo* gogo)
5568 return tree_to_expr(this->get_length_tree(gogo));
5571 // Finish backend representation of the array.
5574 Array_type::finish_backend_element(Gogo* gogo)
5576 Type* et = this->array_type()->element_type();
5577 et->get_backend(gogo);
5578 if (this->is_slice_type())
5580 // This relies on the fact that we always use the same
5581 // structure for a pointer to any given type.
5582 Type* pet = Type::make_pointer_type(et);
5583 pet->get_backend(gogo);
5587 // Return a tree for a pointer to the values in ARRAY.
5590 Array_type::value_pointer_tree(Gogo*, tree array) const
5593 if (this->length() != NULL)
5596 ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))),
5597 build_fold_addr_expr(array));
5602 tree field = TYPE_FIELDS(TREE_TYPE(array));
5603 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
5605 ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field,
5608 if (TREE_CONSTANT(array))
5609 TREE_CONSTANT(ret) = 1;
5613 // Return a tree for the length of the array ARRAY which has this
5617 Array_type::length_tree(Gogo* gogo, tree array)
5619 if (this->length_ != NULL)
5621 if (TREE_CODE(array) == SAVE_EXPR)
5622 return fold_convert(integer_type_node, this->get_length_tree(gogo));
5624 return omit_one_operand(integer_type_node,
5625 this->get_length_tree(gogo), array);
5628 // This is an open array. We need to read the length field.
5630 tree type = TREE_TYPE(array);
5631 go_assert(TREE_CODE(type) == RECORD_TYPE);
5633 tree field = DECL_CHAIN(TYPE_FIELDS(type));
5634 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
5636 tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
5637 if (TREE_CONSTANT(array))
5638 TREE_CONSTANT(ret) = 1;
5642 // Return a tree for the capacity of the array ARRAY which has this
5646 Array_type::capacity_tree(Gogo* gogo, tree array)
5648 if (this->length_ != NULL)
5649 return omit_one_operand(integer_type_node, this->get_length_tree(gogo),
5652 // This is an open array. We need to read the capacity field.
5654 tree type = TREE_TYPE(array);
5655 go_assert(TREE_CODE(type) == RECORD_TYPE);
5657 tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type)));
5658 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
5660 return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
5666 Array_type::do_export(Export* exp) const
5668 exp->write_c_string("[");
5669 if (this->length_ != NULL)
5670 this->length_->export_expression(exp);
5671 exp->write_c_string("] ");
5672 exp->write_type(this->element_type_);
5678 Array_type::do_import(Import* imp)
5680 imp->require_c_string("[");
5682 if (imp->peek_char() == ']')
5685 length = Expression::import_expression(imp);
5686 imp->require_c_string("] ");
5687 Type* element_type = imp->read_type();
5688 return Type::make_array_type(element_type, length);
5691 // The type of an array type descriptor.
5694 Array_type::make_array_type_descriptor_type()
5699 Type* tdt = Type::make_type_descriptor_type();
5700 Type* ptdt = Type::make_type_descriptor_ptr_type();
5702 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5705 Type::make_builtin_struct_type(4,
5709 "len", uintptr_type);
5711 ret = Type::make_builtin_named_type("ArrayType", sf);
5717 // The type of an slice type descriptor.
5720 Array_type::make_slice_type_descriptor_type()
5725 Type* tdt = Type::make_type_descriptor_type();
5726 Type* ptdt = Type::make_type_descriptor_ptr_type();
5729 Type::make_builtin_struct_type(2,
5733 ret = Type::make_builtin_named_type("SliceType", sf);
5739 // Build a type descriptor for an array/slice type.
5742 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5744 if (this->length_ != NULL)
5745 return this->array_type_descriptor(gogo, name);
5747 return this->slice_type_descriptor(gogo, name);
5750 // Build a type descriptor for an array type.
5753 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
5755 Location bloc = Linemap::predeclared_location();
5757 Type* atdt = Array_type::make_array_type_descriptor_type();
5759 const Struct_field_list* fields = atdt->struct_type()->fields();
5761 Expression_list* vals = new Expression_list();
5764 Struct_field_list::const_iterator p = fields->begin();
5765 go_assert(p->is_field_name("commonType"));
5766 vals->push_back(this->type_descriptor_constructor(gogo,
5767 RUNTIME_TYPE_KIND_ARRAY,
5771 go_assert(p->is_field_name("elem"));
5772 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5775 go_assert(p->is_field_name("slice"));
5776 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
5777 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
5780 go_assert(p->is_field_name("len"));
5781 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
5784 go_assert(p == fields->end());
5786 return Expression::make_struct_composite_literal(atdt, vals, bloc);
5789 // Build a type descriptor for a slice type.
5792 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
5794 Location bloc = Linemap::predeclared_location();
5796 Type* stdt = Array_type::make_slice_type_descriptor_type();
5798 const Struct_field_list* fields = stdt->struct_type()->fields();
5800 Expression_list* vals = new Expression_list();
5803 Struct_field_list::const_iterator p = fields->begin();
5804 go_assert(p->is_field_name("commonType"));
5805 vals->push_back(this->type_descriptor_constructor(gogo,
5806 RUNTIME_TYPE_KIND_SLICE,
5810 go_assert(p->is_field_name("elem"));
5811 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5814 go_assert(p == fields->end());
5816 return Expression::make_struct_composite_literal(stdt, vals, bloc);
5819 // Reflection string.
5822 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
5824 ret->push_back('[');
5825 if (this->length_ != NULL)
5830 if (!this->length_->integer_constant_value(true, val, &type))
5831 error_at(this->length_->location(),
5832 "array length must be integer constant expression");
5833 else if (mpz_cmp_si(val, 0) < 0)
5834 error_at(this->length_->location(), "array length is negative");
5835 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
5836 error_at(this->length_->location(), "array length is too large");
5840 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
5845 ret->push_back(']');
5847 this->append_reflection(this->element_type_, gogo, ret);
5853 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5855 ret->push_back('A');
5856 this->append_mangled_name(this->element_type_, gogo, ret);
5857 if (this->length_ != NULL)
5862 if (!this->length_->integer_constant_value(true, val, &type))
5863 error_at(this->length_->location(),
5864 "array length must be integer constant expression");
5865 else if (mpz_cmp_si(val, 0) < 0)
5866 error_at(this->length_->location(), "array length is negative");
5867 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
5868 error_at(this->length_->location(), "array size is too large");
5872 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
5877 ret->push_back('e');
5880 // Make an array type.
5883 Type::make_array_type(Type* element_type, Expression* length)
5885 return new Array_type(element_type, length);
5893 Map_type::do_traverse(Traverse* traverse)
5895 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
5896 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
5897 return TRAVERSE_EXIT;
5898 return TRAVERSE_CONTINUE;
5901 // Check that the map type is OK.
5904 Map_type::do_verify()
5906 // The runtime support uses "map[void]void".
5907 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
5908 error_at(this->location_, "invalid map key type");
5912 // Whether two map types are identical.
5915 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
5917 return (Type::are_identical(this->key_type(), t->key_type(),
5918 errors_are_identical, NULL)
5919 && Type::are_identical(this->val_type(), t->val_type(),
5920 errors_are_identical, NULL));
5926 Map_type::do_hash_for_method(Gogo* gogo) const
5928 return (this->key_type_->hash_for_method(gogo)
5929 + this->val_type_->hash_for_method(gogo)
5933 // Get the backend representation for a map type. A map type is
5934 // represented as a pointer to a struct. The struct is __go_map in
5938 Map_type::do_get_backend(Gogo* gogo)
5940 static Btype* backend_map_type;
5941 if (backend_map_type == NULL)
5943 std::vector<Backend::Btyped_identifier> bfields(4);
5945 Location bloc = Linemap::predeclared_location();
5947 Type* pdt = Type::make_type_descriptor_ptr_type();
5948 bfields[0].name = "__descriptor";
5949 bfields[0].btype = pdt->get_backend(gogo);
5950 bfields[0].location = bloc;
5952 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5953 bfields[1].name = "__element_count";
5954 bfields[1].btype = uintptr_type->get_backend(gogo);
5955 bfields[1].location = bloc;
5957 bfields[2].name = "__bucket_count";
5958 bfields[2].btype = bfields[1].btype;
5959 bfields[2].location = bloc;
5961 Btype* bvt = gogo->backend()->void_type();
5962 Btype* bpvt = gogo->backend()->pointer_type(bvt);
5963 Btype* bppvt = gogo->backend()->pointer_type(bpvt);
5964 bfields[3].name = "__buckets";
5965 bfields[3].btype = bppvt;
5966 bfields[3].location = bloc;
5968 Btype *bt = gogo->backend()->struct_type(bfields);
5969 bt = gogo->backend()->named_type("__go_map", bt, bloc);
5970 backend_map_type = gogo->backend()->pointer_type(bt);
5972 return backend_map_type;
5975 // The type of a map type descriptor.
5978 Map_type::make_map_type_descriptor_type()
5983 Type* tdt = Type::make_type_descriptor_type();
5984 Type* ptdt = Type::make_type_descriptor_ptr_type();
5987 Type::make_builtin_struct_type(3,
5992 ret = Type::make_builtin_named_type("MapType", sf);
5998 // Build a type descriptor for a map type.
6001 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6003 Location bloc = Linemap::predeclared_location();
6005 Type* mtdt = Map_type::make_map_type_descriptor_type();
6007 const Struct_field_list* fields = mtdt->struct_type()->fields();
6009 Expression_list* vals = new Expression_list();
6012 Struct_field_list::const_iterator p = fields->begin();
6013 go_assert(p->is_field_name("commonType"));
6014 vals->push_back(this->type_descriptor_constructor(gogo,
6015 RUNTIME_TYPE_KIND_MAP,
6019 go_assert(p->is_field_name("key"));
6020 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
6023 go_assert(p->is_field_name("elem"));
6024 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
6027 go_assert(p == fields->end());
6029 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
6032 // A mapping from map types to map descriptors.
6034 Map_type::Map_descriptors Map_type::map_descriptors;
6036 // Build a map descriptor for this type. Return a pointer to it.
6039 Map_type::map_descriptor_pointer(Gogo* gogo, Location location)
6041 Bvariable* bvar = this->map_descriptor(gogo);
6042 tree var_tree = var_to_tree(bvar);
6043 if (var_tree == error_mark_node)
6044 return error_mark_node;
6045 return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
6048 // Build a map descriptor for this type.
6051 Map_type::map_descriptor(Gogo* gogo)
6053 std::pair<Map_type*, Bvariable*> val(this, NULL);
6054 std::pair<Map_type::Map_descriptors::iterator, bool> ins =
6055 Map_type::map_descriptors.insert(val);
6057 return ins.first->second;
6059 Type* key_type = this->key_type_;
6060 Type* val_type = this->val_type_;
6062 // The map entry type is a struct with three fields. Build that
6063 // struct so that we can get the offsets of the key and value within
6064 // a map entry. The first field should technically be a pointer to
6065 // this type itself, but since we only care about field offsets we
6066 // just use pointer to bool.
6067 Type* pbool = Type::make_pointer_type(Type::make_boolean_type());
6068 Struct_type* map_entry_type =
6069 Type::make_builtin_struct_type(3,
6074 Type* map_descriptor_type = Map_type::make_map_descriptor_type();
6076 const Struct_field_list* fields =
6077 map_descriptor_type->struct_type()->fields();
6079 Expression_list* vals = new Expression_list();
6082 Location bloc = Linemap::predeclared_location();
6084 Struct_field_list::const_iterator p = fields->begin();
6086 go_assert(p->is_field_name("__map_descriptor"));
6087 vals->push_back(Expression::make_type_descriptor(this, bloc));
6090 go_assert(p->is_field_name("__entry_size"));
6091 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
6092 vals->push_back(Expression::make_type_info(map_entry_type, type_info));
6094 Struct_field_list::const_iterator pf = map_entry_type->fields()->begin();
6096 go_assert(pf->is_field_name("__key"));
6099 go_assert(p->is_field_name("__key_offset"));
6100 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6103 go_assert(pf->is_field_name("__val"));
6106 go_assert(p->is_field_name("__val_offset"));
6107 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6110 go_assert(p == fields->end());
6112 Expression* initializer =
6113 Expression::make_struct_composite_literal(map_descriptor_type, vals, bloc);
6115 std::string mangled_name = "__go_map_" + this->mangled_name(gogo);
6116 Btype* map_descriptor_btype = map_descriptor_type->get_backend(gogo);
6117 Bvariable* bvar = gogo->backend()->immutable_struct(mangled_name, true,
6118 map_descriptor_btype,
6121 Translate_context context(gogo, NULL, NULL, NULL);
6122 context.set_is_const();
6123 Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
6125 gogo->backend()->immutable_struct_set_init(bvar, mangled_name, true,
6126 map_descriptor_btype, bloc,
6129 ins.first->second = bvar;
6133 // Build the type of a map descriptor. This must match the struct
6134 // __go_map_descriptor in libgo/runtime/map.h.
6137 Map_type::make_map_descriptor_type()
6142 Type* ptdt = Type::make_type_descriptor_ptr_type();
6143 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6145 Type::make_builtin_struct_type(4,
6146 "__map_descriptor", ptdt,
6147 "__entry_size", uintptr_type,
6148 "__key_offset", uintptr_type,
6149 "__val_offset", uintptr_type);
6150 ret = Type::make_builtin_named_type("__go_map_descriptor", sf);
6155 // Reflection string for a map.
6158 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
6160 ret->append("map[");
6161 this->append_reflection(this->key_type_, gogo, ret);
6163 this->append_reflection(this->val_type_, gogo, ret);
6166 // Mangled name for a map.
6169 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6171 ret->push_back('M');
6172 this->append_mangled_name(this->key_type_, gogo, ret);
6174 this->append_mangled_name(this->val_type_, gogo, ret);
6177 // Export a map type.
6180 Map_type::do_export(Export* exp) const
6182 exp->write_c_string("map [");
6183 exp->write_type(this->key_type_);
6184 exp->write_c_string("] ");
6185 exp->write_type(this->val_type_);
6188 // Import a map type.
6191 Map_type::do_import(Import* imp)
6193 imp->require_c_string("map [");
6194 Type* key_type = imp->read_type();
6195 imp->require_c_string("] ");
6196 Type* val_type = imp->read_type();
6197 return Type::make_map_type(key_type, val_type, imp->location());
6203 Type::make_map_type(Type* key_type, Type* val_type, Location location)
6205 return new Map_type(key_type, val_type, location);
6208 // Class Channel_type.
6213 Channel_type::do_hash_for_method(Gogo* gogo) const
6215 unsigned int ret = 0;
6216 if (this->may_send_)
6218 if (this->may_receive_)
6220 if (this->element_type_ != NULL)
6221 ret += this->element_type_->hash_for_method(gogo) << 2;
6225 // Whether this type is the same as T.
6228 Channel_type::is_identical(const Channel_type* t,
6229 bool errors_are_identical) const
6231 if (!Type::are_identical(this->element_type(), t->element_type(),
6232 errors_are_identical, NULL))
6234 return (this->may_send_ == t->may_send_
6235 && this->may_receive_ == t->may_receive_);
6238 // Return the tree for a channel type. A channel is a pointer to a
6239 // __go_channel struct. The __go_channel struct is defined in
6240 // libgo/runtime/channel.h.
6243 Channel_type::do_get_backend(Gogo* gogo)
6245 static Btype* backend_channel_type;
6246 if (backend_channel_type == NULL)
6248 std::vector<Backend::Btyped_identifier> bfields;
6249 Btype* bt = gogo->backend()->struct_type(bfields);
6250 bt = gogo->backend()->named_type("__go_channel", bt,
6251 Linemap::predeclared_location());
6252 backend_channel_type = gogo->backend()->pointer_type(bt);
6254 return backend_channel_type;
6257 // Build a type descriptor for a channel type.
6260 Channel_type::make_chan_type_descriptor_type()
6265 Type* tdt = Type::make_type_descriptor_type();
6266 Type* ptdt = Type::make_type_descriptor_ptr_type();
6268 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6271 Type::make_builtin_struct_type(3,
6274 "dir", uintptr_type);
6276 ret = Type::make_builtin_named_type("ChanType", sf);
6282 // Build a type descriptor for a map type.
6285 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6287 Location bloc = Linemap::predeclared_location();
6289 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
6291 const Struct_field_list* fields = ctdt->struct_type()->fields();
6293 Expression_list* vals = new Expression_list();
6296 Struct_field_list::const_iterator p = fields->begin();
6297 go_assert(p->is_field_name("commonType"));
6298 vals->push_back(this->type_descriptor_constructor(gogo,
6299 RUNTIME_TYPE_KIND_CHAN,
6303 go_assert(p->is_field_name("elem"));
6304 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
6307 go_assert(p->is_field_name("dir"));
6308 // These bits must match the ones in libgo/runtime/go-type.h.
6310 if (this->may_receive_)
6312 if (this->may_send_)
6315 mpz_init_set_ui(iv, val);
6316 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
6320 go_assert(p == fields->end());
6322 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
6325 // Reflection string.
6328 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
6330 if (!this->may_send_)
6332 ret->append("chan");
6333 if (!this->may_receive_)
6335 ret->push_back(' ');
6336 this->append_reflection(this->element_type_, gogo, ret);
6342 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6344 ret->push_back('C');
6345 this->append_mangled_name(this->element_type_, gogo, ret);
6346 if (this->may_send_)
6347 ret->push_back('s');
6348 if (this->may_receive_)
6349 ret->push_back('r');
6350 ret->push_back('e');
6356 Channel_type::do_export(Export* exp) const
6358 exp->write_c_string("chan ");
6359 if (this->may_send_ && !this->may_receive_)
6360 exp->write_c_string("-< ");
6361 else if (this->may_receive_ && !this->may_send_)
6362 exp->write_c_string("<- ");
6363 exp->write_type(this->element_type_);
6369 Channel_type::do_import(Import* imp)
6371 imp->require_c_string("chan ");
6375 if (imp->match_c_string("-< "))
6379 may_receive = false;
6381 else if (imp->match_c_string("<- "))
6393 Type* element_type = imp->read_type();
6395 return Type::make_channel_type(may_send, may_receive, element_type);
6398 // Make a new channel type.
6401 Type::make_channel_type(bool send, bool receive, Type* element_type)
6403 return new Channel_type(send, receive, element_type);
6406 // Class Interface_type.
6411 Interface_type::do_traverse(Traverse* traverse)
6413 Typed_identifier_list* methods = (this->methods_are_finalized_
6414 ? this->all_methods_
6415 : this->parse_methods_);
6416 if (methods == NULL)
6417 return TRAVERSE_CONTINUE;
6418 return methods->traverse(traverse);
6421 // Finalize the methods. This handles interface inheritance.
6424 Interface_type::finalize_methods()
6426 if (this->methods_are_finalized_)
6428 this->methods_are_finalized_ = true;
6429 if (this->parse_methods_ == NULL)
6432 this->all_methods_ = new Typed_identifier_list();
6433 this->all_methods_->reserve(this->parse_methods_->size());
6434 Typed_identifier_list inherit;
6435 for (Typed_identifier_list::const_iterator pm =
6436 this->parse_methods_->begin();
6437 pm != this->parse_methods_->end();
6440 const Typed_identifier* p = &*pm;
6441 if (p->name().empty())
6442 inherit.push_back(*p);
6443 else if (this->find_method(p->name()) == NULL)
6444 this->all_methods_->push_back(*p);
6446 error_at(p->location(), "duplicate method %qs",
6447 Gogo::message_name(p->name()).c_str());
6450 std::vector<Named_type*> seen;
6451 seen.reserve(inherit.size());
6452 bool issued_recursive_error = false;
6453 while (!inherit.empty())
6455 Type* t = inherit.back().type();
6456 Location tl = inherit.back().location();
6459 Interface_type* it = t->interface_type();
6463 error_at(tl, "interface contains embedded non-interface");
6468 if (!issued_recursive_error)
6470 error_at(tl, "invalid recursive interface");
6471 issued_recursive_error = true;
6476 Named_type* nt = t->named_type();
6477 if (nt != NULL && it->parse_methods_ != NULL)
6479 std::vector<Named_type*>::const_iterator q;
6480 for (q = seen.begin(); q != seen.end(); ++q)
6484 error_at(tl, "inherited interface loop");
6488 if (q != seen.end())
6493 const Typed_identifier_list* imethods = it->parse_methods_;
6494 if (imethods == NULL)
6496 for (Typed_identifier_list::const_iterator q = imethods->begin();
6497 q != imethods->end();
6500 if (q->name().empty())
6501 inherit.push_back(*q);
6502 else if (this->find_method(q->name()) == NULL)
6503 this->all_methods_->push_back(Typed_identifier(q->name(),
6506 error_at(tl, "inherited method %qs is ambiguous",
6507 Gogo::message_name(q->name()).c_str());
6511 if (!this->all_methods_->empty())
6512 this->all_methods_->sort_by_name();
6515 delete this->all_methods_;
6516 this->all_methods_ = NULL;
6520 // Return the method NAME, or NULL.
6522 const Typed_identifier*
6523 Interface_type::find_method(const std::string& name) const
6525 go_assert(this->methods_are_finalized_);
6526 if (this->all_methods_ == NULL)
6528 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6529 p != this->all_methods_->end();
6531 if (p->name() == name)
6536 // Return the method index.
6539 Interface_type::method_index(const std::string& name) const
6541 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
6543 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6544 p != this->all_methods_->end();
6546 if (p->name() == name)
6551 // Return whether NAME is an unexported method, for better error
6555 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
6557 go_assert(this->methods_are_finalized_);
6558 if (this->all_methods_ == NULL)
6560 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6561 p != this->all_methods_->end();
6564 const std::string& method_name(p->name());
6565 if (Gogo::is_hidden_name(method_name)
6566 && name == Gogo::unpack_hidden_name(method_name)
6567 && gogo->pack_hidden_name(name, false) != method_name)
6573 // Whether this type is identical with T.
6576 Interface_type::is_identical(const Interface_type* t,
6577 bool errors_are_identical) const
6579 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
6581 // We require the same methods with the same types. The methods
6582 // have already been sorted.
6583 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
6584 return this->all_methods_ == t->all_methods_;
6586 if (this->assume_identical(this, t) || t->assume_identical(t, this))
6589 Assume_identical* hold_ai = this->assume_identical_;
6590 Assume_identical ai;
6594 this->assume_identical_ = &ai;
6596 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
6597 Typed_identifier_list::const_iterator p2;
6598 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
6600 if (p1 == this->all_methods_->end())
6602 if (p1->name() != p2->name()
6603 || !Type::are_identical(p1->type(), p2->type(),
6604 errors_are_identical, NULL))
6608 this->assume_identical_ = hold_ai;
6610 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
6613 // Return true if T1 and T2 are assumed to be identical during a type
6617 Interface_type::assume_identical(const Interface_type* t1,
6618 const Interface_type* t2) const
6620 for (Assume_identical* p = this->assume_identical_;
6623 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
6628 // Whether we can assign the interface type T to this type. The types
6629 // are known to not be identical. An interface assignment is only
6630 // permitted if T is known to implement all methods in THIS.
6631 // Otherwise a type guard is required.
6634 Interface_type::is_compatible_for_assign(const Interface_type* t,
6635 std::string* reason) const
6637 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
6638 if (this->all_methods_ == NULL)
6640 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6641 p != this->all_methods_->end();
6644 const Typed_identifier* m = t->find_method(p->name());
6650 snprintf(buf, sizeof buf,
6651 _("need explicit conversion; missing method %s%s%s"),
6652 open_quote, Gogo::message_name(p->name()).c_str(),
6654 reason->assign(buf);
6659 std::string subreason;
6660 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
6664 std::string n = Gogo::message_name(p->name());
6665 size_t len = 100 + n.length() + subreason.length();
6666 char* buf = new char[len];
6667 if (subreason.empty())
6668 snprintf(buf, len, _("incompatible type for method %s%s%s"),
6669 open_quote, n.c_str(), close_quote);
6672 _("incompatible type for method %s%s%s (%s)"),
6673 open_quote, n.c_str(), close_quote,
6675 reason->assign(buf);
6688 Interface_type::do_hash_for_method(Gogo*) const
6690 go_assert(this->methods_are_finalized_);
6691 unsigned int ret = 0;
6692 if (this->all_methods_ != NULL)
6694 for (Typed_identifier_list::const_iterator p =
6695 this->all_methods_->begin();
6696 p != this->all_methods_->end();
6699 ret = Type::hash_string(p->name(), ret);
6700 // We don't use the method type in the hash, to avoid
6701 // infinite recursion if an interface method uses a type
6702 // which is an interface which inherits from the interface
6704 // type T interface { F() interface {T}}
6711 // Return true if T implements the interface. If it does not, and
6712 // REASON is not NULL, set *REASON to a useful error message.
6715 Interface_type::implements_interface(const Type* t, std::string* reason) const
6717 go_assert(this->methods_are_finalized_);
6718 if (this->all_methods_ == NULL)
6721 bool is_pointer = false;
6722 const Named_type* nt = t->named_type();
6723 const Struct_type* st = t->struct_type();
6724 // If we start with a named type, we don't dereference it to find
6728 const Type* pt = t->points_to();
6731 // If T is a pointer to a named type, then we need to look at
6732 // the type to which it points.
6734 nt = pt->named_type();
6735 st = pt->struct_type();
6739 // If we have a named type, get the methods from it rather than from
6744 // Only named and struct types have methods.
6745 if (nt == NULL && st == NULL)
6749 if (t->points_to() != NULL
6750 && t->points_to()->interface_type() != NULL)
6751 reason->assign(_("pointer to interface type has no methods"));
6753 reason->assign(_("type has no methods"));
6758 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
6762 if (t->points_to() != NULL
6763 && t->points_to()->interface_type() != NULL)
6764 reason->assign(_("pointer to interface type has no methods"));
6766 reason->assign(_("type has no methods"));
6771 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6772 p != this->all_methods_->end();
6775 bool is_ambiguous = false;
6776 Method* m = (nt != NULL
6777 ? nt->method_function(p->name(), &is_ambiguous)
6778 : st->method_function(p->name(), &is_ambiguous));
6783 std::string n = Gogo::message_name(p->name());
6784 size_t len = n.length() + 100;
6785 char* buf = new char[len];
6787 snprintf(buf, len, _("ambiguous method %s%s%s"),
6788 open_quote, n.c_str(), close_quote);
6790 snprintf(buf, len, _("missing method %s%s%s"),
6791 open_quote, n.c_str(), close_quote);
6792 reason->assign(buf);
6798 Function_type *p_fn_type = p->type()->function_type();
6799 Function_type* m_fn_type = m->type()->function_type();
6800 go_assert(p_fn_type != NULL && m_fn_type != NULL);
6801 std::string subreason;
6802 if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
6806 std::string n = Gogo::message_name(p->name());
6807 size_t len = 100 + n.length() + subreason.length();
6808 char* buf = new char[len];
6809 if (subreason.empty())
6810 snprintf(buf, len, _("incompatible type for method %s%s%s"),
6811 open_quote, n.c_str(), close_quote);
6814 _("incompatible type for method %s%s%s (%s)"),
6815 open_quote, n.c_str(), close_quote,
6817 reason->assign(buf);
6823 if (!is_pointer && !m->is_value_method())
6827 std::string n = Gogo::message_name(p->name());
6828 size_t len = 100 + n.length();
6829 char* buf = new char[len];
6830 snprintf(buf, len, _("method %s%s%s requires a pointer"),
6831 open_quote, n.c_str(), close_quote);
6832 reason->assign(buf);
6842 // Return the backend representation of the empty interface type. We
6843 // use the same struct for all empty interfaces.
6846 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
6848 static Btype* empty_interface_type;
6849 if (empty_interface_type == NULL)
6851 std::vector<Backend::Btyped_identifier> bfields(2);
6853 Location bloc = Linemap::predeclared_location();
6855 Type* pdt = Type::make_type_descriptor_ptr_type();
6856 bfields[0].name = "__type_descriptor";
6857 bfields[0].btype = pdt->get_backend(gogo);
6858 bfields[0].location = bloc;
6860 Type* vt = Type::make_pointer_type(Type::make_void_type());
6861 bfields[1].name = "__object";
6862 bfields[1].btype = vt->get_backend(gogo);
6863 bfields[1].location = bloc;
6865 empty_interface_type = gogo->backend()->struct_type(bfields);
6867 return empty_interface_type;
6870 // Return the fields of a non-empty interface type. This is not
6871 // declared in types.h so that types.h doesn't have to #include
6875 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
6876 bool use_placeholder,
6877 std::vector<Backend::Btyped_identifier>* bfields)
6879 Location loc = type->location();
6881 std::vector<Backend::Btyped_identifier> mfields(type->methods()->size() + 1);
6883 Type* pdt = Type::make_type_descriptor_ptr_type();
6884 mfields[0].name = "__type_descriptor";
6885 mfields[0].btype = pdt->get_backend(gogo);
6886 mfields[0].location = loc;
6888 std::string last_name = "";
6890 for (Typed_identifier_list::const_iterator p = type->methods()->begin();
6891 p != type->methods()->end();
6894 // The type of the method in Go only includes the parameters.
6895 // The actual method also has a receiver, which is always a
6896 // pointer. We need to add that pointer type here in order to
6897 // generate the correct type for the backend.
6898 Function_type* ft = p->type()->function_type();
6899 go_assert(ft->receiver() == NULL);
6901 const Typed_identifier_list* params = ft->parameters();
6902 Typed_identifier_list* mparams = new Typed_identifier_list();
6904 mparams->reserve(params->size() + 1);
6905 Type* vt = Type::make_pointer_type(Type::make_void_type());
6906 mparams->push_back(Typed_identifier("", vt, ft->location()));
6909 for (Typed_identifier_list::const_iterator pp = params->begin();
6910 pp != params->end();
6912 mparams->push_back(*pp);
6915 Typed_identifier_list* mresults = (ft->results() == NULL
6917 : ft->results()->copy());
6918 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
6921 mfields[i].name = Gogo::unpack_hidden_name(p->name());
6922 mfields[i].btype = (use_placeholder
6923 ? mft->get_backend_placeholder(gogo)
6924 : mft->get_backend(gogo));
6925 mfields[i].location = loc;
6926 // Sanity check: the names should be sorted.
6927 go_assert(p->name() > last_name);
6928 last_name = p->name();
6931 Btype* methods = gogo->backend()->struct_type(mfields);
6935 (*bfields)[0].name = "__methods";
6936 (*bfields)[0].btype = gogo->backend()->pointer_type(methods);
6937 (*bfields)[0].location = loc;
6939 Type* vt = Type::make_pointer_type(Type::make_void_type());
6940 (*bfields)[1].name = "__object";
6941 (*bfields)[1].btype = vt->get_backend(gogo);
6942 (*bfields)[1].location = Linemap::predeclared_location();
6945 // Return a tree for an interface type. An interface is a pointer to
6946 // a struct. The struct has three fields. The first field is a
6947 // pointer to the type descriptor for the dynamic type of the object.
6948 // The second field is a pointer to a table of methods for the
6949 // interface to be used with the object. The third field is the value
6950 // of the object itself.
6953 Interface_type::do_get_backend(Gogo* gogo)
6955 if (this->is_empty())
6956 return Interface_type::get_backend_empty_interface_type(gogo);
6959 if (this->interface_btype_ != NULL)
6960 return this->interface_btype_;
6961 this->interface_btype_ =
6962 gogo->backend()->placeholder_struct_type("", this->location_);
6963 std::vector<Backend::Btyped_identifier> bfields;
6964 get_backend_interface_fields(gogo, this, false, &bfields);
6965 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
6967 this->interface_btype_ = gogo->backend()->error_type();
6968 return this->interface_btype_;
6972 // Finish the backend representation of the methods.
6975 Interface_type::finish_backend_methods(Gogo* gogo)
6977 if (!this->interface_type()->is_empty())
6979 const Typed_identifier_list* methods = this->methods();
6980 if (methods != NULL)
6982 for (Typed_identifier_list::const_iterator p = methods->begin();
6983 p != methods->end();
6985 p->type()->get_backend(gogo);
6990 // The type of an interface type descriptor.
6993 Interface_type::make_interface_type_descriptor_type()
6998 Type* tdt = Type::make_type_descriptor_type();
6999 Type* ptdt = Type::make_type_descriptor_ptr_type();
7001 Type* string_type = Type::lookup_string_type();
7002 Type* pointer_string_type = Type::make_pointer_type(string_type);
7005 Type::make_builtin_struct_type(3,
7006 "name", pointer_string_type,
7007 "pkgPath", pointer_string_type,
7010 Type* nsm = Type::make_builtin_named_type("imethod", sm);
7012 Type* slice_nsm = Type::make_array_type(nsm, NULL);
7014 Struct_type* s = Type::make_builtin_struct_type(2,
7016 "methods", slice_nsm);
7018 ret = Type::make_builtin_named_type("InterfaceType", s);
7024 // Build a type descriptor for an interface type.
7027 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7029 Location bloc = Linemap::predeclared_location();
7031 Type* itdt = Interface_type::make_interface_type_descriptor_type();
7033 const Struct_field_list* ifields = itdt->struct_type()->fields();
7035 Expression_list* ivals = new Expression_list();
7038 Struct_field_list::const_iterator pif = ifields->begin();
7039 go_assert(pif->is_field_name("commonType"));
7040 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
7041 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
7045 go_assert(pif->is_field_name("methods"));
7047 Expression_list* methods = new Expression_list();
7048 if (this->all_methods_ != NULL)
7050 Type* elemtype = pif->type()->array_type()->element_type();
7052 methods->reserve(this->all_methods_->size());
7053 for (Typed_identifier_list::const_iterator pm =
7054 this->all_methods_->begin();
7055 pm != this->all_methods_->end();
7058 const Struct_field_list* mfields = elemtype->struct_type()->fields();
7060 Expression_list* mvals = new Expression_list();
7063 Struct_field_list::const_iterator pmf = mfields->begin();
7064 go_assert(pmf->is_field_name("name"));
7065 std::string s = Gogo::unpack_hidden_name(pm->name());
7066 Expression* e = Expression::make_string(s, bloc);
7067 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7070 go_assert(pmf->is_field_name("pkgPath"));
7071 if (!Gogo::is_hidden_name(pm->name()))
7072 mvals->push_back(Expression::make_nil(bloc));
7075 s = Gogo::hidden_name_prefix(pm->name());
7076 e = Expression::make_string(s, bloc);
7077 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7081 go_assert(pmf->is_field_name("typ"));
7082 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
7085 go_assert(pmf == mfields->end());
7087 e = Expression::make_struct_composite_literal(elemtype, mvals,
7089 methods->push_back(e);
7093 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
7097 go_assert(pif == ifields->end());
7099 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
7102 // Reflection string.
7105 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
7107 ret->append("interface {");
7108 const Typed_identifier_list* methods = this->parse_methods_;
7109 if (methods != NULL)
7111 ret->push_back(' ');
7112 for (Typed_identifier_list::const_iterator p = methods->begin();
7113 p != methods->end();
7116 if (p != methods->begin())
7118 if (p->name().empty())
7119 this->append_reflection(p->type(), gogo, ret);
7122 if (!Gogo::is_hidden_name(p->name()))
7123 ret->append(p->name());
7126 // This matches what the gc compiler does.
7127 std::string prefix = Gogo::hidden_name_prefix(p->name());
7128 ret->append(prefix.substr(prefix.find('.') + 1));
7129 ret->push_back('.');
7130 ret->append(Gogo::unpack_hidden_name(p->name()));
7132 std::string sub = p->type()->reflection(gogo);
7133 go_assert(sub.compare(0, 4, "func") == 0);
7134 sub = sub.substr(4);
7138 ret->push_back(' ');
7146 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7148 go_assert(this->methods_are_finalized_);
7150 ret->push_back('I');
7152 const Typed_identifier_list* methods = this->all_methods_;
7153 if (methods != NULL && !this->seen_)
7156 for (Typed_identifier_list::const_iterator p = methods->begin();
7157 p != methods->end();
7160 if (!p->name().empty())
7162 std::string n = Gogo::unpack_hidden_name(p->name());
7164 snprintf(buf, sizeof buf, "%u_",
7165 static_cast<unsigned int>(n.length()));
7169 this->append_mangled_name(p->type(), gogo, ret);
7171 this->seen_ = false;
7174 ret->push_back('e');
7180 Interface_type::do_export(Export* exp) const
7182 exp->write_c_string("interface { ");
7184 const Typed_identifier_list* methods = this->parse_methods_;
7185 if (methods != NULL)
7187 for (Typed_identifier_list::const_iterator pm = methods->begin();
7188 pm != methods->end();
7191 if (pm->name().empty())
7193 exp->write_c_string("? ");
7194 exp->write_type(pm->type());
7198 exp->write_string(pm->name());
7199 exp->write_c_string(" (");
7201 const Function_type* fntype = pm->type()->function_type();
7204 const Typed_identifier_list* parameters = fntype->parameters();
7205 if (parameters != NULL)
7207 bool is_varargs = fntype->is_varargs();
7208 for (Typed_identifier_list::const_iterator pp =
7209 parameters->begin();
7210 pp != parameters->end();
7216 exp->write_c_string(", ");
7217 exp->write_name(pp->name());
7218 exp->write_c_string(" ");
7219 if (!is_varargs || pp + 1 != parameters->end())
7220 exp->write_type(pp->type());
7223 exp->write_c_string("...");
7224 Type *pptype = pp->type();
7225 exp->write_type(pptype->array_type()->element_type());
7230 exp->write_c_string(")");
7232 const Typed_identifier_list* results = fntype->results();
7233 if (results != NULL)
7235 exp->write_c_string(" ");
7236 if (results->size() == 1 && results->begin()->name().empty())
7237 exp->write_type(results->begin()->type());
7241 exp->write_c_string("(");
7242 for (Typed_identifier_list::const_iterator p =
7244 p != results->end();
7250 exp->write_c_string(", ");
7251 exp->write_name(p->name());
7252 exp->write_c_string(" ");
7253 exp->write_type(p->type());
7255 exp->write_c_string(")");
7260 exp->write_c_string("; ");
7264 exp->write_c_string("}");
7267 // Import an interface type.
7270 Interface_type::do_import(Import* imp)
7272 imp->require_c_string("interface { ");
7274 Typed_identifier_list* methods = new Typed_identifier_list;
7275 while (imp->peek_char() != '}')
7277 std::string name = imp->read_identifier();
7281 imp->require_c_string(" ");
7282 Type* t = imp->read_type();
7283 methods->push_back(Typed_identifier("", t, imp->location()));
7284 imp->require_c_string("; ");
7288 imp->require_c_string(" (");
7290 Typed_identifier_list* parameters;
7291 bool is_varargs = false;
7292 if (imp->peek_char() == ')')
7296 parameters = new Typed_identifier_list;
7299 std::string name = imp->read_name();
7300 imp->require_c_string(" ");
7302 if (imp->match_c_string("..."))
7308 Type* ptype = imp->read_type();
7310 ptype = Type::make_array_type(ptype, NULL);
7311 parameters->push_back(Typed_identifier(name, ptype,
7313 if (imp->peek_char() != ',')
7315 go_assert(!is_varargs);
7316 imp->require_c_string(", ");
7319 imp->require_c_string(")");
7321 Typed_identifier_list* results;
7322 if (imp->peek_char() != ' ')
7326 results = new Typed_identifier_list;
7328 if (imp->peek_char() != '(')
7330 Type* rtype = imp->read_type();
7331 results->push_back(Typed_identifier("", rtype, imp->location()));
7338 std::string name = imp->read_name();
7339 imp->require_c_string(" ");
7340 Type* rtype = imp->read_type();
7341 results->push_back(Typed_identifier(name, rtype,
7343 if (imp->peek_char() != ',')
7345 imp->require_c_string(", ");
7347 imp->require_c_string(")");
7351 Function_type* fntype = Type::make_function_type(NULL, parameters,
7355 fntype->set_is_varargs();
7356 methods->push_back(Typed_identifier(name, fntype, imp->location()));
7358 imp->require_c_string("; ");
7361 imp->require_c_string("}");
7363 if (methods->empty())
7369 return Type::make_interface_type(methods, imp->location());
7372 // Make an interface type.
7375 Type::make_interface_type(Typed_identifier_list* methods,
7378 return new Interface_type(methods, location);
7381 // Make an empty interface type.
7384 Type::make_empty_interface_type(Location location)
7386 Interface_type* ret = new Interface_type(NULL, location);
7387 ret->finalize_methods();
7393 // Bind a method to an object.
7396 Method::bind_method(Expression* expr, Location location) const
7398 if (this->stub_ == NULL)
7400 // When there is no stub object, the binding is determined by
7402 return this->do_bind_method(expr, location);
7404 return Expression::make_bound_method(expr, this->stub_, location);
7407 // Return the named object associated with a method. This may only be
7408 // called after methods are finalized.
7411 Method::named_object() const
7413 if (this->stub_ != NULL)
7415 return this->do_named_object();
7418 // Class Named_method.
7420 // The type of the method.
7423 Named_method::do_type() const
7425 if (this->named_object_->is_function())
7426 return this->named_object_->func_value()->type();
7427 else if (this->named_object_->is_function_declaration())
7428 return this->named_object_->func_declaration_value()->type();
7433 // Return the location of the method receiver.
7436 Named_method::do_receiver_location() const
7438 return this->do_type()->receiver()->location();
7441 // Bind a method to an object.
7444 Named_method::do_bind_method(Expression* expr, Location location) const
7446 Named_object* no = this->named_object_;
7447 Bound_method_expression* bme = Expression::make_bound_method(expr, no,
7449 // If this is not a local method, and it does not use a stub, then
7450 // the real method expects a different type. We need to cast the
7452 if (this->depth() > 0 && !this->needs_stub_method())
7454 Function_type* ftype = this->do_type();
7455 go_assert(ftype->is_method());
7456 Type* frtype = ftype->receiver()->type();
7457 bme->set_first_argument_type(frtype);
7462 // Class Interface_method.
7464 // Bind a method to an object.
7467 Interface_method::do_bind_method(Expression* expr,
7468 Location location) const
7470 return Expression::make_interface_field_reference(expr, this->name_,
7476 // Insert a new method. Return true if it was inserted, false
7480 Methods::insert(const std::string& name, Method* m)
7482 std::pair<Method_map::iterator, bool> ins =
7483 this->methods_.insert(std::make_pair(name, m));
7488 Method* old_method = ins.first->second;
7489 if (m->depth() < old_method->depth())
7492 ins.first->second = m;
7497 if (m->depth() == old_method->depth())
7498 old_method->set_is_ambiguous();
7504 // Return the number of unambiguous methods.
7507 Methods::count() const
7510 for (Method_map::const_iterator p = this->methods_.begin();
7511 p != this->methods_.end();
7513 if (!p->second->is_ambiguous())
7518 // Class Named_type.
7520 // Return the name of the type.
7523 Named_type::name() const
7525 return this->named_object_->name();
7528 // Return the name of the type to use in an error message.
7531 Named_type::message_name() const
7533 return this->named_object_->message_name();
7536 // Whether this is an alias. There are currently only two aliases so
7537 // we just recognize them by name.
7540 Named_type::is_alias() const
7542 if (!this->is_builtin())
7544 const std::string& name(this->name());
7545 return name == "byte" || name == "rune";
7548 // Return the base type for this type. We have to be careful about
7549 // circular type definitions, which are invalid but may be seen here.
7552 Named_type::named_base()
7557 Type* ret = this->type_->base();
7558 this->seen_ = false;
7563 Named_type::named_base() const
7568 const Type* ret = this->type_->base();
7569 this->seen_ = false;
7573 // Return whether this is an error type. We have to be careful about
7574 // circular type definitions, which are invalid but may be seen here.
7577 Named_type::is_named_error_type() const
7582 bool ret = this->type_->is_error_type();
7583 this->seen_ = false;
7587 // Whether this type is comparable. We have to be careful about
7588 // circular type definitions.
7591 Named_type::named_type_is_comparable(std::string* reason) const
7596 bool ret = Type::are_compatible_for_comparison(true, this->type_,
7597 this->type_, reason);
7598 this->seen_ = false;
7602 // Add a method to this type.
7605 Named_type::add_method(const std::string& name, Function* function)
7607 if (this->local_methods_ == NULL)
7608 this->local_methods_ = new Bindings(NULL);
7609 return this->local_methods_->add_function(name, NULL, function);
7612 // Add a method declaration to this type.
7615 Named_type::add_method_declaration(const std::string& name, Package* package,
7616 Function_type* type,
7619 if (this->local_methods_ == NULL)
7620 this->local_methods_ = new Bindings(NULL);
7621 return this->local_methods_->add_function_declaration(name, package, type,
7625 // Add an existing method to this type.
7628 Named_type::add_existing_method(Named_object* no)
7630 if (this->local_methods_ == NULL)
7631 this->local_methods_ = new Bindings(NULL);
7632 this->local_methods_->add_named_object(no);
7635 // Look for a local method NAME, and returns its named object, or NULL
7639 Named_type::find_local_method(const std::string& name) const
7641 if (this->local_methods_ == NULL)
7643 return this->local_methods_->lookup(name);
7646 // Return whether NAME is an unexported field or method, for better
7650 Named_type::is_unexported_local_method(Gogo* gogo,
7651 const std::string& name) const
7653 Bindings* methods = this->local_methods_;
7654 if (methods != NULL)
7656 for (Bindings::const_declarations_iterator p =
7657 methods->begin_declarations();
7658 p != methods->end_declarations();
7661 if (Gogo::is_hidden_name(p->first)
7662 && name == Gogo::unpack_hidden_name(p->first)
7663 && gogo->pack_hidden_name(name, false) != p->first)
7670 // Build the complete list of methods for this type, which means
7671 // recursively including all methods for anonymous fields. Create all
7675 Named_type::finalize_methods(Gogo* gogo)
7677 if (this->all_methods_ != NULL)
7680 if (this->local_methods_ != NULL
7681 && (this->points_to() != NULL || this->interface_type() != NULL))
7683 const Bindings* lm = this->local_methods_;
7684 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
7685 p != lm->end_declarations();
7687 error_at(p->second->location(),
7688 "invalid pointer or interface receiver type");
7689 delete this->local_methods_;
7690 this->local_methods_ = NULL;
7694 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
7697 // Return the method NAME, or NULL if there isn't one or if it is
7698 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
7702 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
7704 return Type::method_function(this->all_methods_, name, is_ambiguous);
7707 // Return a pointer to the interface method table for this type for
7708 // the interface INTERFACE. IS_POINTER is true if this is for a
7712 Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface,
7715 go_assert(!interface->is_empty());
7717 Interface_method_tables** pimt = (is_pointer
7718 ? &this->interface_method_tables_
7719 : &this->pointer_interface_method_tables_);
7722 *pimt = new Interface_method_tables(5);
7724 std::pair<const Interface_type*, tree> val(interface, NULL_TREE);
7725 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
7729 // This is a new entry in the hash table.
7730 go_assert(ins.first->second == NULL_TREE);
7731 ins.first->second = gogo->interface_method_table_for_type(interface,
7736 tree decl = ins.first->second;
7737 if (decl == error_mark_node)
7738 return error_mark_node;
7739 go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL);
7740 return build_fold_addr_expr(decl);
7743 // Return whether a named type has any hidden fields.
7746 Named_type::named_type_has_hidden_fields(std::string* reason) const
7751 bool ret = this->type_->has_hidden_fields(this, reason);
7752 this->seen_ = false;
7756 // Look for a use of a complete type within another type. This is
7757 // used to check that we don't try to use a type within itself.
7759 class Find_type_use : public Traverse
7762 Find_type_use(Named_type* find_type)
7763 : Traverse(traverse_types),
7764 find_type_(find_type), found_(false)
7767 // Whether we found the type.
7770 { return this->found_; }
7777 // The type we are looking for.
7778 Named_type* find_type_;
7779 // Whether we found the type.
7783 // Check for FIND_TYPE in TYPE.
7786 Find_type_use::type(Type* type)
7788 if (type->named_type() != NULL && this->find_type_ == type->named_type())
7790 this->found_ = true;
7791 return TRAVERSE_EXIT;
7794 // It's OK if we see a reference to the type in any type which is
7795 // essentially a pointer: a pointer, a slice, a function, a map, or
7797 if (type->points_to() != NULL
7798 || type->is_slice_type()
7799 || type->function_type() != NULL
7800 || type->map_type() != NULL
7801 || type->channel_type() != NULL)
7802 return TRAVERSE_SKIP_COMPONENTS;
7804 // For an interface, a reference to the type in a method type should
7805 // be ignored, but we have to consider direct inheritance. When
7806 // this is called, there may be cases of direct inheritance
7807 // represented as a method with no name.
7808 if (type->interface_type() != NULL)
7810 const Typed_identifier_list* methods = type->interface_type()->methods();
7811 if (methods != NULL)
7813 for (Typed_identifier_list::const_iterator p = methods->begin();
7814 p != methods->end();
7817 if (p->name().empty())
7819 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
7820 return TRAVERSE_EXIT;
7824 return TRAVERSE_SKIP_COMPONENTS;
7827 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
7828 // to convert TYPE to the backend representation before we convert
7830 if (type->named_type() != NULL)
7832 switch (type->base()->classification())
7834 case Type::TYPE_ERROR:
7835 case Type::TYPE_BOOLEAN:
7836 case Type::TYPE_INTEGER:
7837 case Type::TYPE_FLOAT:
7838 case Type::TYPE_COMPLEX:
7839 case Type::TYPE_STRING:
7840 case Type::TYPE_NIL:
7843 case Type::TYPE_ARRAY:
7844 case Type::TYPE_STRUCT:
7845 this->find_type_->add_dependency(type->named_type());
7848 case Type::TYPE_NAMED:
7849 case Type::TYPE_FORWARD:
7850 go_assert(saw_errors());
7853 case Type::TYPE_VOID:
7854 case Type::TYPE_SINK:
7855 case Type::TYPE_FUNCTION:
7856 case Type::TYPE_POINTER:
7857 case Type::TYPE_CALL_MULTIPLE_RESULT:
7858 case Type::TYPE_MAP:
7859 case Type::TYPE_CHANNEL:
7860 case Type::TYPE_INTERFACE:
7866 return TRAVERSE_CONTINUE;
7869 // Verify that a named type does not refer to itself.
7872 Named_type::do_verify()
7874 Find_type_use find(this);
7875 Type::traverse(this->type_, &find);
7878 error_at(this->location_, "invalid recursive type %qs",
7879 this->message_name().c_str());
7880 this->is_error_ = true;
7884 // Check whether any of the local methods overloads an existing
7885 // struct field or interface method. We don't need to check the
7886 // list of methods against itself: that is handled by the Bindings
7888 if (this->local_methods_ != NULL)
7890 Struct_type* st = this->type_->struct_type();
7893 for (Bindings::const_declarations_iterator p =
7894 this->local_methods_->begin_declarations();
7895 p != this->local_methods_->end_declarations();
7898 const std::string& name(p->first);
7899 if (st != NULL && st->find_local_field(name, NULL) != NULL)
7901 error_at(p->second->location(),
7902 "method %qs redeclares struct field name",
7903 Gogo::message_name(name).c_str());
7912 // Return whether this type is or contains a pointer.
7915 Named_type::do_has_pointer() const
7920 bool ret = this->type_->has_pointer();
7921 this->seen_ = false;
7925 // Return whether comparisons for this type can use the identity
7929 Named_type::do_compare_is_identity(Gogo* gogo) const
7931 // We don't use this->seen_ here because compare_is_identity may
7932 // call base() later, and that will mess up if seen_ is set here.
7933 if (this->seen_in_compare_is_identity_)
7935 this->seen_in_compare_is_identity_ = true;
7936 bool ret = this->type_->compare_is_identity(gogo);
7937 this->seen_in_compare_is_identity_ = false;
7941 // Return a hash code. This is used for method lookup. We simply
7942 // hash on the name itself.
7945 Named_type::do_hash_for_method(Gogo* gogo) const
7947 if (this->is_alias())
7948 return this->type_->named_type()->do_hash_for_method(gogo);
7950 const std::string& name(this->named_object()->name());
7951 unsigned int ret = Type::hash_string(name, 0);
7953 // GOGO will be NULL here when called from Type_hash_identical.
7954 // That is OK because that is only used for internal hash tables
7955 // where we are going to be comparing named types for equality. In
7956 // other cases, which are cases where the runtime is going to
7957 // compare hash codes to see if the types are the same, we need to
7958 // include the package prefix and name in the hash.
7959 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
7961 const Package* package = this->named_object()->package();
7962 if (package == NULL)
7964 ret = Type::hash_string(gogo->unique_prefix(), ret);
7965 ret = Type::hash_string(gogo->package_name(), ret);
7969 ret = Type::hash_string(package->unique_prefix(), ret);
7970 ret = Type::hash_string(package->name(), ret);
7977 // Convert a named type to the backend representation. In order to
7978 // get dependencies right, we fill in a dummy structure for this type,
7979 // then convert all the dependencies, then complete this type. When
7980 // this function is complete, the size of the type is known.
7983 Named_type::convert(Gogo* gogo)
7985 if (this->is_error_ || this->is_converted_)
7988 this->create_placeholder(gogo);
7990 // Convert all the dependencies. If they refer indirectly back to
7991 // this type, they will pick up the intermediate tree we just
7993 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
7994 p != this->dependencies_.end();
7996 (*p)->convert(gogo);
7998 // Complete this type.
7999 Btype* bt = this->named_btype_;
8000 Type* base = this->type_->base();
8001 switch (base->classification())
8018 // The size of these types is already correct. We don't worry
8019 // about filling them in until later, when we also track
8020 // circular references.
8025 std::vector<Backend::Btyped_identifier> bfields;
8026 get_backend_struct_fields(gogo, base->struct_type()->fields(),
8028 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8029 bt = gogo->backend()->error_type();
8034 // Slice types were completed in create_placeholder.
8035 if (!base->is_slice_type())
8037 Btype* bet = base->array_type()->get_backend_element(gogo, true);
8038 Bexpression* blen = base->array_type()->get_backend_length(gogo);
8039 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
8040 bt = gogo->backend()->error_type();
8044 case TYPE_INTERFACE:
8045 // Interface types were completed in create_placeholder.
8053 case TYPE_CALL_MULTIPLE_RESULT:
8059 this->named_btype_ = bt;
8060 this->is_converted_ = true;
8061 this->is_placeholder_ = false;
8064 // Create the placeholder for a named type. This is the first step in
8065 // converting to the backend representation.
8068 Named_type::create_placeholder(Gogo* gogo)
8070 if (this->is_error_)
8071 this->named_btype_ = gogo->backend()->error_type();
8073 if (this->named_btype_ != NULL)
8076 // Create the structure for this type. Note that because we call
8077 // base() here, we don't attempt to represent a named type defined
8078 // as another named type. Instead both named types will point to
8079 // different base representations.
8080 Type* base = this->type_->base();
8082 bool set_name = true;
8083 switch (base->classification())
8086 this->is_error_ = true;
8087 this->named_btype_ = gogo->backend()->error_type();
8097 // These are simple basic types, we can just create them
8099 bt = Type::get_named_base_btype(gogo, base);
8104 // All maps and channels have the same backend representation.
8105 bt = Type::get_named_base_btype(gogo, base);
8111 bool for_function = base->classification() == TYPE_FUNCTION;
8112 bt = gogo->backend()->placeholder_pointer_type(this->name(),
8120 bt = gogo->backend()->placeholder_struct_type(this->name(),
8122 this->is_placeholder_ = true;
8127 if (base->is_slice_type())
8128 bt = gogo->backend()->placeholder_struct_type(this->name(),
8132 bt = gogo->backend()->placeholder_array_type(this->name(),
8134 this->is_placeholder_ = true;
8139 case TYPE_INTERFACE:
8140 if (base->interface_type()->is_empty())
8141 bt = Interface_type::get_backend_empty_interface_type(gogo);
8144 bt = gogo->backend()->placeholder_struct_type(this->name(),
8152 case TYPE_CALL_MULTIPLE_RESULT:
8159 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
8161 this->named_btype_ = bt;
8163 if (base->is_slice_type())
8165 // We do not record slices as dependencies of other types,
8166 // because we can fill them in completely here with the final
8168 std::vector<Backend::Btyped_identifier> bfields;
8169 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
8170 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8171 this->named_btype_ = gogo->backend()->error_type();
8173 else if (base->interface_type() != NULL
8174 && !base->interface_type()->is_empty())
8176 // We do not record interfaces as dependencies of other types,
8177 // because we can fill them in completely here with the final
8179 std::vector<Backend::Btyped_identifier> bfields;
8180 get_backend_interface_fields(gogo, base->interface_type(), true,
8182 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8183 this->named_btype_ = gogo->backend()->error_type();
8187 // Get a tree for a named type.
8190 Named_type::do_get_backend(Gogo* gogo)
8192 if (this->is_error_)
8193 return gogo->backend()->error_type();
8195 Btype* bt = this->named_btype_;
8197 if (!gogo->named_types_are_converted())
8199 // We have not completed converting named types. NAMED_BTYPE_
8200 // is a placeholder and we shouldn't do anything further.
8204 // We don't build dependencies for types whose sizes do not
8205 // change or are not relevant, so we may see them here while
8206 // converting types.
8207 this->create_placeholder(gogo);
8208 bt = this->named_btype_;
8209 go_assert(bt != NULL);
8213 // We are not converting types. This should only be called if the
8214 // type has already been converted.
8215 if (!this->is_converted_)
8217 go_assert(saw_errors());
8218 return gogo->backend()->error_type();
8221 go_assert(bt != NULL);
8223 // Complete the tree.
8224 Type* base = this->type_->base();
8226 switch (base->classification())
8229 return gogo->backend()->error_type();
8243 if (!this->seen_in_get_backend_)
8245 this->seen_in_get_backend_ = true;
8246 base->struct_type()->finish_backend_fields(gogo);
8247 this->seen_in_get_backend_ = false;
8252 if (!this->seen_in_get_backend_)
8254 this->seen_in_get_backend_ = true;
8255 base->array_type()->finish_backend_element(gogo);
8256 this->seen_in_get_backend_ = false;
8260 case TYPE_INTERFACE:
8261 if (!this->seen_in_get_backend_)
8263 this->seen_in_get_backend_ = true;
8264 base->interface_type()->finish_backend_methods(gogo);
8265 this->seen_in_get_backend_ = false;
8270 // Don't build a circular data structure. GENERIC can't handle
8272 if (this->seen_in_get_backend_)
8274 this->is_circular_ = true;
8275 return gogo->backend()->circular_pointer_type(bt, true);
8277 this->seen_in_get_backend_ = true;
8278 bt1 = Type::get_named_base_btype(gogo, base);
8279 this->seen_in_get_backend_ = false;
8280 if (this->is_circular_)
8281 bt1 = gogo->backend()->circular_pointer_type(bt, true);
8282 if (!gogo->backend()->set_placeholder_function_type(bt, bt1))
8283 bt = gogo->backend()->error_type();
8287 // Don't build a circular data structure. GENERIC can't handle
8289 if (this->seen_in_get_backend_)
8291 this->is_circular_ = true;
8292 return gogo->backend()->circular_pointer_type(bt, false);
8294 this->seen_in_get_backend_ = true;
8295 bt1 = Type::get_named_base_btype(gogo, base);
8296 this->seen_in_get_backend_ = false;
8297 if (this->is_circular_)
8298 bt1 = gogo->backend()->circular_pointer_type(bt, false);
8299 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
8300 bt = gogo->backend()->error_type();
8305 case TYPE_CALL_MULTIPLE_RESULT:
8314 // Build a type descriptor for a named type.
8317 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8319 if (name == NULL && this->is_alias())
8320 return this->type_->type_descriptor(gogo, this->type_);
8322 // If NAME is not NULL, then we don't really want the type
8323 // descriptor for this type; we want the descriptor for the
8324 // underlying type, giving it the name NAME.
8325 return this->named_type_descriptor(gogo, this->type_,
8326 name == NULL ? this : name);
8329 // Add to the reflection string. This is used mostly for the name of
8330 // the type used in a type descriptor, not for actual reflection
8334 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
8336 if (this->is_alias())
8338 this->append_reflection(this->type_, gogo, ret);
8341 if (!this->is_builtin())
8343 const Package* package = this->named_object_->package();
8344 if (package != NULL)
8345 ret->append(package->name());
8347 ret->append(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& unique_prefix(no->package() == NULL
8375 ? gogo->unique_prefix()
8376 : no->package()->unique_prefix());
8377 const std::string& package_name(no->package() == NULL
8378 ? gogo->package_name()
8379 : no->package()->name());
8380 name = unique_prefix;
8381 name.append(1, '.');
8382 name.append(package_name);
8383 name.append(1, '.');
8384 if (this->in_function_ != NULL)
8386 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
8387 name.append(1, '$');
8390 name.append(Gogo::unpack_hidden_name(no->name()));
8392 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
8397 // Export the type. This is called to export a global type.
8400 Named_type::export_named_type(Export* exp, const std::string&) const
8402 // We don't need to write the name of the type here, because it will
8403 // be written by Export::write_type anyhow.
8404 exp->write_c_string("type ");
8405 exp->write_type(this);
8406 exp->write_c_string(";\n");
8409 // Import a named type.
8412 Named_type::import_named_type(Import* imp, Named_type** ptype)
8414 imp->require_c_string("type ");
8415 Type *type = imp->read_type();
8416 *ptype = type->named_type();
8417 go_assert(*ptype != NULL);
8418 imp->require_c_string(";\n");
8421 // Export the type when it is referenced by another type. In this
8422 // case Export::export_type will already have issued the name.
8425 Named_type::do_export(Export* exp) const
8427 exp->write_type(this->type_);
8429 // To save space, we only export the methods directly attached to
8431 Bindings* methods = this->local_methods_;
8432 if (methods == NULL)
8435 exp->write_c_string("\n");
8436 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
8437 p != methods->end_definitions();
8440 exp->write_c_string(" ");
8441 (*p)->export_named_object(exp);
8444 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
8445 p != methods->end_declarations();
8448 if (p->second->is_function_declaration())
8450 exp->write_c_string(" ");
8451 p->second->export_named_object(exp);
8456 // Make a named type.
8459 Type::make_named_type(Named_object* named_object, Type* type,
8462 return new Named_type(named_object, type, location);
8465 // Finalize the methods for TYPE. It will be a named type or a struct
8466 // type. This sets *ALL_METHODS to the list of methods, and builds
8467 // all required stubs.
8470 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
8471 Methods** all_methods)
8473 *all_methods = NULL;
8474 Types_seen types_seen;
8475 Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen,
8477 Type::build_stub_methods(gogo, type, *all_methods, location);
8480 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
8481 // build up the struct field indexes as we go. DEPTH is the depth of
8482 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
8483 // adding these methods for an anonymous field with pointer type.
8484 // NEEDS_STUB_METHOD is true if we need to use a stub method which
8485 // calls the real method. TYPES_SEEN is used to avoid infinite
8489 Type::add_methods_for_type(const Type* type,
8490 const Method::Field_indexes* field_indexes,
8492 bool is_embedded_pointer,
8493 bool needs_stub_method,
8494 Types_seen* types_seen,
8497 // Pointer types may not have methods.
8498 if (type->points_to() != NULL)
8501 const Named_type* nt = type->named_type();
8504 std::pair<Types_seen::iterator, bool> ins = types_seen->insert(nt);
8510 Type::add_local_methods_for_type(nt, field_indexes, depth,
8511 is_embedded_pointer, needs_stub_method,
8514 Type::add_embedded_methods_for_type(type, field_indexes, depth,
8515 is_embedded_pointer, needs_stub_method,
8516 types_seen, methods);
8518 // If we are called with depth > 0, then we are looking at an
8519 // anonymous field of a struct. If such a field has interface type,
8520 // then we need to add the interface methods. We don't want to add
8521 // them when depth == 0, because we will already handle them
8522 // following the usual rules for an interface type.
8524 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
8527 // Add the local methods for the named type NT to *METHODS. The
8528 // parameters are as for add_methods_to_type.
8531 Type::add_local_methods_for_type(const Named_type* nt,
8532 const Method::Field_indexes* field_indexes,
8534 bool is_embedded_pointer,
8535 bool needs_stub_method,
8538 const Bindings* local_methods = nt->local_methods();
8539 if (local_methods == NULL)
8542 if (*methods == NULL)
8543 *methods = new Methods();
8545 for (Bindings::const_declarations_iterator p =
8546 local_methods->begin_declarations();
8547 p != local_methods->end_declarations();
8550 Named_object* no = p->second;
8551 bool is_value_method = (is_embedded_pointer
8552 || !Type::method_expects_pointer(no));
8553 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
8555 || (depth > 0 && is_value_method)));
8556 if (!(*methods)->insert(no->name(), m))
8561 // Add the embedded methods for TYPE to *METHODS. These are the
8562 // methods attached to anonymous fields. The parameters are as for
8563 // add_methods_to_type.
8566 Type::add_embedded_methods_for_type(const Type* type,
8567 const Method::Field_indexes* field_indexes,
8569 bool is_embedded_pointer,
8570 bool needs_stub_method,
8571 Types_seen* types_seen,
8574 // Look for anonymous fields in TYPE. TYPE has fields if it is a
8576 const Struct_type* st = type->struct_type();
8580 const Struct_field_list* fields = st->fields();
8585 for (Struct_field_list::const_iterator pf = fields->begin();
8586 pf != fields->end();
8589 if (!pf->is_anonymous())
8592 Type* ftype = pf->type();
8593 bool is_pointer = false;
8594 if (ftype->points_to() != NULL)
8596 ftype = ftype->points_to();
8599 Named_type* fnt = ftype->named_type();
8602 // This is an error, but it will be diagnosed elsewhere.
8606 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
8607 sub_field_indexes->next = field_indexes;
8608 sub_field_indexes->field_index = i;
8610 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
8611 (is_embedded_pointer || is_pointer),
8620 // If TYPE is an interface type, then add its method to *METHODS.
8621 // This is for interface methods attached to an anonymous field. The
8622 // parameters are as for add_methods_for_type.
8625 Type::add_interface_methods_for_type(const Type* type,
8626 const Method::Field_indexes* field_indexes,
8630 const Interface_type* it = type->interface_type();
8634 const Typed_identifier_list* imethods = it->methods();
8635 if (imethods == NULL)
8638 if (*methods == NULL)
8639 *methods = new Methods();
8641 for (Typed_identifier_list::const_iterator pm = imethods->begin();
8642 pm != imethods->end();
8645 Function_type* fntype = pm->type()->function_type();
8648 // This is an error, but it should be reported elsewhere
8649 // when we look at the methods for IT.
8652 go_assert(!fntype->is_method());
8653 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
8654 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
8655 field_indexes, depth);
8656 if (!(*methods)->insert(pm->name(), m))
8661 // Build stub methods for TYPE as needed. METHODS is the set of
8662 // methods for the type. A stub method may be needed when a type
8663 // inherits a method from an anonymous field. When we need the
8664 // address of the method, as in a type descriptor, we need to build a
8665 // little stub which does the required field dereferences and jumps to
8666 // the real method. LOCATION is the location of the type definition.
8669 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
8672 if (methods == NULL)
8674 for (Methods::const_iterator p = methods->begin();
8675 p != methods->end();
8678 Method* m = p->second;
8679 if (m->is_ambiguous() || !m->needs_stub_method())
8682 const std::string& name(p->first);
8684 // Build a stub method.
8686 const Function_type* fntype = m->type();
8688 static unsigned int counter;
8690 snprintf(buf, sizeof buf, "$this%u", counter);
8693 Type* receiver_type = const_cast<Type*>(type);
8694 if (!m->is_value_method())
8695 receiver_type = Type::make_pointer_type(receiver_type);
8696 Location receiver_location = m->receiver_location();
8697 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
8700 const Typed_identifier_list* fnparams = fntype->parameters();
8701 Typed_identifier_list* stub_params;
8702 if (fnparams == NULL || fnparams->empty())
8706 // We give each stub parameter a unique name.
8707 stub_params = new Typed_identifier_list();
8708 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
8709 pp != fnparams->end();
8713 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
8714 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
8720 const Typed_identifier_list* fnresults = fntype->results();
8721 Typed_identifier_list* stub_results;
8722 if (fnresults == NULL || fnresults->empty())
8723 stub_results = NULL;
8726 // We create the result parameters without any names, since
8727 // we won't refer to them.
8728 stub_results = new Typed_identifier_list();
8729 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
8730 pr != fnresults->end();
8732 stub_results->push_back(Typed_identifier("", pr->type(),
8736 Function_type* stub_type = Type::make_function_type(receiver,
8739 fntype->location());
8740 if (fntype->is_varargs())
8741 stub_type->set_is_varargs();
8743 // We only create the function in the package which creates the
8745 const Package* package;
8746 if (type->named_type() == NULL)
8749 package = type->named_type()->named_object()->package();
8751 if (package != NULL)
8752 stub = Named_object::make_function_declaration(name, package,
8753 stub_type, location);
8756 stub = gogo->start_function(name, stub_type, false,
8757 fntype->location());
8758 Type::build_one_stub_method(gogo, m, buf, stub_params,
8759 fntype->is_varargs(), location);
8760 gogo->finish_function(fntype->location());
8763 m->set_stub_object(stub);
8767 // Build a stub method which adjusts the receiver as required to call
8768 // METHOD. RECEIVER_NAME is the name we used for the receiver.
8769 // PARAMS is the list of function parameters.
8772 Type::build_one_stub_method(Gogo* gogo, Method* method,
8773 const char* receiver_name,
8774 const Typed_identifier_list* params,
8778 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
8779 go_assert(receiver_object != NULL);
8781 Expression* expr = Expression::make_var_reference(receiver_object, location);
8782 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
8783 if (expr->type()->points_to() == NULL)
8784 expr = Expression::make_unary(OPERATOR_AND, expr, location);
8786 Expression_list* arguments;
8787 if (params == NULL || params->empty())
8791 arguments = new Expression_list();
8792 for (Typed_identifier_list::const_iterator p = params->begin();
8796 Named_object* param = gogo->lookup(p->name(), NULL);
8797 go_assert(param != NULL);
8798 Expression* param_ref = Expression::make_var_reference(param,
8800 arguments->push_back(param_ref);
8804 Expression* func = method->bind_method(expr, location);
8805 go_assert(func != NULL);
8806 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
8808 call->set_hidden_fields_are_ok();
8809 size_t count = call->result_count();
8811 gogo->add_statement(Statement::make_statement(call, true));
8814 Expression_list* retvals = new Expression_list();
8816 retvals->push_back(call);
8819 for (size_t i = 0; i < count; ++i)
8820 retvals->push_back(Expression::make_call_result(call, i));
8822 Return_statement* retstat = Statement::make_return_statement(retvals,
8825 // We can return values with hidden fields from a stub. This is
8826 // necessary if the method is itself hidden.
8827 retstat->set_hidden_fields_are_ok();
8829 gogo->add_statement(retstat);
8833 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
8834 // in reverse order.
8837 Type::apply_field_indexes(Expression* expr,
8838 const Method::Field_indexes* field_indexes,
8841 if (field_indexes == NULL)
8843 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
8844 Struct_type* stype = expr->type()->deref()->struct_type();
8845 go_assert(stype != NULL
8846 && field_indexes->field_index < stype->field_count());
8847 if (expr->type()->struct_type() == NULL)
8849 go_assert(expr->type()->points_to() != NULL);
8850 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
8851 go_assert(expr->type()->struct_type() == stype);
8853 return Expression::make_field_reference(expr, field_indexes->field_index,
8857 // Return whether NO is a method for which the receiver is a pointer.
8860 Type::method_expects_pointer(const Named_object* no)
8862 const Function_type *fntype;
8863 if (no->is_function())
8864 fntype = no->func_value()->type();
8865 else if (no->is_function_declaration())
8866 fntype = no->func_declaration_value()->type();
8869 return fntype->receiver()->type()->points_to() != NULL;
8872 // Given a set of methods for a type, METHODS, return the method NAME,
8873 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
8874 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
8875 // but is ambiguous (and return NULL).
8878 Type::method_function(const Methods* methods, const std::string& name,
8881 if (is_ambiguous != NULL)
8882 *is_ambiguous = false;
8883 if (methods == NULL)
8885 Methods::const_iterator p = methods->find(name);
8886 if (p == methods->end())
8888 Method* m = p->second;
8889 if (m->is_ambiguous())
8891 if (is_ambiguous != NULL)
8892 *is_ambiguous = true;
8898 // Look for field or method NAME for TYPE. Return an Expression for
8899 // the field or method bound to EXPR. If there is no such field or
8900 // method, give an appropriate error and return an error expression.
8903 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
8904 const std::string& name,
8907 if (type->deref()->is_error_type())
8908 return Expression::make_error(location);
8910 const Named_type* nt = type->deref()->named_type();
8911 const Struct_type* st = type->deref()->struct_type();
8912 const Interface_type* it = type->interface_type();
8914 // If this is a pointer to a pointer, then it is possible that the
8915 // pointed-to type has methods.
8916 bool dereferenced = false;
8920 && type->points_to() != NULL
8921 && type->points_to()->points_to() != NULL)
8923 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
8924 type = type->points_to();
8925 if (type->deref()->is_error_type())
8926 return Expression::make_error(location);
8927 nt = type->points_to()->named_type();
8928 st = type->points_to()->struct_type();
8929 dereferenced = true;
8932 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
8933 || expr->is_addressable());
8934 std::vector<const Named_type*> seen;
8935 bool is_method = false;
8936 bool found_pointer_method = false;
8939 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
8940 &seen, NULL, &is_method,
8941 &found_pointer_method, &ambig1, &ambig2))
8946 go_assert(st != NULL);
8947 if (type->struct_type() == NULL)
8949 go_assert(type->points_to() != NULL);
8950 expr = Expression::make_unary(OPERATOR_MULT, expr,
8952 go_assert(expr->type()->struct_type() == st);
8954 ret = st->field_reference(expr, name, location);
8956 else if (it != NULL && it->find_method(name) != NULL)
8957 ret = Expression::make_interface_field_reference(expr, name,
8963 m = nt->method_function(name, NULL);
8964 else if (st != NULL)
8965 m = st->method_function(name, NULL);
8968 go_assert(m != NULL);
8969 if (dereferenced && m->is_value_method())
8972 "calling value method requires explicit dereference");
8973 return Expression::make_error(location);
8975 if (!m->is_value_method() && expr->type()->points_to() == NULL)
8976 expr = Expression::make_unary(OPERATOR_AND, expr, location);
8977 ret = m->bind_method(expr, location);
8979 go_assert(ret != NULL);
8984 if (!ambig1.empty())
8985 error_at(location, "%qs is ambiguous via %qs and %qs",
8986 Gogo::message_name(name).c_str(), ambig1.c_str(),
8988 else if (found_pointer_method)
8989 error_at(location, "method requires a pointer");
8990 else if (nt == NULL && st == NULL && it == NULL)
8992 ("reference to field %qs in object which "
8993 "has no fields or methods"),
8994 Gogo::message_name(name).c_str());
8998 if (!Gogo::is_hidden_name(name))
8999 is_unexported = false;
9002 std::string unpacked = Gogo::unpack_hidden_name(name);
9004 is_unexported = Type::is_unexported_field_or_method(gogo, type,
9009 error_at(location, "reference to unexported field or method %qs",
9010 Gogo::message_name(name).c_str());
9012 error_at(location, "reference to undefined field or method %qs",
9013 Gogo::message_name(name).c_str());
9015 return Expression::make_error(location);
9019 // Look in TYPE for a field or method named NAME, return true if one
9020 // is found. This looks through embedded anonymous fields and handles
9021 // ambiguity. If a method is found, sets *IS_METHOD to true;
9022 // otherwise, if a field is found, set it to false. If
9023 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
9024 // whose address can not be taken. SEEN is used to avoid infinite
9025 // recursion on invalid types.
9027 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
9028 // method we couldn't use because it requires a pointer. LEVEL is
9029 // used for recursive calls, and can be NULL for a non-recursive call.
9030 // When this function returns false because it finds that the name is
9031 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
9032 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
9033 // will be unchanged.
9035 // This function just returns whether or not there is a field or
9036 // method, and whether it is a field or method. It doesn't build an
9037 // expression to refer to it. If it is a method, we then look in the
9038 // list of all methods for the type. If it is a field, the search has
9039 // to be done again, looking only for fields, and building up the
9040 // expression as we go.
9043 Type::find_field_or_method(const Type* type,
9044 const std::string& name,
9045 bool receiver_can_be_pointer,
9046 std::vector<const Named_type*>* seen,
9049 bool* found_pointer_method,
9050 std::string* ambig1,
9051 std::string* ambig2)
9053 // Named types can have locally defined methods.
9054 const Named_type* nt = type->named_type();
9055 if (nt == NULL && type->points_to() != NULL)
9056 nt = type->points_to()->named_type();
9059 Named_object* no = nt->find_local_method(name);
9062 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
9068 // Record that we have found a pointer method in order to
9069 // give a better error message if we don't find anything
9071 *found_pointer_method = true;
9074 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9080 // We've already seen this type when searching for methods.
9086 // Interface types can have methods.
9087 const Interface_type* it = type->interface_type();
9088 if (it != NULL && it->find_method(name) != NULL)
9094 // Struct types can have fields. They can also inherit fields and
9095 // methods from anonymous fields.
9096 const Struct_type* st = type->deref()->struct_type();
9099 const Struct_field_list* fields = st->fields();
9104 seen->push_back(nt);
9106 int found_level = 0;
9107 bool found_is_method = false;
9108 std::string found_ambig1;
9109 std::string found_ambig2;
9110 const Struct_field* found_parent = NULL;
9111 for (Struct_field_list::const_iterator pf = fields->begin();
9112 pf != fields->end();
9115 if (pf->is_field_name(name))
9123 if (!pf->is_anonymous())
9126 if (pf->type()->deref()->is_error_type()
9127 || pf->type()->deref()->is_undefined())
9130 Named_type* fnt = pf->type()->named_type();
9132 fnt = pf->type()->deref()->named_type();
9133 go_assert(fnt != NULL);
9135 int sublevel = level == NULL ? 1 : *level + 1;
9137 std::string subambig1;
9138 std::string subambig2;
9139 bool subfound = Type::find_field_or_method(fnt,
9141 receiver_can_be_pointer,
9145 found_pointer_method,
9150 if (!subambig1.empty())
9152 // The name was found via this field, but is ambiguous.
9153 // if the ambiguity is lower or at the same level as
9154 // anything else we have already found, then we want to
9155 // pass the ambiguity back to the caller.
9156 if (found_level == 0 || sublevel <= found_level)
9158 found_ambig1 = (Gogo::message_name(pf->field_name())
9160 found_ambig2 = (Gogo::message_name(pf->field_name())
9162 found_level = sublevel;
9168 // The name was found via this field. Use the level to see
9169 // if we want to use this one, or whether it introduces an
9171 if (found_level == 0 || sublevel < found_level)
9173 found_level = sublevel;
9174 found_is_method = sub_is_method;
9175 found_ambig1.clear();
9176 found_ambig2.clear();
9177 found_parent = &*pf;
9179 else if (sublevel > found_level)
9181 else if (found_ambig1.empty())
9183 // We found an ambiguity.
9184 go_assert(found_parent != NULL);
9185 found_ambig1 = Gogo::message_name(found_parent->field_name());
9186 found_ambig2 = Gogo::message_name(pf->field_name());
9190 // We found an ambiguity, but we already know of one.
9191 // Just report the earlier one.
9196 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
9197 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
9198 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
9199 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
9204 if (found_level == 0)
9206 else if (!found_ambig1.empty())
9208 go_assert(!found_ambig1.empty());
9209 ambig1->assign(found_ambig1);
9210 ambig2->assign(found_ambig2);
9212 *level = found_level;
9218 *level = found_level;
9219 *is_method = found_is_method;
9224 // Return whether NAME is an unexported field or method for TYPE.
9227 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
9228 const std::string& name,
9229 std::vector<const Named_type*>* seen)
9231 const Named_type* nt = type->named_type();
9233 nt = type->deref()->named_type();
9236 if (nt->is_unexported_local_method(gogo, name))
9239 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9245 // We've already seen this type.
9251 const Interface_type* it = type->interface_type();
9252 if (it != NULL && it->is_unexported_method(gogo, name))
9255 type = type->deref();
9257 const Struct_type* st = type->struct_type();
9258 if (st != NULL && st->is_unexported_local_field(gogo, name))
9264 const Struct_field_list* fields = st->fields();
9269 seen->push_back(nt);
9271 for (Struct_field_list::const_iterator pf = fields->begin();
9272 pf != fields->end();
9275 if (pf->is_anonymous()
9276 && !pf->type()->deref()->is_error_type()
9277 && !pf->type()->deref()->is_undefined())
9279 Named_type* subtype = pf->type()->named_type();
9280 if (subtype == NULL)
9281 subtype = pf->type()->deref()->named_type();
9282 if (subtype == NULL)
9284 // This is an error, but it will be diagnosed elsewhere.
9287 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
9302 // Class Forward_declaration.
9304 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
9305 : Type(TYPE_FORWARD),
9306 named_object_(named_object->resolve()), warned_(false)
9308 go_assert(this->named_object_->is_unknown()
9309 || this->named_object_->is_type_declaration());
9312 // Return the named object.
9315 Forward_declaration_type::named_object()
9317 return this->named_object_->resolve();
9321 Forward_declaration_type::named_object() const
9323 return this->named_object_->resolve();
9326 // Return the name of the forward declared type.
9329 Forward_declaration_type::name() const
9331 return this->named_object()->name();
9334 // Warn about a use of a type which has been declared but not defined.
9337 Forward_declaration_type::warn() const
9339 Named_object* no = this->named_object_->resolve();
9340 if (no->is_unknown())
9342 // The name was not defined anywhere.
9345 error_at(this->named_object_->location(),
9346 "use of undefined type %qs",
9347 no->message_name().c_str());
9348 this->warned_ = true;
9351 else if (no->is_type_declaration())
9353 // The name was seen as a type, but the type was never defined.
9354 if (no->type_declaration_value()->using_type())
9356 error_at(this->named_object_->location(),
9357 "use of undefined type %qs",
9358 no->message_name().c_str());
9359 this->warned_ = true;
9364 // The name was defined, but not as a type.
9367 error_at(this->named_object_->location(), "expected type");
9368 this->warned_ = true;
9373 // Get the base type of a declaration. This gives an error if the
9374 // type has not yet been defined.
9377 Forward_declaration_type::real_type()
9379 if (this->is_defined())
9380 return this->named_object()->type_value();
9384 return Type::make_error_type();
9389 Forward_declaration_type::real_type() const
9391 if (this->is_defined())
9392 return this->named_object()->type_value();
9396 return Type::make_error_type();
9400 // Return whether the base type is defined.
9403 Forward_declaration_type::is_defined() const
9405 return this->named_object()->is_type();
9408 // Add a method. This is used when methods are defined before the
9412 Forward_declaration_type::add_method(const std::string& name,
9415 Named_object* no = this->named_object();
9416 if (no->is_unknown())
9417 no->declare_as_type();
9418 return no->type_declaration_value()->add_method(name, function);
9421 // Add a method declaration. This is used when methods are declared
9425 Forward_declaration_type::add_method_declaration(const std::string& name,
9427 Function_type* type,
9430 Named_object* no = this->named_object();
9431 if (no->is_unknown())
9432 no->declare_as_type();
9433 Type_declaration* td = no->type_declaration_value();
9434 return td->add_method_declaration(name, package, type, location);
9440 Forward_declaration_type::do_traverse(Traverse* traverse)
9442 if (this->is_defined()
9443 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
9444 return TRAVERSE_EXIT;
9445 return TRAVERSE_CONTINUE;
9448 // Get the backend representation for the type.
9451 Forward_declaration_type::do_get_backend(Gogo* gogo)
9453 if (this->is_defined())
9454 return Type::get_named_base_btype(gogo, this->real_type());
9457 return gogo->backend()->error_type();
9459 // We represent an undefined type as a struct with no fields. That
9460 // should work fine for the backend, since the same case can arise
9462 std::vector<Backend::Btyped_identifier> fields;
9463 Btype* bt = gogo->backend()->struct_type(fields);
9464 return gogo->backend()->named_type(this->name(), bt,
9465 this->named_object()->location());
9468 // Build a type descriptor for a forwarded type.
9471 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9473 Location ploc = Linemap::predeclared_location();
9474 if (!this->is_defined())
9475 return Expression::make_error(ploc);
9478 Type* t = this->real_type();
9480 return this->named_type_descriptor(gogo, t, name);
9482 return Expression::make_type_descriptor(t, ploc);
9486 // The reflection string.
9489 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
9491 this->append_reflection(this->real_type(), gogo, ret);
9494 // The mangled name.
9497 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
9499 if (this->is_defined())
9500 this->append_mangled_name(this->real_type(), gogo, ret);
9503 const Named_object* no = this->named_object();
9505 if (no->package() == NULL)
9506 name = gogo->package_name();
9508 name = no->package()->name();
9510 name += Gogo::unpack_hidden_name(no->name());
9512 snprintf(buf, sizeof buf, "N%u_",
9513 static_cast<unsigned int>(name.length()));
9519 // Export a forward declaration. This can happen when a defined type
9520 // refers to a type which is only declared (and is presumably defined
9521 // in some other file in the same package).
9524 Forward_declaration_type::do_export(Export*) const
9526 // If there is a base type, that should be exported instead of this.
9527 go_assert(!this->is_defined());
9529 // We don't output anything.
9532 // Make a forward declaration.
9535 Type::make_forward_declaration(Named_object* named_object)
9537 return new Forward_declaration_type(named_object);
9540 // Class Typed_identifier_list.
9542 // Sort the entries by name.
9544 struct Typed_identifier_list_sort
9548 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
9549 { return t1.name() < t2.name(); }
9553 Typed_identifier_list::sort_by_name()
9555 std::sort(this->entries_.begin(), this->entries_.end(),
9556 Typed_identifier_list_sort());
9562 Typed_identifier_list::traverse(Traverse* traverse)
9564 for (Typed_identifier_list::const_iterator p = this->begin();
9568 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
9569 return TRAVERSE_EXIT;
9571 return TRAVERSE_CONTINUE;
9576 Typed_identifier_list*
9577 Typed_identifier_list::copy() const
9579 Typed_identifier_list* ret = new Typed_identifier_list();
9580 for (Typed_identifier_list::const_iterator p = this->begin();
9583 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));