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)
2233 Numeric_constant nc;
2234 if (!at->length()->numeric_constant_value(&nc))
2237 if (!nc.to_int(&ival))
2240 return at->element_type()->is_backend_type_size_known(gogo);
2245 // Begin converting this type to the backend representation.
2246 // This will create a placeholder if necessary.
2247 this->get_backend(gogo);
2248 return this->named_type()->is_named_backend_type_size_known();
2252 Forward_declaration_type* fdt = this->forward_declaration_type();
2253 return fdt->real_type()->is_backend_type_size_known(gogo);
2257 case TYPE_CALL_MULTIPLE_RESULT:
2265 // If the size of the type can be determined, set *PSIZE to the size
2266 // in bytes and return true. Otherwise, return false. This queries
2270 Type::backend_type_size(Gogo* gogo, unsigned int *psize)
2272 if (!this->is_backend_type_size_known(gogo))
2274 Btype* bt = this->get_backend_placeholder(gogo);
2275 size_t size = gogo->backend()->type_size(bt);
2276 *psize = static_cast<unsigned int>(size);
2282 // If the alignment of the type can be determined, set *PALIGN to
2283 // the alignment in bytes and return true. Otherwise, return false.
2286 Type::backend_type_align(Gogo* gogo, unsigned int *palign)
2288 if (!this->is_backend_type_size_known(gogo))
2290 Btype* bt = this->get_backend_placeholder(gogo);
2291 size_t align = gogo->backend()->type_alignment(bt);
2292 *palign = static_cast<unsigned int>(align);
2293 if (*palign != align)
2298 // Like backend_type_align, but return the alignment when used as a
2302 Type::backend_type_field_align(Gogo* gogo, unsigned int *palign)
2304 if (!this->is_backend_type_size_known(gogo))
2306 Btype* bt = this->get_backend_placeholder(gogo);
2307 size_t a = gogo->backend()->type_field_alignment(bt);
2308 *palign = static_cast<unsigned int>(a);
2314 // Default function to export a type.
2317 Type::do_export(Export*) const
2325 Type::import_type(Import* imp)
2327 if (imp->match_c_string("("))
2328 return Function_type::do_import(imp);
2329 else if (imp->match_c_string("*"))
2330 return Pointer_type::do_import(imp);
2331 else if (imp->match_c_string("struct "))
2332 return Struct_type::do_import(imp);
2333 else if (imp->match_c_string("["))
2334 return Array_type::do_import(imp);
2335 else if (imp->match_c_string("map "))
2336 return Map_type::do_import(imp);
2337 else if (imp->match_c_string("chan "))
2338 return Channel_type::do_import(imp);
2339 else if (imp->match_c_string("interface"))
2340 return Interface_type::do_import(imp);
2343 error_at(imp->location(), "import error: expected type");
2344 return Type::make_error_type();
2348 // A type used to indicate a parsing error. This exists to simplify
2349 // later error detection.
2351 class Error_type : public Type
2360 do_compare_is_identity(Gogo*) const
2364 do_get_backend(Gogo* gogo)
2365 { return gogo->backend()->error_type(); }
2368 do_type_descriptor(Gogo*, Named_type*)
2369 { return Expression::make_error(Linemap::predeclared_location()); }
2372 do_reflection(Gogo*, std::string*) const
2373 { go_assert(saw_errors()); }
2376 do_mangled_name(Gogo*, std::string* ret) const
2377 { ret->push_back('E'); }
2381 Type::make_error_type()
2383 static Error_type singleton_error_type;
2384 return &singleton_error_type;
2389 class Void_type : public Type
2398 do_compare_is_identity(Gogo*) const
2402 do_get_backend(Gogo* gogo)
2403 { return gogo->backend()->void_type(); }
2406 do_type_descriptor(Gogo*, Named_type*)
2407 { go_unreachable(); }
2410 do_reflection(Gogo*, std::string*) const
2414 do_mangled_name(Gogo*, std::string* ret) const
2415 { ret->push_back('v'); }
2419 Type::make_void_type()
2421 static Void_type singleton_void_type;
2422 return &singleton_void_type;
2425 // The boolean type.
2427 class Boolean_type : public Type
2431 : Type(TYPE_BOOLEAN)
2436 do_compare_is_identity(Gogo*) const
2440 do_get_backend(Gogo* gogo)
2441 { return gogo->backend()->bool_type(); }
2444 do_type_descriptor(Gogo*, Named_type* name);
2446 // We should not be asked for the reflection string of a basic type.
2448 do_reflection(Gogo*, std::string* ret) const
2449 { ret->append("bool"); }
2452 do_mangled_name(Gogo*, std::string* ret) const
2453 { ret->push_back('b'); }
2456 // Make the type descriptor.
2459 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2462 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
2465 Named_object* no = gogo->lookup_global("bool");
2466 go_assert(no != NULL);
2467 return Type::type_descriptor(gogo, no->type_value());
2472 Type::make_boolean_type()
2474 static Boolean_type boolean_type;
2475 return &boolean_type;
2478 // The named type "bool".
2480 static Named_type* named_bool_type;
2482 // Get the named type "bool".
2485 Type::lookup_bool_type()
2487 return named_bool_type;
2490 // Make the named type "bool".
2493 Type::make_named_bool_type()
2495 Type* bool_type = Type::make_boolean_type();
2496 Named_object* named_object =
2497 Named_object::make_type("bool", NULL, bool_type,
2498 Linemap::predeclared_location());
2499 Named_type* named_type = named_object->type_value();
2500 named_bool_type = named_type;
2504 // Class Integer_type.
2506 Integer_type::Named_integer_types Integer_type::named_integer_types;
2508 // Create a new integer type. Non-abstract integer types always have
2512 Integer_type::create_integer_type(const char* name, bool is_unsigned,
2513 int bits, int runtime_type_kind)
2515 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
2517 std::string sname(name);
2518 Named_object* named_object =
2519 Named_object::make_type(sname, NULL, integer_type,
2520 Linemap::predeclared_location());
2521 Named_type* named_type = named_object->type_value();
2522 std::pair<Named_integer_types::iterator, bool> ins =
2523 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
2524 go_assert(ins.second);
2528 // Look up an existing integer type.
2531 Integer_type::lookup_integer_type(const char* name)
2533 Named_integer_types::const_iterator p =
2534 Integer_type::named_integer_types.find(name);
2535 go_assert(p != Integer_type::named_integer_types.end());
2539 // Create a new abstract integer type.
2542 Integer_type::create_abstract_integer_type()
2544 static Integer_type* abstract_type;
2545 if (abstract_type == NULL)
2546 abstract_type = new Integer_type(true, false, INT_TYPE_SIZE,
2547 RUNTIME_TYPE_KIND_INT);
2548 return abstract_type;
2551 // Create a new abstract character type.
2554 Integer_type::create_abstract_character_type()
2556 static Integer_type* abstract_type;
2557 if (abstract_type == NULL)
2559 abstract_type = new Integer_type(true, false, 32,
2560 RUNTIME_TYPE_KIND_INT32);
2561 abstract_type->set_is_rune();
2563 return abstract_type;
2566 // Integer type compatibility.
2569 Integer_type::is_identical(const Integer_type* t) const
2571 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
2573 return this->is_abstract_ == t->is_abstract_;
2579 Integer_type::do_hash_for_method(Gogo*) const
2581 return ((this->bits_ << 4)
2582 + ((this->is_unsigned_ ? 1 : 0) << 8)
2583 + ((this->is_abstract_ ? 1 : 0) << 9));
2586 // Convert an Integer_type to the backend representation.
2589 Integer_type::do_get_backend(Gogo* gogo)
2591 if (this->is_abstract_)
2593 go_assert(saw_errors());
2594 return gogo->backend()->error_type();
2596 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
2599 // The type descriptor for an integer type. Integer types are always
2603 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2605 go_assert(name != NULL || saw_errors());
2606 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2609 // We should not be asked for the reflection string of a basic type.
2612 Integer_type::do_reflection(Gogo*, std::string*) const
2614 go_assert(saw_errors());
2620 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
2623 snprintf(buf, sizeof buf, "i%s%s%de",
2624 this->is_abstract_ ? "a" : "",
2625 this->is_unsigned_ ? "u" : "",
2630 // Make an integer type.
2633 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
2634 int runtime_type_kind)
2636 return Integer_type::create_integer_type(name, is_unsigned, bits,
2640 // Make an abstract integer type.
2643 Type::make_abstract_integer_type()
2645 return Integer_type::create_abstract_integer_type();
2648 // Make an abstract character type.
2651 Type::make_abstract_character_type()
2653 return Integer_type::create_abstract_character_type();
2656 // Look up an integer type.
2659 Type::lookup_integer_type(const char* name)
2661 return Integer_type::lookup_integer_type(name);
2664 // Class Float_type.
2666 Float_type::Named_float_types Float_type::named_float_types;
2668 // Create a new float type. Non-abstract float types always have
2672 Float_type::create_float_type(const char* name, int bits,
2673 int runtime_type_kind)
2675 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
2676 std::string sname(name);
2677 Named_object* named_object =
2678 Named_object::make_type(sname, NULL, float_type,
2679 Linemap::predeclared_location());
2680 Named_type* named_type = named_object->type_value();
2681 std::pair<Named_float_types::iterator, bool> ins =
2682 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
2683 go_assert(ins.second);
2687 // Look up an existing float type.
2690 Float_type::lookup_float_type(const char* name)
2692 Named_float_types::const_iterator p =
2693 Float_type::named_float_types.find(name);
2694 go_assert(p != Float_type::named_float_types.end());
2698 // Create a new abstract float type.
2701 Float_type::create_abstract_float_type()
2703 static Float_type* abstract_type;
2704 if (abstract_type == NULL)
2705 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
2706 return abstract_type;
2709 // Whether this type is identical with T.
2712 Float_type::is_identical(const Float_type* t) const
2714 if (this->bits_ != t->bits_)
2716 return this->is_abstract_ == t->is_abstract_;
2722 Float_type::do_hash_for_method(Gogo*) const
2724 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2727 // Convert to the backend representation.
2730 Float_type::do_get_backend(Gogo* gogo)
2732 return gogo->backend()->float_type(this->bits_);
2735 // The type descriptor for a float type. Float types are always named.
2738 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2740 go_assert(name != NULL || saw_errors());
2741 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2744 // We should not be asked for the reflection string of a basic type.
2747 Float_type::do_reflection(Gogo*, std::string*) const
2749 go_assert(saw_errors());
2755 Float_type::do_mangled_name(Gogo*, std::string* ret) const
2758 snprintf(buf, sizeof buf, "f%s%de",
2759 this->is_abstract_ ? "a" : "",
2764 // Make a floating point type.
2767 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
2769 return Float_type::create_float_type(name, bits, runtime_type_kind);
2772 // Make an abstract float type.
2775 Type::make_abstract_float_type()
2777 return Float_type::create_abstract_float_type();
2780 // Look up a float type.
2783 Type::lookup_float_type(const char* name)
2785 return Float_type::lookup_float_type(name);
2788 // Class Complex_type.
2790 Complex_type::Named_complex_types Complex_type::named_complex_types;
2792 // Create a new complex type. Non-abstract complex types always have
2796 Complex_type::create_complex_type(const char* name, int bits,
2797 int runtime_type_kind)
2799 Complex_type* complex_type = new Complex_type(false, bits,
2801 std::string sname(name);
2802 Named_object* named_object =
2803 Named_object::make_type(sname, NULL, complex_type,
2804 Linemap::predeclared_location());
2805 Named_type* named_type = named_object->type_value();
2806 std::pair<Named_complex_types::iterator, bool> ins =
2807 Complex_type::named_complex_types.insert(std::make_pair(sname,
2809 go_assert(ins.second);
2813 // Look up an existing complex type.
2816 Complex_type::lookup_complex_type(const char* name)
2818 Named_complex_types::const_iterator p =
2819 Complex_type::named_complex_types.find(name);
2820 go_assert(p != Complex_type::named_complex_types.end());
2824 // Create a new abstract complex type.
2827 Complex_type::create_abstract_complex_type()
2829 static Complex_type* abstract_type;
2830 if (abstract_type == NULL)
2831 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
2832 return abstract_type;
2835 // Whether this type is identical with T.
2838 Complex_type::is_identical(const Complex_type *t) const
2840 if (this->bits_ != t->bits_)
2842 return this->is_abstract_ == t->is_abstract_;
2848 Complex_type::do_hash_for_method(Gogo*) const
2850 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2853 // Convert to the backend representation.
2856 Complex_type::do_get_backend(Gogo* gogo)
2858 return gogo->backend()->complex_type(this->bits_);
2861 // The type descriptor for a complex type. Complex types are always
2865 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2867 go_assert(name != NULL || saw_errors());
2868 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2871 // We should not be asked for the reflection string of a basic type.
2874 Complex_type::do_reflection(Gogo*, std::string*) const
2876 go_assert(saw_errors());
2882 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
2885 snprintf(buf, sizeof buf, "c%s%de",
2886 this->is_abstract_ ? "a" : "",
2891 // Make a complex type.
2894 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
2896 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
2899 // Make an abstract complex type.
2902 Type::make_abstract_complex_type()
2904 return Complex_type::create_abstract_complex_type();
2907 // Look up a complex type.
2910 Type::lookup_complex_type(const char* name)
2912 return Complex_type::lookup_complex_type(name);
2915 // Class String_type.
2917 // Convert String_type to the backend representation. A string is a
2918 // struct with two fields: a pointer to the characters and a length.
2921 String_type::do_get_backend(Gogo* gogo)
2923 static Btype* backend_string_type;
2924 if (backend_string_type == NULL)
2926 std::vector<Backend::Btyped_identifier> fields(2);
2928 Type* b = gogo->lookup_global("byte")->type_value();
2929 Type* pb = Type::make_pointer_type(b);
2931 // We aren't going to get back to this field to finish the
2932 // backend representation, so force it to be finished now.
2933 if (!gogo->named_types_are_converted())
2935 pb->get_backend_placeholder(gogo);
2936 pb->finish_backend(gogo);
2939 fields[0].name = "__data";
2940 fields[0].btype = pb->get_backend(gogo);
2941 fields[0].location = Linemap::predeclared_location();
2943 Type* int_type = Type::lookup_integer_type("int");
2944 fields[1].name = "__length";
2945 fields[1].btype = int_type->get_backend(gogo);
2946 fields[1].location = fields[0].location;
2948 backend_string_type = gogo->backend()->struct_type(fields);
2950 return backend_string_type;
2953 // Return a tree for the length of STRING.
2956 String_type::length_tree(Gogo*, tree string)
2958 tree string_type = TREE_TYPE(string);
2959 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2960 tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type));
2961 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)),
2963 return fold_build3(COMPONENT_REF, integer_type_node, string,
2964 length_field, NULL_TREE);
2967 // Return a tree for a pointer to the bytes of STRING.
2970 String_type::bytes_tree(Gogo*, tree string)
2972 tree string_type = TREE_TYPE(string);
2973 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2974 tree bytes_field = TYPE_FIELDS(string_type);
2975 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)),
2977 return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string,
2978 bytes_field, NULL_TREE);
2981 // The type descriptor for the string type.
2984 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2987 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
2990 Named_object* no = gogo->lookup_global("string");
2991 go_assert(no != NULL);
2992 return Type::type_descriptor(gogo, no->type_value());
2996 // We should not be asked for the reflection string of a basic type.
2999 String_type::do_reflection(Gogo*, std::string* ret) const
3001 ret->append("string");
3004 // Mangled name of a string type.
3007 String_type::do_mangled_name(Gogo*, std::string* ret) const
3009 ret->push_back('z');
3012 // Make a string type.
3015 Type::make_string_type()
3017 static String_type string_type;
3018 return &string_type;
3021 // The named type "string".
3023 static Named_type* named_string_type;
3025 // Get the named type "string".
3028 Type::lookup_string_type()
3030 return named_string_type;
3033 // Make the named type string.
3036 Type::make_named_string_type()
3038 Type* string_type = Type::make_string_type();
3039 Named_object* named_object =
3040 Named_object::make_type("string", NULL, string_type,
3041 Linemap::predeclared_location());
3042 Named_type* named_type = named_object->type_value();
3043 named_string_type = named_type;
3047 // The sink type. This is the type of the blank identifier _. Any
3048 // type may be assigned to it.
3050 class Sink_type : public Type
3059 do_compare_is_identity(Gogo*) const
3063 do_get_backend(Gogo*)
3064 { go_unreachable(); }
3067 do_type_descriptor(Gogo*, Named_type*)
3068 { go_unreachable(); }
3071 do_reflection(Gogo*, std::string*) const
3072 { go_unreachable(); }
3075 do_mangled_name(Gogo*, std::string*) const
3076 { go_unreachable(); }
3079 // Make the sink type.
3082 Type::make_sink_type()
3084 static Sink_type sink_type;
3088 // Class Function_type.
3093 Function_type::do_traverse(Traverse* traverse)
3095 if (this->receiver_ != NULL
3096 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
3097 return TRAVERSE_EXIT;
3098 if (this->parameters_ != NULL
3099 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
3100 return TRAVERSE_EXIT;
3101 if (this->results_ != NULL
3102 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
3103 return TRAVERSE_EXIT;
3104 return TRAVERSE_CONTINUE;
3107 // Returns whether T is a valid redeclaration of this type. If this
3108 // returns false, and REASON is not NULL, *REASON may be set to a
3109 // brief explanation of why it returned false.
3112 Function_type::is_valid_redeclaration(const Function_type* t,
3113 std::string* reason) const
3115 if (!this->is_identical(t, false, true, reason))
3118 // A redeclaration of a function is required to use the same names
3119 // for the receiver and parameters.
3120 if (this->receiver() != NULL
3121 && this->receiver()->name() != t->receiver()->name())
3124 *reason = "receiver name changed";
3128 const Typed_identifier_list* parms1 = this->parameters();
3129 const Typed_identifier_list* parms2 = t->parameters();
3132 Typed_identifier_list::const_iterator p1 = parms1->begin();
3133 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3134 p2 != parms2->end();
3137 if (p1->name() != p2->name())
3140 *reason = "parameter name changed";
3144 // This is called at parse time, so we may have unknown
3146 Type* t1 = p1->type()->forwarded();
3147 Type* t2 = p2->type()->forwarded();
3149 && t1->forward_declaration_type() != NULL
3150 && (t2->forward_declaration_type() == NULL
3151 || (t1->forward_declaration_type()->named_object()
3152 != t2->forward_declaration_type()->named_object())))
3157 const Typed_identifier_list* results1 = this->results();
3158 const Typed_identifier_list* results2 = t->results();
3159 if (results1 != NULL)
3161 Typed_identifier_list::const_iterator res1 = results1->begin();
3162 for (Typed_identifier_list::const_iterator res2 = results2->begin();
3163 res2 != results2->end();
3166 if (res1->name() != res2->name())
3169 *reason = "result name changed";
3173 // This is called at parse time, so we may have unknown
3175 Type* t1 = res1->type()->forwarded();
3176 Type* t2 = res2->type()->forwarded();
3178 && t1->forward_declaration_type() != NULL
3179 && (t2->forward_declaration_type() == NULL
3180 || (t1->forward_declaration_type()->named_object()
3181 != t2->forward_declaration_type()->named_object())))
3189 // Check whether T is the same as this type.
3192 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
3193 bool errors_are_identical,
3194 std::string* reason) const
3196 if (!ignore_receiver)
3198 const Typed_identifier* r1 = this->receiver();
3199 const Typed_identifier* r2 = t->receiver();
3200 if ((r1 != NULL) != (r2 != NULL))
3203 *reason = _("different receiver types");
3208 if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
3211 if (reason != NULL && !reason->empty())
3212 *reason = "receiver: " + *reason;
3218 const Typed_identifier_list* parms1 = this->parameters();
3219 const Typed_identifier_list* parms2 = t->parameters();
3220 if ((parms1 != NULL) != (parms2 != NULL))
3223 *reason = _("different number of parameters");
3228 Typed_identifier_list::const_iterator p1 = parms1->begin();
3229 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3230 p2 != parms2->end();
3233 if (p1 == parms1->end())
3236 *reason = _("different number of parameters");
3240 if (!Type::are_identical(p1->type(), p2->type(),
3241 errors_are_identical, NULL))
3244 *reason = _("different parameter types");
3248 if (p1 != parms1->end())
3251 *reason = _("different number of parameters");
3256 if (this->is_varargs() != t->is_varargs())
3259 *reason = _("different varargs");
3263 const Typed_identifier_list* results1 = this->results();
3264 const Typed_identifier_list* results2 = t->results();
3265 if ((results1 != NULL) != (results2 != NULL))
3268 *reason = _("different number of results");
3271 if (results1 != NULL)
3273 Typed_identifier_list::const_iterator res1 = results1->begin();
3274 for (Typed_identifier_list::const_iterator res2 = results2->begin();
3275 res2 != results2->end();
3278 if (res1 == results1->end())
3281 *reason = _("different number of results");
3285 if (!Type::are_identical(res1->type(), res2->type(),
3286 errors_are_identical, NULL))
3289 *reason = _("different result types");
3293 if (res1 != results1->end())
3296 *reason = _("different number of results");
3307 Function_type::do_hash_for_method(Gogo* gogo) const
3309 unsigned int ret = 0;
3310 // We ignore the receiver type for hash codes, because we need to
3311 // get the same hash code for a method in an interface and a method
3312 // declared for a type. The former will not have a receiver.
3313 if (this->parameters_ != NULL)
3316 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3317 p != this->parameters_->end();
3319 ret += p->type()->hash_for_method(gogo) << shift;
3321 if (this->results_ != NULL)
3324 for (Typed_identifier_list::const_iterator p = this->results_->begin();
3325 p != this->results_->end();
3327 ret += p->type()->hash_for_method(gogo) << shift;
3329 if (this->is_varargs_)
3335 // Get the backend representation for a function type.
3338 Function_type::do_get_backend(Gogo* gogo)
3340 Backend::Btyped_identifier breceiver;
3341 if (this->receiver_ != NULL)
3343 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
3345 // We always pass the address of the receiver parameter, in
3346 // order to make interface calls work with unknown types.
3347 Type* rtype = this->receiver_->type();
3348 if (rtype->points_to() == NULL)
3349 rtype = Type::make_pointer_type(rtype);
3350 breceiver.btype = rtype->get_backend(gogo);
3351 breceiver.location = this->receiver_->location();
3354 std::vector<Backend::Btyped_identifier> bparameters;
3355 if (this->parameters_ != NULL)
3357 bparameters.resize(this->parameters_->size());
3359 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3360 p != this->parameters_->end();
3363 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
3364 bparameters[i].btype = p->type()->get_backend(gogo);
3365 bparameters[i].location = p->location();
3367 go_assert(i == bparameters.size());
3370 std::vector<Backend::Btyped_identifier> bresults;
3371 if (this->results_ != NULL)
3373 bresults.resize(this->results_->size());
3375 for (Typed_identifier_list::const_iterator p = this->results_->begin();
3376 p != this->results_->end();
3379 bresults[i].name = Gogo::unpack_hidden_name(p->name());
3380 bresults[i].btype = p->type()->get_backend(gogo);
3381 bresults[i].location = p->location();
3383 go_assert(i == bresults.size());
3386 return gogo->backend()->function_type(breceiver, bparameters, bresults,
3390 // The type of a function type descriptor.
3393 Function_type::make_function_type_descriptor_type()
3398 Type* tdt = Type::make_type_descriptor_type();
3399 Type* ptdt = Type::make_type_descriptor_ptr_type();
3401 Type* bool_type = Type::lookup_bool_type();
3403 Type* slice_type = Type::make_array_type(ptdt, NULL);
3405 Struct_type* s = Type::make_builtin_struct_type(4,
3407 "dotdotdot", bool_type,
3411 ret = Type::make_builtin_named_type("FuncType", s);
3417 // The type descriptor for a function type.
3420 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3422 Location bloc = Linemap::predeclared_location();
3424 Type* ftdt = Function_type::make_function_type_descriptor_type();
3426 const Struct_field_list* fields = ftdt->struct_type()->fields();
3428 Expression_list* vals = new Expression_list();
3431 Struct_field_list::const_iterator p = fields->begin();
3432 go_assert(p->is_field_name("commonType"));
3433 vals->push_back(this->type_descriptor_constructor(gogo,
3434 RUNTIME_TYPE_KIND_FUNC,
3438 go_assert(p->is_field_name("dotdotdot"));
3439 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
3442 go_assert(p->is_field_name("in"));
3443 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
3444 this->parameters()));
3447 go_assert(p->is_field_name("out"));
3448 vals->push_back(this->type_descriptor_params(p->type(), NULL,
3452 go_assert(p == fields->end());
3454 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
3457 // Return a composite literal for the parameters or results of a type
3461 Function_type::type_descriptor_params(Type* params_type,
3462 const Typed_identifier* receiver,
3463 const Typed_identifier_list* params)
3465 Location bloc = Linemap::predeclared_location();
3467 if (receiver == NULL && params == NULL)
3468 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
3470 Expression_list* vals = new Expression_list();
3471 vals->reserve((params == NULL ? 0 : params->size())
3472 + (receiver != NULL ? 1 : 0));
3474 if (receiver != NULL)
3475 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
3479 for (Typed_identifier_list::const_iterator p = params->begin();
3482 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
3485 return Expression::make_slice_composite_literal(params_type, vals, bloc);
3488 // The reflection string.
3491 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
3493 // FIXME: Turn this off until we straighten out the type of the
3494 // struct field used in a go statement which calls a method.
3495 // go_assert(this->receiver_ == NULL);
3497 ret->append("func");
3499 if (this->receiver_ != NULL)
3501 ret->push_back('(');
3502 this->append_reflection(this->receiver_->type(), gogo, ret);
3503 ret->push_back(')');
3506 ret->push_back('(');
3507 const Typed_identifier_list* params = this->parameters();
3510 bool is_varargs = this->is_varargs_;
3511 for (Typed_identifier_list::const_iterator p = params->begin();
3515 if (p != params->begin())
3517 if (!is_varargs || p + 1 != params->end())
3518 this->append_reflection(p->type(), gogo, ret);
3522 this->append_reflection(p->type()->array_type()->element_type(),
3527 ret->push_back(')');
3529 const Typed_identifier_list* results = this->results();
3530 if (results != NULL && !results->empty())
3532 if (results->size() == 1)
3533 ret->push_back(' ');
3536 for (Typed_identifier_list::const_iterator p = results->begin();
3537 p != results->end();
3540 if (p != results->begin())
3542 this->append_reflection(p->type(), gogo, ret);
3544 if (results->size() > 1)
3545 ret->push_back(')');
3552 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3554 ret->push_back('F');
3556 if (this->receiver_ != NULL)
3558 ret->push_back('m');
3559 this->append_mangled_name(this->receiver_->type(), gogo, ret);
3562 const Typed_identifier_list* params = this->parameters();
3565 ret->push_back('p');
3566 for (Typed_identifier_list::const_iterator p = params->begin();
3569 this->append_mangled_name(p->type(), gogo, ret);
3570 if (this->is_varargs_)
3571 ret->push_back('V');
3572 ret->push_back('e');
3575 const Typed_identifier_list* results = this->results();
3576 if (results != NULL)
3578 ret->push_back('r');
3579 for (Typed_identifier_list::const_iterator p = results->begin();
3580 p != results->end();
3582 this->append_mangled_name(p->type(), gogo, ret);
3583 ret->push_back('e');
3586 ret->push_back('e');
3589 // Export a function type.
3592 Function_type::do_export(Export* exp) const
3594 // We don't write out the receiver. The only function types which
3595 // should have a receiver are the ones associated with explicitly
3596 // defined methods. For those the receiver type is written out by
3597 // Function::export_func.
3599 exp->write_c_string("(");
3601 if (this->parameters_ != NULL)
3603 bool is_varargs = this->is_varargs_;
3604 for (Typed_identifier_list::const_iterator p =
3605 this->parameters_->begin();
3606 p != this->parameters_->end();
3612 exp->write_c_string(", ");
3613 exp->write_name(p->name());
3614 exp->write_c_string(" ");
3615 if (!is_varargs || p + 1 != this->parameters_->end())
3616 exp->write_type(p->type());
3619 exp->write_c_string("...");
3620 exp->write_type(p->type()->array_type()->element_type());
3624 exp->write_c_string(")");
3626 const Typed_identifier_list* results = this->results_;
3627 if (results != NULL)
3629 exp->write_c_string(" ");
3630 if (results->size() == 1 && results->begin()->name().empty())
3631 exp->write_type(results->begin()->type());
3635 exp->write_c_string("(");
3636 for (Typed_identifier_list::const_iterator p = results->begin();
3637 p != results->end();
3643 exp->write_c_string(", ");
3644 exp->write_name(p->name());
3645 exp->write_c_string(" ");
3646 exp->write_type(p->type());
3648 exp->write_c_string(")");
3653 // Import a function type.
3656 Function_type::do_import(Import* imp)
3658 imp->require_c_string("(");
3659 Typed_identifier_list* parameters;
3660 bool is_varargs = false;
3661 if (imp->peek_char() == ')')
3665 parameters = new Typed_identifier_list();
3668 std::string name = imp->read_name();
3669 imp->require_c_string(" ");
3671 if (imp->match_c_string("..."))
3677 Type* ptype = imp->read_type();
3679 ptype = Type::make_array_type(ptype, NULL);
3680 parameters->push_back(Typed_identifier(name, ptype,
3682 if (imp->peek_char() != ',')
3684 go_assert(!is_varargs);
3685 imp->require_c_string(", ");
3688 imp->require_c_string(")");
3690 Typed_identifier_list* results;
3691 if (imp->peek_char() != ' ')
3696 results = new Typed_identifier_list;
3697 if (imp->peek_char() != '(')
3699 Type* rtype = imp->read_type();
3700 results->push_back(Typed_identifier("", rtype, imp->location()));
3707 std::string name = imp->read_name();
3708 imp->require_c_string(" ");
3709 Type* rtype = imp->read_type();
3710 results->push_back(Typed_identifier(name, rtype,
3712 if (imp->peek_char() != ',')
3714 imp->require_c_string(", ");
3716 imp->require_c_string(")");
3720 Function_type* ret = Type::make_function_type(NULL, parameters, results,
3723 ret->set_is_varargs();
3727 // Make a copy of a function type without a receiver.
3730 Function_type::copy_without_receiver() const
3732 go_assert(this->is_method());
3733 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
3736 if (this->is_varargs())
3737 ret->set_is_varargs();
3738 if (this->is_builtin())
3739 ret->set_is_builtin();
3743 // Make a copy of a function type with a receiver.
3746 Function_type::copy_with_receiver(Type* receiver_type) const
3748 go_assert(!this->is_method());
3749 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
3751 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
3754 if (this->is_varargs_)
3755 ret->set_is_varargs();
3759 // Make a function type.
3762 Type::make_function_type(Typed_identifier* receiver,
3763 Typed_identifier_list* parameters,
3764 Typed_identifier_list* results,
3767 return new Function_type(receiver, parameters, results, location);
3770 // Class Pointer_type.
3775 Pointer_type::do_traverse(Traverse* traverse)
3777 return Type::traverse(this->to_type_, traverse);
3783 Pointer_type::do_hash_for_method(Gogo* gogo) const
3785 return this->to_type_->hash_for_method(gogo) << 4;
3788 // Get the backend representation for a pointer type.
3791 Pointer_type::do_get_backend(Gogo* gogo)
3793 Btype* to_btype = this->to_type_->get_backend(gogo);
3794 return gogo->backend()->pointer_type(to_btype);
3797 // The type of a pointer type descriptor.
3800 Pointer_type::make_pointer_type_descriptor_type()
3805 Type* tdt = Type::make_type_descriptor_type();
3806 Type* ptdt = Type::make_type_descriptor_ptr_type();
3808 Struct_type* s = Type::make_builtin_struct_type(2,
3812 ret = Type::make_builtin_named_type("PtrType", s);
3818 // The type descriptor for a pointer type.
3821 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3823 if (this->is_unsafe_pointer_type())
3825 go_assert(name != NULL);
3826 return this->plain_type_descriptor(gogo,
3827 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
3832 Location bloc = Linemap::predeclared_location();
3834 const Methods* methods;
3835 Type* deref = this->points_to();
3836 if (deref->named_type() != NULL)
3837 methods = deref->named_type()->methods();
3838 else if (deref->struct_type() != NULL)
3839 methods = deref->struct_type()->methods();
3843 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
3845 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
3847 Expression_list* vals = new Expression_list();
3850 Struct_field_list::const_iterator p = fields->begin();
3851 go_assert(p->is_field_name("commonType"));
3852 vals->push_back(this->type_descriptor_constructor(gogo,
3853 RUNTIME_TYPE_KIND_PTR,
3854 name, methods, false));
3857 go_assert(p->is_field_name("elem"));
3858 vals->push_back(Expression::make_type_descriptor(deref, bloc));
3860 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
3864 // Reflection string.
3867 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
3869 ret->push_back('*');
3870 this->append_reflection(this->to_type_, gogo, ret);
3876 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3878 ret->push_back('p');
3879 this->append_mangled_name(this->to_type_, gogo, ret);
3885 Pointer_type::do_export(Export* exp) const
3887 exp->write_c_string("*");
3888 if (this->is_unsafe_pointer_type())
3889 exp->write_c_string("any");
3891 exp->write_type(this->to_type_);
3897 Pointer_type::do_import(Import* imp)
3899 imp->require_c_string("*");
3900 if (imp->match_c_string("any"))
3903 return Type::make_pointer_type(Type::make_void_type());
3905 Type* to = imp->read_type();
3906 return Type::make_pointer_type(to);
3909 // Make a pointer type.
3912 Type::make_pointer_type(Type* to_type)
3914 typedef Unordered_map(Type*, Pointer_type*) Hashtable;
3915 static Hashtable pointer_types;
3916 Hashtable::const_iterator p = pointer_types.find(to_type);
3917 if (p != pointer_types.end())
3919 Pointer_type* ret = new Pointer_type(to_type);
3920 pointer_types[to_type] = ret;
3924 // The nil type. We use a special type for nil because it is not the
3925 // same as any other type. In C term nil has type void*, but there is
3926 // no such type in Go.
3928 class Nil_type : public Type
3937 do_compare_is_identity(Gogo*) const
3941 do_get_backend(Gogo* gogo)
3942 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
3945 do_type_descriptor(Gogo*, Named_type*)
3946 { go_unreachable(); }
3949 do_reflection(Gogo*, std::string*) const
3950 { go_unreachable(); }
3953 do_mangled_name(Gogo*, std::string* ret) const
3954 { ret->push_back('n'); }
3957 // Make the nil type.
3960 Type::make_nil_type()
3962 static Nil_type singleton_nil_type;
3963 return &singleton_nil_type;
3966 // The type of a function call which returns multiple values. This is
3967 // really a struct, but we don't want to confuse a function call which
3968 // returns a struct with a function call which returns multiple
3971 class Call_multiple_result_type : public Type
3974 Call_multiple_result_type(Call_expression* call)
3975 : Type(TYPE_CALL_MULTIPLE_RESULT),
3981 do_has_pointer() const
3983 go_assert(saw_errors());
3988 do_compare_is_identity(Gogo*) const
3992 do_get_backend(Gogo* gogo)
3994 go_assert(saw_errors());
3995 return gogo->backend()->error_type();
3999 do_type_descriptor(Gogo*, Named_type*)
4001 go_assert(saw_errors());
4002 return Expression::make_error(Linemap::unknown_location());
4006 do_reflection(Gogo*, std::string*) const
4007 { go_assert(saw_errors()); }
4010 do_mangled_name(Gogo*, std::string*) const
4011 { go_assert(saw_errors()); }
4014 // The expression being called.
4015 Call_expression* call_;
4018 // Make a call result type.
4021 Type::make_call_multiple_result_type(Call_expression* call)
4023 return new Call_multiple_result_type(call);
4026 // Class Struct_field.
4028 // Get the name of a field.
4031 Struct_field::field_name() const
4033 const std::string& name(this->typed_identifier_.name());
4038 // This is called during parsing, before anything is lowered, so
4039 // we have to be pretty careful to avoid dereferencing an
4040 // unknown type name.
4041 Type* t = this->typed_identifier_.type();
4043 if (t->classification() == Type::TYPE_POINTER)
4046 Pointer_type* ptype = static_cast<Pointer_type*>(t);
4047 dt = ptype->points_to();
4049 if (dt->forward_declaration_type() != NULL)
4050 return dt->forward_declaration_type()->name();
4051 else if (dt->named_type() != NULL)
4052 return dt->named_type()->name();
4053 else if (t->is_error_type() || dt->is_error_type())
4055 static const std::string error_string = "*error*";
4056 return error_string;
4060 // Avoid crashing in the erroneous case where T is named but
4063 if (t->forward_declaration_type() != NULL)
4064 return t->forward_declaration_type()->name();
4065 else if (t->named_type() != NULL)
4066 return t->named_type()->name();
4073 // Return whether this field is named NAME.
4076 Struct_field::is_field_name(const std::string& name) const
4078 const std::string& me(this->typed_identifier_.name());
4083 Type* t = this->typed_identifier_.type();
4084 if (t->points_to() != NULL)
4086 Named_type* nt = t->named_type();
4087 if (nt != NULL && nt->name() == name)
4090 // This is a horrible hack caused by the fact that we don't pack
4091 // the names of builtin types. FIXME.
4094 && nt->name() == Gogo::unpack_hidden_name(name))
4101 // Class Struct_type.
4106 Struct_type::do_traverse(Traverse* traverse)
4108 Struct_field_list* fields = this->fields_;
4111 for (Struct_field_list::iterator p = fields->begin();
4115 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
4116 return TRAVERSE_EXIT;
4119 return TRAVERSE_CONTINUE;
4122 // Verify that the struct type is complete and valid.
4125 Struct_type::do_verify()
4127 Struct_field_list* fields = this->fields_;
4130 for (Struct_field_list::iterator p = fields->begin();
4134 Type* t = p->type();
4135 if (t->is_undefined())
4137 error_at(p->location(), "struct field type is incomplete");
4138 p->set_type(Type::make_error_type());
4140 else if (p->is_anonymous())
4142 if (t->named_type() != NULL && t->points_to() != NULL)
4144 error_at(p->location(), "embedded type may not be a pointer");
4145 p->set_type(Type::make_error_type());
4147 else if (t->points_to() != NULL
4148 && t->points_to()->interface_type() != NULL)
4150 error_at(p->location(),
4151 "embedded type may not be pointer to interface");
4152 p->set_type(Type::make_error_type());
4159 // Whether this contains a pointer.
4162 Struct_type::do_has_pointer() const
4164 const Struct_field_list* fields = this->fields();
4167 for (Struct_field_list::const_iterator p = fields->begin();
4171 if (p->type()->has_pointer())
4177 // Whether this type is identical to T.
4180 Struct_type::is_identical(const Struct_type* t,
4181 bool errors_are_identical) const
4183 const Struct_field_list* fields1 = this->fields();
4184 const Struct_field_list* fields2 = t->fields();
4185 if (fields1 == NULL || fields2 == NULL)
4186 return fields1 == fields2;
4187 Struct_field_list::const_iterator pf2 = fields2->begin();
4188 for (Struct_field_list::const_iterator pf1 = fields1->begin();
4189 pf1 != fields1->end();
4192 if (pf2 == fields2->end())
4194 if (pf1->field_name() != pf2->field_name())
4196 if (pf1->is_anonymous() != pf2->is_anonymous()
4197 || !Type::are_identical(pf1->type(), pf2->type(),
4198 errors_are_identical, NULL))
4200 if (!pf1->has_tag())
4207 if (!pf2->has_tag())
4209 if (pf1->tag() != pf2->tag())
4213 if (pf2 != fields2->end())
4218 // Whether this struct type has any hidden fields.
4221 Struct_type::struct_has_hidden_fields(const Named_type* within,
4222 std::string* reason) const
4224 const Struct_field_list* fields = this->fields();
4227 const Package* within_package = (within == NULL
4229 : within->named_object()->package());
4230 for (Struct_field_list::const_iterator pf = fields->begin();
4231 pf != fields->end();
4234 if (within_package != NULL
4235 && !pf->is_anonymous()
4236 && Gogo::is_hidden_name(pf->field_name()))
4240 std::string within_name = within->named_object()->message_name();
4241 std::string name = Gogo::message_name(pf->field_name());
4242 size_t bufsize = 200 + within_name.length() + name.length();
4243 char* buf = new char[bufsize];
4244 snprintf(buf, bufsize,
4245 _("implicit assignment of %s%s%s hidden field %s%s%s"),
4246 open_quote, within_name.c_str(), close_quote,
4247 open_quote, name.c_str(), close_quote);
4248 reason->assign(buf);
4254 if (pf->type()->has_hidden_fields(within, reason))
4261 // Whether comparisons of this struct type are simple identity
4265 Struct_type::do_compare_is_identity(Gogo* gogo) const
4267 const Struct_field_list* fields = this->fields_;
4270 unsigned int offset = 0;
4271 for (Struct_field_list::const_iterator pf = fields->begin();
4272 pf != fields->end();
4275 if (!pf->type()->compare_is_identity(gogo))
4278 unsigned int field_align;
4279 if (!pf->type()->backend_type_align(gogo, &field_align))
4281 if ((offset & (field_align - 1)) != 0)
4283 // This struct has padding. We don't guarantee that that
4284 // padding is zero-initialized for a stack variable, so we
4285 // can't use memcmp to compare struct values.
4289 unsigned int field_size;
4290 if (!pf->type()->backend_type_size(gogo, &field_size))
4292 offset += field_size;
4297 // Build identity and hash functions for this struct.
4302 Struct_type::do_hash_for_method(Gogo* gogo) const
4304 unsigned int ret = 0;
4305 if (this->fields() != NULL)
4307 for (Struct_field_list::const_iterator pf = this->fields()->begin();
4308 pf != this->fields()->end();
4310 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
4315 // Find the local field NAME.
4318 Struct_type::find_local_field(const std::string& name,
4319 unsigned int *pindex) const
4321 const Struct_field_list* fields = this->fields_;
4325 for (Struct_field_list::const_iterator pf = fields->begin();
4326 pf != fields->end();
4329 if (pf->is_field_name(name))
4339 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
4341 Field_reference_expression*
4342 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
4343 Location location) const
4346 return this->field_reference_depth(struct_expr, name, location, NULL,
4350 // Return an expression for a field, along with the depth at which it
4353 Field_reference_expression*
4354 Struct_type::field_reference_depth(Expression* struct_expr,
4355 const std::string& name,
4357 Saw_named_type* saw,
4358 unsigned int* depth) const
4360 const Struct_field_list* fields = this->fields_;
4364 // Look for a field with this name.
4366 for (Struct_field_list::const_iterator pf = fields->begin();
4367 pf != fields->end();
4370 if (pf->is_field_name(name))
4373 return Expression::make_field_reference(struct_expr, i, location);
4377 // Look for an anonymous field which contains a field with this
4379 unsigned int found_depth = 0;
4380 Field_reference_expression* ret = NULL;
4382 for (Struct_field_list::const_iterator pf = fields->begin();
4383 pf != fields->end();
4386 if (!pf->is_anonymous())
4389 Struct_type* st = pf->type()->deref()->struct_type();
4393 Saw_named_type* hold_saw = saw;
4394 Saw_named_type saw_here;
4395 Named_type* nt = pf->type()->named_type();
4397 nt = pf->type()->deref()->named_type();
4401 for (q = saw; q != NULL; q = q->next)
4405 // If this is an error, it will be reported
4412 saw_here.next = saw;
4417 // Look for a reference using a NULL struct expression. If we
4418 // find one, fill in the struct expression with a reference to
4420 unsigned int subdepth;
4421 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
4431 if (ret == NULL || subdepth < found_depth)
4436 found_depth = subdepth;
4437 Expression* here = Expression::make_field_reference(struct_expr, i,
4439 if (pf->type()->points_to() != NULL)
4440 here = Expression::make_unary(OPERATOR_MULT, here, location);
4441 while (sub->expr() != NULL)
4443 sub = sub->expr()->deref()->field_reference_expression();
4444 go_assert(sub != NULL);
4446 sub->set_struct_expression(here);
4448 else if (subdepth > found_depth)
4452 // We do not handle ambiguity here--it should be handled by
4453 // Type::bind_field_or_method.
4461 *depth = found_depth + 1;
4466 // Return the total number of fields, including embedded fields.
4469 Struct_type::total_field_count() const
4471 if (this->fields_ == NULL)
4473 unsigned int ret = 0;
4474 for (Struct_field_list::const_iterator pf = this->fields_->begin();
4475 pf != this->fields_->end();
4478 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
4481 ret += pf->type()->struct_type()->total_field_count();
4486 // Return whether NAME is an unexported field, for better error reporting.
4489 Struct_type::is_unexported_local_field(Gogo* gogo,
4490 const std::string& name) const
4492 const Struct_field_list* fields = this->fields_;
4495 for (Struct_field_list::const_iterator pf = fields->begin();
4496 pf != fields->end();
4499 const std::string& field_name(pf->field_name());
4500 if (Gogo::is_hidden_name(field_name)
4501 && name == Gogo::unpack_hidden_name(field_name)
4502 && gogo->pack_hidden_name(name, false) != field_name)
4509 // Finalize the methods of an unnamed struct.
4512 Struct_type::finalize_methods(Gogo* gogo)
4514 if (this->all_methods_ != NULL)
4516 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
4519 // Return the method NAME, or NULL if there isn't one or if it is
4520 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
4524 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
4526 return Type::method_function(this->all_methods_, name, is_ambiguous);
4529 // Convert struct fields to the backend representation. This is not
4530 // declared in types.h so that types.h doesn't have to #include
4534 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
4535 bool use_placeholder,
4536 std::vector<Backend::Btyped_identifier>* bfields)
4538 bfields->resize(fields->size());
4540 for (Struct_field_list::const_iterator p = fields->begin();
4544 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
4545 (*bfields)[i].btype = (use_placeholder
4546 ? p->type()->get_backend_placeholder(gogo)
4547 : p->type()->get_backend(gogo));
4548 (*bfields)[i].location = p->location();
4550 go_assert(i == fields->size());
4553 // Get the tree for a struct type.
4556 Struct_type::do_get_backend(Gogo* gogo)
4558 std::vector<Backend::Btyped_identifier> bfields;
4559 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
4560 return gogo->backend()->struct_type(bfields);
4563 // Finish the backend representation of the fields of a struct.
4566 Struct_type::finish_backend_fields(Gogo* gogo)
4568 const Struct_field_list* fields = this->fields_;
4571 for (Struct_field_list::const_iterator p = fields->begin();
4574 p->type()->get_backend(gogo);
4578 // The type of a struct type descriptor.
4581 Struct_type::make_struct_type_descriptor_type()
4586 Type* tdt = Type::make_type_descriptor_type();
4587 Type* ptdt = Type::make_type_descriptor_ptr_type();
4589 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4590 Type* string_type = Type::lookup_string_type();
4591 Type* pointer_string_type = Type::make_pointer_type(string_type);
4594 Type::make_builtin_struct_type(5,
4595 "name", pointer_string_type,
4596 "pkgPath", pointer_string_type,
4598 "tag", pointer_string_type,
4599 "offset", uintptr_type);
4600 Type* nsf = Type::make_builtin_named_type("structField", sf);
4602 Type* slice_type = Type::make_array_type(nsf, NULL);
4604 Struct_type* s = Type::make_builtin_struct_type(2,
4606 "fields", slice_type);
4608 ret = Type::make_builtin_named_type("StructType", s);
4614 // Build a type descriptor for a struct type.
4617 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4619 Location bloc = Linemap::predeclared_location();
4621 Type* stdt = Struct_type::make_struct_type_descriptor_type();
4623 const Struct_field_list* fields = stdt->struct_type()->fields();
4625 Expression_list* vals = new Expression_list();
4628 const Methods* methods = this->methods();
4629 // A named struct should not have methods--the methods should attach
4630 // to the named type.
4631 go_assert(methods == NULL || name == NULL);
4633 Struct_field_list::const_iterator ps = fields->begin();
4634 go_assert(ps->is_field_name("commonType"));
4635 vals->push_back(this->type_descriptor_constructor(gogo,
4636 RUNTIME_TYPE_KIND_STRUCT,
4637 name, methods, true));
4640 go_assert(ps->is_field_name("fields"));
4642 Expression_list* elements = new Expression_list();
4643 elements->reserve(this->fields_->size());
4644 Type* element_type = ps->type()->array_type()->element_type();
4645 for (Struct_field_list::const_iterator pf = this->fields_->begin();
4646 pf != this->fields_->end();
4649 const Struct_field_list* f = element_type->struct_type()->fields();
4651 Expression_list* fvals = new Expression_list();
4654 Struct_field_list::const_iterator q = f->begin();
4655 go_assert(q->is_field_name("name"));
4656 if (pf->is_anonymous())
4657 fvals->push_back(Expression::make_nil(bloc));
4660 std::string n = Gogo::unpack_hidden_name(pf->field_name());
4661 Expression* s = Expression::make_string(n, bloc);
4662 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4666 go_assert(q->is_field_name("pkgPath"));
4667 if (!Gogo::is_hidden_name(pf->field_name()))
4668 fvals->push_back(Expression::make_nil(bloc));
4671 std::string n = Gogo::hidden_name_prefix(pf->field_name());
4672 Expression* s = Expression::make_string(n, bloc);
4673 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4677 go_assert(q->is_field_name("typ"));
4678 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
4681 go_assert(q->is_field_name("tag"));
4683 fvals->push_back(Expression::make_nil(bloc));
4686 Expression* s = Expression::make_string(pf->tag(), bloc);
4687 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4691 go_assert(q->is_field_name("offset"));
4692 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
4694 Expression* v = Expression::make_struct_composite_literal(element_type,
4696 elements->push_back(v);
4699 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
4702 return Expression::make_struct_composite_literal(stdt, vals, bloc);
4705 // Write the hash function for a struct which can not use the identity
4709 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
4710 Function_type* hash_fntype,
4711 Function_type* equal_fntype)
4713 Location bloc = Linemap::predeclared_location();
4715 // The pointer to the struct that we are going to hash. This is an
4716 // argument to the hash function we are implementing here.
4717 Named_object* key_arg = gogo->lookup("key", NULL);
4718 go_assert(key_arg != NULL);
4719 Type* key_arg_type = key_arg->var_value()->type();
4721 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4725 mpz_init_set_ui(ival, 0);
4726 Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
4729 // Make a temporary to hold the return value, initialized to 0.
4730 Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
4732 gogo->add_statement(retval);
4734 // Make a temporary to hold the key as a uintptr.
4735 Expression* ref = Expression::make_var_reference(key_arg, bloc);
4736 ref = Expression::make_cast(uintptr_type, ref, bloc);
4737 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
4739 gogo->add_statement(key);
4741 // Loop over the struct fields.
4743 const Struct_field_list* fields = this->fields_;
4744 for (Struct_field_list::const_iterator pf = fields->begin();
4745 pf != fields->end();
4752 // Multiply retval by 33.
4753 mpz_init_set_ui(ival, 33);
4754 Expression* i33 = Expression::make_integer(&ival, uintptr_type,
4758 ref = Expression::make_temporary_reference(retval, bloc);
4759 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ,
4761 gogo->add_statement(s);
4764 // Get a pointer to the value of this field.
4765 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
4766 ref = Expression::make_temporary_reference(key, bloc);
4767 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
4769 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
4771 // Get the size of this field.
4772 Expression* size = Expression::make_type_info(pf->type(),
4773 Expression::TYPE_INFO_SIZE);
4775 // Get the hash function to use for the type of this field.
4776 Named_object* hash_fn;
4777 Named_object* equal_fn;
4778 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
4779 equal_fntype, &hash_fn, &equal_fn);
4781 // Call the hash function for the field.
4782 Expression_list* args = new Expression_list();
4783 args->push_back(subkey);
4784 args->push_back(size);
4785 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
4786 Expression* call = Expression::make_call(func, args, false, bloc);
4788 // Add the field's hash value to retval.
4789 Temporary_reference_expression* tref =
4790 Expression::make_temporary_reference(retval, bloc);
4791 tref->set_is_lvalue();
4792 Statement* s = Statement::make_assignment_operation(OPERATOR_PLUSEQ,
4794 gogo->add_statement(s);
4797 // Return retval to the caller of the hash function.
4798 Expression_list* vals = new Expression_list();
4799 ref = Expression::make_temporary_reference(retval, bloc);
4800 vals->push_back(ref);
4801 Statement* s = Statement::make_return_statement(vals, bloc);
4802 gogo->add_statement(s);
4805 // Write the equality function for a struct which can not use the
4806 // identity function.
4809 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
4811 Location bloc = Linemap::predeclared_location();
4813 // The pointers to the structs we are going to compare.
4814 Named_object* key1_arg = gogo->lookup("key1", NULL);
4815 Named_object* key2_arg = gogo->lookup("key2", NULL);
4816 go_assert(key1_arg != NULL && key2_arg != NULL);
4818 // Build temporaries with the right types.
4819 Type* pt = Type::make_pointer_type(name != NULL
4820 ? static_cast<Type*>(name)
4821 : static_cast<Type*>(this));
4823 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
4824 ref = Expression::make_unsafe_cast(pt, ref, bloc);
4825 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
4826 gogo->add_statement(p1);
4828 ref = Expression::make_var_reference(key2_arg, bloc);
4829 ref = Expression::make_unsafe_cast(pt, ref, bloc);
4830 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
4831 gogo->add_statement(p2);
4833 const Struct_field_list* fields = this->fields_;
4834 unsigned int field_index = 0;
4835 for (Struct_field_list::const_iterator pf = fields->begin();
4836 pf != fields->end();
4837 ++pf, ++field_index)
4839 // Compare one field in both P1 and P2.
4840 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
4841 f1 = Expression::make_unary(OPERATOR_MULT, f1, bloc);
4842 f1 = Expression::make_field_reference(f1, field_index, bloc);
4844 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
4845 f2 = Expression::make_unary(OPERATOR_MULT, f2, bloc);
4846 f2 = Expression::make_field_reference(f2, field_index, bloc);
4848 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
4850 // If the values are not equal, return false.
4851 gogo->start_block(bloc);
4852 Expression_list* vals = new Expression_list();
4853 vals->push_back(Expression::make_boolean(false, bloc));
4854 Statement* s = Statement::make_return_statement(vals, bloc);
4855 gogo->add_statement(s);
4856 Block* then_block = gogo->finish_block(bloc);
4858 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
4859 gogo->add_statement(s);
4862 // All the fields are equal, so return true.
4863 Expression_list* vals = new Expression_list();
4864 vals->push_back(Expression::make_boolean(true, bloc));
4865 Statement* s = Statement::make_return_statement(vals, bloc);
4866 gogo->add_statement(s);
4869 // Reflection string.
4872 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
4874 ret->append("struct { ");
4876 for (Struct_field_list::const_iterator p = this->fields_->begin();
4877 p != this->fields_->end();
4880 if (p != this->fields_->begin())
4882 if (p->is_anonymous())
4883 ret->push_back('?');
4885 ret->append(Gogo::unpack_hidden_name(p->field_name()));
4886 ret->push_back(' ');
4887 this->append_reflection(p->type(), gogo, ret);
4891 const std::string& tag(p->tag());
4893 for (std::string::const_iterator p = tag.begin();
4898 ret->append("\\x00");
4899 else if (*p == '\n')
4901 else if (*p == '\t')
4904 ret->append("\\\"");
4905 else if (*p == '\\')
4906 ret->append("\\\\");
4910 ret->push_back('"');
4920 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4922 ret->push_back('S');
4924 const Struct_field_list* fields = this->fields_;
4927 for (Struct_field_list::const_iterator p = fields->begin();
4931 if (p->is_anonymous())
4935 std::string n = Gogo::unpack_hidden_name(p->field_name());
4937 snprintf(buf, sizeof buf, "%u_",
4938 static_cast<unsigned int>(n.length()));
4942 this->append_mangled_name(p->type(), gogo, ret);
4945 const std::string& tag(p->tag());
4947 for (std::string::const_iterator p = tag.begin();
4951 if (ISALNUM(*p) || *p == '_')
4956 snprintf(buf, sizeof buf, ".%x.",
4957 static_cast<unsigned int>(*p));
4962 snprintf(buf, sizeof buf, "T%u_",
4963 static_cast<unsigned int>(out.length()));
4970 ret->push_back('e');
4973 // If the offset of field INDEX in the backend implementation can be
4974 // determined, set *POFFSET to the offset in bytes and return true.
4975 // Otherwise, return false.
4978 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
4979 unsigned int* poffset)
4981 if (!this->is_backend_type_size_known(gogo))
4983 Btype* bt = this->get_backend_placeholder(gogo);
4984 size_t offset = gogo->backend()->type_field_offset(bt, index);
4985 *poffset = static_cast<unsigned int>(offset);
4986 if (*poffset != offset)
4994 Struct_type::do_export(Export* exp) const
4996 exp->write_c_string("struct { ");
4997 const Struct_field_list* fields = this->fields_;
4998 go_assert(fields != NULL);
4999 for (Struct_field_list::const_iterator p = fields->begin();
5003 if (p->is_anonymous())
5004 exp->write_string("? ");
5007 exp->write_string(p->field_name());
5008 exp->write_c_string(" ");
5010 exp->write_type(p->type());
5014 exp->write_c_string(" ");
5016 Expression::make_string(p->tag(), Linemap::predeclared_location());
5017 expr->export_expression(exp);
5021 exp->write_c_string("; ");
5023 exp->write_c_string("}");
5029 Struct_type::do_import(Import* imp)
5031 imp->require_c_string("struct { ");
5032 Struct_field_list* fields = new Struct_field_list;
5033 if (imp->peek_char() != '}')
5038 if (imp->match_c_string("? "))
5042 name = imp->read_identifier();
5043 imp->require_c_string(" ");
5045 Type* ftype = imp->read_type();
5047 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
5049 if (imp->peek_char() == ' ')
5052 Expression* expr = Expression::import_expression(imp);
5053 String_expression* sexpr = expr->string_expression();
5054 go_assert(sexpr != NULL);
5055 sf.set_tag(sexpr->val());
5059 imp->require_c_string("; ");
5060 fields->push_back(sf);
5061 if (imp->peek_char() == '}')
5065 imp->require_c_string("}");
5067 return Type::make_struct_type(fields, imp->location());
5070 // Make a struct type.
5073 Type::make_struct_type(Struct_field_list* fields,
5076 return new Struct_type(fields, location);
5079 // Class Array_type.
5081 // Whether two array types are identical.
5084 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
5086 if (!Type::are_identical(this->element_type(), t->element_type(),
5087 errors_are_identical, NULL))
5090 Expression* l1 = this->length();
5091 Expression* l2 = t->length();
5093 // Slices of the same element type are identical.
5094 if (l1 == NULL && l2 == NULL)
5097 // Arrays of the same element type are identical if they have the
5099 if (l1 != NULL && l2 != NULL)
5104 // Try to determine the lengths. If we can't, assume the arrays
5105 // are not identical.
5107 Numeric_constant nc1, nc2;
5108 if (l1->numeric_constant_value(&nc1)
5109 && l2->numeric_constant_value(&nc2))
5112 if (nc1.to_int(&v1))
5115 if (nc2.to_int(&v2))
5117 ret = mpz_cmp(v1, v2) == 0;
5126 // Otherwise the arrays are not identical.
5133 Array_type::do_traverse(Traverse* traverse)
5135 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
5136 return TRAVERSE_EXIT;
5137 if (this->length_ != NULL
5138 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
5139 return TRAVERSE_EXIT;
5140 return TRAVERSE_CONTINUE;
5143 // Check that the length is valid.
5146 Array_type::verify_length()
5148 if (this->length_ == NULL)
5151 Type_context context(Type::lookup_integer_type("int"), false);
5152 this->length_->determine_type(&context);
5154 if (!this->length_->is_constant())
5156 error_at(this->length_->location(), "array bound is not constant");
5160 Numeric_constant nc;
5161 if (!this->length_->numeric_constant_value(&nc))
5163 if (this->length_->type()->integer_type() != NULL
5164 || this->length_->type()->float_type() != NULL)
5165 error_at(this->length_->location(), "array bound is not constant");
5167 error_at(this->length_->location(), "array bound is not numeric");
5172 switch (nc.to_unsigned_long(&val))
5174 case Numeric_constant::NC_UL_VALID:
5176 case Numeric_constant::NC_UL_NOTINT:
5177 error_at(this->length_->location(), "array bound truncated to integer");
5179 case Numeric_constant::NC_UL_NEGATIVE:
5180 error_at(this->length_->location(), "negative array bound");
5182 case Numeric_constant::NC_UL_BIG:
5183 error_at(this->length_->location(), "array bound overflows");
5189 Type* int_type = Type::lookup_integer_type("int");
5190 unsigned int tbits = int_type->integer_type()->bits();
5191 if (sizeof(val) <= tbits * 8
5192 && val >> (tbits - 1) != 0)
5194 error_at(this->length_->location(), "array bound overflows");
5204 Array_type::do_verify()
5206 if (!this->verify_length())
5207 this->length_ = Expression::make_error(this->length_->location());
5211 // Whether we can use memcmp to compare this array.
5214 Array_type::do_compare_is_identity(Gogo* gogo) const
5216 if (this->length_ == NULL)
5219 // Check for [...], which indicates that this is not a real type.
5220 if (this->length_->is_nil_expression())
5223 if (!this->element_type_->compare_is_identity(gogo))
5226 // If there is any padding, then we can't use memcmp.
5229 if (!this->element_type_->backend_type_size(gogo, &size)
5230 || !this->element_type_->backend_type_align(gogo, &align))
5232 if ((size & (align - 1)) != 0)
5238 // Array type hash code.
5241 Array_type::do_hash_for_method(Gogo* gogo) const
5243 // There is no very convenient way to get a hash code for the
5245 return this->element_type_->hash_for_method(gogo) + 1;
5248 // Write the hash function for an array which can not use the identify
5252 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
5253 Function_type* hash_fntype,
5254 Function_type* equal_fntype)
5256 Location bloc = Linemap::predeclared_location();
5258 // The pointer to the array that we are going to hash. This is an
5259 // argument to the hash function we are implementing here.
5260 Named_object* key_arg = gogo->lookup("key", NULL);
5261 go_assert(key_arg != NULL);
5262 Type* key_arg_type = key_arg->var_value()->type();
5264 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5268 mpz_init_set_ui(ival, 0);
5269 Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
5272 // Make a temporary to hold the return value, initialized to 0.
5273 Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
5275 gogo->add_statement(retval);
5277 // Make a temporary to hold the key as a uintptr.
5278 Expression* ref = Expression::make_var_reference(key_arg, bloc);
5279 ref = Expression::make_cast(uintptr_type, ref, bloc);
5280 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
5282 gogo->add_statement(key);
5284 // Loop over the array elements.
5286 Type* int_type = Type::lookup_integer_type("int");
5287 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
5288 gogo->add_statement(index);
5290 Expression* iref = Expression::make_temporary_reference(index, bloc);
5291 Expression* aref = Expression::make_var_reference(key_arg, bloc);
5292 Type* pt = Type::make_pointer_type(name != NULL
5293 ? static_cast<Type*>(name)
5294 : static_cast<Type*>(this));
5295 aref = Expression::make_cast(pt, aref, bloc);
5296 For_range_statement* for_range = Statement::make_for_range_statement(iref,
5301 gogo->start_block(bloc);
5303 // Multiply retval by 33.
5304 mpz_init_set_ui(ival, 33);
5305 Expression* i33 = Expression::make_integer(&ival, uintptr_type, bloc);
5308 ref = Expression::make_temporary_reference(retval, bloc);
5309 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ, ref,
5311 gogo->add_statement(s);
5313 // Get the hash function for the element type.
5314 Named_object* hash_fn;
5315 Named_object* equal_fn;
5316 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
5317 hash_fntype, equal_fntype, &hash_fn,
5320 // Get a pointer to this element in the loop.
5321 Expression* subkey = Expression::make_temporary_reference(key, bloc);
5322 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
5324 // Get the size of each element.
5325 Expression* ele_size = Expression::make_type_info(this->element_type_,
5326 Expression::TYPE_INFO_SIZE);
5328 // Get the hash of this element.
5329 Expression_list* args = new Expression_list();
5330 args->push_back(subkey);
5331 args->push_back(ele_size);
5332 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
5333 Expression* call = Expression::make_call(func, args, false, bloc);
5335 // Add the element's hash value to retval.
5336 Temporary_reference_expression* tref =
5337 Expression::make_temporary_reference(retval, bloc);
5338 tref->set_is_lvalue();
5339 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, call, bloc);
5340 gogo->add_statement(s);
5342 // Increase the element pointer.
5343 tref = Expression::make_temporary_reference(key, bloc);
5344 tref->set_is_lvalue();
5345 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
5348 Block* statements = gogo->finish_block(bloc);
5350 for_range->add_statements(statements);
5351 gogo->add_statement(for_range);
5353 // Return retval to the caller of the hash function.
5354 Expression_list* vals = new Expression_list();
5355 ref = Expression::make_temporary_reference(retval, bloc);
5356 vals->push_back(ref);
5357 s = Statement::make_return_statement(vals, bloc);
5358 gogo->add_statement(s);
5361 // Write the equality function for an array which can not use the
5362 // identity function.
5365 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
5367 Location bloc = Linemap::predeclared_location();
5369 // The pointers to the arrays we are going to compare.
5370 Named_object* key1_arg = gogo->lookup("key1", NULL);
5371 Named_object* key2_arg = gogo->lookup("key2", NULL);
5372 go_assert(key1_arg != NULL && key2_arg != NULL);
5374 // Build temporaries for the keys with the right types.
5375 Type* pt = Type::make_pointer_type(name != NULL
5376 ? static_cast<Type*>(name)
5377 : static_cast<Type*>(this));
5379 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
5380 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5381 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
5382 gogo->add_statement(p1);
5384 ref = Expression::make_var_reference(key2_arg, bloc);
5385 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5386 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
5387 gogo->add_statement(p2);
5389 // Loop over the array elements.
5391 Type* int_type = Type::lookup_integer_type("int");
5392 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
5393 gogo->add_statement(index);
5395 Expression* iref = Expression::make_temporary_reference(index, bloc);
5396 Expression* aref = Expression::make_temporary_reference(p1, bloc);
5397 For_range_statement* for_range = Statement::make_for_range_statement(iref,
5402 gogo->start_block(bloc);
5404 // Compare element in P1 and P2.
5405 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
5406 e1 = Expression::make_unary(OPERATOR_MULT, e1, bloc);
5407 ref = Expression::make_temporary_reference(index, bloc);
5408 e1 = Expression::make_array_index(e1, ref, NULL, bloc);
5410 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
5411 e2 = Expression::make_unary(OPERATOR_MULT, e2, bloc);
5412 ref = Expression::make_temporary_reference(index, bloc);
5413 e2 = Expression::make_array_index(e2, ref, NULL, bloc);
5415 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
5417 // If the elements are not equal, return false.
5418 gogo->start_block(bloc);
5419 Expression_list* vals = new Expression_list();
5420 vals->push_back(Expression::make_boolean(false, bloc));
5421 Statement* s = Statement::make_return_statement(vals, bloc);
5422 gogo->add_statement(s);
5423 Block* then_block = gogo->finish_block(bloc);
5425 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
5426 gogo->add_statement(s);
5428 Block* statements = gogo->finish_block(bloc);
5430 for_range->add_statements(statements);
5431 gogo->add_statement(for_range);
5433 // All the elements are equal, so return true.
5434 vals = new Expression_list();
5435 vals->push_back(Expression::make_boolean(true, bloc));
5436 s = Statement::make_return_statement(vals, bloc);
5437 gogo->add_statement(s);
5440 // Get a tree for the length of a fixed array. The length may be
5441 // computed using a function call, so we must only evaluate it once.
5444 Array_type::get_length_tree(Gogo* gogo)
5446 go_assert(this->length_ != NULL);
5447 if (this->length_tree_ == NULL_TREE)
5449 Numeric_constant nc;
5451 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
5453 if (mpz_sgn(val) < 0)
5455 this->length_tree_ = error_mark_node;
5456 return this->length_tree_;
5458 Type* t = nc.type();
5460 t = Type::lookup_integer_type("int");
5461 else if (t->is_abstract())
5462 t = t->make_non_abstract_type();
5463 tree tt = type_to_tree(t->get_backend(gogo));
5464 this->length_tree_ = Expression::integer_constant_tree(val, tt);
5469 // Make up a translation context for the array length
5470 // expression. FIXME: This won't work in general.
5471 Translate_context context(gogo, NULL, NULL, NULL);
5472 tree len = this->length_->get_tree(&context);
5473 if (len != error_mark_node)
5475 len = convert_to_integer(integer_type_node, len);
5476 len = save_expr(len);
5478 this->length_tree_ = len;
5481 return this->length_tree_;
5484 // Get the backend representation of the fields of a slice. This is
5485 // not declared in types.h so that types.h doesn't have to #include
5488 // We use int for the count and capacity fields. This matches 6g.
5489 // The language more or less assumes that we can't allocate space of a
5490 // size which does not fit in int.
5493 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
5494 std::vector<Backend::Btyped_identifier>* bfields)
5498 Type* pet = Type::make_pointer_type(type->element_type());
5499 Btype* pbet = (use_placeholder
5500 ? pet->get_backend_placeholder(gogo)
5501 : pet->get_backend(gogo));
5502 Location ploc = Linemap::predeclared_location();
5504 Backend::Btyped_identifier* p = &(*bfields)[0];
5505 p->name = "__values";
5509 Type* int_type = Type::lookup_integer_type("int");
5512 p->name = "__count";
5513 p->btype = int_type->get_backend(gogo);
5517 p->name = "__capacity";
5518 p->btype = int_type->get_backend(gogo);
5522 // Get a tree for the type of this array. A fixed array is simply
5523 // represented as ARRAY_TYPE with the appropriate index--i.e., it is
5524 // just like an array in C. An open array is a struct with three
5525 // fields: a data pointer, the length, and the capacity.
5528 Array_type::do_get_backend(Gogo* gogo)
5530 if (this->length_ == NULL)
5532 std::vector<Backend::Btyped_identifier> bfields;
5533 get_backend_slice_fields(gogo, this, false, &bfields);
5534 return gogo->backend()->struct_type(bfields);
5538 Btype* element = this->get_backend_element(gogo, false);
5539 Bexpression* len = this->get_backend_length(gogo);
5540 return gogo->backend()->array_type(element, len);
5544 // Return the backend representation of the element type.
5547 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
5549 if (use_placeholder)
5550 return this->element_type_->get_backend_placeholder(gogo);
5552 return this->element_type_->get_backend(gogo);
5555 // Return the backend representation of the length.
5558 Array_type::get_backend_length(Gogo* gogo)
5560 return tree_to_expr(this->get_length_tree(gogo));
5563 // Finish backend representation of the array.
5566 Array_type::finish_backend_element(Gogo* gogo)
5568 Type* et = this->array_type()->element_type();
5569 et->get_backend(gogo);
5570 if (this->is_slice_type())
5572 // This relies on the fact that we always use the same
5573 // structure for a pointer to any given type.
5574 Type* pet = Type::make_pointer_type(et);
5575 pet->get_backend(gogo);
5579 // Return a tree for a pointer to the values in ARRAY.
5582 Array_type::value_pointer_tree(Gogo*, tree array) const
5585 if (this->length() != NULL)
5588 ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))),
5589 build_fold_addr_expr(array));
5594 tree field = TYPE_FIELDS(TREE_TYPE(array));
5595 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
5597 ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field,
5600 if (TREE_CONSTANT(array))
5601 TREE_CONSTANT(ret) = 1;
5605 // Return a tree for the length of the array ARRAY which has this
5609 Array_type::length_tree(Gogo* gogo, tree array)
5611 if (this->length_ != NULL)
5613 if (TREE_CODE(array) == SAVE_EXPR)
5614 return fold_convert(integer_type_node, this->get_length_tree(gogo));
5616 return omit_one_operand(integer_type_node,
5617 this->get_length_tree(gogo), array);
5620 // This is an open array. We need to read the length field.
5622 tree type = TREE_TYPE(array);
5623 go_assert(TREE_CODE(type) == RECORD_TYPE);
5625 tree field = DECL_CHAIN(TYPE_FIELDS(type));
5626 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
5628 tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
5629 if (TREE_CONSTANT(array))
5630 TREE_CONSTANT(ret) = 1;
5634 // Return a tree for the capacity of the array ARRAY which has this
5638 Array_type::capacity_tree(Gogo* gogo, tree array)
5640 if (this->length_ != NULL)
5641 return omit_one_operand(integer_type_node, this->get_length_tree(gogo),
5644 // This is an open array. We need to read the capacity field.
5646 tree type = TREE_TYPE(array);
5647 go_assert(TREE_CODE(type) == RECORD_TYPE);
5649 tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type)));
5650 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
5652 return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
5658 Array_type::do_export(Export* exp) const
5660 exp->write_c_string("[");
5661 if (this->length_ != NULL)
5662 this->length_->export_expression(exp);
5663 exp->write_c_string("] ");
5664 exp->write_type(this->element_type_);
5670 Array_type::do_import(Import* imp)
5672 imp->require_c_string("[");
5674 if (imp->peek_char() == ']')
5677 length = Expression::import_expression(imp);
5678 imp->require_c_string("] ");
5679 Type* element_type = imp->read_type();
5680 return Type::make_array_type(element_type, length);
5683 // The type of an array type descriptor.
5686 Array_type::make_array_type_descriptor_type()
5691 Type* tdt = Type::make_type_descriptor_type();
5692 Type* ptdt = Type::make_type_descriptor_ptr_type();
5694 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5697 Type::make_builtin_struct_type(4,
5701 "len", uintptr_type);
5703 ret = Type::make_builtin_named_type("ArrayType", sf);
5709 // The type of an slice type descriptor.
5712 Array_type::make_slice_type_descriptor_type()
5717 Type* tdt = Type::make_type_descriptor_type();
5718 Type* ptdt = Type::make_type_descriptor_ptr_type();
5721 Type::make_builtin_struct_type(2,
5725 ret = Type::make_builtin_named_type("SliceType", sf);
5731 // Build a type descriptor for an array/slice type.
5734 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5736 if (this->length_ != NULL)
5737 return this->array_type_descriptor(gogo, name);
5739 return this->slice_type_descriptor(gogo, name);
5742 // Build a type descriptor for an array type.
5745 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
5747 Location bloc = Linemap::predeclared_location();
5749 Type* atdt = Array_type::make_array_type_descriptor_type();
5751 const Struct_field_list* fields = atdt->struct_type()->fields();
5753 Expression_list* vals = new Expression_list();
5756 Struct_field_list::const_iterator p = fields->begin();
5757 go_assert(p->is_field_name("commonType"));
5758 vals->push_back(this->type_descriptor_constructor(gogo,
5759 RUNTIME_TYPE_KIND_ARRAY,
5763 go_assert(p->is_field_name("elem"));
5764 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5767 go_assert(p->is_field_name("slice"));
5768 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
5769 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
5772 go_assert(p->is_field_name("len"));
5773 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
5776 go_assert(p == fields->end());
5778 return Expression::make_struct_composite_literal(atdt, vals, bloc);
5781 // Build a type descriptor for a slice type.
5784 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
5786 Location bloc = Linemap::predeclared_location();
5788 Type* stdt = Array_type::make_slice_type_descriptor_type();
5790 const Struct_field_list* fields = stdt->struct_type()->fields();
5792 Expression_list* vals = new Expression_list();
5795 Struct_field_list::const_iterator p = fields->begin();
5796 go_assert(p->is_field_name("commonType"));
5797 vals->push_back(this->type_descriptor_constructor(gogo,
5798 RUNTIME_TYPE_KIND_SLICE,
5802 go_assert(p->is_field_name("elem"));
5803 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5806 go_assert(p == fields->end());
5808 return Expression::make_struct_composite_literal(stdt, vals, bloc);
5811 // Reflection string.
5814 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
5816 ret->push_back('[');
5817 if (this->length_ != NULL)
5819 Numeric_constant nc;
5821 if (!this->length_->numeric_constant_value(&nc)
5822 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
5823 error_at(this->length_->location(), "invalid array length");
5827 snprintf(buf, sizeof buf, "%lu", val);
5831 ret->push_back(']');
5833 this->append_reflection(this->element_type_, gogo, ret);
5839 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5841 ret->push_back('A');
5842 this->append_mangled_name(this->element_type_, gogo, ret);
5843 if (this->length_ != NULL)
5845 Numeric_constant nc;
5847 if (!this->length_->numeric_constant_value(&nc)
5848 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
5849 error_at(this->length_->location(), "invalid array length");
5853 snprintf(buf, sizeof buf, "%lu", val);
5857 ret->push_back('e');
5860 // Make an array type.
5863 Type::make_array_type(Type* element_type, Expression* length)
5865 return new Array_type(element_type, length);
5873 Map_type::do_traverse(Traverse* traverse)
5875 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
5876 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
5877 return TRAVERSE_EXIT;
5878 return TRAVERSE_CONTINUE;
5881 // Check that the map type is OK.
5884 Map_type::do_verify()
5886 // The runtime support uses "map[void]void".
5887 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
5888 error_at(this->location_, "invalid map key type");
5892 // Whether two map types are identical.
5895 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
5897 return (Type::are_identical(this->key_type(), t->key_type(),
5898 errors_are_identical, NULL)
5899 && Type::are_identical(this->val_type(), t->val_type(),
5900 errors_are_identical, NULL));
5906 Map_type::do_hash_for_method(Gogo* gogo) const
5908 return (this->key_type_->hash_for_method(gogo)
5909 + this->val_type_->hash_for_method(gogo)
5913 // Get the backend representation for a map type. A map type is
5914 // represented as a pointer to a struct. The struct is __go_map in
5918 Map_type::do_get_backend(Gogo* gogo)
5920 static Btype* backend_map_type;
5921 if (backend_map_type == NULL)
5923 std::vector<Backend::Btyped_identifier> bfields(4);
5925 Location bloc = Linemap::predeclared_location();
5927 Type* pdt = Type::make_type_descriptor_ptr_type();
5928 bfields[0].name = "__descriptor";
5929 bfields[0].btype = pdt->get_backend(gogo);
5930 bfields[0].location = bloc;
5932 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5933 bfields[1].name = "__element_count";
5934 bfields[1].btype = uintptr_type->get_backend(gogo);
5935 bfields[1].location = bloc;
5937 bfields[2].name = "__bucket_count";
5938 bfields[2].btype = bfields[1].btype;
5939 bfields[2].location = bloc;
5941 Btype* bvt = gogo->backend()->void_type();
5942 Btype* bpvt = gogo->backend()->pointer_type(bvt);
5943 Btype* bppvt = gogo->backend()->pointer_type(bpvt);
5944 bfields[3].name = "__buckets";
5945 bfields[3].btype = bppvt;
5946 bfields[3].location = bloc;
5948 Btype *bt = gogo->backend()->struct_type(bfields);
5949 bt = gogo->backend()->named_type("__go_map", bt, bloc);
5950 backend_map_type = gogo->backend()->pointer_type(bt);
5952 return backend_map_type;
5955 // The type of a map type descriptor.
5958 Map_type::make_map_type_descriptor_type()
5963 Type* tdt = Type::make_type_descriptor_type();
5964 Type* ptdt = Type::make_type_descriptor_ptr_type();
5967 Type::make_builtin_struct_type(3,
5972 ret = Type::make_builtin_named_type("MapType", sf);
5978 // Build a type descriptor for a map type.
5981 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5983 Location bloc = Linemap::predeclared_location();
5985 Type* mtdt = Map_type::make_map_type_descriptor_type();
5987 const Struct_field_list* fields = mtdt->struct_type()->fields();
5989 Expression_list* vals = new Expression_list();
5992 Struct_field_list::const_iterator p = fields->begin();
5993 go_assert(p->is_field_name("commonType"));
5994 vals->push_back(this->type_descriptor_constructor(gogo,
5995 RUNTIME_TYPE_KIND_MAP,
5999 go_assert(p->is_field_name("key"));
6000 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
6003 go_assert(p->is_field_name("elem"));
6004 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
6007 go_assert(p == fields->end());
6009 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
6012 // A mapping from map types to map descriptors.
6014 Map_type::Map_descriptors Map_type::map_descriptors;
6016 // Build a map descriptor for this type. Return a pointer to it.
6019 Map_type::map_descriptor_pointer(Gogo* gogo, Location location)
6021 Bvariable* bvar = this->map_descriptor(gogo);
6022 tree var_tree = var_to_tree(bvar);
6023 if (var_tree == error_mark_node)
6024 return error_mark_node;
6025 return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
6028 // Build a map descriptor for this type.
6031 Map_type::map_descriptor(Gogo* gogo)
6033 std::pair<Map_type*, Bvariable*> val(this, NULL);
6034 std::pair<Map_type::Map_descriptors::iterator, bool> ins =
6035 Map_type::map_descriptors.insert(val);
6037 return ins.first->second;
6039 Type* key_type = this->key_type_;
6040 Type* val_type = this->val_type_;
6042 // The map entry type is a struct with three fields. Build that
6043 // struct so that we can get the offsets of the key and value within
6044 // a map entry. The first field should technically be a pointer to
6045 // this type itself, but since we only care about field offsets we
6046 // just use pointer to bool.
6047 Type* pbool = Type::make_pointer_type(Type::make_boolean_type());
6048 Struct_type* map_entry_type =
6049 Type::make_builtin_struct_type(3,
6054 Type* map_descriptor_type = Map_type::make_map_descriptor_type();
6056 const Struct_field_list* fields =
6057 map_descriptor_type->struct_type()->fields();
6059 Expression_list* vals = new Expression_list();
6062 Location bloc = Linemap::predeclared_location();
6064 Struct_field_list::const_iterator p = fields->begin();
6066 go_assert(p->is_field_name("__map_descriptor"));
6067 vals->push_back(Expression::make_type_descriptor(this, bloc));
6070 go_assert(p->is_field_name("__entry_size"));
6071 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
6072 vals->push_back(Expression::make_type_info(map_entry_type, type_info));
6074 Struct_field_list::const_iterator pf = map_entry_type->fields()->begin();
6076 go_assert(pf->is_field_name("__key"));
6079 go_assert(p->is_field_name("__key_offset"));
6080 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6083 go_assert(pf->is_field_name("__val"));
6086 go_assert(p->is_field_name("__val_offset"));
6087 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6090 go_assert(p == fields->end());
6092 Expression* initializer =
6093 Expression::make_struct_composite_literal(map_descriptor_type, vals, bloc);
6095 std::string mangled_name = "__go_map_" + this->mangled_name(gogo);
6096 Btype* map_descriptor_btype = map_descriptor_type->get_backend(gogo);
6097 Bvariable* bvar = gogo->backend()->immutable_struct(mangled_name, true,
6098 map_descriptor_btype,
6101 Translate_context context(gogo, NULL, NULL, NULL);
6102 context.set_is_const();
6103 Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
6105 gogo->backend()->immutable_struct_set_init(bvar, mangled_name, true,
6106 map_descriptor_btype, bloc,
6109 ins.first->second = bvar;
6113 // Build the type of a map descriptor. This must match the struct
6114 // __go_map_descriptor in libgo/runtime/map.h.
6117 Map_type::make_map_descriptor_type()
6122 Type* ptdt = Type::make_type_descriptor_ptr_type();
6123 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6125 Type::make_builtin_struct_type(4,
6126 "__map_descriptor", ptdt,
6127 "__entry_size", uintptr_type,
6128 "__key_offset", uintptr_type,
6129 "__val_offset", uintptr_type);
6130 ret = Type::make_builtin_named_type("__go_map_descriptor", sf);
6135 // Reflection string for a map.
6138 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
6140 ret->append("map[");
6141 this->append_reflection(this->key_type_, gogo, ret);
6143 this->append_reflection(this->val_type_, gogo, ret);
6146 // Mangled name for a map.
6149 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6151 ret->push_back('M');
6152 this->append_mangled_name(this->key_type_, gogo, ret);
6154 this->append_mangled_name(this->val_type_, gogo, ret);
6157 // Export a map type.
6160 Map_type::do_export(Export* exp) const
6162 exp->write_c_string("map [");
6163 exp->write_type(this->key_type_);
6164 exp->write_c_string("] ");
6165 exp->write_type(this->val_type_);
6168 // Import a map type.
6171 Map_type::do_import(Import* imp)
6173 imp->require_c_string("map [");
6174 Type* key_type = imp->read_type();
6175 imp->require_c_string("] ");
6176 Type* val_type = imp->read_type();
6177 return Type::make_map_type(key_type, val_type, imp->location());
6183 Type::make_map_type(Type* key_type, Type* val_type, Location location)
6185 return new Map_type(key_type, val_type, location);
6188 // Class Channel_type.
6193 Channel_type::do_hash_for_method(Gogo* gogo) const
6195 unsigned int ret = 0;
6196 if (this->may_send_)
6198 if (this->may_receive_)
6200 if (this->element_type_ != NULL)
6201 ret += this->element_type_->hash_for_method(gogo) << 2;
6205 // Whether this type is the same as T.
6208 Channel_type::is_identical(const Channel_type* t,
6209 bool errors_are_identical) const
6211 if (!Type::are_identical(this->element_type(), t->element_type(),
6212 errors_are_identical, NULL))
6214 return (this->may_send_ == t->may_send_
6215 && this->may_receive_ == t->may_receive_);
6218 // Return the tree for a channel type. A channel is a pointer to a
6219 // __go_channel struct. The __go_channel struct is defined in
6220 // libgo/runtime/channel.h.
6223 Channel_type::do_get_backend(Gogo* gogo)
6225 static Btype* backend_channel_type;
6226 if (backend_channel_type == NULL)
6228 std::vector<Backend::Btyped_identifier> bfields;
6229 Btype* bt = gogo->backend()->struct_type(bfields);
6230 bt = gogo->backend()->named_type("__go_channel", bt,
6231 Linemap::predeclared_location());
6232 backend_channel_type = gogo->backend()->pointer_type(bt);
6234 return backend_channel_type;
6237 // Build a type descriptor for a channel type.
6240 Channel_type::make_chan_type_descriptor_type()
6245 Type* tdt = Type::make_type_descriptor_type();
6246 Type* ptdt = Type::make_type_descriptor_ptr_type();
6248 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6251 Type::make_builtin_struct_type(3,
6254 "dir", uintptr_type);
6256 ret = Type::make_builtin_named_type("ChanType", sf);
6262 // Build a type descriptor for a map type.
6265 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6267 Location bloc = Linemap::predeclared_location();
6269 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
6271 const Struct_field_list* fields = ctdt->struct_type()->fields();
6273 Expression_list* vals = new Expression_list();
6276 Struct_field_list::const_iterator p = fields->begin();
6277 go_assert(p->is_field_name("commonType"));
6278 vals->push_back(this->type_descriptor_constructor(gogo,
6279 RUNTIME_TYPE_KIND_CHAN,
6283 go_assert(p->is_field_name("elem"));
6284 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
6287 go_assert(p->is_field_name("dir"));
6288 // These bits must match the ones in libgo/runtime/go-type.h.
6290 if (this->may_receive_)
6292 if (this->may_send_)
6295 mpz_init_set_ui(iv, val);
6296 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
6300 go_assert(p == fields->end());
6302 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
6305 // Reflection string.
6308 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
6310 if (!this->may_send_)
6312 ret->append("chan");
6313 if (!this->may_receive_)
6315 ret->push_back(' ');
6316 this->append_reflection(this->element_type_, gogo, ret);
6322 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6324 ret->push_back('C');
6325 this->append_mangled_name(this->element_type_, gogo, ret);
6326 if (this->may_send_)
6327 ret->push_back('s');
6328 if (this->may_receive_)
6329 ret->push_back('r');
6330 ret->push_back('e');
6336 Channel_type::do_export(Export* exp) const
6338 exp->write_c_string("chan ");
6339 if (this->may_send_ && !this->may_receive_)
6340 exp->write_c_string("-< ");
6341 else if (this->may_receive_ && !this->may_send_)
6342 exp->write_c_string("<- ");
6343 exp->write_type(this->element_type_);
6349 Channel_type::do_import(Import* imp)
6351 imp->require_c_string("chan ");
6355 if (imp->match_c_string("-< "))
6359 may_receive = false;
6361 else if (imp->match_c_string("<- "))
6373 Type* element_type = imp->read_type();
6375 return Type::make_channel_type(may_send, may_receive, element_type);
6378 // Make a new channel type.
6381 Type::make_channel_type(bool send, bool receive, Type* element_type)
6383 return new Channel_type(send, receive, element_type);
6386 // Class Interface_type.
6391 Interface_type::do_traverse(Traverse* traverse)
6393 Typed_identifier_list* methods = (this->methods_are_finalized_
6394 ? this->all_methods_
6395 : this->parse_methods_);
6396 if (methods == NULL)
6397 return TRAVERSE_CONTINUE;
6398 return methods->traverse(traverse);
6401 // Finalize the methods. This handles interface inheritance.
6404 Interface_type::finalize_methods()
6406 if (this->methods_are_finalized_)
6408 this->methods_are_finalized_ = true;
6409 if (this->parse_methods_ == NULL)
6412 this->all_methods_ = new Typed_identifier_list();
6413 this->all_methods_->reserve(this->parse_methods_->size());
6414 Typed_identifier_list inherit;
6415 for (Typed_identifier_list::const_iterator pm =
6416 this->parse_methods_->begin();
6417 pm != this->parse_methods_->end();
6420 const Typed_identifier* p = &*pm;
6421 if (p->name().empty())
6422 inherit.push_back(*p);
6423 else if (this->find_method(p->name()) == NULL)
6424 this->all_methods_->push_back(*p);
6426 error_at(p->location(), "duplicate method %qs",
6427 Gogo::message_name(p->name()).c_str());
6430 std::vector<Named_type*> seen;
6431 seen.reserve(inherit.size());
6432 bool issued_recursive_error = false;
6433 while (!inherit.empty())
6435 Type* t = inherit.back().type();
6436 Location tl = inherit.back().location();
6439 Interface_type* it = t->interface_type();
6443 error_at(tl, "interface contains embedded non-interface");
6448 if (!issued_recursive_error)
6450 error_at(tl, "invalid recursive interface");
6451 issued_recursive_error = true;
6456 Named_type* nt = t->named_type();
6457 if (nt != NULL && it->parse_methods_ != NULL)
6459 std::vector<Named_type*>::const_iterator q;
6460 for (q = seen.begin(); q != seen.end(); ++q)
6464 error_at(tl, "inherited interface loop");
6468 if (q != seen.end())
6473 const Typed_identifier_list* imethods = it->parse_methods_;
6474 if (imethods == NULL)
6476 for (Typed_identifier_list::const_iterator q = imethods->begin();
6477 q != imethods->end();
6480 if (q->name().empty())
6481 inherit.push_back(*q);
6482 else if (this->find_method(q->name()) == NULL)
6483 this->all_methods_->push_back(Typed_identifier(q->name(),
6486 error_at(tl, "inherited method %qs is ambiguous",
6487 Gogo::message_name(q->name()).c_str());
6491 if (!this->all_methods_->empty())
6492 this->all_methods_->sort_by_name();
6495 delete this->all_methods_;
6496 this->all_methods_ = NULL;
6500 // Return the method NAME, or NULL.
6502 const Typed_identifier*
6503 Interface_type::find_method(const std::string& name) const
6505 go_assert(this->methods_are_finalized_);
6506 if (this->all_methods_ == NULL)
6508 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6509 p != this->all_methods_->end();
6511 if (p->name() == name)
6516 // Return the method index.
6519 Interface_type::method_index(const std::string& name) const
6521 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
6523 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6524 p != this->all_methods_->end();
6526 if (p->name() == name)
6531 // Return whether NAME is an unexported method, for better error
6535 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
6537 go_assert(this->methods_are_finalized_);
6538 if (this->all_methods_ == NULL)
6540 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6541 p != this->all_methods_->end();
6544 const std::string& method_name(p->name());
6545 if (Gogo::is_hidden_name(method_name)
6546 && name == Gogo::unpack_hidden_name(method_name)
6547 && gogo->pack_hidden_name(name, false) != method_name)
6553 // Whether this type is identical with T.
6556 Interface_type::is_identical(const Interface_type* t,
6557 bool errors_are_identical) const
6559 // If methods have not been finalized, then we are asking whether
6560 // func redeclarations are the same. This is an error, so for
6561 // simplicity we say they are never the same.
6562 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
6565 // We require the same methods with the same types. The methods
6566 // have already been sorted.
6567 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
6568 return this->all_methods_ == t->all_methods_;
6570 if (this->assume_identical(this, t) || t->assume_identical(t, this))
6573 Assume_identical* hold_ai = this->assume_identical_;
6574 Assume_identical ai;
6578 this->assume_identical_ = &ai;
6580 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
6581 Typed_identifier_list::const_iterator p2;
6582 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
6584 if (p1 == this->all_methods_->end())
6586 if (p1->name() != p2->name()
6587 || !Type::are_identical(p1->type(), p2->type(),
6588 errors_are_identical, NULL))
6592 this->assume_identical_ = hold_ai;
6594 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
6597 // Return true if T1 and T2 are assumed to be identical during a type
6601 Interface_type::assume_identical(const Interface_type* t1,
6602 const Interface_type* t2) const
6604 for (Assume_identical* p = this->assume_identical_;
6607 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
6612 // Whether we can assign the interface type T to this type. The types
6613 // are known to not be identical. An interface assignment is only
6614 // permitted if T is known to implement all methods in THIS.
6615 // Otherwise a type guard is required.
6618 Interface_type::is_compatible_for_assign(const Interface_type* t,
6619 std::string* reason) const
6621 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
6622 if (this->all_methods_ == NULL)
6624 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6625 p != this->all_methods_->end();
6628 const Typed_identifier* m = t->find_method(p->name());
6634 snprintf(buf, sizeof buf,
6635 _("need explicit conversion; missing method %s%s%s"),
6636 open_quote, Gogo::message_name(p->name()).c_str(),
6638 reason->assign(buf);
6643 std::string subreason;
6644 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
6648 std::string n = Gogo::message_name(p->name());
6649 size_t len = 100 + n.length() + subreason.length();
6650 char* buf = new char[len];
6651 if (subreason.empty())
6652 snprintf(buf, len, _("incompatible type for method %s%s%s"),
6653 open_quote, n.c_str(), close_quote);
6656 _("incompatible type for method %s%s%s (%s)"),
6657 open_quote, n.c_str(), close_quote,
6659 reason->assign(buf);
6672 Interface_type::do_hash_for_method(Gogo*) const
6674 go_assert(this->methods_are_finalized_);
6675 unsigned int ret = 0;
6676 if (this->all_methods_ != NULL)
6678 for (Typed_identifier_list::const_iterator p =
6679 this->all_methods_->begin();
6680 p != this->all_methods_->end();
6683 ret = Type::hash_string(p->name(), ret);
6684 // We don't use the method type in the hash, to avoid
6685 // infinite recursion if an interface method uses a type
6686 // which is an interface which inherits from the interface
6688 // type T interface { F() interface {T}}
6695 // Return true if T implements the interface. If it does not, and
6696 // REASON is not NULL, set *REASON to a useful error message.
6699 Interface_type::implements_interface(const Type* t, std::string* reason) const
6701 go_assert(this->methods_are_finalized_);
6702 if (this->all_methods_ == NULL)
6705 bool is_pointer = false;
6706 const Named_type* nt = t->named_type();
6707 const Struct_type* st = t->struct_type();
6708 // If we start with a named type, we don't dereference it to find
6712 const Type* pt = t->points_to();
6715 // If T is a pointer to a named type, then we need to look at
6716 // the type to which it points.
6718 nt = pt->named_type();
6719 st = pt->struct_type();
6723 // If we have a named type, get the methods from it rather than from
6728 // Only named and struct types have methods.
6729 if (nt == NULL && st == NULL)
6733 if (t->points_to() != NULL
6734 && t->points_to()->interface_type() != NULL)
6735 reason->assign(_("pointer to interface type has no methods"));
6737 reason->assign(_("type has no methods"));
6742 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
6746 if (t->points_to() != NULL
6747 && t->points_to()->interface_type() != NULL)
6748 reason->assign(_("pointer to interface type has no methods"));
6750 reason->assign(_("type has no methods"));
6755 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6756 p != this->all_methods_->end();
6759 bool is_ambiguous = false;
6760 Method* m = (nt != NULL
6761 ? nt->method_function(p->name(), &is_ambiguous)
6762 : st->method_function(p->name(), &is_ambiguous));
6767 std::string n = Gogo::message_name(p->name());
6768 size_t len = n.length() + 100;
6769 char* buf = new char[len];
6771 snprintf(buf, len, _("ambiguous method %s%s%s"),
6772 open_quote, n.c_str(), close_quote);
6774 snprintf(buf, len, _("missing method %s%s%s"),
6775 open_quote, n.c_str(), close_quote);
6776 reason->assign(buf);
6782 Function_type *p_fn_type = p->type()->function_type();
6783 Function_type* m_fn_type = m->type()->function_type();
6784 go_assert(p_fn_type != NULL && m_fn_type != NULL);
6785 std::string subreason;
6786 if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
6790 std::string n = Gogo::message_name(p->name());
6791 size_t len = 100 + n.length() + subreason.length();
6792 char* buf = new char[len];
6793 if (subreason.empty())
6794 snprintf(buf, len, _("incompatible type for method %s%s%s"),
6795 open_quote, n.c_str(), close_quote);
6798 _("incompatible type for method %s%s%s (%s)"),
6799 open_quote, n.c_str(), close_quote,
6801 reason->assign(buf);
6807 if (!is_pointer && !m->is_value_method())
6811 std::string n = Gogo::message_name(p->name());
6812 size_t len = 100 + n.length();
6813 char* buf = new char[len];
6814 snprintf(buf, len, _("method %s%s%s requires a pointer"),
6815 open_quote, n.c_str(), close_quote);
6816 reason->assign(buf);
6826 // Return the backend representation of the empty interface type. We
6827 // use the same struct for all empty interfaces.
6830 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
6832 static Btype* empty_interface_type;
6833 if (empty_interface_type == NULL)
6835 std::vector<Backend::Btyped_identifier> bfields(2);
6837 Location bloc = Linemap::predeclared_location();
6839 Type* pdt = Type::make_type_descriptor_ptr_type();
6840 bfields[0].name = "__type_descriptor";
6841 bfields[0].btype = pdt->get_backend(gogo);
6842 bfields[0].location = bloc;
6844 Type* vt = Type::make_pointer_type(Type::make_void_type());
6845 bfields[1].name = "__object";
6846 bfields[1].btype = vt->get_backend(gogo);
6847 bfields[1].location = bloc;
6849 empty_interface_type = gogo->backend()->struct_type(bfields);
6851 return empty_interface_type;
6854 // Return the fields of a non-empty interface type. This is not
6855 // declared in types.h so that types.h doesn't have to #include
6859 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
6860 bool use_placeholder,
6861 std::vector<Backend::Btyped_identifier>* bfields)
6863 Location loc = type->location();
6865 std::vector<Backend::Btyped_identifier> mfields(type->methods()->size() + 1);
6867 Type* pdt = Type::make_type_descriptor_ptr_type();
6868 mfields[0].name = "__type_descriptor";
6869 mfields[0].btype = pdt->get_backend(gogo);
6870 mfields[0].location = loc;
6872 std::string last_name = "";
6874 for (Typed_identifier_list::const_iterator p = type->methods()->begin();
6875 p != type->methods()->end();
6878 // The type of the method in Go only includes the parameters.
6879 // The actual method also has a receiver, which is always a
6880 // pointer. We need to add that pointer type here in order to
6881 // generate the correct type for the backend.
6882 Function_type* ft = p->type()->function_type();
6883 go_assert(ft->receiver() == NULL);
6885 const Typed_identifier_list* params = ft->parameters();
6886 Typed_identifier_list* mparams = new Typed_identifier_list();
6888 mparams->reserve(params->size() + 1);
6889 Type* vt = Type::make_pointer_type(Type::make_void_type());
6890 mparams->push_back(Typed_identifier("", vt, ft->location()));
6893 for (Typed_identifier_list::const_iterator pp = params->begin();
6894 pp != params->end();
6896 mparams->push_back(*pp);
6899 Typed_identifier_list* mresults = (ft->results() == NULL
6901 : ft->results()->copy());
6902 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
6905 mfields[i].name = Gogo::unpack_hidden_name(p->name());
6906 mfields[i].btype = (use_placeholder
6907 ? mft->get_backend_placeholder(gogo)
6908 : mft->get_backend(gogo));
6909 mfields[i].location = loc;
6910 // Sanity check: the names should be sorted.
6911 go_assert(p->name() > last_name);
6912 last_name = p->name();
6915 Btype* methods = gogo->backend()->struct_type(mfields);
6919 (*bfields)[0].name = "__methods";
6920 (*bfields)[0].btype = gogo->backend()->pointer_type(methods);
6921 (*bfields)[0].location = loc;
6923 Type* vt = Type::make_pointer_type(Type::make_void_type());
6924 (*bfields)[1].name = "__object";
6925 (*bfields)[1].btype = vt->get_backend(gogo);
6926 (*bfields)[1].location = Linemap::predeclared_location();
6929 // Return a tree for an interface type. An interface is a pointer to
6930 // a struct. The struct has three fields. The first field is a
6931 // pointer to the type descriptor for the dynamic type of the object.
6932 // The second field is a pointer to a table of methods for the
6933 // interface to be used with the object. The third field is the value
6934 // of the object itself.
6937 Interface_type::do_get_backend(Gogo* gogo)
6939 if (this->is_empty())
6940 return Interface_type::get_backend_empty_interface_type(gogo);
6943 if (this->interface_btype_ != NULL)
6944 return this->interface_btype_;
6945 this->interface_btype_ =
6946 gogo->backend()->placeholder_struct_type("", this->location_);
6947 std::vector<Backend::Btyped_identifier> bfields;
6948 get_backend_interface_fields(gogo, this, false, &bfields);
6949 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
6951 this->interface_btype_ = gogo->backend()->error_type();
6952 return this->interface_btype_;
6956 // Finish the backend representation of the methods.
6959 Interface_type::finish_backend_methods(Gogo* gogo)
6961 if (!this->interface_type()->is_empty())
6963 const Typed_identifier_list* methods = this->methods();
6964 if (methods != NULL)
6966 for (Typed_identifier_list::const_iterator p = methods->begin();
6967 p != methods->end();
6969 p->type()->get_backend(gogo);
6974 // The type of an interface type descriptor.
6977 Interface_type::make_interface_type_descriptor_type()
6982 Type* tdt = Type::make_type_descriptor_type();
6983 Type* ptdt = Type::make_type_descriptor_ptr_type();
6985 Type* string_type = Type::lookup_string_type();
6986 Type* pointer_string_type = Type::make_pointer_type(string_type);
6989 Type::make_builtin_struct_type(3,
6990 "name", pointer_string_type,
6991 "pkgPath", pointer_string_type,
6994 Type* nsm = Type::make_builtin_named_type("imethod", sm);
6996 Type* slice_nsm = Type::make_array_type(nsm, NULL);
6998 Struct_type* s = Type::make_builtin_struct_type(2,
7000 "methods", slice_nsm);
7002 ret = Type::make_builtin_named_type("InterfaceType", s);
7008 // Build a type descriptor for an interface type.
7011 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7013 Location bloc = Linemap::predeclared_location();
7015 Type* itdt = Interface_type::make_interface_type_descriptor_type();
7017 const Struct_field_list* ifields = itdt->struct_type()->fields();
7019 Expression_list* ivals = new Expression_list();
7022 Struct_field_list::const_iterator pif = ifields->begin();
7023 go_assert(pif->is_field_name("commonType"));
7024 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
7025 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
7029 go_assert(pif->is_field_name("methods"));
7031 Expression_list* methods = new Expression_list();
7032 if (this->all_methods_ != NULL)
7034 Type* elemtype = pif->type()->array_type()->element_type();
7036 methods->reserve(this->all_methods_->size());
7037 for (Typed_identifier_list::const_iterator pm =
7038 this->all_methods_->begin();
7039 pm != this->all_methods_->end();
7042 const Struct_field_list* mfields = elemtype->struct_type()->fields();
7044 Expression_list* mvals = new Expression_list();
7047 Struct_field_list::const_iterator pmf = mfields->begin();
7048 go_assert(pmf->is_field_name("name"));
7049 std::string s = Gogo::unpack_hidden_name(pm->name());
7050 Expression* e = Expression::make_string(s, bloc);
7051 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7054 go_assert(pmf->is_field_name("pkgPath"));
7055 if (!Gogo::is_hidden_name(pm->name()))
7056 mvals->push_back(Expression::make_nil(bloc));
7059 s = Gogo::hidden_name_prefix(pm->name());
7060 e = Expression::make_string(s, bloc);
7061 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7065 go_assert(pmf->is_field_name("typ"));
7066 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
7069 go_assert(pmf == mfields->end());
7071 e = Expression::make_struct_composite_literal(elemtype, mvals,
7073 methods->push_back(e);
7077 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
7081 go_assert(pif == ifields->end());
7083 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
7086 // Reflection string.
7089 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
7091 ret->append("interface {");
7092 const Typed_identifier_list* methods = this->parse_methods_;
7093 if (methods != NULL)
7095 ret->push_back(' ');
7096 for (Typed_identifier_list::const_iterator p = methods->begin();
7097 p != methods->end();
7100 if (p != methods->begin())
7102 if (p->name().empty())
7103 this->append_reflection(p->type(), gogo, ret);
7106 if (!Gogo::is_hidden_name(p->name()))
7107 ret->append(p->name());
7110 // This matches what the gc compiler does.
7111 std::string prefix = Gogo::hidden_name_prefix(p->name());
7112 ret->append(prefix.substr(prefix.find('.') + 1));
7113 ret->push_back('.');
7114 ret->append(Gogo::unpack_hidden_name(p->name()));
7116 std::string sub = p->type()->reflection(gogo);
7117 go_assert(sub.compare(0, 4, "func") == 0);
7118 sub = sub.substr(4);
7122 ret->push_back(' ');
7130 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7132 go_assert(this->methods_are_finalized_);
7134 ret->push_back('I');
7136 const Typed_identifier_list* methods = this->all_methods_;
7137 if (methods != NULL && !this->seen_)
7140 for (Typed_identifier_list::const_iterator p = methods->begin();
7141 p != methods->end();
7144 if (!p->name().empty())
7146 std::string n = Gogo::unpack_hidden_name(p->name());
7148 snprintf(buf, sizeof buf, "%u_",
7149 static_cast<unsigned int>(n.length()));
7153 this->append_mangled_name(p->type(), gogo, ret);
7155 this->seen_ = false;
7158 ret->push_back('e');
7164 Interface_type::do_export(Export* exp) const
7166 exp->write_c_string("interface { ");
7168 const Typed_identifier_list* methods = this->parse_methods_;
7169 if (methods != NULL)
7171 for (Typed_identifier_list::const_iterator pm = methods->begin();
7172 pm != methods->end();
7175 if (pm->name().empty())
7177 exp->write_c_string("? ");
7178 exp->write_type(pm->type());
7182 exp->write_string(pm->name());
7183 exp->write_c_string(" (");
7185 const Function_type* fntype = pm->type()->function_type();
7188 const Typed_identifier_list* parameters = fntype->parameters();
7189 if (parameters != NULL)
7191 bool is_varargs = fntype->is_varargs();
7192 for (Typed_identifier_list::const_iterator pp =
7193 parameters->begin();
7194 pp != parameters->end();
7200 exp->write_c_string(", ");
7201 exp->write_name(pp->name());
7202 exp->write_c_string(" ");
7203 if (!is_varargs || pp + 1 != parameters->end())
7204 exp->write_type(pp->type());
7207 exp->write_c_string("...");
7208 Type *pptype = pp->type();
7209 exp->write_type(pptype->array_type()->element_type());
7214 exp->write_c_string(")");
7216 const Typed_identifier_list* results = fntype->results();
7217 if (results != NULL)
7219 exp->write_c_string(" ");
7220 if (results->size() == 1 && results->begin()->name().empty())
7221 exp->write_type(results->begin()->type());
7225 exp->write_c_string("(");
7226 for (Typed_identifier_list::const_iterator p =
7228 p != results->end();
7234 exp->write_c_string(", ");
7235 exp->write_name(p->name());
7236 exp->write_c_string(" ");
7237 exp->write_type(p->type());
7239 exp->write_c_string(")");
7244 exp->write_c_string("; ");
7248 exp->write_c_string("}");
7251 // Import an interface type.
7254 Interface_type::do_import(Import* imp)
7256 imp->require_c_string("interface { ");
7258 Typed_identifier_list* methods = new Typed_identifier_list;
7259 while (imp->peek_char() != '}')
7261 std::string name = imp->read_identifier();
7265 imp->require_c_string(" ");
7266 Type* t = imp->read_type();
7267 methods->push_back(Typed_identifier("", t, imp->location()));
7268 imp->require_c_string("; ");
7272 imp->require_c_string(" (");
7274 Typed_identifier_list* parameters;
7275 bool is_varargs = false;
7276 if (imp->peek_char() == ')')
7280 parameters = new Typed_identifier_list;
7283 std::string name = imp->read_name();
7284 imp->require_c_string(" ");
7286 if (imp->match_c_string("..."))
7292 Type* ptype = imp->read_type();
7294 ptype = Type::make_array_type(ptype, NULL);
7295 parameters->push_back(Typed_identifier(name, ptype,
7297 if (imp->peek_char() != ',')
7299 go_assert(!is_varargs);
7300 imp->require_c_string(", ");
7303 imp->require_c_string(")");
7305 Typed_identifier_list* results;
7306 if (imp->peek_char() != ' ')
7310 results = new Typed_identifier_list;
7312 if (imp->peek_char() != '(')
7314 Type* rtype = imp->read_type();
7315 results->push_back(Typed_identifier("", rtype, imp->location()));
7322 std::string name = imp->read_name();
7323 imp->require_c_string(" ");
7324 Type* rtype = imp->read_type();
7325 results->push_back(Typed_identifier(name, rtype,
7327 if (imp->peek_char() != ',')
7329 imp->require_c_string(", ");
7331 imp->require_c_string(")");
7335 Function_type* fntype = Type::make_function_type(NULL, parameters,
7339 fntype->set_is_varargs();
7340 methods->push_back(Typed_identifier(name, fntype, imp->location()));
7342 imp->require_c_string("; ");
7345 imp->require_c_string("}");
7347 if (methods->empty())
7353 return Type::make_interface_type(methods, imp->location());
7356 // Make an interface type.
7359 Type::make_interface_type(Typed_identifier_list* methods,
7362 return new Interface_type(methods, location);
7365 // Make an empty interface type.
7368 Type::make_empty_interface_type(Location location)
7370 Interface_type* ret = new Interface_type(NULL, location);
7371 ret->finalize_methods();
7377 // Bind a method to an object.
7380 Method::bind_method(Expression* expr, Location location) const
7382 if (this->stub_ == NULL)
7384 // When there is no stub object, the binding is determined by
7386 return this->do_bind_method(expr, location);
7388 return Expression::make_bound_method(expr, this->stub_, location);
7391 // Return the named object associated with a method. This may only be
7392 // called after methods are finalized.
7395 Method::named_object() const
7397 if (this->stub_ != NULL)
7399 return this->do_named_object();
7402 // Class Named_method.
7404 // The type of the method.
7407 Named_method::do_type() const
7409 if (this->named_object_->is_function())
7410 return this->named_object_->func_value()->type();
7411 else if (this->named_object_->is_function_declaration())
7412 return this->named_object_->func_declaration_value()->type();
7417 // Return the location of the method receiver.
7420 Named_method::do_receiver_location() const
7422 return this->do_type()->receiver()->location();
7425 // Bind a method to an object.
7428 Named_method::do_bind_method(Expression* expr, Location location) const
7430 Named_object* no = this->named_object_;
7431 Bound_method_expression* bme = Expression::make_bound_method(expr, no,
7433 // If this is not a local method, and it does not use a stub, then
7434 // the real method expects a different type. We need to cast the
7436 if (this->depth() > 0 && !this->needs_stub_method())
7438 Function_type* ftype = this->do_type();
7439 go_assert(ftype->is_method());
7440 Type* frtype = ftype->receiver()->type();
7441 bme->set_first_argument_type(frtype);
7446 // Class Interface_method.
7448 // Bind a method to an object.
7451 Interface_method::do_bind_method(Expression* expr,
7452 Location location) const
7454 return Expression::make_interface_field_reference(expr, this->name_,
7460 // Insert a new method. Return true if it was inserted, false
7464 Methods::insert(const std::string& name, Method* m)
7466 std::pair<Method_map::iterator, bool> ins =
7467 this->methods_.insert(std::make_pair(name, m));
7472 Method* old_method = ins.first->second;
7473 if (m->depth() < old_method->depth())
7476 ins.first->second = m;
7481 if (m->depth() == old_method->depth())
7482 old_method->set_is_ambiguous();
7488 // Return the number of unambiguous methods.
7491 Methods::count() const
7494 for (Method_map::const_iterator p = this->methods_.begin();
7495 p != this->methods_.end();
7497 if (!p->second->is_ambiguous())
7502 // Class Named_type.
7504 // Return the name of the type.
7507 Named_type::name() const
7509 return this->named_object_->name();
7512 // Return the name of the type to use in an error message.
7515 Named_type::message_name() const
7517 return this->named_object_->message_name();
7520 // Whether this is an alias. There are currently only two aliases so
7521 // we just recognize them by name.
7524 Named_type::is_alias() const
7526 if (!this->is_builtin())
7528 const std::string& name(this->name());
7529 return name == "byte" || name == "rune";
7532 // Return the base type for this type. We have to be careful about
7533 // circular type definitions, which are invalid but may be seen here.
7536 Named_type::named_base()
7541 Type* ret = this->type_->base();
7542 this->seen_ = false;
7547 Named_type::named_base() const
7552 const Type* ret = this->type_->base();
7553 this->seen_ = false;
7557 // Return whether this is an error type. We have to be careful about
7558 // circular type definitions, which are invalid but may be seen here.
7561 Named_type::is_named_error_type() const
7566 bool ret = this->type_->is_error_type();
7567 this->seen_ = false;
7571 // Whether this type is comparable. We have to be careful about
7572 // circular type definitions.
7575 Named_type::named_type_is_comparable(std::string* reason) const
7580 bool ret = Type::are_compatible_for_comparison(true, this->type_,
7581 this->type_, reason);
7582 this->seen_ = false;
7586 // Add a method to this type.
7589 Named_type::add_method(const std::string& name, Function* function)
7591 if (this->local_methods_ == NULL)
7592 this->local_methods_ = new Bindings(NULL);
7593 return this->local_methods_->add_function(name, NULL, function);
7596 // Add a method declaration to this type.
7599 Named_type::add_method_declaration(const std::string& name, Package* package,
7600 Function_type* type,
7603 if (this->local_methods_ == NULL)
7604 this->local_methods_ = new Bindings(NULL);
7605 return this->local_methods_->add_function_declaration(name, package, type,
7609 // Add an existing method to this type.
7612 Named_type::add_existing_method(Named_object* no)
7614 if (this->local_methods_ == NULL)
7615 this->local_methods_ = new Bindings(NULL);
7616 this->local_methods_->add_named_object(no);
7619 // Look for a local method NAME, and returns its named object, or NULL
7623 Named_type::find_local_method(const std::string& name) const
7625 if (this->local_methods_ == NULL)
7627 return this->local_methods_->lookup(name);
7630 // Return whether NAME is an unexported field or method, for better
7634 Named_type::is_unexported_local_method(Gogo* gogo,
7635 const std::string& name) const
7637 Bindings* methods = this->local_methods_;
7638 if (methods != NULL)
7640 for (Bindings::const_declarations_iterator p =
7641 methods->begin_declarations();
7642 p != methods->end_declarations();
7645 if (Gogo::is_hidden_name(p->first)
7646 && name == Gogo::unpack_hidden_name(p->first)
7647 && gogo->pack_hidden_name(name, false) != p->first)
7654 // Build the complete list of methods for this type, which means
7655 // recursively including all methods for anonymous fields. Create all
7659 Named_type::finalize_methods(Gogo* gogo)
7661 if (this->all_methods_ != NULL)
7664 if (this->local_methods_ != NULL
7665 && (this->points_to() != NULL || this->interface_type() != NULL))
7667 const Bindings* lm = this->local_methods_;
7668 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
7669 p != lm->end_declarations();
7671 error_at(p->second->location(),
7672 "invalid pointer or interface receiver type");
7673 delete this->local_methods_;
7674 this->local_methods_ = NULL;
7678 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
7681 // Return the method NAME, or NULL if there isn't one or if it is
7682 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
7686 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
7688 return Type::method_function(this->all_methods_, name, is_ambiguous);
7691 // Return a pointer to the interface method table for this type for
7692 // the interface INTERFACE. IS_POINTER is true if this is for a
7696 Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface,
7699 go_assert(!interface->is_empty());
7701 Interface_method_tables** pimt = (is_pointer
7702 ? &this->interface_method_tables_
7703 : &this->pointer_interface_method_tables_);
7706 *pimt = new Interface_method_tables(5);
7708 std::pair<const Interface_type*, tree> val(interface, NULL_TREE);
7709 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
7713 // This is a new entry in the hash table.
7714 go_assert(ins.first->second == NULL_TREE);
7715 ins.first->second = gogo->interface_method_table_for_type(interface,
7720 tree decl = ins.first->second;
7721 if (decl == error_mark_node)
7722 return error_mark_node;
7723 go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL);
7724 return build_fold_addr_expr(decl);
7727 // Return whether a named type has any hidden fields.
7730 Named_type::named_type_has_hidden_fields(std::string* reason) const
7735 bool ret = this->type_->has_hidden_fields(this, reason);
7736 this->seen_ = false;
7740 // Look for a use of a complete type within another type. This is
7741 // used to check that we don't try to use a type within itself.
7743 class Find_type_use : public Traverse
7746 Find_type_use(Named_type* find_type)
7747 : Traverse(traverse_types),
7748 find_type_(find_type), found_(false)
7751 // Whether we found the type.
7754 { return this->found_; }
7761 // The type we are looking for.
7762 Named_type* find_type_;
7763 // Whether we found the type.
7767 // Check for FIND_TYPE in TYPE.
7770 Find_type_use::type(Type* type)
7772 if (type->named_type() != NULL && this->find_type_ == type->named_type())
7774 this->found_ = true;
7775 return TRAVERSE_EXIT;
7778 // It's OK if we see a reference to the type in any type which is
7779 // essentially a pointer: a pointer, a slice, a function, a map, or
7781 if (type->points_to() != NULL
7782 || type->is_slice_type()
7783 || type->function_type() != NULL
7784 || type->map_type() != NULL
7785 || type->channel_type() != NULL)
7786 return TRAVERSE_SKIP_COMPONENTS;
7788 // For an interface, a reference to the type in a method type should
7789 // be ignored, but we have to consider direct inheritance. When
7790 // this is called, there may be cases of direct inheritance
7791 // represented as a method with no name.
7792 if (type->interface_type() != NULL)
7794 const Typed_identifier_list* methods = type->interface_type()->methods();
7795 if (methods != NULL)
7797 for (Typed_identifier_list::const_iterator p = methods->begin();
7798 p != methods->end();
7801 if (p->name().empty())
7803 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
7804 return TRAVERSE_EXIT;
7808 return TRAVERSE_SKIP_COMPONENTS;
7811 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
7812 // to convert TYPE to the backend representation before we convert
7814 if (type->named_type() != NULL)
7816 switch (type->base()->classification())
7818 case Type::TYPE_ERROR:
7819 case Type::TYPE_BOOLEAN:
7820 case Type::TYPE_INTEGER:
7821 case Type::TYPE_FLOAT:
7822 case Type::TYPE_COMPLEX:
7823 case Type::TYPE_STRING:
7824 case Type::TYPE_NIL:
7827 case Type::TYPE_ARRAY:
7828 case Type::TYPE_STRUCT:
7829 this->find_type_->add_dependency(type->named_type());
7832 case Type::TYPE_NAMED:
7833 case Type::TYPE_FORWARD:
7834 go_assert(saw_errors());
7837 case Type::TYPE_VOID:
7838 case Type::TYPE_SINK:
7839 case Type::TYPE_FUNCTION:
7840 case Type::TYPE_POINTER:
7841 case Type::TYPE_CALL_MULTIPLE_RESULT:
7842 case Type::TYPE_MAP:
7843 case Type::TYPE_CHANNEL:
7844 case Type::TYPE_INTERFACE:
7850 return TRAVERSE_CONTINUE;
7853 // Verify that a named type does not refer to itself.
7856 Named_type::do_verify()
7858 Find_type_use find(this);
7859 Type::traverse(this->type_, &find);
7862 error_at(this->location_, "invalid recursive type %qs",
7863 this->message_name().c_str());
7864 this->is_error_ = true;
7868 // Check whether any of the local methods overloads an existing
7869 // struct field or interface method. We don't need to check the
7870 // list of methods against itself: that is handled by the Bindings
7872 if (this->local_methods_ != NULL)
7874 Struct_type* st = this->type_->struct_type();
7877 for (Bindings::const_declarations_iterator p =
7878 this->local_methods_->begin_declarations();
7879 p != this->local_methods_->end_declarations();
7882 const std::string& name(p->first);
7883 if (st != NULL && st->find_local_field(name, NULL) != NULL)
7885 error_at(p->second->location(),
7886 "method %qs redeclares struct field name",
7887 Gogo::message_name(name).c_str());
7896 // Return whether this type is or contains a pointer.
7899 Named_type::do_has_pointer() const
7904 bool ret = this->type_->has_pointer();
7905 this->seen_ = false;
7909 // Return whether comparisons for this type can use the identity
7913 Named_type::do_compare_is_identity(Gogo* gogo) const
7915 // We don't use this->seen_ here because compare_is_identity may
7916 // call base() later, and that will mess up if seen_ is set here.
7917 if (this->seen_in_compare_is_identity_)
7919 this->seen_in_compare_is_identity_ = true;
7920 bool ret = this->type_->compare_is_identity(gogo);
7921 this->seen_in_compare_is_identity_ = false;
7925 // Return a hash code. This is used for method lookup. We simply
7926 // hash on the name itself.
7929 Named_type::do_hash_for_method(Gogo* gogo) const
7931 if (this->is_alias())
7932 return this->type_->named_type()->do_hash_for_method(gogo);
7934 const std::string& name(this->named_object()->name());
7935 unsigned int ret = Type::hash_string(name, 0);
7937 // GOGO will be NULL here when called from Type_hash_identical.
7938 // That is OK because that is only used for internal hash tables
7939 // where we are going to be comparing named types for equality. In
7940 // other cases, which are cases where the runtime is going to
7941 // compare hash codes to see if the types are the same, we need to
7942 // include the package prefix and name in the hash.
7943 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
7945 const Package* package = this->named_object()->package();
7946 if (package == NULL)
7948 ret = Type::hash_string(gogo->unique_prefix(), ret);
7949 ret = Type::hash_string(gogo->package_name(), ret);
7953 ret = Type::hash_string(package->unique_prefix(), ret);
7954 ret = Type::hash_string(package->name(), ret);
7961 // Convert a named type to the backend representation. In order to
7962 // get dependencies right, we fill in a dummy structure for this type,
7963 // then convert all the dependencies, then complete this type. When
7964 // this function is complete, the size of the type is known.
7967 Named_type::convert(Gogo* gogo)
7969 if (this->is_error_ || this->is_converted_)
7972 this->create_placeholder(gogo);
7974 // Convert all the dependencies. If they refer indirectly back to
7975 // this type, they will pick up the intermediate tree we just
7977 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
7978 p != this->dependencies_.end();
7980 (*p)->convert(gogo);
7982 // Complete this type.
7983 Btype* bt = this->named_btype_;
7984 Type* base = this->type_->base();
7985 switch (base->classification())
8002 // The size of these types is already correct. We don't worry
8003 // about filling them in until later, when we also track
8004 // circular references.
8009 std::vector<Backend::Btyped_identifier> bfields;
8010 get_backend_struct_fields(gogo, base->struct_type()->fields(),
8012 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8013 bt = gogo->backend()->error_type();
8018 // Slice types were completed in create_placeholder.
8019 if (!base->is_slice_type())
8021 Btype* bet = base->array_type()->get_backend_element(gogo, true);
8022 Bexpression* blen = base->array_type()->get_backend_length(gogo);
8023 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
8024 bt = gogo->backend()->error_type();
8028 case TYPE_INTERFACE:
8029 // Interface types were completed in create_placeholder.
8037 case TYPE_CALL_MULTIPLE_RESULT:
8043 this->named_btype_ = bt;
8044 this->is_converted_ = true;
8045 this->is_placeholder_ = false;
8048 // Create the placeholder for a named type. This is the first step in
8049 // converting to the backend representation.
8052 Named_type::create_placeholder(Gogo* gogo)
8054 if (this->is_error_)
8055 this->named_btype_ = gogo->backend()->error_type();
8057 if (this->named_btype_ != NULL)
8060 // Create the structure for this type. Note that because we call
8061 // base() here, we don't attempt to represent a named type defined
8062 // as another named type. Instead both named types will point to
8063 // different base representations.
8064 Type* base = this->type_->base();
8066 bool set_name = true;
8067 switch (base->classification())
8070 this->is_error_ = true;
8071 this->named_btype_ = gogo->backend()->error_type();
8081 // These are simple basic types, we can just create them
8083 bt = Type::get_named_base_btype(gogo, base);
8088 // All maps and channels have the same backend representation.
8089 bt = Type::get_named_base_btype(gogo, base);
8095 bool for_function = base->classification() == TYPE_FUNCTION;
8096 bt = gogo->backend()->placeholder_pointer_type(this->name(),
8104 bt = gogo->backend()->placeholder_struct_type(this->name(),
8106 this->is_placeholder_ = true;
8111 if (base->is_slice_type())
8112 bt = gogo->backend()->placeholder_struct_type(this->name(),
8116 bt = gogo->backend()->placeholder_array_type(this->name(),
8118 this->is_placeholder_ = true;
8123 case TYPE_INTERFACE:
8124 if (base->interface_type()->is_empty())
8125 bt = Interface_type::get_backend_empty_interface_type(gogo);
8128 bt = gogo->backend()->placeholder_struct_type(this->name(),
8136 case TYPE_CALL_MULTIPLE_RESULT:
8143 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
8145 this->named_btype_ = bt;
8147 if (base->is_slice_type())
8149 // We do not record slices as dependencies of other types,
8150 // because we can fill them in completely here with the final
8152 std::vector<Backend::Btyped_identifier> bfields;
8153 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
8154 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8155 this->named_btype_ = gogo->backend()->error_type();
8157 else if (base->interface_type() != NULL
8158 && !base->interface_type()->is_empty())
8160 // We do not record interfaces as dependencies of other types,
8161 // because we can fill them in completely here with the final
8163 std::vector<Backend::Btyped_identifier> bfields;
8164 get_backend_interface_fields(gogo, base->interface_type(), true,
8166 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8167 this->named_btype_ = gogo->backend()->error_type();
8171 // Get a tree for a named type.
8174 Named_type::do_get_backend(Gogo* gogo)
8176 if (this->is_error_)
8177 return gogo->backend()->error_type();
8179 Btype* bt = this->named_btype_;
8181 if (!gogo->named_types_are_converted())
8183 // We have not completed converting named types. NAMED_BTYPE_
8184 // is a placeholder and we shouldn't do anything further.
8188 // We don't build dependencies for types whose sizes do not
8189 // change or are not relevant, so we may see them here while
8190 // converting types.
8191 this->create_placeholder(gogo);
8192 bt = this->named_btype_;
8193 go_assert(bt != NULL);
8197 // We are not converting types. This should only be called if the
8198 // type has already been converted.
8199 if (!this->is_converted_)
8201 go_assert(saw_errors());
8202 return gogo->backend()->error_type();
8205 go_assert(bt != NULL);
8207 // Complete the tree.
8208 Type* base = this->type_->base();
8210 switch (base->classification())
8213 return gogo->backend()->error_type();
8227 if (!this->seen_in_get_backend_)
8229 this->seen_in_get_backend_ = true;
8230 base->struct_type()->finish_backend_fields(gogo);
8231 this->seen_in_get_backend_ = false;
8236 if (!this->seen_in_get_backend_)
8238 this->seen_in_get_backend_ = true;
8239 base->array_type()->finish_backend_element(gogo);
8240 this->seen_in_get_backend_ = false;
8244 case TYPE_INTERFACE:
8245 if (!this->seen_in_get_backend_)
8247 this->seen_in_get_backend_ = true;
8248 base->interface_type()->finish_backend_methods(gogo);
8249 this->seen_in_get_backend_ = false;
8254 // Don't build a circular data structure. GENERIC can't handle
8256 if (this->seen_in_get_backend_)
8258 this->is_circular_ = true;
8259 return gogo->backend()->circular_pointer_type(bt, true);
8261 this->seen_in_get_backend_ = true;
8262 bt1 = Type::get_named_base_btype(gogo, base);
8263 this->seen_in_get_backend_ = false;
8264 if (this->is_circular_)
8265 bt1 = gogo->backend()->circular_pointer_type(bt, true);
8266 if (!gogo->backend()->set_placeholder_function_type(bt, bt1))
8267 bt = gogo->backend()->error_type();
8271 // Don't build a circular data structure. GENERIC can't handle
8273 if (this->seen_in_get_backend_)
8275 this->is_circular_ = true;
8276 return gogo->backend()->circular_pointer_type(bt, false);
8278 this->seen_in_get_backend_ = true;
8279 bt1 = Type::get_named_base_btype(gogo, base);
8280 this->seen_in_get_backend_ = false;
8281 if (this->is_circular_)
8282 bt1 = gogo->backend()->circular_pointer_type(bt, false);
8283 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
8284 bt = gogo->backend()->error_type();
8289 case TYPE_CALL_MULTIPLE_RESULT:
8298 // Build a type descriptor for a named type.
8301 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8303 if (name == NULL && this->is_alias())
8304 return this->type_->type_descriptor(gogo, this->type_);
8306 // If NAME is not NULL, then we don't really want the type
8307 // descriptor for this type; we want the descriptor for the
8308 // underlying type, giving it the name NAME.
8309 return this->named_type_descriptor(gogo, this->type_,
8310 name == NULL ? this : name);
8313 // Add to the reflection string. This is used mostly for the name of
8314 // the type used in a type descriptor, not for actual reflection
8318 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
8320 if (this->is_alias())
8322 this->append_reflection(this->type_, gogo, ret);
8325 if (!this->is_builtin())
8327 const Package* package = this->named_object_->package();
8328 if (package != NULL)
8329 ret->append(package->name());
8331 ret->append(gogo->package_name());
8332 ret->push_back('.');
8334 if (this->in_function_ != NULL)
8336 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
8337 ret->push_back('$');
8339 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
8342 // Get the mangled name.
8345 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8347 if (this->is_alias())
8349 this->append_mangled_name(this->type_, gogo, ret);
8352 Named_object* no = this->named_object_;
8354 if (this->is_builtin())
8355 go_assert(this->in_function_ == NULL);
8358 const std::string& unique_prefix(no->package() == NULL
8359 ? gogo->unique_prefix()
8360 : no->package()->unique_prefix());
8361 const std::string& package_name(no->package() == NULL
8362 ? gogo->package_name()
8363 : no->package()->name());
8364 name = unique_prefix;
8365 name.append(1, '.');
8366 name.append(package_name);
8367 name.append(1, '.');
8368 if (this->in_function_ != NULL)
8370 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
8371 name.append(1, '$');
8374 name.append(Gogo::unpack_hidden_name(no->name()));
8376 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
8381 // Export the type. This is called to export a global type.
8384 Named_type::export_named_type(Export* exp, const std::string&) const
8386 // We don't need to write the name of the type here, because it will
8387 // be written by Export::write_type anyhow.
8388 exp->write_c_string("type ");
8389 exp->write_type(this);
8390 exp->write_c_string(";\n");
8393 // Import a named type.
8396 Named_type::import_named_type(Import* imp, Named_type** ptype)
8398 imp->require_c_string("type ");
8399 Type *type = imp->read_type();
8400 *ptype = type->named_type();
8401 go_assert(*ptype != NULL);
8402 imp->require_c_string(";\n");
8405 // Export the type when it is referenced by another type. In this
8406 // case Export::export_type will already have issued the name.
8409 Named_type::do_export(Export* exp) const
8411 exp->write_type(this->type_);
8413 // To save space, we only export the methods directly attached to
8415 Bindings* methods = this->local_methods_;
8416 if (methods == NULL)
8419 exp->write_c_string("\n");
8420 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
8421 p != methods->end_definitions();
8424 exp->write_c_string(" ");
8425 (*p)->export_named_object(exp);
8428 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
8429 p != methods->end_declarations();
8432 if (p->second->is_function_declaration())
8434 exp->write_c_string(" ");
8435 p->second->export_named_object(exp);
8440 // Make a named type.
8443 Type::make_named_type(Named_object* named_object, Type* type,
8446 return new Named_type(named_object, type, location);
8449 // Finalize the methods for TYPE. It will be a named type or a struct
8450 // type. This sets *ALL_METHODS to the list of methods, and builds
8451 // all required stubs.
8454 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
8455 Methods** all_methods)
8457 *all_methods = NULL;
8458 Types_seen types_seen;
8459 Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen,
8461 Type::build_stub_methods(gogo, type, *all_methods, location);
8464 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
8465 // build up the struct field indexes as we go. DEPTH is the depth of
8466 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
8467 // adding these methods for an anonymous field with pointer type.
8468 // NEEDS_STUB_METHOD is true if we need to use a stub method which
8469 // calls the real method. TYPES_SEEN is used to avoid infinite
8473 Type::add_methods_for_type(const Type* type,
8474 const Method::Field_indexes* field_indexes,
8476 bool is_embedded_pointer,
8477 bool needs_stub_method,
8478 Types_seen* types_seen,
8481 // Pointer types may not have methods.
8482 if (type->points_to() != NULL)
8485 const Named_type* nt = type->named_type();
8488 std::pair<Types_seen::iterator, bool> ins = types_seen->insert(nt);
8494 Type::add_local_methods_for_type(nt, field_indexes, depth,
8495 is_embedded_pointer, needs_stub_method,
8498 Type::add_embedded_methods_for_type(type, field_indexes, depth,
8499 is_embedded_pointer, needs_stub_method,
8500 types_seen, methods);
8502 // If we are called with depth > 0, then we are looking at an
8503 // anonymous field of a struct. If such a field has interface type,
8504 // then we need to add the interface methods. We don't want to add
8505 // them when depth == 0, because we will already handle them
8506 // following the usual rules for an interface type.
8508 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
8511 // Add the local methods for the named type NT to *METHODS. The
8512 // parameters are as for add_methods_to_type.
8515 Type::add_local_methods_for_type(const Named_type* nt,
8516 const Method::Field_indexes* field_indexes,
8518 bool is_embedded_pointer,
8519 bool needs_stub_method,
8522 const Bindings* local_methods = nt->local_methods();
8523 if (local_methods == NULL)
8526 if (*methods == NULL)
8527 *methods = new Methods();
8529 for (Bindings::const_declarations_iterator p =
8530 local_methods->begin_declarations();
8531 p != local_methods->end_declarations();
8534 Named_object* no = p->second;
8535 bool is_value_method = (is_embedded_pointer
8536 || !Type::method_expects_pointer(no));
8537 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
8539 || (depth > 0 && is_value_method)));
8540 if (!(*methods)->insert(no->name(), m))
8545 // Add the embedded methods for TYPE to *METHODS. These are the
8546 // methods attached to anonymous fields. The parameters are as for
8547 // add_methods_to_type.
8550 Type::add_embedded_methods_for_type(const Type* type,
8551 const Method::Field_indexes* field_indexes,
8553 bool is_embedded_pointer,
8554 bool needs_stub_method,
8555 Types_seen* types_seen,
8558 // Look for anonymous fields in TYPE. TYPE has fields if it is a
8560 const Struct_type* st = type->struct_type();
8564 const Struct_field_list* fields = st->fields();
8569 for (Struct_field_list::const_iterator pf = fields->begin();
8570 pf != fields->end();
8573 if (!pf->is_anonymous())
8576 Type* ftype = pf->type();
8577 bool is_pointer = false;
8578 if (ftype->points_to() != NULL)
8580 ftype = ftype->points_to();
8583 Named_type* fnt = ftype->named_type();
8586 // This is an error, but it will be diagnosed elsewhere.
8590 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
8591 sub_field_indexes->next = field_indexes;
8592 sub_field_indexes->field_index = i;
8594 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
8595 (is_embedded_pointer || is_pointer),
8604 // If TYPE is an interface type, then add its method to *METHODS.
8605 // This is for interface methods attached to an anonymous field. The
8606 // parameters are as for add_methods_for_type.
8609 Type::add_interface_methods_for_type(const Type* type,
8610 const Method::Field_indexes* field_indexes,
8614 const Interface_type* it = type->interface_type();
8618 const Typed_identifier_list* imethods = it->methods();
8619 if (imethods == NULL)
8622 if (*methods == NULL)
8623 *methods = new Methods();
8625 for (Typed_identifier_list::const_iterator pm = imethods->begin();
8626 pm != imethods->end();
8629 Function_type* fntype = pm->type()->function_type();
8632 // This is an error, but it should be reported elsewhere
8633 // when we look at the methods for IT.
8636 go_assert(!fntype->is_method());
8637 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
8638 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
8639 field_indexes, depth);
8640 if (!(*methods)->insert(pm->name(), m))
8645 // Build stub methods for TYPE as needed. METHODS is the set of
8646 // methods for the type. A stub method may be needed when a type
8647 // inherits a method from an anonymous field. When we need the
8648 // address of the method, as in a type descriptor, we need to build a
8649 // little stub which does the required field dereferences and jumps to
8650 // the real method. LOCATION is the location of the type definition.
8653 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
8656 if (methods == NULL)
8658 for (Methods::const_iterator p = methods->begin();
8659 p != methods->end();
8662 Method* m = p->second;
8663 if (m->is_ambiguous() || !m->needs_stub_method())
8666 const std::string& name(p->first);
8668 // Build a stub method.
8670 const Function_type* fntype = m->type();
8672 static unsigned int counter;
8674 snprintf(buf, sizeof buf, "$this%u", counter);
8677 Type* receiver_type = const_cast<Type*>(type);
8678 if (!m->is_value_method())
8679 receiver_type = Type::make_pointer_type(receiver_type);
8680 Location receiver_location = m->receiver_location();
8681 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
8684 const Typed_identifier_list* fnparams = fntype->parameters();
8685 Typed_identifier_list* stub_params;
8686 if (fnparams == NULL || fnparams->empty())
8690 // We give each stub parameter a unique name.
8691 stub_params = new Typed_identifier_list();
8692 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
8693 pp != fnparams->end();
8697 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
8698 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
8704 const Typed_identifier_list* fnresults = fntype->results();
8705 Typed_identifier_list* stub_results;
8706 if (fnresults == NULL || fnresults->empty())
8707 stub_results = NULL;
8710 // We create the result parameters without any names, since
8711 // we won't refer to them.
8712 stub_results = new Typed_identifier_list();
8713 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
8714 pr != fnresults->end();
8716 stub_results->push_back(Typed_identifier("", pr->type(),
8720 Function_type* stub_type = Type::make_function_type(receiver,
8723 fntype->location());
8724 if (fntype->is_varargs())
8725 stub_type->set_is_varargs();
8727 // We only create the function in the package which creates the
8729 const Package* package;
8730 if (type->named_type() == NULL)
8733 package = type->named_type()->named_object()->package();
8735 if (package != NULL)
8736 stub = Named_object::make_function_declaration(name, package,
8737 stub_type, location);
8740 stub = gogo->start_function(name, stub_type, false,
8741 fntype->location());
8742 Type::build_one_stub_method(gogo, m, buf, stub_params,
8743 fntype->is_varargs(), location);
8744 gogo->finish_function(fntype->location());
8747 m->set_stub_object(stub);
8751 // Build a stub method which adjusts the receiver as required to call
8752 // METHOD. RECEIVER_NAME is the name we used for the receiver.
8753 // PARAMS is the list of function parameters.
8756 Type::build_one_stub_method(Gogo* gogo, Method* method,
8757 const char* receiver_name,
8758 const Typed_identifier_list* params,
8762 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
8763 go_assert(receiver_object != NULL);
8765 Expression* expr = Expression::make_var_reference(receiver_object, location);
8766 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
8767 if (expr->type()->points_to() == NULL)
8768 expr = Expression::make_unary(OPERATOR_AND, expr, location);
8770 Expression_list* arguments;
8771 if (params == NULL || params->empty())
8775 arguments = new Expression_list();
8776 for (Typed_identifier_list::const_iterator p = params->begin();
8780 Named_object* param = gogo->lookup(p->name(), NULL);
8781 go_assert(param != NULL);
8782 Expression* param_ref = Expression::make_var_reference(param,
8784 arguments->push_back(param_ref);
8788 Expression* func = method->bind_method(expr, location);
8789 go_assert(func != NULL);
8790 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
8792 call->set_hidden_fields_are_ok();
8793 size_t count = call->result_count();
8795 gogo->add_statement(Statement::make_statement(call, true));
8798 Expression_list* retvals = new Expression_list();
8800 retvals->push_back(call);
8803 for (size_t i = 0; i < count; ++i)
8804 retvals->push_back(Expression::make_call_result(call, i));
8806 Return_statement* retstat = Statement::make_return_statement(retvals,
8809 // We can return values with hidden fields from a stub. This is
8810 // necessary if the method is itself hidden.
8811 retstat->set_hidden_fields_are_ok();
8813 gogo->add_statement(retstat);
8817 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
8818 // in reverse order.
8821 Type::apply_field_indexes(Expression* expr,
8822 const Method::Field_indexes* field_indexes,
8825 if (field_indexes == NULL)
8827 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
8828 Struct_type* stype = expr->type()->deref()->struct_type();
8829 go_assert(stype != NULL
8830 && field_indexes->field_index < stype->field_count());
8831 if (expr->type()->struct_type() == NULL)
8833 go_assert(expr->type()->points_to() != NULL);
8834 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
8835 go_assert(expr->type()->struct_type() == stype);
8837 return Expression::make_field_reference(expr, field_indexes->field_index,
8841 // Return whether NO is a method for which the receiver is a pointer.
8844 Type::method_expects_pointer(const Named_object* no)
8846 const Function_type *fntype;
8847 if (no->is_function())
8848 fntype = no->func_value()->type();
8849 else if (no->is_function_declaration())
8850 fntype = no->func_declaration_value()->type();
8853 return fntype->receiver()->type()->points_to() != NULL;
8856 // Given a set of methods for a type, METHODS, return the method NAME,
8857 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
8858 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
8859 // but is ambiguous (and return NULL).
8862 Type::method_function(const Methods* methods, const std::string& name,
8865 if (is_ambiguous != NULL)
8866 *is_ambiguous = false;
8867 if (methods == NULL)
8869 Methods::const_iterator p = methods->find(name);
8870 if (p == methods->end())
8872 Method* m = p->second;
8873 if (m->is_ambiguous())
8875 if (is_ambiguous != NULL)
8876 *is_ambiguous = true;
8882 // Look for field or method NAME for TYPE. Return an Expression for
8883 // the field or method bound to EXPR. If there is no such field or
8884 // method, give an appropriate error and return an error expression.
8887 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
8888 const std::string& name,
8891 if (type->deref()->is_error_type())
8892 return Expression::make_error(location);
8894 const Named_type* nt = type->deref()->named_type();
8895 const Struct_type* st = type->deref()->struct_type();
8896 const Interface_type* it = type->interface_type();
8898 // If this is a pointer to a pointer, then it is possible that the
8899 // pointed-to type has methods.
8900 bool dereferenced = false;
8904 && type->points_to() != NULL
8905 && type->points_to()->points_to() != NULL)
8907 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
8908 type = type->points_to();
8909 if (type->deref()->is_error_type())
8910 return Expression::make_error(location);
8911 nt = type->points_to()->named_type();
8912 st = type->points_to()->struct_type();
8913 dereferenced = true;
8916 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
8917 || expr->is_addressable());
8918 std::vector<const Named_type*> seen;
8919 bool is_method = false;
8920 bool found_pointer_method = false;
8923 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
8924 &seen, NULL, &is_method,
8925 &found_pointer_method, &ambig1, &ambig2))
8930 go_assert(st != NULL);
8931 if (type->struct_type() == NULL)
8933 go_assert(type->points_to() != NULL);
8934 expr = Expression::make_unary(OPERATOR_MULT, expr,
8936 go_assert(expr->type()->struct_type() == st);
8938 ret = st->field_reference(expr, name, location);
8940 else if (it != NULL && it->find_method(name) != NULL)
8941 ret = Expression::make_interface_field_reference(expr, name,
8947 m = nt->method_function(name, NULL);
8948 else if (st != NULL)
8949 m = st->method_function(name, NULL);
8952 go_assert(m != NULL);
8953 if (dereferenced && m->is_value_method())
8956 "calling value method requires explicit dereference");
8957 return Expression::make_error(location);
8959 if (!m->is_value_method() && expr->type()->points_to() == NULL)
8960 expr = Expression::make_unary(OPERATOR_AND, expr, location);
8961 ret = m->bind_method(expr, location);
8963 go_assert(ret != NULL);
8968 if (!ambig1.empty())
8969 error_at(location, "%qs is ambiguous via %qs and %qs",
8970 Gogo::message_name(name).c_str(), ambig1.c_str(),
8972 else if (found_pointer_method)
8973 error_at(location, "method requires a pointer");
8974 else if (nt == NULL && st == NULL && it == NULL)
8976 ("reference to field %qs in object which "
8977 "has no fields or methods"),
8978 Gogo::message_name(name).c_str());
8982 if (!Gogo::is_hidden_name(name))
8983 is_unexported = false;
8986 std::string unpacked = Gogo::unpack_hidden_name(name);
8988 is_unexported = Type::is_unexported_field_or_method(gogo, type,
8993 error_at(location, "reference to unexported field or method %qs",
8994 Gogo::message_name(name).c_str());
8996 error_at(location, "reference to undefined field or method %qs",
8997 Gogo::message_name(name).c_str());
8999 return Expression::make_error(location);
9003 // Look in TYPE for a field or method named NAME, return true if one
9004 // is found. This looks through embedded anonymous fields and handles
9005 // ambiguity. If a method is found, sets *IS_METHOD to true;
9006 // otherwise, if a field is found, set it to false. If
9007 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
9008 // whose address can not be taken. SEEN is used to avoid infinite
9009 // recursion on invalid types.
9011 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
9012 // method we couldn't use because it requires a pointer. LEVEL is
9013 // used for recursive calls, and can be NULL for a non-recursive call.
9014 // When this function returns false because it finds that the name is
9015 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
9016 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
9017 // will be unchanged.
9019 // This function just returns whether or not there is a field or
9020 // method, and whether it is a field or method. It doesn't build an
9021 // expression to refer to it. If it is a method, we then look in the
9022 // list of all methods for the type. If it is a field, the search has
9023 // to be done again, looking only for fields, and building up the
9024 // expression as we go.
9027 Type::find_field_or_method(const Type* type,
9028 const std::string& name,
9029 bool receiver_can_be_pointer,
9030 std::vector<const Named_type*>* seen,
9033 bool* found_pointer_method,
9034 std::string* ambig1,
9035 std::string* ambig2)
9037 // Named types can have locally defined methods.
9038 const Named_type* nt = type->named_type();
9039 if (nt == NULL && type->points_to() != NULL)
9040 nt = type->points_to()->named_type();
9043 Named_object* no = nt->find_local_method(name);
9046 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
9052 // Record that we have found a pointer method in order to
9053 // give a better error message if we don't find anything
9055 *found_pointer_method = true;
9058 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9064 // We've already seen this type when searching for methods.
9070 // Interface types can have methods.
9071 const Interface_type* it = type->interface_type();
9072 if (it != NULL && it->find_method(name) != NULL)
9078 // Struct types can have fields. They can also inherit fields and
9079 // methods from anonymous fields.
9080 const Struct_type* st = type->deref()->struct_type();
9083 const Struct_field_list* fields = st->fields();
9088 seen->push_back(nt);
9090 int found_level = 0;
9091 bool found_is_method = false;
9092 std::string found_ambig1;
9093 std::string found_ambig2;
9094 const Struct_field* found_parent = NULL;
9095 for (Struct_field_list::const_iterator pf = fields->begin();
9096 pf != fields->end();
9099 if (pf->is_field_name(name))
9107 if (!pf->is_anonymous())
9110 if (pf->type()->deref()->is_error_type()
9111 || pf->type()->deref()->is_undefined())
9114 Named_type* fnt = pf->type()->named_type();
9116 fnt = pf->type()->deref()->named_type();
9117 go_assert(fnt != NULL);
9119 int sublevel = level == NULL ? 1 : *level + 1;
9121 std::string subambig1;
9122 std::string subambig2;
9123 bool subfound = Type::find_field_or_method(fnt,
9125 receiver_can_be_pointer,
9129 found_pointer_method,
9134 if (!subambig1.empty())
9136 // The name was found via this field, but is ambiguous.
9137 // if the ambiguity is lower or at the same level as
9138 // anything else we have already found, then we want to
9139 // pass the ambiguity back to the caller.
9140 if (found_level == 0 || sublevel <= found_level)
9142 found_ambig1 = (Gogo::message_name(pf->field_name())
9144 found_ambig2 = (Gogo::message_name(pf->field_name())
9146 found_level = sublevel;
9152 // The name was found via this field. Use the level to see
9153 // if we want to use this one, or whether it introduces an
9155 if (found_level == 0 || sublevel < found_level)
9157 found_level = sublevel;
9158 found_is_method = sub_is_method;
9159 found_ambig1.clear();
9160 found_ambig2.clear();
9161 found_parent = &*pf;
9163 else if (sublevel > found_level)
9165 else if (found_ambig1.empty())
9167 // We found an ambiguity.
9168 go_assert(found_parent != NULL);
9169 found_ambig1 = Gogo::message_name(found_parent->field_name());
9170 found_ambig2 = Gogo::message_name(pf->field_name());
9174 // We found an ambiguity, but we already know of one.
9175 // Just report the earlier one.
9180 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
9181 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
9182 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
9183 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
9188 if (found_level == 0)
9190 else if (!found_ambig1.empty())
9192 go_assert(!found_ambig1.empty());
9193 ambig1->assign(found_ambig1);
9194 ambig2->assign(found_ambig2);
9196 *level = found_level;
9202 *level = found_level;
9203 *is_method = found_is_method;
9208 // Return whether NAME is an unexported field or method for TYPE.
9211 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
9212 const std::string& name,
9213 std::vector<const Named_type*>* seen)
9215 const Named_type* nt = type->named_type();
9217 nt = type->deref()->named_type();
9220 if (nt->is_unexported_local_method(gogo, name))
9223 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9229 // We've already seen this type.
9235 const Interface_type* it = type->interface_type();
9236 if (it != NULL && it->is_unexported_method(gogo, name))
9239 type = type->deref();
9241 const Struct_type* st = type->struct_type();
9242 if (st != NULL && st->is_unexported_local_field(gogo, name))
9248 const Struct_field_list* fields = st->fields();
9253 seen->push_back(nt);
9255 for (Struct_field_list::const_iterator pf = fields->begin();
9256 pf != fields->end();
9259 if (pf->is_anonymous()
9260 && !pf->type()->deref()->is_error_type()
9261 && !pf->type()->deref()->is_undefined())
9263 Named_type* subtype = pf->type()->named_type();
9264 if (subtype == NULL)
9265 subtype = pf->type()->deref()->named_type();
9266 if (subtype == NULL)
9268 // This is an error, but it will be diagnosed elsewhere.
9271 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
9286 // Class Forward_declaration.
9288 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
9289 : Type(TYPE_FORWARD),
9290 named_object_(named_object->resolve()), warned_(false)
9292 go_assert(this->named_object_->is_unknown()
9293 || this->named_object_->is_type_declaration());
9296 // Return the named object.
9299 Forward_declaration_type::named_object()
9301 return this->named_object_->resolve();
9305 Forward_declaration_type::named_object() const
9307 return this->named_object_->resolve();
9310 // Return the name of the forward declared type.
9313 Forward_declaration_type::name() const
9315 return this->named_object()->name();
9318 // Warn about a use of a type which has been declared but not defined.
9321 Forward_declaration_type::warn() const
9323 Named_object* no = this->named_object_->resolve();
9324 if (no->is_unknown())
9326 // The name was not defined anywhere.
9329 error_at(this->named_object_->location(),
9330 "use of undefined type %qs",
9331 no->message_name().c_str());
9332 this->warned_ = true;
9335 else if (no->is_type_declaration())
9337 // The name was seen as a type, but the type was never defined.
9338 if (no->type_declaration_value()->using_type())
9340 error_at(this->named_object_->location(),
9341 "use of undefined type %qs",
9342 no->message_name().c_str());
9343 this->warned_ = true;
9348 // The name was defined, but not as a type.
9351 error_at(this->named_object_->location(), "expected type");
9352 this->warned_ = true;
9357 // Get the base type of a declaration. This gives an error if the
9358 // type has not yet been defined.
9361 Forward_declaration_type::real_type()
9363 if (this->is_defined())
9364 return this->named_object()->type_value();
9368 return Type::make_error_type();
9373 Forward_declaration_type::real_type() const
9375 if (this->is_defined())
9376 return this->named_object()->type_value();
9380 return Type::make_error_type();
9384 // Return whether the base type is defined.
9387 Forward_declaration_type::is_defined() const
9389 return this->named_object()->is_type();
9392 // Add a method. This is used when methods are defined before the
9396 Forward_declaration_type::add_method(const std::string& name,
9399 Named_object* no = this->named_object();
9400 if (no->is_unknown())
9401 no->declare_as_type();
9402 return no->type_declaration_value()->add_method(name, function);
9405 // Add a method declaration. This is used when methods are declared
9409 Forward_declaration_type::add_method_declaration(const std::string& name,
9411 Function_type* type,
9414 Named_object* no = this->named_object();
9415 if (no->is_unknown())
9416 no->declare_as_type();
9417 Type_declaration* td = no->type_declaration_value();
9418 return td->add_method_declaration(name, package, type, location);
9424 Forward_declaration_type::do_traverse(Traverse* traverse)
9426 if (this->is_defined()
9427 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
9428 return TRAVERSE_EXIT;
9429 return TRAVERSE_CONTINUE;
9432 // Get the backend representation for the type.
9435 Forward_declaration_type::do_get_backend(Gogo* gogo)
9437 if (this->is_defined())
9438 return Type::get_named_base_btype(gogo, this->real_type());
9441 return gogo->backend()->error_type();
9443 // We represent an undefined type as a struct with no fields. That
9444 // should work fine for the backend, since the same case can arise
9446 std::vector<Backend::Btyped_identifier> fields;
9447 Btype* bt = gogo->backend()->struct_type(fields);
9448 return gogo->backend()->named_type(this->name(), bt,
9449 this->named_object()->location());
9452 // Build a type descriptor for a forwarded type.
9455 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9457 Location ploc = Linemap::predeclared_location();
9458 if (!this->is_defined())
9459 return Expression::make_error(ploc);
9462 Type* t = this->real_type();
9464 return this->named_type_descriptor(gogo, t, name);
9466 return Expression::make_type_descriptor(t, ploc);
9470 // The reflection string.
9473 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
9475 this->append_reflection(this->real_type(), gogo, ret);
9478 // The mangled name.
9481 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
9483 if (this->is_defined())
9484 this->append_mangled_name(this->real_type(), gogo, ret);
9487 const Named_object* no = this->named_object();
9489 if (no->package() == NULL)
9490 name = gogo->package_name();
9492 name = no->package()->name();
9494 name += Gogo::unpack_hidden_name(no->name());
9496 snprintf(buf, sizeof buf, "N%u_",
9497 static_cast<unsigned int>(name.length()));
9503 // Export a forward declaration. This can happen when a defined type
9504 // refers to a type which is only declared (and is presumably defined
9505 // in some other file in the same package).
9508 Forward_declaration_type::do_export(Export*) const
9510 // If there is a base type, that should be exported instead of this.
9511 go_assert(!this->is_defined());
9513 // We don't output anything.
9516 // Make a forward declaration.
9519 Type::make_forward_declaration(Named_object* named_object)
9521 return new Forward_declaration_type(named_object);
9524 // Class Typed_identifier_list.
9526 // Sort the entries by name.
9528 struct Typed_identifier_list_sort
9532 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
9533 { return t1.name() < t2.name(); }
9537 Typed_identifier_list::sort_by_name()
9539 std::sort(this->entries_.begin(), this->entries_.end(),
9540 Typed_identifier_list_sort());
9546 Typed_identifier_list::traverse(Traverse* traverse)
9548 for (Typed_identifier_list::const_iterator p = this->begin();
9552 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
9553 return TRAVERSE_EXIT;
9555 return TRAVERSE_CONTINUE;
9560 Typed_identifier_list*
9561 Typed_identifier_list::copy() const
9563 Typed_identifier_list* ret = new Typed_identifier_list();
9564 for (Typed_identifier_list::const_iterator p = this->begin();
9567 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));