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"
39 Type::Type(Type_classification classification)
40 : classification_(classification), btype_(NULL), type_descriptor_var_(NULL)
48 // Get the base type for a type--skip names and forward declarations.
53 switch (this->classification_)
56 return this->named_type()->named_base();
58 return this->forward_declaration_type()->real_type()->base();
67 switch (this->classification_)
70 return this->named_type()->named_base();
72 return this->forward_declaration_type()->real_type()->base();
78 // Skip defined forward declarations.
84 Forward_declaration_type* ftype = t->forward_declaration_type();
85 while (ftype != NULL && ftype->is_defined())
87 t = ftype->real_type();
88 ftype = t->forward_declaration_type();
94 Type::forwarded() const
97 const Forward_declaration_type* ftype = t->forward_declaration_type();
98 while (ftype != NULL && ftype->is_defined())
100 t = ftype->real_type();
101 ftype = t->forward_declaration_type();
106 // If this is a named type, return it. Otherwise, return NULL.
111 return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
115 Type::named_type() const
117 return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
120 // Return true if this type is not defined.
123 Type::is_undefined() const
125 return this->forwarded()->forward_declaration_type() != NULL;
128 // Return true if this is a basic type: a type which is not composed
129 // of other types, and is not void.
132 Type::is_basic_type() const
134 switch (this->classification_)
157 return this->base()->is_basic_type();
164 // Return true if this is an abstract type.
167 Type::is_abstract() const
169 switch (this->classification())
172 return this->integer_type()->is_abstract();
174 return this->float_type()->is_abstract();
176 return this->complex_type()->is_abstract();
178 return this->is_abstract_string_type();
180 return this->is_abstract_boolean_type();
186 // Return a non-abstract version of an abstract type.
189 Type::make_non_abstract_type()
191 go_assert(this->is_abstract());
192 switch (this->classification())
195 return Type::lookup_integer_type("int");
197 return Type::lookup_float_type("float64");
199 return Type::lookup_complex_type("complex128");
201 return Type::lookup_string_type();
203 return Type::lookup_bool_type();
209 // Return true if this is an error type. Don't give an error if we
210 // try to dereference an undefined forwarding type, as this is called
211 // in the parser when the type may legitimately be undefined.
214 Type::is_error_type() const
216 const Type* t = this->forwarded();
217 // Note that we return false for an undefined forward type.
218 switch (t->classification_)
223 return t->named_type()->is_named_error_type();
229 // If this is a pointer type, return the type to which it points.
230 // Otherwise, return NULL.
233 Type::points_to() const
235 const Pointer_type* ptype = this->convert<const Pointer_type,
237 return ptype == NULL ? NULL : ptype->points_to();
240 // Return whether this is an open array type.
243 Type::is_slice_type() const
245 return this->array_type() != NULL && this->array_type()->length() == NULL;
248 // Return whether this is the predeclared constant nil being used as a
252 Type::is_nil_constant_as_type() const
254 const Type* t = this->forwarded();
255 if (t->forward_declaration_type() != NULL)
257 const Named_object* no = t->forward_declaration_type()->named_object();
258 if (no->is_unknown())
259 no = no->unknown_value()->real_named_object();
262 && no->const_value()->expr()->is_nil_expression())
271 Type::traverse(Type* type, Traverse* traverse)
273 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
274 || (traverse->traverse_mask()
275 & Traverse::traverse_expressions) != 0);
276 if (traverse->remember_type(type))
278 // We have already traversed this type.
279 return TRAVERSE_CONTINUE;
281 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
283 int t = traverse->type(type);
284 if (t == TRAVERSE_EXIT)
285 return TRAVERSE_EXIT;
286 else if (t == TRAVERSE_SKIP_COMPONENTS)
287 return TRAVERSE_CONTINUE;
289 // An array type has an expression which we need to traverse if
290 // traverse_expressions is set.
291 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
292 return TRAVERSE_EXIT;
293 return TRAVERSE_CONTINUE;
296 // Default implementation for do_traverse for child class.
299 Type::do_traverse(Traverse*)
301 return TRAVERSE_CONTINUE;
304 // Return whether two types are identical. If ERRORS_ARE_IDENTICAL,
305 // then return true for all erroneous types; this is used to avoid
306 // cascading errors. If REASON is not NULL, optionally set *REASON to
307 // the reason the types are not identical.
310 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
313 if (t1 == NULL || t2 == NULL)
315 // Something is wrong.
316 return errors_are_identical ? true : t1 == t2;
319 // Skip defined forward declarations.
320 t1 = t1->forwarded();
321 t2 = t2->forwarded();
326 // An undefined forward declaration is an error.
327 if (t1->forward_declaration_type() != NULL
328 || t2->forward_declaration_type() != NULL)
329 return errors_are_identical;
331 // Avoid cascading errors with error types.
332 if (t1->is_error_type() || t2->is_error_type())
334 if (errors_are_identical)
336 return t1->is_error_type() && t2->is_error_type();
339 // Get a good reason for the sink type. Note that the sink type on
340 // the left hand side of an assignment is handled in are_assignable.
341 if (t1->is_sink_type() || t2->is_sink_type())
344 *reason = "invalid use of _";
348 // A named type is only identical to itself.
349 if (t1->named_type() != NULL || t2->named_type() != NULL)
352 // Check type shapes.
353 if (t1->classification() != t2->classification())
356 switch (t1->classification())
362 // These types are always identical.
366 return t1->integer_type()->is_identical(t2->integer_type());
369 return t1->float_type()->is_identical(t2->float_type());
372 return t1->complex_type()->is_identical(t2->complex_type());
375 return t1->function_type()->is_identical(t2->function_type(),
377 errors_are_identical,
381 return Type::are_identical(t1->points_to(), t2->points_to(),
382 errors_are_identical, reason);
385 return t1->struct_type()->is_identical(t2->struct_type(),
386 errors_are_identical);
389 return t1->array_type()->is_identical(t2->array_type(),
390 errors_are_identical);
393 return t1->map_type()->is_identical(t2->map_type(),
394 errors_are_identical);
397 return t1->channel_type()->is_identical(t2->channel_type(),
398 errors_are_identical);
401 return t1->interface_type()->is_identical(t2->interface_type(),
402 errors_are_identical);
404 case TYPE_CALL_MULTIPLE_RESULT:
406 *reason = "invalid use of multiple value function call";
414 // Return true if it's OK to have a binary operation with types LHS
415 // and RHS. This is not used for shifts or comparisons.
418 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
420 if (Type::are_identical(lhs, rhs, true, NULL))
423 // A constant of abstract bool type may be mixed with any bool type.
424 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
425 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
428 // A constant of abstract string type may be mixed with any string
430 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
431 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
437 // A constant of abstract integer, float, or complex type may be
438 // mixed with an integer, float, or complex type.
439 if ((rhs->is_abstract()
440 && (rhs->integer_type() != NULL
441 || rhs->float_type() != NULL
442 || rhs->complex_type() != NULL)
443 && (lhs->integer_type() != NULL
444 || lhs->float_type() != NULL
445 || lhs->complex_type() != NULL))
446 || (lhs->is_abstract()
447 && (lhs->integer_type() != NULL
448 || lhs->float_type() != NULL
449 || lhs->complex_type() != NULL)
450 && (rhs->integer_type() != NULL
451 || rhs->float_type() != NULL
452 || rhs->complex_type() != NULL)))
455 // The nil type may be compared to a pointer, an interface type, a
456 // slice type, a channel type, a map type, or a function type.
457 if (lhs->is_nil_type()
458 && (rhs->points_to() != NULL
459 || rhs->interface_type() != NULL
460 || rhs->is_slice_type()
461 || rhs->map_type() != NULL
462 || rhs->channel_type() != NULL
463 || rhs->function_type() != NULL))
465 if (rhs->is_nil_type()
466 && (lhs->points_to() != NULL
467 || lhs->interface_type() != NULL
468 || lhs->is_slice_type()
469 || lhs->map_type() != NULL
470 || lhs->channel_type() != NULL
471 || lhs->function_type() != NULL))
477 // Return true if a value with type T1 may be compared with a value of
478 // type T2. IS_EQUALITY_OP is true for == or !=, false for <, etc.
481 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
482 const Type *t2, std::string *reason)
485 && !Type::are_assignable(t1, t2, NULL)
486 && !Type::are_assignable(t2, t1, NULL))
489 *reason = "incompatible types in binary expression";
495 if (t1->integer_type() == NULL
496 && t1->float_type() == NULL
497 && !t1->is_string_type())
500 *reason = _("invalid comparison of non-ordered type");
504 else if (t1->is_slice_type()
505 || t1->map_type() != NULL
506 || t1->function_type() != NULL
507 || t2->is_slice_type()
508 || t2->map_type() != NULL
509 || t2->function_type() != NULL)
511 if (!t1->is_nil_type() && !t2->is_nil_type())
515 if (t1->is_slice_type() || t2->is_slice_type())
516 *reason = _("slice can only be compared to nil");
517 else if (t1->map_type() != NULL || t2->map_type() != NULL)
518 *reason = _("map can only be compared to nil");
520 *reason = _("func can only be compared to nil");
522 // Match 6g error messages.
523 if (t1->interface_type() != NULL || t2->interface_type() != NULL)
526 snprintf(buf, sizeof buf, _("invalid operation (%s)"),
536 if (!t1->is_boolean_type()
537 && t1->integer_type() == NULL
538 && t1->float_type() == NULL
539 && t1->complex_type() == NULL
540 && !t1->is_string_type()
541 && t1->points_to() == NULL
542 && t1->channel_type() == NULL
543 && t1->interface_type() == NULL
544 && t1->struct_type() == NULL
545 && t1->array_type() == NULL
546 && !t1->is_nil_type())
549 *reason = _("invalid comparison of non-comparable type");
553 if (t1->named_type() != NULL)
554 return t1->named_type()->named_type_is_comparable(reason);
555 else if (t2->named_type() != NULL)
556 return t2->named_type()->named_type_is_comparable(reason);
557 else if (t1->struct_type() != NULL)
559 const Struct_field_list* fields = t1->struct_type()->fields();
560 for (Struct_field_list::const_iterator p = fields->begin();
564 if (!p->type()->is_comparable())
567 *reason = _("invalid comparison of non-comparable struct");
572 else if (t1->array_type() != NULL)
574 if (!t1->array_type()->element_type()->is_comparable())
577 *reason = _("invalid comparison of non-comparable array");
586 // Return true if a value with type RHS may be assigned to a variable
587 // with type LHS. If CHECK_HIDDEN_FIELDS is true, check whether any
588 // hidden fields are modified. If REASON is not NULL, set *REASON to
589 // the reason the types are not assignable.
592 Type::are_assignable_check_hidden(const Type* lhs, const Type* rhs,
593 bool check_hidden_fields,
596 // Do some checks first. Make sure the types are defined.
598 && rhs->forwarded()->forward_declaration_type() == NULL
599 && rhs->is_void_type())
602 *reason = "non-value used as value";
606 if (lhs != NULL && lhs->forwarded()->forward_declaration_type() == NULL)
608 // Any value may be assigned to the blank identifier.
609 if (lhs->is_sink_type())
612 // All fields of a struct must be exported, or the assignment
613 // must be in the same package.
614 if (check_hidden_fields
616 && rhs->forwarded()->forward_declaration_type() == NULL)
618 if (lhs->has_hidden_fields(NULL, reason)
619 || rhs->has_hidden_fields(NULL, reason))
624 // Identical types are assignable.
625 if (Type::are_identical(lhs, rhs, true, reason))
628 // The types are assignable if they have identical underlying types
629 // and either LHS or RHS is not a named type.
630 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
631 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
632 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
635 // The types are assignable if LHS is an interface type and RHS
636 // implements the required methods.
637 const Interface_type* lhs_interface_type = lhs->interface_type();
638 if (lhs_interface_type != NULL)
640 if (lhs_interface_type->implements_interface(rhs, reason))
642 const Interface_type* rhs_interface_type = rhs->interface_type();
643 if (rhs_interface_type != NULL
644 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
649 // The type are assignable if RHS is a bidirectional channel type,
650 // LHS is a channel type, they have identical element types, and
651 // either LHS or RHS is not a named type.
652 if (lhs->channel_type() != NULL
653 && rhs->channel_type() != NULL
654 && rhs->channel_type()->may_send()
655 && rhs->channel_type()->may_receive()
656 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
657 && Type::are_identical(lhs->channel_type()->element_type(),
658 rhs->channel_type()->element_type(),
663 // The nil type may be assigned to a pointer, function, slice, map,
664 // channel, or interface type.
665 if (rhs->is_nil_type()
666 && (lhs->points_to() != NULL
667 || lhs->function_type() != NULL
668 || lhs->is_slice_type()
669 || lhs->map_type() != NULL
670 || lhs->channel_type() != NULL
671 || lhs->interface_type() != NULL))
674 // An untyped numeric constant may be assigned to a numeric type if
675 // it is representable in that type.
676 if ((rhs->is_abstract()
677 && (rhs->integer_type() != NULL
678 || rhs->float_type() != NULL
679 || rhs->complex_type() != NULL))
680 && (lhs->integer_type() != NULL
681 || lhs->float_type() != NULL
682 || lhs->complex_type() != NULL))
685 // Give some better error messages.
686 if (reason != NULL && reason->empty())
688 if (rhs->interface_type() != NULL)
689 reason->assign(_("need explicit conversion"));
690 else if (rhs->is_call_multiple_result_type())
691 reason->assign(_("multiple value function call in "
692 "single value context"));
693 else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
695 size_t len = (lhs->named_type()->name().length()
696 + rhs->named_type()->name().length()
698 char* buf = new char[len];
699 snprintf(buf, len, _("cannot use type %s as type %s"),
700 rhs->named_type()->message_name().c_str(),
701 lhs->named_type()->message_name().c_str());
710 // Return true if a value with type RHS may be assigned to a variable
711 // with type LHS. If REASON is not NULL, set *REASON to the reason
712 // the types are not assignable.
715 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
717 return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
720 // Like are_assignable but don't check for hidden fields.
723 Type::are_assignable_hidden_ok(const Type* lhs, const Type* rhs,
726 return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
729 // Return true if a value with type RHS may be converted to type LHS.
730 // If REASON is not NULL, set *REASON to the reason the types are not
734 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
736 // The types are convertible if they are assignable.
737 if (Type::are_assignable(lhs, rhs, reason))
740 // The types are convertible if they have identical underlying
742 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
743 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
746 // The types are convertible if they are both unnamed pointer types
747 // and their pointer base types have identical underlying types.
748 if (lhs->named_type() == NULL
749 && rhs->named_type() == NULL
750 && lhs->points_to() != NULL
751 && rhs->points_to() != NULL
752 && (lhs->points_to()->named_type() != NULL
753 || rhs->points_to()->named_type() != NULL)
754 && Type::are_identical(lhs->points_to()->base(),
755 rhs->points_to()->base(),
760 // Integer and floating point types are convertible to each other.
761 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
762 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
765 // Complex types are convertible to each other.
766 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
769 // An integer, or []byte, or []int, may be converted to a string.
770 if (lhs->is_string_type())
772 if (rhs->integer_type() != NULL)
774 if (rhs->is_slice_type())
776 const Type* e = rhs->array_type()->element_type()->forwarded();
777 if (e->integer_type() != NULL
778 && (e == Type::lookup_integer_type("uint8")
779 || e == Type::lookup_integer_type("int")))
784 // A string may be converted to []byte or []int.
785 if (rhs->is_string_type() && lhs->is_slice_type())
787 const Type* e = lhs->array_type()->element_type()->forwarded();
788 if (e->integer_type() != NULL
789 && (e == Type::lookup_integer_type("uint8")
790 || e == Type::lookup_integer_type("int")))
794 // An unsafe.Pointer type may be converted to any pointer type or to
795 // uintptr, and vice-versa.
796 if (lhs->is_unsafe_pointer_type()
797 && (rhs->points_to() != NULL
798 || (rhs->integer_type() != NULL
799 && rhs->forwarded() == Type::lookup_integer_type("uintptr"))))
801 if (rhs->is_unsafe_pointer_type()
802 && (lhs->points_to() != NULL
803 || (lhs->integer_type() != NULL
804 && lhs->forwarded() == Type::lookup_integer_type("uintptr"))))
807 // Give a better error message.
811 *reason = "invalid type conversion";
814 std::string s = "invalid type conversion (";
824 // Return whether this type has any hidden fields. This is only a
825 // possibility for a few types.
828 Type::has_hidden_fields(const Named_type* within, std::string* reason) const
830 switch (this->forwarded()->classification_)
833 return this->named_type()->named_type_has_hidden_fields(reason);
835 return this->struct_type()->struct_has_hidden_fields(within, reason);
837 return this->array_type()->array_has_hidden_fields(within, reason);
843 // Return a hash code for the type to be used for method lookup.
846 Type::hash_for_method(Gogo* gogo) const
848 unsigned int ret = 0;
849 if (this->classification_ != TYPE_FORWARD)
850 ret += this->classification_;
851 return ret + this->do_hash_for_method(gogo);
854 // Default implementation of do_hash_for_method. This is appropriate
855 // for types with no subfields.
858 Type::do_hash_for_method(Gogo*) const
863 // Return a hash code for a string, given a starting hash.
866 Type::hash_string(const std::string& s, unsigned int h)
868 const char* p = s.data();
869 size_t len = s.length();
870 for (; len > 0; --len)
878 // A hash table mapping unnamed types to the backend representation of
881 Type::Type_btypes Type::type_btypes;
883 // Return a tree representing this type.
886 Type::get_backend(Gogo* gogo)
888 if (this->btype_ != NULL)
891 if (this->forward_declaration_type() != NULL
892 || this->named_type() != NULL)
893 return this->get_btype_without_hash(gogo);
895 if (this->is_error_type())
896 return gogo->backend()->error_type();
898 // To avoid confusing the backend, translate all identical Go types
899 // to the same backend representation. We use a hash table to do
900 // that. There is no need to use the hash table for named types, as
901 // named types are only identical to themselves.
903 std::pair<Type*, Btype*> val(this, NULL);
904 std::pair<Type_btypes::iterator, bool> ins =
905 Type::type_btypes.insert(val);
906 if (!ins.second && ins.first->second != NULL)
908 if (gogo != NULL && gogo->named_types_are_converted())
909 this->btype_ = ins.first->second;
910 return ins.first->second;
913 Btype* bt = this->get_btype_without_hash(gogo);
915 if (ins.first->second == NULL)
916 ins.first->second = bt;
919 // We have already created a backend representation for this
920 // type. This can happen when an unnamed type is defined using
921 // a named type which in turns uses an identical unnamed type.
922 // Use the tree we created earlier and ignore the one we just
924 bt = ins.first->second;
925 if (gogo == NULL || !gogo->named_types_are_converted())
933 // Return the backend representation for a type without looking in the
934 // hash table for identical types. This is used for named types,
935 // since a named type is never identical to any other type.
938 Type::get_btype_without_hash(Gogo* gogo)
940 if (this->btype_ == NULL)
942 Btype* bt = this->do_get_backend(gogo);
944 // For a recursive function or pointer type, we will temporarily
945 // return a circular pointer type during the recursion. We
946 // don't want to record that for a forwarding type, as it may
948 if (this->forward_declaration_type() != NULL
949 && gogo->backend()->is_circular_pointer_type(bt))
952 if (gogo == NULL || !gogo->named_types_are_converted())
960 // Return a pointer to the type descriptor for this type.
963 Type::type_descriptor_pointer(Gogo* gogo, Location location)
965 Type* t = this->forwarded();
966 if (t->type_descriptor_var_ == NULL)
968 t->make_type_descriptor_var(gogo);
969 go_assert(t->type_descriptor_var_ != NULL);
971 tree var_tree = var_to_tree(t->type_descriptor_var_);
972 if (var_tree == error_mark_node)
973 return error_mark_node;
974 return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
977 // A mapping from unnamed types to type descriptor variables.
979 Type::Type_descriptor_vars Type::type_descriptor_vars;
981 // Build the type descriptor for this type.
984 Type::make_type_descriptor_var(Gogo* gogo)
986 go_assert(this->type_descriptor_var_ == NULL);
988 Named_type* nt = this->named_type();
990 // We can have multiple instances of unnamed types, but we only want
991 // to emit the type descriptor once. We use a hash table. This is
992 // not necessary for named types, as they are unique, and we store
993 // the type descriptor in the type itself.
994 Bvariable** phash = NULL;
997 Bvariable* bvnull = NULL;
998 std::pair<Type_descriptor_vars::iterator, bool> ins =
999 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1002 // We've already build a type descriptor for this type.
1003 this->type_descriptor_var_ = ins.first->second;
1006 phash = &ins.first->second;
1009 std::string var_name = this->type_descriptor_var_name(gogo, nt);
1011 // Build the contents of the type descriptor.
1012 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1014 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1016 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1018 const Package* dummy;
1019 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1021 this->type_descriptor_var_ =
1022 gogo->backend()->immutable_struct_reference(var_name,
1026 *phash = this->type_descriptor_var_;
1030 // See if this type descriptor can appear in multiple packages.
1031 bool is_common = false;
1034 // We create the descriptor for a builtin type whenever we need
1036 is_common = nt->is_builtin();
1040 // This is an unnamed type. The descriptor could be defined in
1041 // any package where it is needed, and the linker will pick one
1042 // descriptor to keep.
1046 // We are going to build the type descriptor in this package. We
1047 // must create the variable before we convert the initializer to the
1048 // backend representation, because the initializer may refer to the
1049 // type descriptor of this type. By setting type_descriptor_var_ we
1050 // ensure that type_descriptor_pointer will work if called while
1051 // converting INITIALIZER.
1053 this->type_descriptor_var_ =
1054 gogo->backend()->immutable_struct(var_name, is_common, initializer_btype,
1057 *phash = this->type_descriptor_var_;
1059 Translate_context context(gogo, NULL, NULL, NULL);
1060 context.set_is_const();
1061 Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
1063 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1064 var_name, is_common,
1065 initializer_btype, loc,
1069 // Return the name of the type descriptor variable. If NT is not
1070 // NULL, use it to get the name. Otherwise this is an unnamed type.
1073 Type::type_descriptor_var_name(Gogo* gogo, Named_type* nt)
1076 return "__go_td_" + this->mangled_name(gogo);
1078 Named_object* no = nt->named_object();
1079 const Named_object* in_function = nt->in_function();
1080 std::string ret = "__go_tdn_";
1081 if (nt->is_builtin())
1082 go_assert(in_function == NULL);
1085 const std::string& unique_prefix(no->package() == NULL
1086 ? gogo->unique_prefix()
1087 : no->package()->unique_prefix());
1088 const std::string& package_name(no->package() == NULL
1089 ? gogo->package_name()
1090 : no->package()->name());
1091 ret.append(unique_prefix);
1093 ret.append(package_name);
1095 if (in_function != NULL)
1097 ret.append(Gogo::unpack_hidden_name(in_function->name()));
1101 ret.append(no->name());
1105 // Return true if this type descriptor is defined in a different
1106 // package. If this returns true it sets *PACKAGE to the package.
1109 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1110 const Package** package)
1114 if (nt->named_object()->package() != NULL)
1116 // This is a named type defined in a different package. The
1117 // type descriptor should be defined in that package.
1118 *package = nt->named_object()->package();
1124 if (this->points_to() != NULL
1125 && this->points_to()->named_type() != NULL
1126 && this->points_to()->named_type()->named_object()->package() != NULL)
1128 // This is an unnamed pointer to a named type defined in a
1129 // different package. The descriptor should be defined in
1131 *package = this->points_to()->named_type()->named_object()->package();
1138 // Return a composite literal for a type descriptor.
1141 Type::type_descriptor(Gogo* gogo, Type* type)
1143 return type->do_type_descriptor(gogo, NULL);
1146 // Return a composite literal for a type descriptor with a name.
1149 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1151 go_assert(name != NULL && type->named_type() != name);
1152 return type->do_type_descriptor(gogo, name);
1155 // Make a builtin struct type from a list of fields. The fields are
1156 // pairs of a name and a type.
1159 Type::make_builtin_struct_type(int nfields, ...)
1162 va_start(ap, nfields);
1164 Location bloc = Linemap::predeclared_location();
1165 Struct_field_list* sfl = new Struct_field_list();
1166 for (int i = 0; i < nfields; i++)
1168 const char* field_name = va_arg(ap, const char *);
1169 Type* type = va_arg(ap, Type*);
1170 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1175 return Type::make_struct_type(sfl, bloc);
1178 // A list of builtin named types.
1180 std::vector<Named_type*> Type::named_builtin_types;
1182 // Make a builtin named type.
1185 Type::make_builtin_named_type(const char* name, Type* type)
1187 Location bloc = Linemap::predeclared_location();
1188 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1189 Named_type* ret = no->type_value();
1190 Type::named_builtin_types.push_back(ret);
1194 // Convert the named builtin types.
1197 Type::convert_builtin_named_types(Gogo* gogo)
1199 for (std::vector<Named_type*>::const_iterator p =
1200 Type::named_builtin_types.begin();
1201 p != Type::named_builtin_types.end();
1204 bool r = (*p)->verify();
1206 (*p)->convert(gogo);
1210 // Return the type of a type descriptor. We should really tie this to
1211 // runtime.Type rather than copying it. This must match commonType in
1212 // libgo/go/runtime/type.go.
1215 Type::make_type_descriptor_type()
1220 Location bloc = Linemap::predeclared_location();
1222 Type* uint8_type = Type::lookup_integer_type("uint8");
1223 Type* uint32_type = Type::lookup_integer_type("uint32");
1224 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1225 Type* string_type = Type::lookup_string_type();
1226 Type* pointer_string_type = Type::make_pointer_type(string_type);
1228 // This is an unnamed version of unsafe.Pointer. Perhaps we
1229 // should use the named version instead, although that would
1230 // require us to create the unsafe package if it has not been
1231 // imported. It probably doesn't matter.
1232 Type* void_type = Type::make_void_type();
1233 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1235 // Forward declaration for the type descriptor type.
1236 Named_object* named_type_descriptor_type =
1237 Named_object::make_type_declaration("commonType", NULL, bloc);
1238 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1239 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1241 // The type of a method on a concrete type.
1242 Struct_type* method_type =
1243 Type::make_builtin_struct_type(5,
1244 "name", pointer_string_type,
1245 "pkgPath", pointer_string_type,
1246 "mtyp", pointer_type_descriptor_type,
1247 "typ", pointer_type_descriptor_type,
1248 "tfn", unsafe_pointer_type);
1249 Named_type* named_method_type =
1250 Type::make_builtin_named_type("method", method_type);
1252 // Information for types with a name or methods.
1253 Type* slice_named_method_type =
1254 Type::make_array_type(named_method_type, NULL);
1255 Struct_type* uncommon_type =
1256 Type::make_builtin_struct_type(3,
1257 "name", pointer_string_type,
1258 "pkgPath", pointer_string_type,
1259 "methods", slice_named_method_type);
1260 Named_type* named_uncommon_type =
1261 Type::make_builtin_named_type("uncommonType", uncommon_type);
1263 Type* pointer_uncommon_type =
1264 Type::make_pointer_type(named_uncommon_type);
1266 // The type descriptor type.
1268 Typed_identifier_list* params = new Typed_identifier_list();
1269 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1270 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1272 Typed_identifier_list* results = new Typed_identifier_list();
1273 results->push_back(Typed_identifier("", uintptr_type, bloc));
1275 Type* hashfn_type = Type::make_function_type(NULL, params, results, bloc);
1277 params = new Typed_identifier_list();
1278 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1279 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1280 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1282 results = new Typed_identifier_list();
1283 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1285 Type* equalfn_type = Type::make_function_type(NULL, params, results,
1288 Struct_type* type_descriptor_type =
1289 Type::make_builtin_struct_type(10,
1291 "align", uint8_type,
1292 "fieldAlign", uint8_type,
1293 "size", uintptr_type,
1294 "hash", uint32_type,
1295 "hashfn", hashfn_type,
1296 "equalfn", equalfn_type,
1297 "string", pointer_string_type,
1298 "", pointer_uncommon_type,
1300 pointer_type_descriptor_type);
1302 Named_type* named = Type::make_builtin_named_type("commonType",
1303 type_descriptor_type);
1305 named_type_descriptor_type->set_type_value(named);
1313 // Make the type of a pointer to a type descriptor as represented in
1317 Type::make_type_descriptor_ptr_type()
1321 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1325 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1326 // hash code for this type and which compare whether two values of
1327 // this type are equal. If NAME is not NULL it is the name of this
1328 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1329 // functions, for convenience; they may be NULL.
1332 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1333 Function_type* equal_fntype, Named_object** hash_fn,
1334 Named_object** equal_fn)
1336 if (hash_fntype == NULL || equal_fntype == NULL)
1338 Location bloc = Linemap::predeclared_location();
1340 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1341 Type* void_type = Type::make_void_type();
1342 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1344 if (hash_fntype == NULL)
1346 Typed_identifier_list* params = new Typed_identifier_list();
1347 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1349 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1351 Typed_identifier_list* results = new Typed_identifier_list();
1352 results->push_back(Typed_identifier("", uintptr_type, bloc));
1354 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1356 if (equal_fntype == NULL)
1358 Typed_identifier_list* params = new Typed_identifier_list();
1359 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1361 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1363 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1365 Typed_identifier_list* results = new Typed_identifier_list();
1366 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1369 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1373 const char* hash_fnname;
1374 const char* equal_fnname;
1375 if (this->compare_is_identity())
1377 hash_fnname = "__go_type_hash_identity";
1378 equal_fnname = "__go_type_equal_identity";
1380 else if (!this->is_comparable())
1382 hash_fnname = "__go_type_hash_error";
1383 equal_fnname = "__go_type_equal_error";
1387 switch (this->base()->classification())
1389 case Type::TYPE_ERROR:
1390 case Type::TYPE_VOID:
1391 case Type::TYPE_NIL:
1392 case Type::TYPE_FUNCTION:
1393 case Type::TYPE_MAP:
1394 // For these types is_comparable should have returned false.
1397 case Type::TYPE_BOOLEAN:
1398 case Type::TYPE_INTEGER:
1399 case Type::TYPE_POINTER:
1400 case Type::TYPE_CHANNEL:
1401 // For these types compare_is_identity should have returned true.
1404 case Type::TYPE_FLOAT:
1405 hash_fnname = "__go_type_hash_float";
1406 equal_fnname = "__go_type_equal_float";
1409 case Type::TYPE_COMPLEX:
1410 hash_fnname = "__go_type_hash_complex";
1411 equal_fnname = "__go_type_equal_complex";
1414 case Type::TYPE_STRING:
1415 hash_fnname = "__go_type_hash_string";
1416 equal_fnname = "__go_type_equal_string";
1419 case Type::TYPE_STRUCT:
1421 // This is a struct which can not be compared using a
1422 // simple identity function. We need to build a function
1424 this->specific_type_functions(gogo, name, hash_fntype,
1425 equal_fntype, hash_fn, equal_fn);
1429 case Type::TYPE_ARRAY:
1430 if (this->is_slice_type())
1432 // Type::is_compatible_for_comparison should have
1438 // This is an array which can not be compared using a
1439 // simple identity function. We need to build a
1440 // function for comparison.
1441 this->specific_type_functions(gogo, name, hash_fntype,
1442 equal_fntype, hash_fn, equal_fn);
1447 case Type::TYPE_INTERFACE:
1448 if (this->interface_type()->is_empty())
1450 hash_fnname = "__go_type_hash_empty_interface";
1451 equal_fnname = "__go_type_equal_empty_interface";
1455 hash_fnname = "__go_type_hash_interface";
1456 equal_fnname = "__go_type_equal_interface";
1460 case Type::TYPE_NAMED:
1461 case Type::TYPE_FORWARD:
1470 Location bloc = Linemap::predeclared_location();
1471 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1473 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1474 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1475 equal_fntype, bloc);
1476 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1479 // A hash table mapping types to the specific hash functions.
1481 Type::Type_functions Type::type_functions_table;
1483 // Handle a type function which is specific to a type: a struct or
1484 // array which can not use an identity comparison.
1487 Type::specific_type_functions(Gogo* gogo, Named_type* name,
1488 Function_type* hash_fntype,
1489 Function_type* equal_fntype,
1490 Named_object** hash_fn,
1491 Named_object** equal_fn)
1493 Hash_equal_fn fnull(NULL, NULL);
1494 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1495 std::pair<Type_functions::iterator, bool> ins =
1496 Type::type_functions_table.insert(val);
1499 // We already have functions for this type
1500 *hash_fn = ins.first->second.first;
1501 *equal_fn = ins.first->second.second;
1505 std::string base_name;
1507 base_name = gogo->pack_hidden_name(this->mangled_name(gogo), false);
1510 // This name is already hidden or not as appropriate.
1511 base_name = name->name();
1512 const Named_object* in_function = name->in_function();
1513 if (in_function != NULL)
1514 base_name += '$' + in_function->name();
1516 std::string hash_name = base_name + "$hash";
1517 std::string equal_name = base_name + "$equal";
1519 Location bloc = Linemap::predeclared_location();
1521 const Package* package = NULL;
1522 bool is_defined_elsewhere =
1523 this->type_descriptor_defined_elsewhere(name, &package);
1524 if (is_defined_elsewhere)
1526 *hash_fn = Named_object::make_function_declaration(hash_name, package,
1528 *equal_fn = Named_object::make_function_declaration(equal_name, package,
1529 equal_fntype, bloc);
1533 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
1534 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
1538 ins.first->second.first = *hash_fn;
1539 ins.first->second.second = *equal_fn;
1541 if (!is_defined_elsewhere)
1543 if (gogo->in_global_scope())
1544 this->write_specific_type_functions(gogo, name, hash_name, hash_fntype,
1545 equal_name, equal_fntype);
1547 gogo->queue_specific_type_function(this, name, hash_name, hash_fntype,
1548 equal_name, equal_fntype);
1552 // Write the hash and equality functions for a type which needs to be
1553 // written specially.
1556 Type::write_specific_type_functions(Gogo* gogo, Named_type* name,
1557 const std::string& hash_name,
1558 Function_type* hash_fntype,
1559 const std::string& equal_name,
1560 Function_type* equal_fntype)
1562 Location bloc = Linemap::predeclared_location();
1564 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
1566 gogo->start_block(bloc);
1568 if (this->struct_type() != NULL)
1569 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
1571 else if (this->array_type() != NULL)
1572 this->array_type()->write_hash_function(gogo, name, hash_fntype,
1577 Block* b = gogo->finish_block(bloc);
1578 gogo->add_block(b, bloc);
1579 gogo->lower_block(hash_fn, b);
1580 gogo->finish_function(bloc);
1582 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
1584 gogo->start_block(bloc);
1586 if (this->struct_type() != NULL)
1587 this->struct_type()->write_equal_function(gogo, name);
1588 else if (this->array_type() != NULL)
1589 this->array_type()->write_equal_function(gogo, name);
1593 b = gogo->finish_block(bloc);
1594 gogo->add_block(b, bloc);
1595 gogo->lower_block(equal_fn, b);
1596 gogo->finish_function(bloc);
1599 // Return a composite literal for the type descriptor for a plain type
1600 // of kind RUNTIME_TYPE_KIND named NAME.
1603 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
1604 Named_type* name, const Methods* methods,
1605 bool only_value_methods)
1607 Location bloc = Linemap::predeclared_location();
1609 Type* td_type = Type::make_type_descriptor_type();
1610 const Struct_field_list* fields = td_type->struct_type()->fields();
1612 Expression_list* vals = new Expression_list();
1615 if (!this->has_pointer())
1616 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
1617 Struct_field_list::const_iterator p = fields->begin();
1618 go_assert(p->is_field_name("Kind"));
1620 mpz_init_set_ui(iv, runtime_type_kind);
1621 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1624 go_assert(p->is_field_name("align"));
1625 Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT;
1626 vals->push_back(Expression::make_type_info(this, type_info));
1629 go_assert(p->is_field_name("fieldAlign"));
1630 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
1631 vals->push_back(Expression::make_type_info(this, type_info));
1634 go_assert(p->is_field_name("size"));
1635 type_info = Expression::TYPE_INFO_SIZE;
1636 vals->push_back(Expression::make_type_info(this, type_info));
1639 go_assert(p->is_field_name("hash"));
1640 mpz_set_ui(iv, this->hash_for_method(gogo));
1641 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1644 go_assert(p->is_field_name("hashfn"));
1645 Function_type* hash_fntype = p->type()->function_type();
1648 go_assert(p->is_field_name("equalfn"));
1649 Function_type* equal_fntype = p->type()->function_type();
1651 Named_object* hash_fn;
1652 Named_object* equal_fn;
1653 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
1655 vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
1656 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
1659 go_assert(p->is_field_name("string"));
1660 Expression* s = Expression::make_string((name != NULL
1661 ? name->reflection(gogo)
1662 : this->reflection(gogo)),
1664 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1667 go_assert(p->is_field_name("uncommonType"));
1668 if (name == NULL && methods == NULL)
1669 vals->push_back(Expression::make_nil(bloc));
1672 if (methods == NULL)
1673 methods = name->methods();
1674 vals->push_back(this->uncommon_type_constructor(gogo,
1677 only_value_methods));
1681 go_assert(p->is_field_name("ptrToThis"));
1683 vals->push_back(Expression::make_nil(bloc));
1686 Type* pt = Type::make_pointer_type(name);
1687 vals->push_back(Expression::make_type_descriptor(pt, bloc));
1691 go_assert(p == fields->end());
1695 return Expression::make_struct_composite_literal(td_type, vals, bloc);
1698 // Return a composite literal for the uncommon type information for
1699 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
1700 // struct. If name is not NULL, it is the name of the type. If
1701 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
1702 // is true if only value methods should be included. At least one of
1703 // NAME and METHODS must not be NULL.
1706 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
1707 Named_type* name, const Methods* methods,
1708 bool only_value_methods) const
1710 Location bloc = Linemap::predeclared_location();
1712 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
1714 Expression_list* vals = new Expression_list();
1717 Struct_field_list::const_iterator p = fields->begin();
1718 go_assert(p->is_field_name("name"));
1721 go_assert(p->is_field_name("pkgPath"));
1725 vals->push_back(Expression::make_nil(bloc));
1726 vals->push_back(Expression::make_nil(bloc));
1730 Named_object* no = name->named_object();
1731 std::string n = Gogo::unpack_hidden_name(no->name());
1732 Expression* s = Expression::make_string(n, bloc);
1733 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1735 if (name->is_builtin())
1736 vals->push_back(Expression::make_nil(bloc));
1739 const Package* package = no->package();
1740 const std::string& unique_prefix(package == NULL
1741 ? gogo->unique_prefix()
1742 : package->unique_prefix());
1743 const std::string& package_name(package == NULL
1744 ? gogo->package_name()
1746 n.assign(unique_prefix);
1748 n.append(package_name);
1749 if (name->in_function() != NULL)
1752 n.append(Gogo::unpack_hidden_name(name->in_function()->name()));
1754 s = Expression::make_string(n, bloc);
1755 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1760 go_assert(p->is_field_name("methods"));
1761 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
1762 only_value_methods));
1765 go_assert(p == fields->end());
1767 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
1769 return Expression::make_unary(OPERATOR_AND, r, bloc);
1772 // Sort methods by name.
1778 operator()(const std::pair<std::string, const Method*>& m1,
1779 const std::pair<std::string, const Method*>& m2) const
1780 { return m1.first < m2.first; }
1783 // Return a composite literal for the type method table for this type.
1784 // METHODS_TYPE is the type of the table, and is a slice type.
1785 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
1786 // then only value methods are used.
1789 Type::methods_constructor(Gogo* gogo, Type* methods_type,
1790 const Methods* methods,
1791 bool only_value_methods) const
1793 Location bloc = Linemap::predeclared_location();
1795 std::vector<std::pair<std::string, const Method*> > smethods;
1796 if (methods != NULL)
1798 smethods.reserve(methods->count());
1799 for (Methods::const_iterator p = methods->begin();
1800 p != methods->end();
1803 if (p->second->is_ambiguous())
1805 if (only_value_methods && !p->second->is_value_method())
1807 smethods.push_back(std::make_pair(p->first, p->second));
1811 if (smethods.empty())
1812 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
1814 std::sort(smethods.begin(), smethods.end(), Sort_methods());
1816 Type* method_type = methods_type->array_type()->element_type();
1818 Expression_list* vals = new Expression_list();
1819 vals->reserve(smethods.size());
1820 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
1822 p != smethods.end();
1824 vals->push_back(this->method_constructor(gogo, method_type, p->first,
1825 p->second, only_value_methods));
1827 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
1830 // Return a composite literal for a single method. METHOD_TYPE is the
1831 // type of the entry. METHOD_NAME is the name of the method and M is
1832 // the method information.
1835 Type::method_constructor(Gogo*, Type* method_type,
1836 const std::string& method_name,
1838 bool only_value_methods) const
1840 Location bloc = Linemap::predeclared_location();
1842 const Struct_field_list* fields = method_type->struct_type()->fields();
1844 Expression_list* vals = new Expression_list();
1847 Struct_field_list::const_iterator p = fields->begin();
1848 go_assert(p->is_field_name("name"));
1849 const std::string n = Gogo::unpack_hidden_name(method_name);
1850 Expression* s = Expression::make_string(n, bloc);
1851 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1854 go_assert(p->is_field_name("pkgPath"));
1855 if (!Gogo::is_hidden_name(method_name))
1856 vals->push_back(Expression::make_nil(bloc));
1859 s = Expression::make_string(Gogo::hidden_name_prefix(method_name), bloc);
1860 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1863 Named_object* no = (m->needs_stub_method()
1865 : m->named_object());
1867 Function_type* mtype;
1868 if (no->is_function())
1869 mtype = no->func_value()->type();
1871 mtype = no->func_declaration_value()->type();
1872 go_assert(mtype->is_method());
1873 Type* nonmethod_type = mtype->copy_without_receiver();
1876 go_assert(p->is_field_name("mtyp"));
1877 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
1880 go_assert(p->is_field_name("typ"));
1881 if (!only_value_methods && m->is_value_method())
1883 // This is a value method on a pointer type. Change the type of
1884 // the method to use a pointer receiver. The implementation
1885 // always uses a pointer receiver anyhow.
1886 Type* rtype = mtype->receiver()->type();
1887 Type* prtype = Type::make_pointer_type(rtype);
1888 Typed_identifier* receiver =
1889 new Typed_identifier(mtype->receiver()->name(), prtype,
1890 mtype->receiver()->location());
1891 mtype = Type::make_function_type(receiver,
1892 (mtype->parameters() == NULL
1894 : mtype->parameters()->copy()),
1895 (mtype->results() == NULL
1897 : mtype->results()->copy()),
1900 vals->push_back(Expression::make_type_descriptor(mtype, bloc));
1903 go_assert(p->is_field_name("tfn"));
1904 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
1907 go_assert(p == fields->end());
1909 return Expression::make_struct_composite_literal(method_type, vals, bloc);
1912 // Return a composite literal for the type descriptor of a plain type.
1913 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
1914 // NULL, it is the name to use as well as the list of methods.
1917 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
1920 return this->type_descriptor_constructor(gogo, runtime_type_kind,
1924 // Return the type reflection string for this type.
1927 Type::reflection(Gogo* gogo) const
1931 // The do_reflection virtual function should set RET to the
1932 // reflection string.
1933 this->do_reflection(gogo, &ret);
1938 // Return a mangled name for the type.
1941 Type::mangled_name(Gogo* gogo) const
1945 // The do_mangled_name virtual function should set RET to the
1946 // mangled name. For a composite type it should append a code for
1947 // the composition and then call do_mangled_name on the components.
1948 this->do_mangled_name(gogo, &ret);
1953 // Default function to export a type.
1956 Type::do_export(Export*) const
1964 Type::import_type(Import* imp)
1966 if (imp->match_c_string("("))
1967 return Function_type::do_import(imp);
1968 else if (imp->match_c_string("*"))
1969 return Pointer_type::do_import(imp);
1970 else if (imp->match_c_string("struct "))
1971 return Struct_type::do_import(imp);
1972 else if (imp->match_c_string("["))
1973 return Array_type::do_import(imp);
1974 else if (imp->match_c_string("map "))
1975 return Map_type::do_import(imp);
1976 else if (imp->match_c_string("chan "))
1977 return Channel_type::do_import(imp);
1978 else if (imp->match_c_string("interface"))
1979 return Interface_type::do_import(imp);
1982 error_at(imp->location(), "import error: expected type");
1983 return Type::make_error_type();
1987 // A type used to indicate a parsing error. This exists to simplify
1988 // later error detection.
1990 class Error_type : public Type
1999 do_compare_is_identity() const
2003 do_get_backend(Gogo* gogo)
2004 { return gogo->backend()->error_type(); }
2007 do_type_descriptor(Gogo*, Named_type*)
2008 { return Expression::make_error(Linemap::predeclared_location()); }
2011 do_reflection(Gogo*, std::string*) const
2012 { go_assert(saw_errors()); }
2015 do_mangled_name(Gogo*, std::string* ret) const
2016 { ret->push_back('E'); }
2020 Type::make_error_type()
2022 static Error_type singleton_error_type;
2023 return &singleton_error_type;
2028 class Void_type : public Type
2037 do_compare_is_identity() const
2041 do_get_backend(Gogo* gogo)
2042 { return gogo->backend()->void_type(); }
2045 do_type_descriptor(Gogo*, Named_type*)
2046 { go_unreachable(); }
2049 do_reflection(Gogo*, std::string*) const
2053 do_mangled_name(Gogo*, std::string* ret) const
2054 { ret->push_back('v'); }
2058 Type::make_void_type()
2060 static Void_type singleton_void_type;
2061 return &singleton_void_type;
2064 // The boolean type.
2066 class Boolean_type : public Type
2070 : Type(TYPE_BOOLEAN)
2075 do_compare_is_identity() const
2079 do_get_backend(Gogo* gogo)
2080 { return gogo->backend()->bool_type(); }
2083 do_type_descriptor(Gogo*, Named_type* name);
2085 // We should not be asked for the reflection string of a basic type.
2087 do_reflection(Gogo*, std::string* ret) const
2088 { ret->append("bool"); }
2091 do_mangled_name(Gogo*, std::string* ret) const
2092 { ret->push_back('b'); }
2095 // Make the type descriptor.
2098 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2101 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
2104 Named_object* no = gogo->lookup_global("bool");
2105 go_assert(no != NULL);
2106 return Type::type_descriptor(gogo, no->type_value());
2111 Type::make_boolean_type()
2113 static Boolean_type boolean_type;
2114 return &boolean_type;
2117 // The named type "bool".
2119 static Named_type* named_bool_type;
2121 // Get the named type "bool".
2124 Type::lookup_bool_type()
2126 return named_bool_type;
2129 // Make the named type "bool".
2132 Type::make_named_bool_type()
2134 Type* bool_type = Type::make_boolean_type();
2135 Named_object* named_object =
2136 Named_object::make_type("bool", NULL, bool_type,
2137 Linemap::predeclared_location());
2138 Named_type* named_type = named_object->type_value();
2139 named_bool_type = named_type;
2143 // Class Integer_type.
2145 Integer_type::Named_integer_types Integer_type::named_integer_types;
2147 // Create a new integer type. Non-abstract integer types always have
2151 Integer_type::create_integer_type(const char* name, bool is_unsigned,
2152 int bits, int runtime_type_kind)
2154 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
2156 std::string sname(name);
2157 Named_object* named_object =
2158 Named_object::make_type(sname, NULL, integer_type,
2159 Linemap::predeclared_location());
2160 Named_type* named_type = named_object->type_value();
2161 std::pair<Named_integer_types::iterator, bool> ins =
2162 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
2163 go_assert(ins.second);
2167 // Look up an existing integer type.
2170 Integer_type::lookup_integer_type(const char* name)
2172 Named_integer_types::const_iterator p =
2173 Integer_type::named_integer_types.find(name);
2174 go_assert(p != Integer_type::named_integer_types.end());
2178 // Create a new abstract integer type.
2181 Integer_type::create_abstract_integer_type()
2183 static Integer_type* abstract_type;
2184 if (abstract_type == NULL)
2185 abstract_type = new Integer_type(true, false, INT_TYPE_SIZE,
2186 RUNTIME_TYPE_KIND_INT);
2187 return abstract_type;
2190 // Integer type compatibility.
2193 Integer_type::is_identical(const Integer_type* t) const
2195 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
2197 return this->is_abstract_ == t->is_abstract_;
2203 Integer_type::do_hash_for_method(Gogo*) const
2205 return ((this->bits_ << 4)
2206 + ((this->is_unsigned_ ? 1 : 0) << 8)
2207 + ((this->is_abstract_ ? 1 : 0) << 9));
2210 // Convert an Integer_type to the backend representation.
2213 Integer_type::do_get_backend(Gogo* gogo)
2215 if (this->is_abstract_)
2217 go_assert(saw_errors());
2218 return gogo->backend()->error_type();
2220 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
2223 // The type descriptor for an integer type. Integer types are always
2227 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2229 go_assert(name != NULL);
2230 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2233 // We should not be asked for the reflection string of a basic type.
2236 Integer_type::do_reflection(Gogo*, std::string*) const
2238 go_assert(saw_errors());
2244 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
2247 snprintf(buf, sizeof buf, "i%s%s%de",
2248 this->is_abstract_ ? "a" : "",
2249 this->is_unsigned_ ? "u" : "",
2254 // Make an integer type.
2257 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
2258 int runtime_type_kind)
2260 return Integer_type::create_integer_type(name, is_unsigned, bits,
2264 // Make an abstract integer type.
2267 Type::make_abstract_integer_type()
2269 return Integer_type::create_abstract_integer_type();
2272 // Look up an integer type.
2275 Type::lookup_integer_type(const char* name)
2277 return Integer_type::lookup_integer_type(name);
2280 // Class Float_type.
2282 Float_type::Named_float_types Float_type::named_float_types;
2284 // Create a new float type. Non-abstract float types always have
2288 Float_type::create_float_type(const char* name, int bits,
2289 int runtime_type_kind)
2291 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
2292 std::string sname(name);
2293 Named_object* named_object =
2294 Named_object::make_type(sname, NULL, float_type,
2295 Linemap::predeclared_location());
2296 Named_type* named_type = named_object->type_value();
2297 std::pair<Named_float_types::iterator, bool> ins =
2298 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
2299 go_assert(ins.second);
2303 // Look up an existing float type.
2306 Float_type::lookup_float_type(const char* name)
2308 Named_float_types::const_iterator p =
2309 Float_type::named_float_types.find(name);
2310 go_assert(p != Float_type::named_float_types.end());
2314 // Create a new abstract float type.
2317 Float_type::create_abstract_float_type()
2319 static Float_type* abstract_type;
2320 if (abstract_type == NULL)
2321 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
2322 return abstract_type;
2325 // Whether this type is identical with T.
2328 Float_type::is_identical(const Float_type* t) const
2330 if (this->bits_ != t->bits_)
2332 return this->is_abstract_ == t->is_abstract_;
2338 Float_type::do_hash_for_method(Gogo*) const
2340 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2343 // Convert to the backend representation.
2346 Float_type::do_get_backend(Gogo* gogo)
2348 return gogo->backend()->float_type(this->bits_);
2351 // The type descriptor for a float type. Float types are always named.
2354 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2356 go_assert(name != NULL);
2357 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2360 // We should not be asked for the reflection string of a basic type.
2363 Float_type::do_reflection(Gogo*, std::string*) const
2365 go_assert(saw_errors());
2371 Float_type::do_mangled_name(Gogo*, std::string* ret) const
2374 snprintf(buf, sizeof buf, "f%s%de",
2375 this->is_abstract_ ? "a" : "",
2380 // Make a floating point type.
2383 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
2385 return Float_type::create_float_type(name, bits, runtime_type_kind);
2388 // Make an abstract float type.
2391 Type::make_abstract_float_type()
2393 return Float_type::create_abstract_float_type();
2396 // Look up a float type.
2399 Type::lookup_float_type(const char* name)
2401 return Float_type::lookup_float_type(name);
2404 // Class Complex_type.
2406 Complex_type::Named_complex_types Complex_type::named_complex_types;
2408 // Create a new complex type. Non-abstract complex types always have
2412 Complex_type::create_complex_type(const char* name, int bits,
2413 int runtime_type_kind)
2415 Complex_type* complex_type = new Complex_type(false, bits,
2417 std::string sname(name);
2418 Named_object* named_object =
2419 Named_object::make_type(sname, NULL, complex_type,
2420 Linemap::predeclared_location());
2421 Named_type* named_type = named_object->type_value();
2422 std::pair<Named_complex_types::iterator, bool> ins =
2423 Complex_type::named_complex_types.insert(std::make_pair(sname,
2425 go_assert(ins.second);
2429 // Look up an existing complex type.
2432 Complex_type::lookup_complex_type(const char* name)
2434 Named_complex_types::const_iterator p =
2435 Complex_type::named_complex_types.find(name);
2436 go_assert(p != Complex_type::named_complex_types.end());
2440 // Create a new abstract complex type.
2443 Complex_type::create_abstract_complex_type()
2445 static Complex_type* abstract_type;
2446 if (abstract_type == NULL)
2447 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
2448 return abstract_type;
2451 // Whether this type is identical with T.
2454 Complex_type::is_identical(const Complex_type *t) const
2456 if (this->bits_ != t->bits_)
2458 return this->is_abstract_ == t->is_abstract_;
2464 Complex_type::do_hash_for_method(Gogo*) const
2466 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2469 // Convert to the backend representation.
2472 Complex_type::do_get_backend(Gogo* gogo)
2474 return gogo->backend()->complex_type(this->bits_);
2477 // The type descriptor for a complex type. Complex types are always
2481 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2483 go_assert(name != NULL);
2484 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2487 // We should not be asked for the reflection string of a basic type.
2490 Complex_type::do_reflection(Gogo*, std::string*) const
2492 go_assert(saw_errors());
2498 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
2501 snprintf(buf, sizeof buf, "c%s%de",
2502 this->is_abstract_ ? "a" : "",
2507 // Make a complex type.
2510 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
2512 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
2515 // Make an abstract complex type.
2518 Type::make_abstract_complex_type()
2520 return Complex_type::create_abstract_complex_type();
2523 // Look up a complex type.
2526 Type::lookup_complex_type(const char* name)
2528 return Complex_type::lookup_complex_type(name);
2531 // Class String_type.
2533 // Convert String_type to the backend representation. A string is a
2534 // struct with two fields: a pointer to the characters and a length.
2537 String_type::do_get_backend(Gogo* gogo)
2539 static Btype* backend_string_type;
2540 if (backend_string_type == NULL)
2542 std::vector<Backend::Btyped_identifier> fields(2);
2544 Type* b = gogo->lookup_global("byte")->type_value();
2545 Type* pb = Type::make_pointer_type(b);
2546 fields[0].name = "__data";
2547 fields[0].btype = pb->get_backend(gogo);
2548 fields[0].location = Linemap::predeclared_location();
2550 Type* int_type = Type::lookup_integer_type("int");
2551 fields[1].name = "__length";
2552 fields[1].btype = int_type->get_backend(gogo);
2553 fields[1].location = fields[0].location;
2555 backend_string_type = gogo->backend()->struct_type(fields);
2557 return backend_string_type;
2560 // Return a tree for the length of STRING.
2563 String_type::length_tree(Gogo*, tree string)
2565 tree string_type = TREE_TYPE(string);
2566 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2567 tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type));
2568 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)),
2570 return fold_build3(COMPONENT_REF, integer_type_node, string,
2571 length_field, NULL_TREE);
2574 // Return a tree for a pointer to the bytes of STRING.
2577 String_type::bytes_tree(Gogo*, tree string)
2579 tree string_type = TREE_TYPE(string);
2580 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2581 tree bytes_field = TYPE_FIELDS(string_type);
2582 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)),
2584 return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string,
2585 bytes_field, NULL_TREE);
2588 // The type descriptor for the string type.
2591 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2594 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
2597 Named_object* no = gogo->lookup_global("string");
2598 go_assert(no != NULL);
2599 return Type::type_descriptor(gogo, no->type_value());
2603 // We should not be asked for the reflection string of a basic type.
2606 String_type::do_reflection(Gogo*, std::string* ret) const
2608 ret->append("string");
2611 // Mangled name of a string type.
2614 String_type::do_mangled_name(Gogo*, std::string* ret) const
2616 ret->push_back('z');
2619 // Make a string type.
2622 Type::make_string_type()
2624 static String_type string_type;
2625 return &string_type;
2628 // The named type "string".
2630 static Named_type* named_string_type;
2632 // Get the named type "string".
2635 Type::lookup_string_type()
2637 return named_string_type;
2640 // Make the named type string.
2643 Type::make_named_string_type()
2645 Type* string_type = Type::make_string_type();
2646 Named_object* named_object =
2647 Named_object::make_type("string", NULL, string_type,
2648 Linemap::predeclared_location());
2649 Named_type* named_type = named_object->type_value();
2650 named_string_type = named_type;
2654 // The sink type. This is the type of the blank identifier _. Any
2655 // type may be assigned to it.
2657 class Sink_type : public Type
2666 do_compare_is_identity() const
2670 do_get_backend(Gogo*)
2671 { go_unreachable(); }
2674 do_type_descriptor(Gogo*, Named_type*)
2675 { go_unreachable(); }
2678 do_reflection(Gogo*, std::string*) const
2679 { go_unreachable(); }
2682 do_mangled_name(Gogo*, std::string*) const
2683 { go_unreachable(); }
2686 // Make the sink type.
2689 Type::make_sink_type()
2691 static Sink_type sink_type;
2695 // Class Function_type.
2700 Function_type::do_traverse(Traverse* traverse)
2702 if (this->receiver_ != NULL
2703 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
2704 return TRAVERSE_EXIT;
2705 if (this->parameters_ != NULL
2706 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
2707 return TRAVERSE_EXIT;
2708 if (this->results_ != NULL
2709 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
2710 return TRAVERSE_EXIT;
2711 return TRAVERSE_CONTINUE;
2714 // Returns whether T is a valid redeclaration of this type. If this
2715 // returns false, and REASON is not NULL, *REASON may be set to a
2716 // brief explanation of why it returned false.
2719 Function_type::is_valid_redeclaration(const Function_type* t,
2720 std::string* reason) const
2722 if (!this->is_identical(t, false, true, reason))
2725 // A redeclaration of a function is required to use the same names
2726 // for the receiver and parameters.
2727 if (this->receiver() != NULL
2728 && this->receiver()->name() != t->receiver()->name()
2729 && this->receiver()->name() != Import::import_marker
2730 && t->receiver()->name() != Import::import_marker)
2733 *reason = "receiver name changed";
2737 const Typed_identifier_list* parms1 = this->parameters();
2738 const Typed_identifier_list* parms2 = t->parameters();
2741 Typed_identifier_list::const_iterator p1 = parms1->begin();
2742 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
2743 p2 != parms2->end();
2746 if (p1->name() != p2->name()
2747 && p1->name() != Import::import_marker
2748 && p2->name() != Import::import_marker)
2751 *reason = "parameter name changed";
2755 // This is called at parse time, so we may have unknown
2757 Type* t1 = p1->type()->forwarded();
2758 Type* t2 = p2->type()->forwarded();
2760 && t1->forward_declaration_type() != NULL
2761 && (t2->forward_declaration_type() == NULL
2762 || (t1->forward_declaration_type()->named_object()
2763 != t2->forward_declaration_type()->named_object())))
2768 const Typed_identifier_list* results1 = this->results();
2769 const Typed_identifier_list* results2 = t->results();
2770 if (results1 != NULL)
2772 Typed_identifier_list::const_iterator res1 = results1->begin();
2773 for (Typed_identifier_list::const_iterator res2 = results2->begin();
2774 res2 != results2->end();
2777 if (res1->name() != res2->name()
2778 && res1->name() != Import::import_marker
2779 && res2->name() != Import::import_marker)
2782 *reason = "result name changed";
2786 // This is called at parse time, so we may have unknown
2788 Type* t1 = res1->type()->forwarded();
2789 Type* t2 = res2->type()->forwarded();
2791 && t1->forward_declaration_type() != NULL
2792 && (t2->forward_declaration_type() == NULL
2793 || (t1->forward_declaration_type()->named_object()
2794 != t2->forward_declaration_type()->named_object())))
2802 // Check whether T is the same as this type.
2805 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
2806 bool errors_are_identical,
2807 std::string* reason) const
2809 if (!ignore_receiver)
2811 const Typed_identifier* r1 = this->receiver();
2812 const Typed_identifier* r2 = t->receiver();
2813 if ((r1 != NULL) != (r2 != NULL))
2816 *reason = _("different receiver types");
2821 if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
2824 if (reason != NULL && !reason->empty())
2825 *reason = "receiver: " + *reason;
2831 const Typed_identifier_list* parms1 = this->parameters();
2832 const Typed_identifier_list* parms2 = t->parameters();
2833 if ((parms1 != NULL) != (parms2 != NULL))
2836 *reason = _("different number of parameters");
2841 Typed_identifier_list::const_iterator p1 = parms1->begin();
2842 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
2843 p2 != parms2->end();
2846 if (p1 == parms1->end())
2849 *reason = _("different number of parameters");
2853 if (!Type::are_identical(p1->type(), p2->type(),
2854 errors_are_identical, NULL))
2857 *reason = _("different parameter types");
2861 if (p1 != parms1->end())
2864 *reason = _("different number of parameters");
2869 if (this->is_varargs() != t->is_varargs())
2872 *reason = _("different varargs");
2876 const Typed_identifier_list* results1 = this->results();
2877 const Typed_identifier_list* results2 = t->results();
2878 if ((results1 != NULL) != (results2 != NULL))
2881 *reason = _("different number of results");
2884 if (results1 != NULL)
2886 Typed_identifier_list::const_iterator res1 = results1->begin();
2887 for (Typed_identifier_list::const_iterator res2 = results2->begin();
2888 res2 != results2->end();
2891 if (res1 == results1->end())
2894 *reason = _("different number of results");
2898 if (!Type::are_identical(res1->type(), res2->type(),
2899 errors_are_identical, NULL))
2902 *reason = _("different result types");
2906 if (res1 != results1->end())
2909 *reason = _("different number of results");
2920 Function_type::do_hash_for_method(Gogo* gogo) const
2922 unsigned int ret = 0;
2923 // We ignore the receiver type for hash codes, because we need to
2924 // get the same hash code for a method in an interface and a method
2925 // declared for a type. The former will not have a receiver.
2926 if (this->parameters_ != NULL)
2929 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
2930 p != this->parameters_->end();
2932 ret += p->type()->hash_for_method(gogo) << shift;
2934 if (this->results_ != NULL)
2937 for (Typed_identifier_list::const_iterator p = this->results_->begin();
2938 p != this->results_->end();
2940 ret += p->type()->hash_for_method(gogo) << shift;
2942 if (this->is_varargs_)
2948 // Get the backend representation for a function type.
2951 Function_type::get_function_backend(Gogo* gogo)
2953 Backend::Btyped_identifier breceiver;
2954 if (this->receiver_ != NULL)
2956 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
2958 // We always pass the address of the receiver parameter, in
2959 // order to make interface calls work with unknown types.
2960 Type* rtype = this->receiver_->type();
2961 if (rtype->points_to() == NULL)
2962 rtype = Type::make_pointer_type(rtype);
2963 breceiver.btype = rtype->get_backend(gogo);
2964 breceiver.location = this->receiver_->location();
2967 std::vector<Backend::Btyped_identifier> bparameters;
2968 if (this->parameters_ != NULL)
2970 bparameters.resize(this->parameters_->size());
2972 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
2973 p != this->parameters_->end();
2976 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
2977 bparameters[i].btype = p->type()->get_backend(gogo);
2978 bparameters[i].location = p->location();
2980 go_assert(i == bparameters.size());
2983 std::vector<Backend::Btyped_identifier> bresults;
2984 if (this->results_ != NULL)
2986 bresults.resize(this->results_->size());
2988 for (Typed_identifier_list::const_iterator p = this->results_->begin();
2989 p != this->results_->end();
2992 bresults[i].name = Gogo::unpack_hidden_name(p->name());
2993 bresults[i].btype = p->type()->get_backend(gogo);
2994 bresults[i].location = p->location();
2996 go_assert(i == bresults.size());
2999 return gogo->backend()->function_type(breceiver, bparameters, bresults,
3003 // A hash table mapping function types to their backend placeholders.
3005 Function_type::Placeholders Function_type::placeholders;
3007 // Get the backend representation for a function type. If we are
3008 // still converting types, and this types has multiple results, return
3009 // a placeholder instead. We do this because for multiple results we
3010 // build a struct, and we need to make sure that all the types in the
3011 // struct are valid before we create the struct.
3014 Function_type::do_get_backend(Gogo* gogo)
3016 if (!gogo->named_types_are_converted()
3017 && this->results_ != NULL
3018 && this->results_->size() > 1)
3020 Btype* placeholder =
3021 gogo->backend()->placeholder_pointer_type("", this->location(), true);
3022 Function_type::placeholders.push_back(std::make_pair(this, placeholder));
3025 return this->get_function_backend(gogo);
3028 // Convert function types after all named types are converted.
3031 Function_type::convert_types(Gogo* gogo)
3033 for (Placeholders::const_iterator p = Function_type::placeholders.begin();
3034 p != Function_type::placeholders.end();
3037 Btype* bt = p->first->get_function_backend(gogo);
3038 if (!gogo->backend()->set_placeholder_function_type(p->second, bt))
3039 go_assert(saw_errors());
3043 // The type of a function type descriptor.
3046 Function_type::make_function_type_descriptor_type()
3051 Type* tdt = Type::make_type_descriptor_type();
3052 Type* ptdt = Type::make_type_descriptor_ptr_type();
3054 Type* bool_type = Type::lookup_bool_type();
3056 Type* slice_type = Type::make_array_type(ptdt, NULL);
3058 Struct_type* s = Type::make_builtin_struct_type(4,
3060 "dotdotdot", bool_type,
3064 ret = Type::make_builtin_named_type("FuncType", s);
3070 // The type descriptor for a function type.
3073 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3075 Location bloc = Linemap::predeclared_location();
3077 Type* ftdt = Function_type::make_function_type_descriptor_type();
3079 const Struct_field_list* fields = ftdt->struct_type()->fields();
3081 Expression_list* vals = new Expression_list();
3084 Struct_field_list::const_iterator p = fields->begin();
3085 go_assert(p->is_field_name("commonType"));
3086 vals->push_back(this->type_descriptor_constructor(gogo,
3087 RUNTIME_TYPE_KIND_FUNC,
3091 go_assert(p->is_field_name("dotdotdot"));
3092 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
3095 go_assert(p->is_field_name("in"));
3096 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
3097 this->parameters()));
3100 go_assert(p->is_field_name("out"));
3101 vals->push_back(this->type_descriptor_params(p->type(), NULL,
3105 go_assert(p == fields->end());
3107 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
3110 // Return a composite literal for the parameters or results of a type
3114 Function_type::type_descriptor_params(Type* params_type,
3115 const Typed_identifier* receiver,
3116 const Typed_identifier_list* params)
3118 Location bloc = Linemap::predeclared_location();
3120 if (receiver == NULL && params == NULL)
3121 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
3123 Expression_list* vals = new Expression_list();
3124 vals->reserve((params == NULL ? 0 : params->size())
3125 + (receiver != NULL ? 1 : 0));
3127 if (receiver != NULL)
3128 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
3132 for (Typed_identifier_list::const_iterator p = params->begin();
3135 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
3138 return Expression::make_slice_composite_literal(params_type, vals, bloc);
3141 // The reflection string.
3144 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
3146 // FIXME: Turn this off until we straighten out the type of the
3147 // struct field used in a go statement which calls a method.
3148 // go_assert(this->receiver_ == NULL);
3150 ret->append("func");
3152 if (this->receiver_ != NULL)
3154 ret->push_back('(');
3155 this->append_reflection(this->receiver_->type(), gogo, ret);
3156 ret->push_back(')');
3159 ret->push_back('(');
3160 const Typed_identifier_list* params = this->parameters();
3163 bool is_varargs = this->is_varargs_;
3164 for (Typed_identifier_list::const_iterator p = params->begin();
3168 if (p != params->begin())
3170 if (!is_varargs || p + 1 != params->end())
3171 this->append_reflection(p->type(), gogo, ret);
3175 this->append_reflection(p->type()->array_type()->element_type(),
3180 ret->push_back(')');
3182 const Typed_identifier_list* results = this->results();
3183 if (results != NULL && !results->empty())
3185 if (results->size() == 1)
3186 ret->push_back(' ');
3189 for (Typed_identifier_list::const_iterator p = results->begin();
3190 p != results->end();
3193 if (p != results->begin())
3195 this->append_reflection(p->type(), gogo, ret);
3197 if (results->size() > 1)
3198 ret->push_back(')');
3205 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3207 ret->push_back('F');
3209 if (this->receiver_ != NULL)
3211 ret->push_back('m');
3212 this->append_mangled_name(this->receiver_->type(), gogo, ret);
3215 const Typed_identifier_list* params = this->parameters();
3218 ret->push_back('p');
3219 for (Typed_identifier_list::const_iterator p = params->begin();
3222 this->append_mangled_name(p->type(), gogo, ret);
3223 if (this->is_varargs_)
3224 ret->push_back('V');
3225 ret->push_back('e');
3228 const Typed_identifier_list* results = this->results();
3229 if (results != NULL)
3231 ret->push_back('r');
3232 for (Typed_identifier_list::const_iterator p = results->begin();
3233 p != results->end();
3235 this->append_mangled_name(p->type(), gogo, ret);
3236 ret->push_back('e');
3239 ret->push_back('e');
3242 // Export a function type.
3245 Function_type::do_export(Export* exp) const
3247 // We don't write out the receiver. The only function types which
3248 // should have a receiver are the ones associated with explicitly
3249 // defined methods. For those the receiver type is written out by
3250 // Function::export_func.
3252 exp->write_c_string("(");
3254 if (this->parameters_ != NULL)
3256 bool is_varargs = this->is_varargs_;
3257 for (Typed_identifier_list::const_iterator p =
3258 this->parameters_->begin();
3259 p != this->parameters_->end();
3265 exp->write_c_string(", ");
3266 if (!is_varargs || p + 1 != this->parameters_->end())
3267 exp->write_type(p->type());
3270 exp->write_c_string("...");
3271 exp->write_type(p->type()->array_type()->element_type());
3275 exp->write_c_string(")");
3277 const Typed_identifier_list* results = this->results_;
3278 if (results != NULL)
3280 exp->write_c_string(" ");
3281 if (results->size() == 1)
3282 exp->write_type(results->begin()->type());
3286 exp->write_c_string("(");
3287 for (Typed_identifier_list::const_iterator p = results->begin();
3288 p != results->end();
3294 exp->write_c_string(", ");
3295 exp->write_type(p->type());
3297 exp->write_c_string(")");
3302 // Import a function type.
3305 Function_type::do_import(Import* imp)
3307 imp->require_c_string("(");
3308 Typed_identifier_list* parameters;
3309 bool is_varargs = false;
3310 if (imp->peek_char() == ')')
3314 parameters = new Typed_identifier_list();
3317 if (imp->match_c_string("..."))
3323 Type* ptype = imp->read_type();
3325 ptype = Type::make_array_type(ptype, NULL);
3326 parameters->push_back(Typed_identifier(Import::import_marker,
3327 ptype, imp->location()));
3328 if (imp->peek_char() != ',')
3330 go_assert(!is_varargs);
3331 imp->require_c_string(", ");
3334 imp->require_c_string(")");
3336 Typed_identifier_list* results;
3337 if (imp->peek_char() != ' ')
3342 results = new Typed_identifier_list;
3343 if (imp->peek_char() != '(')
3345 Type* rtype = imp->read_type();
3346 results->push_back(Typed_identifier(Import::import_marker, rtype,
3354 Type* rtype = imp->read_type();
3355 results->push_back(Typed_identifier(Import::import_marker,
3356 rtype, imp->location()));
3357 if (imp->peek_char() != ',')
3359 imp->require_c_string(", ");
3361 imp->require_c_string(")");
3365 Function_type* ret = Type::make_function_type(NULL, parameters, results,
3368 ret->set_is_varargs();
3372 // Make a copy of a function type without a receiver.
3375 Function_type::copy_without_receiver() const
3377 go_assert(this->is_method());
3378 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
3381 if (this->is_varargs())
3382 ret->set_is_varargs();
3383 if (this->is_builtin())
3384 ret->set_is_builtin();
3388 // Make a copy of a function type with a receiver.
3391 Function_type::copy_with_receiver(Type* receiver_type) const
3393 go_assert(!this->is_method());
3394 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
3396 return Type::make_function_type(receiver, this->parameters_,
3397 this->results_, this->location_);
3400 // Make a function type.
3403 Type::make_function_type(Typed_identifier* receiver,
3404 Typed_identifier_list* parameters,
3405 Typed_identifier_list* results,
3408 return new Function_type(receiver, parameters, results, location);
3411 // Class Pointer_type.
3416 Pointer_type::do_traverse(Traverse* traverse)
3418 return Type::traverse(this->to_type_, traverse);
3424 Pointer_type::do_hash_for_method(Gogo* gogo) const
3426 return this->to_type_->hash_for_method(gogo) << 4;
3429 // The tree for a pointer type.
3432 Pointer_type::do_get_backend(Gogo* gogo)
3434 Btype* to_btype = this->to_type_->get_backend(gogo);
3435 return gogo->backend()->pointer_type(to_btype);
3438 // The type of a pointer type descriptor.
3441 Pointer_type::make_pointer_type_descriptor_type()
3446 Type* tdt = Type::make_type_descriptor_type();
3447 Type* ptdt = Type::make_type_descriptor_ptr_type();
3449 Struct_type* s = Type::make_builtin_struct_type(2,
3453 ret = Type::make_builtin_named_type("PtrType", s);
3459 // The type descriptor for a pointer type.
3462 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3464 if (this->is_unsafe_pointer_type())
3466 go_assert(name != NULL);
3467 return this->plain_type_descriptor(gogo,
3468 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
3473 Location bloc = Linemap::predeclared_location();
3475 const Methods* methods;
3476 Type* deref = this->points_to();
3477 if (deref->named_type() != NULL)
3478 methods = deref->named_type()->methods();
3479 else if (deref->struct_type() != NULL)
3480 methods = deref->struct_type()->methods();
3484 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
3486 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
3488 Expression_list* vals = new Expression_list();
3491 Struct_field_list::const_iterator p = fields->begin();
3492 go_assert(p->is_field_name("commonType"));
3493 vals->push_back(this->type_descriptor_constructor(gogo,
3494 RUNTIME_TYPE_KIND_PTR,
3495 name, methods, false));
3498 go_assert(p->is_field_name("elem"));
3499 vals->push_back(Expression::make_type_descriptor(deref, bloc));
3501 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
3505 // Reflection string.
3508 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
3510 ret->push_back('*');
3511 this->append_reflection(this->to_type_, gogo, ret);
3517 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3519 ret->push_back('p');
3520 this->append_mangled_name(this->to_type_, gogo, ret);
3526 Pointer_type::do_export(Export* exp) const
3528 exp->write_c_string("*");
3529 if (this->is_unsafe_pointer_type())
3530 exp->write_c_string("any");
3532 exp->write_type(this->to_type_);
3538 Pointer_type::do_import(Import* imp)
3540 imp->require_c_string("*");
3541 if (imp->match_c_string("any"))
3544 return Type::make_pointer_type(Type::make_void_type());
3546 Type* to = imp->read_type();
3547 return Type::make_pointer_type(to);
3550 // Make a pointer type.
3553 Type::make_pointer_type(Type* to_type)
3555 typedef Unordered_map(Type*, Pointer_type*) Hashtable;
3556 static Hashtable pointer_types;
3557 Hashtable::const_iterator p = pointer_types.find(to_type);
3558 if (p != pointer_types.end())
3560 Pointer_type* ret = new Pointer_type(to_type);
3561 pointer_types[to_type] = ret;
3565 // The nil type. We use a special type for nil because it is not the
3566 // same as any other type. In C term nil has type void*, but there is
3567 // no such type in Go.
3569 class Nil_type : public Type
3578 do_compare_is_identity() const
3582 do_get_backend(Gogo* gogo)
3583 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
3586 do_type_descriptor(Gogo*, Named_type*)
3587 { go_unreachable(); }
3590 do_reflection(Gogo*, std::string*) const
3591 { go_unreachable(); }
3594 do_mangled_name(Gogo*, std::string* ret) const
3595 { ret->push_back('n'); }
3598 // Make the nil type.
3601 Type::make_nil_type()
3603 static Nil_type singleton_nil_type;
3604 return &singleton_nil_type;
3607 // The type of a function call which returns multiple values. This is
3608 // really a struct, but we don't want to confuse a function call which
3609 // returns a struct with a function call which returns multiple
3612 class Call_multiple_result_type : public Type
3615 Call_multiple_result_type(Call_expression* call)
3616 : Type(TYPE_CALL_MULTIPLE_RESULT),
3622 do_has_pointer() const
3624 go_assert(saw_errors());
3629 do_compare_is_identity() const
3633 do_get_backend(Gogo* gogo)
3635 go_assert(saw_errors());
3636 return gogo->backend()->error_type();
3640 do_type_descriptor(Gogo*, Named_type*)
3642 go_assert(saw_errors());
3643 return Expression::make_error(Linemap::unknown_location());
3647 do_reflection(Gogo*, std::string*) const
3648 { go_assert(saw_errors()); }
3651 do_mangled_name(Gogo*, std::string*) const
3652 { go_assert(saw_errors()); }
3655 // The expression being called.
3656 Call_expression* call_;
3659 // Make a call result type.
3662 Type::make_call_multiple_result_type(Call_expression* call)
3664 return new Call_multiple_result_type(call);
3667 // Class Struct_field.
3669 // Get the name of a field.
3672 Struct_field::field_name() const
3674 const std::string& name(this->typed_identifier_.name());
3679 // This is called during parsing, before anything is lowered, so
3680 // we have to be pretty careful to avoid dereferencing an
3681 // unknown type name.
3682 Type* t = this->typed_identifier_.type();
3684 if (t->classification() == Type::TYPE_POINTER)
3687 Pointer_type* ptype = static_cast<Pointer_type*>(t);
3688 dt = ptype->points_to();
3690 if (dt->forward_declaration_type() != NULL)
3691 return dt->forward_declaration_type()->name();
3692 else if (dt->named_type() != NULL)
3693 return dt->named_type()->name();
3694 else if (t->is_error_type() || dt->is_error_type())
3696 static const std::string error_string = "*error*";
3697 return error_string;
3701 // Avoid crashing in the erroneous case where T is named but
3704 if (t->forward_declaration_type() != NULL)
3705 return t->forward_declaration_type()->name();
3706 else if (t->named_type() != NULL)
3707 return t->named_type()->name();
3714 // Return whether this field is named NAME.
3717 Struct_field::is_field_name(const std::string& name) const
3719 const std::string& me(this->typed_identifier_.name());
3724 Type* t = this->typed_identifier_.type();
3725 if (t->points_to() != NULL)
3727 Named_type* nt = t->named_type();
3728 if (nt != NULL && nt->name() == name)
3731 // This is a horrible hack caused by the fact that we don't pack
3732 // the names of builtin types. FIXME.
3735 && nt->name() == Gogo::unpack_hidden_name(name))
3742 // Class Struct_type.
3747 Struct_type::do_traverse(Traverse* traverse)
3749 Struct_field_list* fields = this->fields_;
3752 for (Struct_field_list::iterator p = fields->begin();
3756 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
3757 return TRAVERSE_EXIT;
3760 return TRAVERSE_CONTINUE;
3763 // Verify that the struct type is complete and valid.
3766 Struct_type::do_verify()
3768 Struct_field_list* fields = this->fields_;
3772 for (Struct_field_list::iterator p = fields->begin();
3776 Type* t = p->type();
3777 if (t->is_undefined())
3779 error_at(p->location(), "struct field type is incomplete");
3780 p->set_type(Type::make_error_type());
3783 else if (p->is_anonymous())
3785 if (t->named_type() != NULL && t->points_to() != NULL)
3787 error_at(p->location(), "embedded type may not be a pointer");
3788 p->set_type(Type::make_error_type());
3791 if (t->points_to() != NULL
3792 && t->points_to()->interface_type() != NULL)
3794 error_at(p->location(),
3795 "embedded type may not be pointer to interface");
3796 p->set_type(Type::make_error_type());
3804 // Whether this contains a pointer.
3807 Struct_type::do_has_pointer() const
3809 const Struct_field_list* fields = this->fields();
3812 for (Struct_field_list::const_iterator p = fields->begin();
3816 if (p->type()->has_pointer())
3822 // Whether this type is identical to T.
3825 Struct_type::is_identical(const Struct_type* t,
3826 bool errors_are_identical) const
3828 const Struct_field_list* fields1 = this->fields();
3829 const Struct_field_list* fields2 = t->fields();
3830 if (fields1 == NULL || fields2 == NULL)
3831 return fields1 == fields2;
3832 Struct_field_list::const_iterator pf2 = fields2->begin();
3833 for (Struct_field_list::const_iterator pf1 = fields1->begin();
3834 pf1 != fields1->end();
3837 if (pf2 == fields2->end())
3839 if (pf1->field_name() != pf2->field_name())
3841 if (pf1->is_anonymous() != pf2->is_anonymous()
3842 || !Type::are_identical(pf1->type(), pf2->type(),
3843 errors_are_identical, NULL))
3845 if (!pf1->has_tag())
3852 if (!pf2->has_tag())
3854 if (pf1->tag() != pf2->tag())
3858 if (pf2 != fields2->end())
3863 // Whether this struct type has any hidden fields.
3866 Struct_type::struct_has_hidden_fields(const Named_type* within,
3867 std::string* reason) const
3869 const Struct_field_list* fields = this->fields();
3872 const Package* within_package = (within == NULL
3874 : within->named_object()->package());
3875 for (Struct_field_list::const_iterator pf = fields->begin();
3876 pf != fields->end();
3879 if (within_package != NULL
3880 && !pf->is_anonymous()
3881 && Gogo::is_hidden_name(pf->field_name()))
3885 std::string within_name = within->named_object()->message_name();
3886 std::string name = Gogo::message_name(pf->field_name());
3887 size_t bufsize = 200 + within_name.length() + name.length();
3888 char* buf = new char[bufsize];
3889 snprintf(buf, bufsize,
3890 _("implicit assignment of %s%s%s hidden field %s%s%s"),
3891 open_quote, within_name.c_str(), close_quote,
3892 open_quote, name.c_str(), close_quote);
3893 reason->assign(buf);
3899 if (pf->type()->has_hidden_fields(within, reason))
3906 // Whether comparisons of this struct type are simple identity
3910 Struct_type::do_compare_is_identity() const
3912 const Struct_field_list* fields = this->fields_;
3915 for (Struct_field_list::const_iterator pf = fields->begin();
3916 pf != fields->end();
3918 if (!pf->type()->compare_is_identity())
3923 // Build identity and hash functions for this struct.
3928 Struct_type::do_hash_for_method(Gogo* gogo) const
3930 unsigned int ret = 0;
3931 if (this->fields() != NULL)
3933 for (Struct_field_list::const_iterator pf = this->fields()->begin();
3934 pf != this->fields()->end();
3936 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
3941 // Find the local field NAME.
3944 Struct_type::find_local_field(const std::string& name,
3945 unsigned int *pindex) const
3947 const Struct_field_list* fields = this->fields_;
3951 for (Struct_field_list::const_iterator pf = fields->begin();
3952 pf != fields->end();
3955 if (pf->is_field_name(name))
3965 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
3967 Field_reference_expression*
3968 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
3969 Location location) const
3972 return this->field_reference_depth(struct_expr, name, location, NULL,
3976 // Return an expression for a field, along with the depth at which it
3979 Field_reference_expression*
3980 Struct_type::field_reference_depth(Expression* struct_expr,
3981 const std::string& name,
3983 Saw_named_type* saw,
3984 unsigned int* depth) const
3986 const Struct_field_list* fields = this->fields_;
3990 // Look for a field with this name.
3992 for (Struct_field_list::const_iterator pf = fields->begin();
3993 pf != fields->end();
3996 if (pf->is_field_name(name))
3999 return Expression::make_field_reference(struct_expr, i, location);
4003 // Look for an anonymous field which contains a field with this
4005 unsigned int found_depth = 0;
4006 Field_reference_expression* ret = NULL;
4008 for (Struct_field_list::const_iterator pf = fields->begin();
4009 pf != fields->end();
4012 if (!pf->is_anonymous())
4015 Struct_type* st = pf->type()->deref()->struct_type();
4019 Saw_named_type* hold_saw = saw;
4020 Saw_named_type saw_here;
4021 Named_type* nt = pf->type()->named_type();
4023 nt = pf->type()->deref()->named_type();
4027 for (q = saw; q != NULL; q = q->next)
4031 // If this is an error, it will be reported
4038 saw_here.next = saw;
4043 // Look for a reference using a NULL struct expression. If we
4044 // find one, fill in the struct expression with a reference to
4046 unsigned int subdepth;
4047 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
4057 if (ret == NULL || subdepth < found_depth)
4062 found_depth = subdepth;
4063 Expression* here = Expression::make_field_reference(struct_expr, i,
4065 if (pf->type()->points_to() != NULL)
4066 here = Expression::make_unary(OPERATOR_MULT, here, location);
4067 while (sub->expr() != NULL)
4069 sub = sub->expr()->deref()->field_reference_expression();
4070 go_assert(sub != NULL);
4072 sub->set_struct_expression(here);
4074 else if (subdepth > found_depth)
4078 // We do not handle ambiguity here--it should be handled by
4079 // Type::bind_field_or_method.
4087 *depth = found_depth + 1;
4092 // Return the total number of fields, including embedded fields.
4095 Struct_type::total_field_count() const
4097 if (this->fields_ == NULL)
4099 unsigned int ret = 0;
4100 for (Struct_field_list::const_iterator pf = this->fields_->begin();
4101 pf != this->fields_->end();
4104 if (!pf->is_anonymous() || pf->type()->deref()->struct_type() == NULL)
4107 ret += pf->type()->struct_type()->total_field_count();
4112 // Return whether NAME is an unexported field, for better error reporting.
4115 Struct_type::is_unexported_local_field(Gogo* gogo,
4116 const std::string& name) const
4118 const Struct_field_list* fields = this->fields_;
4121 for (Struct_field_list::const_iterator pf = fields->begin();
4122 pf != fields->end();
4125 const std::string& field_name(pf->field_name());
4126 if (Gogo::is_hidden_name(field_name)
4127 && name == Gogo::unpack_hidden_name(field_name)
4128 && gogo->pack_hidden_name(name, false) != field_name)
4135 // Finalize the methods of an unnamed struct.
4138 Struct_type::finalize_methods(Gogo* gogo)
4140 // If this type needs explicit comparison and hash functions, create
4141 // them now. It would be a bit better to do this only if the
4142 // functions are needed, but they will be static so the backend can
4143 // discard them if they are not used.
4144 if (!this->compare_is_identity() && this->is_comparable())
4146 Named_object* hash_fn;
4147 Named_object* equal_fn;
4148 this->type_functions(gogo, NULL, NULL, NULL, &hash_fn, &equal_fn);
4151 if (this->all_methods_ != NULL)
4153 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
4156 // Return the method NAME, or NULL if there isn't one or if it is
4157 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
4161 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
4163 return Type::method_function(this->all_methods_, name, is_ambiguous);
4166 // Convert struct fields to the backend representation. This is not
4167 // declared in types.h so that types.h doesn't have to #include
4171 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
4172 std::vector<Backend::Btyped_identifier>* bfields)
4174 bfields->resize(fields->size());
4176 for (Struct_field_list::const_iterator p = fields->begin();
4180 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
4181 (*bfields)[i].btype = p->type()->get_backend(gogo);
4182 (*bfields)[i].location = p->location();
4184 go_assert(i == fields->size());
4187 // Get the tree for a struct type.
4190 Struct_type::do_get_backend(Gogo* gogo)
4192 std::vector<Backend::Btyped_identifier> bfields;
4193 get_backend_struct_fields(gogo, this->fields_, &bfields);
4194 return gogo->backend()->struct_type(bfields);
4197 // The type of a struct type descriptor.
4200 Struct_type::make_struct_type_descriptor_type()
4205 Type* tdt = Type::make_type_descriptor_type();
4206 Type* ptdt = Type::make_type_descriptor_ptr_type();
4208 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4209 Type* string_type = Type::lookup_string_type();
4210 Type* pointer_string_type = Type::make_pointer_type(string_type);
4213 Type::make_builtin_struct_type(5,
4214 "name", pointer_string_type,
4215 "pkgPath", pointer_string_type,
4217 "tag", pointer_string_type,
4218 "offset", uintptr_type);
4219 Type* nsf = Type::make_builtin_named_type("structField", sf);
4221 Type* slice_type = Type::make_array_type(nsf, NULL);
4223 Struct_type* s = Type::make_builtin_struct_type(2,
4225 "fields", slice_type);
4227 ret = Type::make_builtin_named_type("StructType", s);
4233 // Build a type descriptor for a struct type.
4236 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4238 Location bloc = Linemap::predeclared_location();
4240 Type* stdt = Struct_type::make_struct_type_descriptor_type();
4242 const Struct_field_list* fields = stdt->struct_type()->fields();
4244 Expression_list* vals = new Expression_list();
4247 const Methods* methods = this->methods();
4248 // A named struct should not have methods--the methods should attach
4249 // to the named type.
4250 go_assert(methods == NULL || name == NULL);
4252 Struct_field_list::const_iterator ps = fields->begin();
4253 go_assert(ps->is_field_name("commonType"));
4254 vals->push_back(this->type_descriptor_constructor(gogo,
4255 RUNTIME_TYPE_KIND_STRUCT,
4256 name, methods, true));
4259 go_assert(ps->is_field_name("fields"));
4261 Expression_list* elements = new Expression_list();
4262 elements->reserve(this->fields_->size());
4263 Type* element_type = ps->type()->array_type()->element_type();
4264 for (Struct_field_list::const_iterator pf = this->fields_->begin();
4265 pf != this->fields_->end();
4268 const Struct_field_list* f = element_type->struct_type()->fields();
4270 Expression_list* fvals = new Expression_list();
4273 Struct_field_list::const_iterator q = f->begin();
4274 go_assert(q->is_field_name("name"));
4275 if (pf->is_anonymous())
4276 fvals->push_back(Expression::make_nil(bloc));
4279 std::string n = Gogo::unpack_hidden_name(pf->field_name());
4280 Expression* s = Expression::make_string(n, bloc);
4281 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4285 go_assert(q->is_field_name("pkgPath"));
4286 if (!Gogo::is_hidden_name(pf->field_name()))
4287 fvals->push_back(Expression::make_nil(bloc));
4290 std::string n = Gogo::hidden_name_prefix(pf->field_name());
4291 Expression* s = Expression::make_string(n, bloc);
4292 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4296 go_assert(q->is_field_name("typ"));
4297 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
4300 go_assert(q->is_field_name("tag"));
4302 fvals->push_back(Expression::make_nil(bloc));
4305 Expression* s = Expression::make_string(pf->tag(), bloc);
4306 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4310 go_assert(q->is_field_name("offset"));
4311 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
4313 Expression* v = Expression::make_struct_composite_literal(element_type,
4315 elements->push_back(v);
4318 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
4321 return Expression::make_struct_composite_literal(stdt, vals, bloc);
4324 // Write the hash function for a struct which can not use the identity
4328 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
4329 Function_type* hash_fntype,
4330 Function_type* equal_fntype)
4332 Location bloc = Linemap::predeclared_location();
4334 // The pointer to the struct that we are going to hash. This is an
4335 // argument to the hash function we are implementing here.
4336 Named_object* key_arg = gogo->lookup("key", NULL);
4337 go_assert(key_arg != NULL);
4338 Type* key_arg_type = key_arg->var_value()->type();
4340 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4344 mpz_init_set_ui(ival, 0);
4345 Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
4348 // Make a temporary to hold the return value, initialized to 0.
4349 Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
4351 gogo->add_statement(retval);
4353 // Make a temporary to hold the key as a uintptr.
4354 Expression* ref = Expression::make_var_reference(key_arg, bloc);
4355 ref = Expression::make_cast(uintptr_type, ref, bloc);
4356 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
4358 gogo->add_statement(key);
4360 // Loop over the struct fields.
4362 const Struct_field_list* fields = this->fields_;
4363 for (Struct_field_list::const_iterator pf = fields->begin();
4364 pf != fields->end();
4371 // Multiply retval by 33.
4372 mpz_init_set_ui(ival, 33);
4373 Expression* i33 = Expression::make_integer(&ival, uintptr_type,
4377 ref = Expression::make_temporary_reference(retval, bloc);
4378 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ,
4380 gogo->add_statement(s);
4383 // Get a pointer to the value of this field.
4384 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
4385 ref = Expression::make_temporary_reference(key, bloc);
4386 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
4388 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
4390 // Get the size of this field.
4391 Expression* size = Expression::make_type_info(pf->type(),
4392 Expression::TYPE_INFO_SIZE);
4394 // Get the hash function to use for the type of this field.
4395 Named_object* hash_fn;
4396 Named_object* equal_fn;
4397 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
4398 equal_fntype, &hash_fn, &equal_fn);
4400 // Call the hash function for the field.
4401 Expression_list* args = new Expression_list();
4402 args->push_back(subkey);
4403 args->push_back(size);
4404 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
4405 Expression* call = Expression::make_call(func, args, false, bloc);
4407 // Add the field's hash value to retval.
4408 Temporary_reference_expression* tref =
4409 Expression::make_temporary_reference(retval, bloc);
4410 tref->set_is_lvalue();
4411 Statement* s = Statement::make_assignment_operation(OPERATOR_PLUSEQ,
4413 gogo->add_statement(s);
4416 // Return retval to the caller of the hash function.
4417 Expression_list* vals = new Expression_list();
4418 ref = Expression::make_temporary_reference(retval, bloc);
4419 vals->push_back(ref);
4420 Statement* s = Statement::make_return_statement(vals, bloc);
4421 gogo->add_statement(s);
4424 // Write the equality function for a struct which can not use the
4425 // identity function.
4428 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
4430 Location bloc = Linemap::predeclared_location();
4432 // The pointers to the structs we are going to compare.
4433 Named_object* key1_arg = gogo->lookup("key1", NULL);
4434 Named_object* key2_arg = gogo->lookup("key2", NULL);
4435 go_assert(key1_arg != NULL && key2_arg != NULL);
4437 // Build temporaries with the right types.
4438 Type* pt = Type::make_pointer_type(name != NULL
4439 ? static_cast<Type*>(name)
4440 : static_cast<Type*>(this));
4442 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
4443 ref = Expression::make_unsafe_cast(pt, ref, bloc);
4444 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
4445 gogo->add_statement(p1);
4447 ref = Expression::make_var_reference(key2_arg, bloc);
4448 ref = Expression::make_unsafe_cast(pt, ref, bloc);
4449 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
4450 gogo->add_statement(p2);
4452 const Struct_field_list* fields = this->fields_;
4453 unsigned int field_index = 0;
4454 for (Struct_field_list::const_iterator pf = fields->begin();
4455 pf != fields->end();
4456 ++pf, ++field_index)
4458 // Compare one field in both P1 and P2.
4459 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
4460 f1 = Expression::make_unary(OPERATOR_MULT, f1, bloc);
4461 f1 = Expression::make_field_reference(f1, field_index, bloc);
4463 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
4464 f2 = Expression::make_unary(OPERATOR_MULT, f2, bloc);
4465 f2 = Expression::make_field_reference(f2, field_index, bloc);
4467 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
4469 // If the values are not equal, return false.
4470 gogo->start_block(bloc);
4471 Expression_list* vals = new Expression_list();
4472 vals->push_back(Expression::make_boolean(false, bloc));
4473 Statement* s = Statement::make_return_statement(vals, bloc);
4474 gogo->add_statement(s);
4475 Block* then_block = gogo->finish_block(bloc);
4477 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
4478 gogo->add_statement(s);
4481 // All the fields are equal, so return true.
4482 Expression_list* vals = new Expression_list();
4483 vals->push_back(Expression::make_boolean(true, bloc));
4484 Statement* s = Statement::make_return_statement(vals, bloc);
4485 gogo->add_statement(s);
4488 // Reflection string.
4491 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
4493 ret->append("struct { ");
4495 for (Struct_field_list::const_iterator p = this->fields_->begin();
4496 p != this->fields_->end();
4499 if (p != this->fields_->begin())
4501 if (p->is_anonymous())
4502 ret->push_back('?');
4504 ret->append(Gogo::unpack_hidden_name(p->field_name()));
4505 ret->push_back(' ');
4506 this->append_reflection(p->type(), gogo, ret);
4510 const std::string& tag(p->tag());
4512 for (std::string::const_iterator p = tag.begin();
4517 ret->append("\\x00");
4518 else if (*p == '\n')
4520 else if (*p == '\t')
4523 ret->append("\\\"");
4524 else if (*p == '\\')
4525 ret->append("\\\\");
4529 ret->push_back('"');
4539 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4541 ret->push_back('S');
4543 const Struct_field_list* fields = this->fields_;
4546 for (Struct_field_list::const_iterator p = fields->begin();
4550 if (p->is_anonymous())
4554 std::string n = Gogo::unpack_hidden_name(p->field_name());
4556 snprintf(buf, sizeof buf, "%u_",
4557 static_cast<unsigned int>(n.length()));
4561 this->append_mangled_name(p->type(), gogo, ret);
4564 const std::string& tag(p->tag());
4566 for (std::string::const_iterator p = tag.begin();
4570 if (ISALNUM(*p) || *p == '_')
4575 snprintf(buf, sizeof buf, ".%x.",
4576 static_cast<unsigned int>(*p));
4581 snprintf(buf, sizeof buf, "T%u_",
4582 static_cast<unsigned int>(out.length()));
4589 ret->push_back('e');
4595 Struct_type::do_export(Export* exp) const
4597 exp->write_c_string("struct { ");
4598 const Struct_field_list* fields = this->fields_;
4599 go_assert(fields != NULL);
4600 for (Struct_field_list::const_iterator p = fields->begin();
4604 if (p->is_anonymous())
4605 exp->write_string("? ");
4608 exp->write_string(p->field_name());
4609 exp->write_c_string(" ");
4611 exp->write_type(p->type());
4615 exp->write_c_string(" ");
4617 Expression::make_string(p->tag(), Linemap::predeclared_location());
4618 expr->export_expression(exp);
4622 exp->write_c_string("; ");
4624 exp->write_c_string("}");
4630 Struct_type::do_import(Import* imp)
4632 imp->require_c_string("struct { ");
4633 Struct_field_list* fields = new Struct_field_list;
4634 if (imp->peek_char() != '}')
4639 if (imp->match_c_string("? "))
4643 name = imp->read_identifier();
4644 imp->require_c_string(" ");
4646 Type* ftype = imp->read_type();
4648 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
4650 if (imp->peek_char() == ' ')
4653 Expression* expr = Expression::import_expression(imp);
4654 String_expression* sexpr = expr->string_expression();
4655 go_assert(sexpr != NULL);
4656 sf.set_tag(sexpr->val());
4660 imp->require_c_string("; ");
4661 fields->push_back(sf);
4662 if (imp->peek_char() == '}')
4666 imp->require_c_string("}");
4668 return Type::make_struct_type(fields, imp->location());
4671 // Make a struct type.
4674 Type::make_struct_type(Struct_field_list* fields,
4677 return new Struct_type(fields, location);
4680 // Class Array_type.
4682 // Whether two array types are identical.
4685 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
4687 if (!Type::are_identical(this->element_type(), t->element_type(),
4688 errors_are_identical, NULL))
4691 Expression* l1 = this->length();
4692 Expression* l2 = t->length();
4694 // Slices of the same element type are identical.
4695 if (l1 == NULL && l2 == NULL)
4698 // Arrays of the same element type are identical if they have the
4700 if (l1 != NULL && l2 != NULL)
4705 // Try to determine the lengths. If we can't, assume the arrays
4706 // are not identical.
4714 if (l1->integer_constant_value(true, v1, &type1)
4715 && l2->integer_constant_value(true, v2, &type2))
4716 ret = mpz_cmp(v1, v2) == 0;
4722 // Otherwise the arrays are not identical.
4726 // If this type needs explicit comparison and hash functions, create
4727 // them now. It would be a bit better to do this only if the
4728 // functions are needed, but they will be static so the backend can
4729 // discard them if they are not used.
4732 Array_type::finalize_methods(Gogo* gogo)
4734 if (this->length_ != NULL
4735 && !this->length_->is_nil_expression()
4736 && !this->compare_is_identity()
4737 && this->is_comparable())
4739 Named_object* hash_fn;
4740 Named_object* equal_fn;
4741 this->type_functions(gogo, NULL, NULL, NULL, &hash_fn, &equal_fn);
4748 Array_type::do_traverse(Traverse* traverse)
4750 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
4751 return TRAVERSE_EXIT;
4752 if (this->length_ != NULL
4753 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
4754 return TRAVERSE_EXIT;
4755 return TRAVERSE_CONTINUE;
4758 // Check that the length is valid.
4761 Array_type::verify_length()
4763 if (this->length_ == NULL)
4766 Type_context context(Type::lookup_integer_type("int"), false);
4767 this->length_->determine_type(&context);
4769 if (!this->length_->is_constant())
4771 error_at(this->length_->location(), "array bound is not constant");
4778 if (!this->length_->integer_constant_value(true, val, &vt))
4782 if (!this->length_->float_constant_value(fval, &vt))
4784 if (this->length_->type()->integer_type() != NULL
4785 || this->length_->type()->float_type() != NULL)
4786 error_at(this->length_->location(),
4787 "array bound is not constant");
4789 error_at(this->length_->location(),
4790 "array bound is not numeric");
4795 if (!mpfr_integer_p(fval))
4797 error_at(this->length_->location(),
4798 "array bound truncated to integer");
4804 mpfr_get_z(val, fval, GMP_RNDN);
4808 if (mpz_sgn(val) < 0)
4810 error_at(this->length_->location(), "negative array bound");
4815 Type* int_type = Type::lookup_integer_type("int");
4816 int tbits = int_type->integer_type()->bits();
4817 int vbits = mpz_sizeinbase(val, 2);
4818 if (vbits + 1 > tbits)
4820 error_at(this->length_->location(), "array bound overflows");
4833 Array_type::do_verify()
4835 if (!this->verify_length())
4837 this->length_ = Expression::make_error(this->length_->location());
4843 // Array type hash code.
4846 Array_type::do_hash_for_method(Gogo* gogo) const
4848 // There is no very convenient way to get a hash code for the
4850 return this->element_type_->hash_for_method(gogo) + 1;
4853 // Write the hash function for an array which can not use the identify
4857 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
4858 Function_type* hash_fntype,
4859 Function_type* equal_fntype)
4861 Location bloc = Linemap::predeclared_location();
4863 // The pointer to the array that we are going to hash. This is an
4864 // argument to the hash function we are implementing here.
4865 Named_object* key_arg = gogo->lookup("key", NULL);
4866 go_assert(key_arg != NULL);
4867 Type* key_arg_type = key_arg->var_value()->type();
4869 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4873 mpz_init_set_ui(ival, 0);
4874 Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
4877 // Make a temporary to hold the return value, initialized to 0.
4878 Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
4880 gogo->add_statement(retval);
4882 // Make a temporary to hold the key as a uintptr.
4883 Expression* ref = Expression::make_var_reference(key_arg, bloc);
4884 ref = Expression::make_cast(uintptr_type, ref, bloc);
4885 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
4887 gogo->add_statement(key);
4889 // Loop over the array elements.
4891 Type* int_type = Type::lookup_integer_type("int");
4892 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
4893 gogo->add_statement(index);
4895 Expression* iref = Expression::make_temporary_reference(index, bloc);
4896 Expression* aref = Expression::make_var_reference(key_arg, bloc);
4897 Type* pt = Type::make_pointer_type(name != NULL
4898 ? static_cast<Type*>(name)
4899 : static_cast<Type*>(this));
4900 aref = Expression::make_cast(pt, aref, bloc);
4901 For_range_statement* for_range = Statement::make_for_range_statement(iref,
4906 gogo->start_block(bloc);
4908 // Multiply retval by 33.
4909 mpz_init_set_ui(ival, 33);
4910 Expression* i33 = Expression::make_integer(&ival, uintptr_type, bloc);
4913 ref = Expression::make_temporary_reference(retval, bloc);
4914 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ, ref,
4916 gogo->add_statement(s);
4918 // Get the hash function for the element type.
4919 Named_object* hash_fn;
4920 Named_object* equal_fn;
4921 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
4922 hash_fntype, equal_fntype, &hash_fn,
4925 // Get a pointer to this element in the loop.
4926 Expression* subkey = Expression::make_temporary_reference(key, bloc);
4927 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
4929 // Get the size of each element.
4930 Expression* ele_size = Expression::make_type_info(this->element_type_,
4931 Expression::TYPE_INFO_SIZE);
4933 // Get the hash of this element.
4934 Expression_list* args = new Expression_list();
4935 args->push_back(subkey);
4936 args->push_back(ele_size);
4937 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
4938 Expression* call = Expression::make_call(func, args, false, bloc);
4940 // Add the element's hash value to retval.
4941 Temporary_reference_expression* tref =
4942 Expression::make_temporary_reference(retval, bloc);
4943 tref->set_is_lvalue();
4944 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, call, bloc);
4945 gogo->add_statement(s);
4947 // Increase the element pointer.
4948 tref = Expression::make_temporary_reference(key, bloc);
4949 tref->set_is_lvalue();
4950 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
4953 Block* statements = gogo->finish_block(bloc);
4955 for_range->add_statements(statements);
4956 gogo->add_statement(for_range);
4958 // Return retval to the caller of the hash function.
4959 Expression_list* vals = new Expression_list();
4960 ref = Expression::make_temporary_reference(retval, bloc);
4961 vals->push_back(ref);
4962 s = Statement::make_return_statement(vals, bloc);
4963 gogo->add_statement(s);
4966 // Write the equality function for an array which can not use the
4967 // identity function.
4970 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
4972 Location bloc = Linemap::predeclared_location();
4974 // The pointers to the arrays we are going to compare.
4975 Named_object* key1_arg = gogo->lookup("key1", NULL);
4976 Named_object* key2_arg = gogo->lookup("key2", NULL);
4977 go_assert(key1_arg != NULL && key2_arg != NULL);
4979 // Build temporaries for the keys with the right types.
4980 Type* pt = Type::make_pointer_type(name != NULL
4981 ? static_cast<Type*>(name)
4982 : static_cast<Type*>(this));
4984 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
4985 ref = Expression::make_unsafe_cast(pt, ref, bloc);
4986 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
4987 gogo->add_statement(p1);
4989 ref = Expression::make_var_reference(key2_arg, bloc);
4990 ref = Expression::make_unsafe_cast(pt, ref, bloc);
4991 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
4992 gogo->add_statement(p2);
4994 // Loop over the array elements.
4996 Type* int_type = Type::lookup_integer_type("int");
4997 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
4998 gogo->add_statement(index);
5000 Expression* iref = Expression::make_temporary_reference(index, bloc);
5001 Expression* aref = Expression::make_temporary_reference(p1, bloc);
5002 For_range_statement* for_range = Statement::make_for_range_statement(iref,
5007 gogo->start_block(bloc);
5009 // Compare element in P1 and P2.
5010 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
5011 e1 = Expression::make_unary(OPERATOR_MULT, e1, bloc);
5012 ref = Expression::make_temporary_reference(index, bloc);
5013 e1 = Expression::make_array_index(e1, ref, NULL, bloc);
5015 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
5016 e2 = Expression::make_unary(OPERATOR_MULT, e2, bloc);
5017 ref = Expression::make_temporary_reference(index, bloc);
5018 e2 = Expression::make_array_index(e2, ref, NULL, bloc);
5020 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
5022 // If the elements are not equal, return false.
5023 gogo->start_block(bloc);
5024 Expression_list* vals = new Expression_list();
5025 vals->push_back(Expression::make_boolean(false, bloc));
5026 Statement* s = Statement::make_return_statement(vals, bloc);
5027 gogo->add_statement(s);
5028 Block* then_block = gogo->finish_block(bloc);
5030 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
5031 gogo->add_statement(s);
5033 Block* statements = gogo->finish_block(bloc);
5035 for_range->add_statements(statements);
5036 gogo->add_statement(for_range);
5038 // All the elements are equal, so return true.
5039 vals = new Expression_list();
5040 vals->push_back(Expression::make_boolean(true, bloc));
5041 s = Statement::make_return_statement(vals, bloc);
5042 gogo->add_statement(s);
5045 // Get a tree for the length of a fixed array. The length may be
5046 // computed using a function call, so we must only evaluate it once.
5049 Array_type::get_length_tree(Gogo* gogo)
5051 go_assert(this->length_ != NULL);
5052 if (this->length_tree_ == NULL_TREE)
5057 if (this->length_->integer_constant_value(true, val, &t))
5060 t = Type::lookup_integer_type("int");
5061 else if (t->is_abstract())
5062 t = t->make_non_abstract_type();
5063 tree tt = type_to_tree(t->get_backend(gogo));
5064 this->length_tree_ = Expression::integer_constant_tree(val, tt);
5071 // Make up a translation context for the array length
5072 // expression. FIXME: This won't work in general.
5073 Translate_context context(gogo, NULL, NULL, NULL);
5074 tree len = this->length_->get_tree(&context);
5075 if (len != error_mark_node)
5077 len = convert_to_integer(integer_type_node, len);
5078 len = save_expr(len);
5080 this->length_tree_ = len;
5083 return this->length_tree_;
5086 // Get the backend representation of the fields of a slice. This is
5087 // not declared in types.h so that types.h doesn't have to #include
5090 // We use int for the count and capacity fields. This matches 6g.
5091 // The language more or less assumes that we can't allocate space of a
5092 // size which does not fit in int.
5095 get_backend_slice_fields(Gogo* gogo, Array_type* type,
5096 std::vector<Backend::Btyped_identifier>* bfields)
5100 Type* pet = Type::make_pointer_type(type->element_type());
5101 Btype* pbet = pet->get_backend(gogo);
5102 Location ploc = Linemap::predeclared_location();
5104 Backend::Btyped_identifier* p = &(*bfields)[0];
5105 p->name = "__values";
5109 Type* int_type = Type::lookup_integer_type("int");
5112 p->name = "__count";
5113 p->btype = int_type->get_backend(gogo);
5117 p->name = "__capacity";
5118 p->btype = int_type->get_backend(gogo);
5122 // Get a tree for the type of this array. A fixed array is simply
5123 // represented as ARRAY_TYPE with the appropriate index--i.e., it is
5124 // just like an array in C. An open array is a struct with three
5125 // fields: a data pointer, the length, and the capacity.
5128 Array_type::do_get_backend(Gogo* gogo)
5130 if (this->length_ == NULL)
5132 std::vector<Backend::Btyped_identifier> bfields;
5133 get_backend_slice_fields(gogo, this, &bfields);
5134 return gogo->backend()->struct_type(bfields);
5138 Btype* element = this->get_backend_element(gogo);
5139 Bexpression* len = this->get_backend_length(gogo);
5140 return gogo->backend()->array_type(element, len);
5144 // Return the backend representation of the element type.
5146 Array_type::get_backend_element(Gogo* gogo)
5148 return this->element_type_->get_backend(gogo);
5151 // Return the backend representation of the length.
5154 Array_type::get_backend_length(Gogo* gogo)
5156 return tree_to_expr(this->get_length_tree(gogo));
5159 // Return a tree for a pointer to the values in ARRAY.
5162 Array_type::value_pointer_tree(Gogo*, tree array) const
5165 if (this->length() != NULL)
5168 ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))),
5169 build_fold_addr_expr(array));
5174 tree field = TYPE_FIELDS(TREE_TYPE(array));
5175 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
5177 ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field,
5180 if (TREE_CONSTANT(array))
5181 TREE_CONSTANT(ret) = 1;
5185 // Return a tree for the length of the array ARRAY which has this
5189 Array_type::length_tree(Gogo* gogo, tree array)
5191 if (this->length_ != NULL)
5193 if (TREE_CODE(array) == SAVE_EXPR)
5194 return fold_convert(integer_type_node, this->get_length_tree(gogo));
5196 return omit_one_operand(integer_type_node,
5197 this->get_length_tree(gogo), array);
5200 // This is an open array. We need to read the length field.
5202 tree type = TREE_TYPE(array);
5203 go_assert(TREE_CODE(type) == RECORD_TYPE);
5205 tree field = DECL_CHAIN(TYPE_FIELDS(type));
5206 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
5208 tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
5209 if (TREE_CONSTANT(array))
5210 TREE_CONSTANT(ret) = 1;
5214 // Return a tree for the capacity of the array ARRAY which has this
5218 Array_type::capacity_tree(Gogo* gogo, tree array)
5220 if (this->length_ != NULL)
5221 return omit_one_operand(sizetype, this->get_length_tree(gogo), array);
5223 // This is an open array. We need to read the capacity field.
5225 tree type = TREE_TYPE(array);
5226 go_assert(TREE_CODE(type) == RECORD_TYPE);
5228 tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type)));
5229 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
5231 return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
5237 Array_type::do_export(Export* exp) const
5239 exp->write_c_string("[");
5240 if (this->length_ != NULL)
5241 this->length_->export_expression(exp);
5242 exp->write_c_string("] ");
5243 exp->write_type(this->element_type_);
5249 Array_type::do_import(Import* imp)
5251 imp->require_c_string("[");
5253 if (imp->peek_char() == ']')
5256 length = Expression::import_expression(imp);
5257 imp->require_c_string("] ");
5258 Type* element_type = imp->read_type();
5259 return Type::make_array_type(element_type, length);
5262 // The type of an array type descriptor.
5265 Array_type::make_array_type_descriptor_type()
5270 Type* tdt = Type::make_type_descriptor_type();
5271 Type* ptdt = Type::make_type_descriptor_ptr_type();
5273 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5276 Type::make_builtin_struct_type(4,
5280 "len", uintptr_type);
5282 ret = Type::make_builtin_named_type("ArrayType", sf);
5288 // The type of an slice type descriptor.
5291 Array_type::make_slice_type_descriptor_type()
5296 Type* tdt = Type::make_type_descriptor_type();
5297 Type* ptdt = Type::make_type_descriptor_ptr_type();
5300 Type::make_builtin_struct_type(2,
5304 ret = Type::make_builtin_named_type("SliceType", sf);
5310 // Build a type descriptor for an array/slice type.
5313 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5315 if (this->length_ != NULL)
5316 return this->array_type_descriptor(gogo, name);
5318 return this->slice_type_descriptor(gogo, name);
5321 // Build a type descriptor for an array type.
5324 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
5326 Location bloc = Linemap::predeclared_location();
5328 Type* atdt = Array_type::make_array_type_descriptor_type();
5330 const Struct_field_list* fields = atdt->struct_type()->fields();
5332 Expression_list* vals = new Expression_list();
5335 Struct_field_list::const_iterator p = fields->begin();
5336 go_assert(p->is_field_name("commonType"));
5337 vals->push_back(this->type_descriptor_constructor(gogo,
5338 RUNTIME_TYPE_KIND_ARRAY,
5342 go_assert(p->is_field_name("elem"));
5343 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5346 go_assert(p->is_field_name("slice"));
5347 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
5348 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
5351 go_assert(p->is_field_name("len"));
5352 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
5355 go_assert(p == fields->end());
5357 return Expression::make_struct_composite_literal(atdt, vals, bloc);
5360 // Build a type descriptor for a slice type.
5363 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
5365 Location bloc = Linemap::predeclared_location();
5367 Type* stdt = Array_type::make_slice_type_descriptor_type();
5369 const Struct_field_list* fields = stdt->struct_type()->fields();
5371 Expression_list* vals = new Expression_list();
5374 Struct_field_list::const_iterator p = fields->begin();
5375 go_assert(p->is_field_name("commonType"));
5376 vals->push_back(this->type_descriptor_constructor(gogo,
5377 RUNTIME_TYPE_KIND_SLICE,
5381 go_assert(p->is_field_name("elem"));
5382 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5385 go_assert(p == fields->end());
5387 return Expression::make_struct_composite_literal(stdt, vals, bloc);
5390 // Reflection string.
5393 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
5395 ret->push_back('[');
5396 if (this->length_ != NULL)
5401 if (!this->length_->integer_constant_value(true, val, &type))
5402 error_at(this->length_->location(),
5403 "array length must be integer constant expression");
5404 else if (mpz_cmp_si(val, 0) < 0)
5405 error_at(this->length_->location(), "array length is negative");
5406 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
5407 error_at(this->length_->location(), "array length is too large");
5411 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
5416 ret->push_back(']');
5418 this->append_reflection(this->element_type_, gogo, ret);
5424 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5426 ret->push_back('A');
5427 this->append_mangled_name(this->element_type_, gogo, ret);
5428 if (this->length_ != NULL)
5433 if (!this->length_->integer_constant_value(true, val, &type))
5434 error_at(this->length_->location(),
5435 "array length must be integer constant expression");
5436 else if (mpz_cmp_si(val, 0) < 0)
5437 error_at(this->length_->location(), "array length is negative");
5438 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
5439 error_at(this->length_->location(), "array size is too large");
5443 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
5448 ret->push_back('e');
5451 // Make an array type.
5454 Type::make_array_type(Type* element_type, Expression* length)
5456 return new Array_type(element_type, length);
5464 Map_type::do_traverse(Traverse* traverse)
5466 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
5467 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
5468 return TRAVERSE_EXIT;
5469 return TRAVERSE_CONTINUE;
5472 // Check that the map type is OK.
5475 Map_type::do_verify()
5477 // The runtime support uses "map[void]void".
5478 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
5480 error_at(this->location_, "invalid map key type");
5486 // Whether two map types are identical.
5489 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
5491 return (Type::are_identical(this->key_type(), t->key_type(),
5492 errors_are_identical, NULL)
5493 && Type::are_identical(this->val_type(), t->val_type(),
5494 errors_are_identical, NULL));
5500 Map_type::do_hash_for_method(Gogo* gogo) const
5502 return (this->key_type_->hash_for_method(gogo)
5503 + this->val_type_->hash_for_method(gogo)
5507 // Get the backend representation for a map type. A map type is
5508 // represented as a pointer to a struct. The struct is __go_map in
5512 Map_type::do_get_backend(Gogo* gogo)
5514 static Btype* backend_map_type;
5515 if (backend_map_type == NULL)
5517 std::vector<Backend::Btyped_identifier> bfields(4);
5519 Location bloc = Linemap::predeclared_location();
5521 Type* pdt = Type::make_type_descriptor_ptr_type();
5522 bfields[0].name = "__descriptor";
5523 bfields[0].btype = pdt->get_backend(gogo);
5524 bfields[0].location = bloc;
5526 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5527 bfields[1].name = "__element_count";
5528 bfields[1].btype = uintptr_type->get_backend(gogo);
5529 bfields[1].location = bloc;
5531 bfields[2].name = "__bucket_count";
5532 bfields[2].btype = bfields[1].btype;
5533 bfields[2].location = bloc;
5535 Btype* bvt = gogo->backend()->void_type();
5536 Btype* bpvt = gogo->backend()->pointer_type(bvt);
5537 Btype* bppvt = gogo->backend()->pointer_type(bpvt);
5538 bfields[3].name = "__buckets";
5539 bfields[3].btype = bppvt;
5540 bfields[3].location = bloc;
5542 Btype *bt = gogo->backend()->struct_type(bfields);
5543 bt = gogo->backend()->named_type("__go_map", bt, bloc);
5544 backend_map_type = gogo->backend()->pointer_type(bt);
5546 return backend_map_type;
5549 // The type of a map type descriptor.
5552 Map_type::make_map_type_descriptor_type()
5557 Type* tdt = Type::make_type_descriptor_type();
5558 Type* ptdt = Type::make_type_descriptor_ptr_type();
5561 Type::make_builtin_struct_type(3,
5566 ret = Type::make_builtin_named_type("MapType", sf);
5572 // Build a type descriptor for a map type.
5575 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5577 Location bloc = Linemap::predeclared_location();
5579 Type* mtdt = Map_type::make_map_type_descriptor_type();
5581 const Struct_field_list* fields = mtdt->struct_type()->fields();
5583 Expression_list* vals = new Expression_list();
5586 Struct_field_list::const_iterator p = fields->begin();
5587 go_assert(p->is_field_name("commonType"));
5588 vals->push_back(this->type_descriptor_constructor(gogo,
5589 RUNTIME_TYPE_KIND_MAP,
5593 go_assert(p->is_field_name("key"));
5594 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
5597 go_assert(p->is_field_name("elem"));
5598 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
5601 go_assert(p == fields->end());
5603 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
5606 // A mapping from map types to map descriptors.
5608 Map_type::Map_descriptors Map_type::map_descriptors;
5610 // Build a map descriptor for this type. Return a pointer to it.
5613 Map_type::map_descriptor_pointer(Gogo* gogo, Location location)
5615 Bvariable* bvar = this->map_descriptor(gogo);
5616 tree var_tree = var_to_tree(bvar);
5617 if (var_tree == error_mark_node)
5618 return error_mark_node;
5619 return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
5622 // Build a map descriptor for this type.
5625 Map_type::map_descriptor(Gogo* gogo)
5627 std::pair<Map_type*, Bvariable*> val(this, NULL);
5628 std::pair<Map_type::Map_descriptors::iterator, bool> ins =
5629 Map_type::map_descriptors.insert(val);
5631 return ins.first->second;
5633 Type* key_type = this->key_type_;
5634 Type* val_type = this->val_type_;
5636 // The map entry type is a struct with three fields. Build that
5637 // struct so that we can get the offsets of the key and value within
5638 // a map entry. The first field should technically be a pointer to
5639 // this type itself, but since we only care about field offsets we
5640 // just use pointer to bool.
5641 Type* pbool = Type::make_pointer_type(Type::make_boolean_type());
5642 Struct_type* map_entry_type =
5643 Type::make_builtin_struct_type(3,
5648 Type* map_descriptor_type = Map_type::make_map_descriptor_type();
5650 const Struct_field_list* fields =
5651 map_descriptor_type->struct_type()->fields();
5653 Expression_list* vals = new Expression_list();
5656 Location bloc = Linemap::predeclared_location();
5658 Struct_field_list::const_iterator p = fields->begin();
5660 go_assert(p->is_field_name("__map_descriptor"));
5661 vals->push_back(Expression::make_type_descriptor(this, bloc));
5664 go_assert(p->is_field_name("__entry_size"));
5665 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
5666 vals->push_back(Expression::make_type_info(map_entry_type, type_info));
5668 Struct_field_list::const_iterator pf = map_entry_type->fields()->begin();
5670 go_assert(pf->is_field_name("__key"));
5673 go_assert(p->is_field_name("__key_offset"));
5674 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
5677 go_assert(pf->is_field_name("__val"));
5680 go_assert(p->is_field_name("__val_offset"));
5681 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
5684 go_assert(p == fields->end());
5686 Expression* initializer =
5687 Expression::make_struct_composite_literal(map_descriptor_type, vals, bloc);
5689 std::string mangled_name = "__go_map_" + this->mangled_name(gogo);
5690 Btype* map_descriptor_btype = map_descriptor_type->get_backend(gogo);
5691 Bvariable* bvar = gogo->backend()->immutable_struct(mangled_name, true,
5692 map_descriptor_btype,
5695 Translate_context context(gogo, NULL, NULL, NULL);
5696 context.set_is_const();
5697 Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
5699 gogo->backend()->immutable_struct_set_init(bvar, mangled_name, true,
5700 map_descriptor_btype, bloc,
5703 ins.first->second = bvar;
5707 // Build the type of a map descriptor. This must match the struct
5708 // __go_map_descriptor in libgo/runtime/map.h.
5711 Map_type::make_map_descriptor_type()
5716 Type* ptdt = Type::make_type_descriptor_ptr_type();
5717 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5719 Type::make_builtin_struct_type(4,
5720 "__map_descriptor", ptdt,
5721 "__entry_size", uintptr_type,
5722 "__key_offset", uintptr_type,
5723 "__val_offset", uintptr_type);
5724 ret = Type::make_builtin_named_type("__go_map_descriptor", sf);
5729 // Reflection string for a map.
5732 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
5734 ret->append("map[");
5735 this->append_reflection(this->key_type_, gogo, ret);
5737 this->append_reflection(this->val_type_, gogo, ret);
5740 // Mangled name for a map.
5743 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5745 ret->push_back('M');
5746 this->append_mangled_name(this->key_type_, gogo, ret);
5748 this->append_mangled_name(this->val_type_, gogo, ret);
5751 // Export a map type.
5754 Map_type::do_export(Export* exp) const
5756 exp->write_c_string("map [");
5757 exp->write_type(this->key_type_);
5758 exp->write_c_string("] ");
5759 exp->write_type(this->val_type_);
5762 // Import a map type.
5765 Map_type::do_import(Import* imp)
5767 imp->require_c_string("map [");
5768 Type* key_type = imp->read_type();
5769 imp->require_c_string("] ");
5770 Type* val_type = imp->read_type();
5771 return Type::make_map_type(key_type, val_type, imp->location());
5777 Type::make_map_type(Type* key_type, Type* val_type, Location location)
5779 return new Map_type(key_type, val_type, location);
5782 // Class Channel_type.
5787 Channel_type::do_hash_for_method(Gogo* gogo) const
5789 unsigned int ret = 0;
5790 if (this->may_send_)
5792 if (this->may_receive_)
5794 if (this->element_type_ != NULL)
5795 ret += this->element_type_->hash_for_method(gogo) << 2;
5799 // Whether this type is the same as T.
5802 Channel_type::is_identical(const Channel_type* t,
5803 bool errors_are_identical) const
5805 if (!Type::are_identical(this->element_type(), t->element_type(),
5806 errors_are_identical, NULL))
5808 return (this->may_send_ == t->may_send_
5809 && this->may_receive_ == t->may_receive_);
5812 // Return the tree for a channel type. A channel is a pointer to a
5813 // __go_channel struct. The __go_channel struct is defined in
5814 // libgo/runtime/channel.h.
5817 Channel_type::do_get_backend(Gogo* gogo)
5819 static Btype* backend_channel_type;
5820 if (backend_channel_type == NULL)
5822 std::vector<Backend::Btyped_identifier> bfields;
5823 Btype* bt = gogo->backend()->struct_type(bfields);
5824 bt = gogo->backend()->named_type("__go_channel", bt,
5825 Linemap::predeclared_location());
5826 backend_channel_type = gogo->backend()->pointer_type(bt);
5828 return backend_channel_type;
5831 // Build a type descriptor for a channel type.
5834 Channel_type::make_chan_type_descriptor_type()
5839 Type* tdt = Type::make_type_descriptor_type();
5840 Type* ptdt = Type::make_type_descriptor_ptr_type();
5842 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5845 Type::make_builtin_struct_type(3,
5848 "dir", uintptr_type);
5850 ret = Type::make_builtin_named_type("ChanType", sf);
5856 // Build a type descriptor for a map type.
5859 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5861 Location bloc = Linemap::predeclared_location();
5863 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
5865 const Struct_field_list* fields = ctdt->struct_type()->fields();
5867 Expression_list* vals = new Expression_list();
5870 Struct_field_list::const_iterator p = fields->begin();
5871 go_assert(p->is_field_name("commonType"));
5872 vals->push_back(this->type_descriptor_constructor(gogo,
5873 RUNTIME_TYPE_KIND_CHAN,
5877 go_assert(p->is_field_name("elem"));
5878 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5881 go_assert(p->is_field_name("dir"));
5882 // These bits must match the ones in libgo/runtime/go-type.h.
5884 if (this->may_receive_)
5886 if (this->may_send_)
5889 mpz_init_set_ui(iv, val);
5890 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
5894 go_assert(p == fields->end());
5896 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
5899 // Reflection string.
5902 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
5904 if (!this->may_send_)
5906 ret->append("chan");
5907 if (!this->may_receive_)
5909 ret->push_back(' ');
5910 this->append_reflection(this->element_type_, gogo, ret);
5916 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5918 ret->push_back('C');
5919 this->append_mangled_name(this->element_type_, gogo, ret);
5920 if (this->may_send_)
5921 ret->push_back('s');
5922 if (this->may_receive_)
5923 ret->push_back('r');
5924 ret->push_back('e');
5930 Channel_type::do_export(Export* exp) const
5932 exp->write_c_string("chan ");
5933 if (this->may_send_ && !this->may_receive_)
5934 exp->write_c_string("-< ");
5935 else if (this->may_receive_ && !this->may_send_)
5936 exp->write_c_string("<- ");
5937 exp->write_type(this->element_type_);
5943 Channel_type::do_import(Import* imp)
5945 imp->require_c_string("chan ");
5949 if (imp->match_c_string("-< "))
5953 may_receive = false;
5955 else if (imp->match_c_string("<- "))
5967 Type* element_type = imp->read_type();
5969 return Type::make_channel_type(may_send, may_receive, element_type);
5972 // Make a new channel type.
5975 Type::make_channel_type(bool send, bool receive, Type* element_type)
5977 return new Channel_type(send, receive, element_type);
5980 // Class Interface_type.
5985 Interface_type::do_traverse(Traverse* traverse)
5987 if (this->methods_ == NULL)
5988 return TRAVERSE_CONTINUE;
5989 return this->methods_->traverse(traverse);
5992 // Finalize the methods. This handles interface inheritance.
5995 Interface_type::finalize_methods()
5997 if (this->methods_ == NULL)
5999 std::vector<Named_type*> seen;
6000 bool is_recursive = false;
6003 while (from < this->methods_->size())
6005 const Typed_identifier* p = &this->methods_->at(from);
6006 if (!p->name().empty())
6009 for (i = 0; i < to; ++i)
6011 if (this->methods_->at(i).name() == p->name())
6013 error_at(p->location(), "duplicate method %qs",
6014 Gogo::message_name(p->name()).c_str());
6021 this->methods_->set(to, *p);
6028 Interface_type* it = p->type()->interface_type();
6031 error_at(p->location(), "interface contains embedded non-interface");
6039 error_at(p->location(), "invalid recursive interface");
6040 is_recursive = true;
6046 Named_type* nt = p->type()->named_type();
6049 std::vector<Named_type*>::const_iterator q;
6050 for (q = seen.begin(); q != seen.end(); ++q)
6054 error_at(p->location(), "inherited interface loop");
6058 if (q != seen.end())
6066 const Typed_identifier_list* methods = it->methods();
6067 if (methods == NULL)
6072 for (Typed_identifier_list::const_iterator q = methods->begin();
6073 q != methods->end();
6076 if (q->name().empty())
6078 if (q->type()->forwarded() == p->type()->forwarded())
6079 error_at(p->location(), "interface inheritance loop");
6083 for (i = from + 1; i < this->methods_->size(); ++i)
6085 const Typed_identifier* r = &this->methods_->at(i);
6086 if (r->name().empty()
6087 && r->type()->forwarded() == q->type()->forwarded())
6089 error_at(p->location(),
6090 "inherited interface listed twice");
6094 if (i == this->methods_->size())
6095 this->methods_->push_back(Typed_identifier(q->name(),
6100 else if (this->find_method(q->name()) == NULL)
6101 this->methods_->push_back(Typed_identifier(q->name(), q->type(),
6106 error_at(p->location(), "inherited method %qs is ambiguous",
6107 Gogo::message_name(q->name()).c_str());
6114 delete this->methods_;
6115 this->methods_ = NULL;
6119 this->methods_->resize(to);
6120 this->methods_->sort_by_name();
6124 // Return the method NAME, or NULL.
6126 const Typed_identifier*
6127 Interface_type::find_method(const std::string& name) const
6129 if (this->methods_ == NULL)
6131 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
6132 p != this->methods_->end();
6134 if (p->name() == name)
6139 // Return the method index.
6142 Interface_type::method_index(const std::string& name) const
6144 go_assert(this->methods_ != NULL);
6146 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
6147 p != this->methods_->end();
6149 if (p->name() == name)
6154 // Return whether NAME is an unexported method, for better error
6158 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
6160 if (this->methods_ == NULL)
6162 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
6163 p != this->methods_->end();
6166 const std::string& method_name(p->name());
6167 if (Gogo::is_hidden_name(method_name)
6168 && name == Gogo::unpack_hidden_name(method_name)
6169 && gogo->pack_hidden_name(name, false) != method_name)
6175 // Whether this type is identical with T.
6178 Interface_type::is_identical(const Interface_type* t,
6179 bool errors_are_identical) const
6181 // We require the same methods with the same types. The methods
6182 // have already been sorted.
6183 if (this->methods() == NULL || t->methods() == NULL)
6184 return this->methods() == t->methods();
6186 Typed_identifier_list::const_iterator p1 = this->methods()->begin();
6187 for (Typed_identifier_list::const_iterator p2 = t->methods()->begin();
6188 p2 != t->methods()->end();
6191 if (p1 == this->methods()->end())
6193 if (p1->name() != p2->name()
6194 || !Type::are_identical(p1->type(), p2->type(),
6195 errors_are_identical, NULL))
6198 if (p1 != this->methods()->end())
6203 // Whether we can assign the interface type T to this type. The types
6204 // are known to not be identical. An interface assignment is only
6205 // permitted if T is known to implement all methods in THIS.
6206 // Otherwise a type guard is required.
6209 Interface_type::is_compatible_for_assign(const Interface_type* t,
6210 std::string* reason) const
6212 if (this->methods() == NULL)
6214 for (Typed_identifier_list::const_iterator p = this->methods()->begin();
6215 p != this->methods()->end();
6218 const Typed_identifier* m = t->find_method(p->name());
6224 snprintf(buf, sizeof buf,
6225 _("need explicit conversion; missing method %s%s%s"),
6226 open_quote, Gogo::message_name(p->name()).c_str(),
6228 reason->assign(buf);
6233 std::string subreason;
6234 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
6238 std::string n = Gogo::message_name(p->name());
6239 size_t len = 100 + n.length() + subreason.length();
6240 char* buf = new char[len];
6241 if (subreason.empty())
6242 snprintf(buf, len, _("incompatible type for method %s%s%s"),
6243 open_quote, n.c_str(), close_quote);
6246 _("incompatible type for method %s%s%s (%s)"),
6247 open_quote, n.c_str(), close_quote,
6249 reason->assign(buf);
6262 Interface_type::do_hash_for_method(Gogo* gogo) const
6264 unsigned int ret = 0;
6265 if (this->methods_ != NULL)
6267 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
6268 p != this->methods_->end();
6271 ret = Type::hash_string(p->name(), ret);
6272 ret += p->type()->hash_for_method(gogo);
6279 // Return true if T implements the interface. If it does not, and
6280 // REASON is not NULL, set *REASON to a useful error message.
6283 Interface_type::implements_interface(const Type* t, std::string* reason) const
6285 if (this->methods_ == NULL)
6288 bool is_pointer = false;
6289 const Named_type* nt = t->named_type();
6290 const Struct_type* st = t->struct_type();
6291 // If we start with a named type, we don't dereference it to find
6295 const Type* pt = t->points_to();
6298 // If T is a pointer to a named type, then we need to look at
6299 // the type to which it points.
6301 nt = pt->named_type();
6302 st = pt->struct_type();
6306 // If we have a named type, get the methods from it rather than from
6311 // Only named and struct types have methods.
6312 if (nt == NULL && st == NULL)
6316 if (t->points_to() != NULL
6317 && t->points_to()->interface_type() != NULL)
6318 reason->assign(_("pointer to interface type has no methods"));
6320 reason->assign(_("type has no methods"));
6325 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
6329 if (t->points_to() != NULL
6330 && t->points_to()->interface_type() != NULL)
6331 reason->assign(_("pointer to interface type has no methods"));
6333 reason->assign(_("type has no methods"));
6338 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
6339 p != this->methods_->end();
6342 bool is_ambiguous = false;
6343 Method* m = (nt != NULL
6344 ? nt->method_function(p->name(), &is_ambiguous)
6345 : st->method_function(p->name(), &is_ambiguous));
6350 std::string n = Gogo::message_name(p->name());
6351 size_t len = n.length() + 100;
6352 char* buf = new char[len];
6354 snprintf(buf, len, _("ambiguous method %s%s%s"),
6355 open_quote, n.c_str(), close_quote);
6357 snprintf(buf, len, _("missing method %s%s%s"),
6358 open_quote, n.c_str(), close_quote);
6359 reason->assign(buf);
6365 Function_type *p_fn_type = p->type()->function_type();
6366 Function_type* m_fn_type = m->type()->function_type();
6367 go_assert(p_fn_type != NULL && m_fn_type != NULL);
6368 std::string subreason;
6369 if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
6373 std::string n = Gogo::message_name(p->name());
6374 size_t len = 100 + n.length() + subreason.length();
6375 char* buf = new char[len];
6376 if (subreason.empty())
6377 snprintf(buf, len, _("incompatible type for method %s%s%s"),
6378 open_quote, n.c_str(), close_quote);
6381 _("incompatible type for method %s%s%s (%s)"),
6382 open_quote, n.c_str(), close_quote,
6384 reason->assign(buf);
6390 if (!is_pointer && !m->is_value_method())
6394 std::string n = Gogo::message_name(p->name());
6395 size_t len = 100 + n.length();
6396 char* buf = new char[len];
6397 snprintf(buf, len, _("method %s%s%s requires a pointer"),
6398 open_quote, n.c_str(), close_quote);
6399 reason->assign(buf);
6409 // Return the backend representation of the empty interface type. We
6410 // use the same struct for all empty interfaces.
6413 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
6415 static Btype* empty_interface_type;
6416 if (empty_interface_type == NULL)
6418 std::vector<Backend::Btyped_identifier> bfields(2);
6420 Location bloc = Linemap::predeclared_location();
6422 Type* pdt = Type::make_type_descriptor_ptr_type();
6423 bfields[0].name = "__type_descriptor";
6424 bfields[0].btype = pdt->get_backend(gogo);
6425 bfields[0].location = bloc;
6427 Type* vt = Type::make_pointer_type(Type::make_void_type());
6428 bfields[1].name = "__object";
6429 bfields[1].btype = vt->get_backend(gogo);
6430 bfields[1].location = bloc;
6432 empty_interface_type = gogo->backend()->struct_type(bfields);
6434 return empty_interface_type;
6437 // Return the fields of a non-empty interface type. This is not
6438 // declared in types.h so that types.h doesn't have to #include
6442 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
6443 std::vector<Backend::Btyped_identifier>* bfields)
6445 Location loc = type->location();
6447 std::vector<Backend::Btyped_identifier> mfields(type->methods()->size() + 1);
6449 Type* pdt = Type::make_type_descriptor_ptr_type();
6450 mfields[0].name = "__type_descriptor";
6451 mfields[0].btype = pdt->get_backend(gogo);
6452 mfields[0].location = loc;
6454 std::string last_name = "";
6456 for (Typed_identifier_list::const_iterator p = type->methods()->begin();
6457 p != type->methods()->end();
6460 mfields[i].name = Gogo::unpack_hidden_name(p->name());
6461 mfields[i].btype = p->type()->get_backend(gogo);
6462 mfields[i].location = loc;
6463 // Sanity check: the names should be sorted.
6464 go_assert(p->name() > last_name);
6465 last_name = p->name();
6468 Btype* methods = gogo->backend()->struct_type(mfields);
6472 (*bfields)[0].name = "__methods";
6473 (*bfields)[0].btype = gogo->backend()->pointer_type(methods);
6474 (*bfields)[0].location = loc;
6476 Type* vt = Type::make_pointer_type(Type::make_void_type());
6477 (*bfields)[1].name = "__object";
6478 (*bfields)[1].btype = vt->get_backend(gogo);
6479 (*bfields)[1].location = Linemap::predeclared_location();
6482 // Return a tree for an interface type. An interface is a pointer to
6483 // a struct. The struct has three fields. The first field is a
6484 // pointer to the type descriptor for the dynamic type of the object.
6485 // The second field is a pointer to a table of methods for the
6486 // interface to be used with the object. The third field is the value
6487 // of the object itself.
6490 Interface_type::do_get_backend(Gogo* gogo)
6492 if (this->methods_ == NULL)
6493 return Interface_type::get_backend_empty_interface_type(gogo);
6496 std::vector<Backend::Btyped_identifier> bfields;
6497 get_backend_interface_fields(gogo, this, &bfields);
6498 return gogo->backend()->struct_type(bfields);
6502 // The type of an interface type descriptor.
6505 Interface_type::make_interface_type_descriptor_type()
6510 Type* tdt = Type::make_type_descriptor_type();
6511 Type* ptdt = Type::make_type_descriptor_ptr_type();
6513 Type* string_type = Type::lookup_string_type();
6514 Type* pointer_string_type = Type::make_pointer_type(string_type);
6517 Type::make_builtin_struct_type(3,
6518 "name", pointer_string_type,
6519 "pkgPath", pointer_string_type,
6522 Type* nsm = Type::make_builtin_named_type("imethod", sm);
6524 Type* slice_nsm = Type::make_array_type(nsm, NULL);
6526 Struct_type* s = Type::make_builtin_struct_type(2,
6528 "methods", slice_nsm);
6530 ret = Type::make_builtin_named_type("InterfaceType", s);
6536 // Build a type descriptor for an interface type.
6539 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6541 Location bloc = Linemap::predeclared_location();
6543 Type* itdt = Interface_type::make_interface_type_descriptor_type();
6545 const Struct_field_list* ifields = itdt->struct_type()->fields();
6547 Expression_list* ivals = new Expression_list();
6550 Struct_field_list::const_iterator pif = ifields->begin();
6551 go_assert(pif->is_field_name("commonType"));
6552 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
6553 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
6557 go_assert(pif->is_field_name("methods"));
6559 Expression_list* methods = new Expression_list();
6560 if (this->methods_ != NULL && !this->methods_->empty())
6562 Type* elemtype = pif->type()->array_type()->element_type();
6564 methods->reserve(this->methods_->size());
6565 for (Typed_identifier_list::const_iterator pm = this->methods_->begin();
6566 pm != this->methods_->end();
6569 const Struct_field_list* mfields = elemtype->struct_type()->fields();
6571 Expression_list* mvals = new Expression_list();
6574 Struct_field_list::const_iterator pmf = mfields->begin();
6575 go_assert(pmf->is_field_name("name"));
6576 std::string s = Gogo::unpack_hidden_name(pm->name());
6577 Expression* e = Expression::make_string(s, bloc);
6578 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
6581 go_assert(pmf->is_field_name("pkgPath"));
6582 if (!Gogo::is_hidden_name(pm->name()))
6583 mvals->push_back(Expression::make_nil(bloc));
6586 s = Gogo::hidden_name_prefix(pm->name());
6587 e = Expression::make_string(s, bloc);
6588 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
6592 go_assert(pmf->is_field_name("typ"));
6593 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
6596 go_assert(pmf == mfields->end());
6598 e = Expression::make_struct_composite_literal(elemtype, mvals,
6600 methods->push_back(e);
6604 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
6608 go_assert(pif == ifields->end());
6610 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
6613 // Reflection string.
6616 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
6618 ret->append("interface {");
6619 if (this->methods_ != NULL)
6621 ret->push_back(' ');
6622 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
6623 p != this->methods_->end();
6626 if (p != this->methods_->begin())
6628 if (!Gogo::is_hidden_name(p->name()))
6629 ret->append(p->name());
6632 // This matches what the gc compiler does.
6633 std::string prefix = Gogo::hidden_name_prefix(p->name());
6634 ret->append(prefix.substr(prefix.find('.') + 1));
6635 ret->push_back('.');
6636 ret->append(Gogo::unpack_hidden_name(p->name()));
6638 std::string sub = p->type()->reflection(gogo);
6639 go_assert(sub.compare(0, 4, "func") == 0);
6640 sub = sub.substr(4);
6643 ret->push_back(' ');
6651 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6653 ret->push_back('I');
6655 const Typed_identifier_list* methods = this->methods_;
6656 if (methods != NULL)
6658 for (Typed_identifier_list::const_iterator p = methods->begin();
6659 p != methods->end();
6662 std::string n = Gogo::unpack_hidden_name(p->name());
6664 snprintf(buf, sizeof buf, "%u_",
6665 static_cast<unsigned int>(n.length()));
6668 this->append_mangled_name(p->type(), gogo, ret);
6672 ret->push_back('e');
6678 Interface_type::do_export(Export* exp) const
6680 exp->write_c_string("interface { ");
6682 const Typed_identifier_list* methods = this->methods_;
6683 if (methods != NULL)
6685 for (Typed_identifier_list::const_iterator pm = methods->begin();
6686 pm != methods->end();
6689 exp->write_string(pm->name());
6690 exp->write_c_string(" (");
6692 const Function_type* fntype = pm->type()->function_type();
6695 const Typed_identifier_list* parameters = fntype->parameters();
6696 if (parameters != NULL)
6698 bool is_varargs = fntype->is_varargs();
6699 for (Typed_identifier_list::const_iterator pp =
6700 parameters->begin();
6701 pp != parameters->end();
6707 exp->write_c_string(", ");
6708 if (!is_varargs || pp + 1 != parameters->end())
6709 exp->write_type(pp->type());
6712 exp->write_c_string("...");
6713 Type *pptype = pp->type();
6714 exp->write_type(pptype->array_type()->element_type());
6719 exp->write_c_string(")");
6721 const Typed_identifier_list* results = fntype->results();
6722 if (results != NULL)
6724 exp->write_c_string(" ");
6725 if (results->size() == 1)
6726 exp->write_type(results->begin()->type());
6730 exp->write_c_string("(");
6731 for (Typed_identifier_list::const_iterator p =
6733 p != results->end();
6739 exp->write_c_string(", ");
6740 exp->write_type(p->type());
6742 exp->write_c_string(")");
6746 exp->write_c_string("; ");
6750 exp->write_c_string("}");
6753 // Import an interface type.
6756 Interface_type::do_import(Import* imp)
6758 imp->require_c_string("interface { ");
6760 Typed_identifier_list* methods = new Typed_identifier_list;
6761 while (imp->peek_char() != '}')
6763 std::string name = imp->read_identifier();
6764 imp->require_c_string(" (");
6766 Typed_identifier_list* parameters;
6767 bool is_varargs = false;
6768 if (imp->peek_char() == ')')
6772 parameters = new Typed_identifier_list;
6775 if (imp->match_c_string("..."))
6781 Type* ptype = imp->read_type();
6783 ptype = Type::make_array_type(ptype, NULL);
6784 parameters->push_back(Typed_identifier(Import::import_marker,
6785 ptype, imp->location()));
6786 if (imp->peek_char() != ',')
6788 go_assert(!is_varargs);
6789 imp->require_c_string(", ");
6792 imp->require_c_string(")");
6794 Typed_identifier_list* results;
6795 if (imp->peek_char() != ' ')
6799 results = new Typed_identifier_list;
6801 if (imp->peek_char() != '(')
6803 Type* rtype = imp->read_type();
6804 results->push_back(Typed_identifier(Import::import_marker,
6805 rtype, imp->location()));
6812 Type* rtype = imp->read_type();
6813 results->push_back(Typed_identifier(Import::import_marker,
6814 rtype, imp->location()));
6815 if (imp->peek_char() != ',')
6817 imp->require_c_string(", ");
6819 imp->require_c_string(")");
6823 Function_type* fntype = Type::make_function_type(NULL, parameters,
6827 fntype->set_is_varargs();
6828 methods->push_back(Typed_identifier(name, fntype, imp->location()));
6830 imp->require_c_string("; ");
6833 imp->require_c_string("}");
6835 if (methods->empty())
6841 return Type::make_interface_type(methods, imp->location());
6844 // Make an interface type.
6847 Type::make_interface_type(Typed_identifier_list* methods,
6850 return new Interface_type(methods, location);
6855 // Bind a method to an object.
6858 Method::bind_method(Expression* expr, Location location) const
6860 if (this->stub_ == NULL)
6862 // When there is no stub object, the binding is determined by
6864 return this->do_bind_method(expr, location);
6866 return Expression::make_bound_method(expr, this->stub_, location);
6869 // Return the named object associated with a method. This may only be
6870 // called after methods are finalized.
6873 Method::named_object() const
6875 if (this->stub_ != NULL)
6877 return this->do_named_object();
6880 // Class Named_method.
6882 // The type of the method.
6885 Named_method::do_type() const
6887 if (this->named_object_->is_function())
6888 return this->named_object_->func_value()->type();
6889 else if (this->named_object_->is_function_declaration())
6890 return this->named_object_->func_declaration_value()->type();
6895 // Return the location of the method receiver.
6898 Named_method::do_receiver_location() const
6900 return this->do_type()->receiver()->location();
6903 // Bind a method to an object.
6906 Named_method::do_bind_method(Expression* expr, Location location) const
6908 Named_object* no = this->named_object_;
6909 Bound_method_expression* bme = Expression::make_bound_method(expr, no,
6911 // If this is not a local method, and it does not use a stub, then
6912 // the real method expects a different type. We need to cast the
6914 if (this->depth() > 0 && !this->needs_stub_method())
6916 Function_type* ftype = this->do_type();
6917 go_assert(ftype->is_method());
6918 Type* frtype = ftype->receiver()->type();
6919 bme->set_first_argument_type(frtype);
6924 // Class Interface_method.
6926 // Bind a method to an object.
6929 Interface_method::do_bind_method(Expression* expr,
6930 Location location) const
6932 return Expression::make_interface_field_reference(expr, this->name_,
6938 // Insert a new method. Return true if it was inserted, false
6942 Methods::insert(const std::string& name, Method* m)
6944 std::pair<Method_map::iterator, bool> ins =
6945 this->methods_.insert(std::make_pair(name, m));
6950 Method* old_method = ins.first->second;
6951 if (m->depth() < old_method->depth())
6954 ins.first->second = m;
6959 if (m->depth() == old_method->depth())
6960 old_method->set_is_ambiguous();
6966 // Return the number of unambiguous methods.
6969 Methods::count() const
6972 for (Method_map::const_iterator p = this->methods_.begin();
6973 p != this->methods_.end();
6975 if (!p->second->is_ambiguous())
6980 // Class Named_type.
6982 // Return the name of the type.
6985 Named_type::name() const
6987 return this->named_object_->name();
6990 // Return the name of the type to use in an error message.
6993 Named_type::message_name() const
6995 return this->named_object_->message_name();
6998 // Return the base type for this type. We have to be careful about
6999 // circular type definitions, which are invalid but may be seen here.
7002 Named_type::named_base()
7007 Type* ret = this->type_->base();
7008 this->seen_ = false;
7013 Named_type::named_base() const
7018 const Type* ret = this->type_->base();
7019 this->seen_ = false;
7023 // Return whether this is an error type. We have to be careful about
7024 // circular type definitions, which are invalid but may be seen here.
7027 Named_type::is_named_error_type() const
7032 bool ret = this->type_->is_error_type();
7033 this->seen_ = false;
7037 // Whether this type is comparable. We have to be careful about
7038 // circular type definitions.
7041 Named_type::named_type_is_comparable(std::string* reason) const
7046 bool ret = Type::are_compatible_for_comparison(true, this->type_,
7047 this->type_, reason);
7048 this->seen_ = false;
7052 // Add a method to this type.
7055 Named_type::add_method(const std::string& name, Function* function)
7057 if (this->local_methods_ == NULL)
7058 this->local_methods_ = new Bindings(NULL);
7059 return this->local_methods_->add_function(name, NULL, function);
7062 // Add a method declaration to this type.
7065 Named_type::add_method_declaration(const std::string& name, Package* package,
7066 Function_type* type,
7069 if (this->local_methods_ == NULL)
7070 this->local_methods_ = new Bindings(NULL);
7071 return this->local_methods_->add_function_declaration(name, package, type,
7075 // Add an existing method to this type.
7078 Named_type::add_existing_method(Named_object* no)
7080 if (this->local_methods_ == NULL)
7081 this->local_methods_ = new Bindings(NULL);
7082 this->local_methods_->add_named_object(no);
7085 // Look for a local method NAME, and returns its named object, or NULL
7089 Named_type::find_local_method(const std::string& name) const
7091 if (this->local_methods_ == NULL)
7093 return this->local_methods_->lookup(name);
7096 // Return whether NAME is an unexported field or method, for better
7100 Named_type::is_unexported_local_method(Gogo* gogo,
7101 const std::string& name) const
7103 Bindings* methods = this->local_methods_;
7104 if (methods != NULL)
7106 for (Bindings::const_declarations_iterator p =
7107 methods->begin_declarations();
7108 p != methods->end_declarations();
7111 if (Gogo::is_hidden_name(p->first)
7112 && name == Gogo::unpack_hidden_name(p->first)
7113 && gogo->pack_hidden_name(name, false) != p->first)
7120 // Build the complete list of methods for this type, which means
7121 // recursively including all methods for anonymous fields. Create all
7125 Named_type::finalize_methods(Gogo* gogo)
7127 // If this type needs explicit comparison and hash functions, create
7128 // them now. It would be a bit better to do this only if the
7129 // functions are needed, but they will be static so the backend can
7130 // discard them if they are not used.
7131 if ((this->struct_type() != NULL
7132 || (this->array_type() != NULL && !this->is_slice_type()))
7133 && !this->compare_is_identity()
7134 && this->is_comparable())
7136 Named_object* hash_fn;
7137 Named_object* equal_fn;
7138 this->type_functions(gogo, this, NULL, NULL, &hash_fn, &equal_fn);
7141 if (this->all_methods_ != NULL)
7144 if (this->local_methods_ != NULL
7145 && (this->points_to() != NULL || this->interface_type() != NULL))
7147 const Bindings* lm = this->local_methods_;
7148 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
7149 p != lm->end_declarations();
7151 error_at(p->second->location(),
7152 "invalid pointer or interface receiver type");
7153 delete this->local_methods_;
7154 this->local_methods_ = NULL;
7158 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
7161 // Return the method NAME, or NULL if there isn't one or if it is
7162 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
7166 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
7168 return Type::method_function(this->all_methods_, name, is_ambiguous);
7171 // Return a pointer to the interface method table for this type for
7172 // the interface INTERFACE. IS_POINTER is true if this is for a
7176 Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface,
7179 go_assert(!interface->is_empty());
7181 Interface_method_tables** pimt = (is_pointer
7182 ? &this->interface_method_tables_
7183 : &this->pointer_interface_method_tables_);
7186 *pimt = new Interface_method_tables(5);
7188 std::pair<const Interface_type*, tree> val(interface, NULL_TREE);
7189 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
7193 // This is a new entry in the hash table.
7194 go_assert(ins.first->second == NULL_TREE);
7195 ins.first->second = gogo->interface_method_table_for_type(interface,
7200 tree decl = ins.first->second;
7201 if (decl == error_mark_node)
7202 return error_mark_node;
7203 go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL);
7204 return build_fold_addr_expr(decl);
7207 // Return whether a named type has any hidden fields.
7210 Named_type::named_type_has_hidden_fields(std::string* reason) const
7215 bool ret = this->type_->has_hidden_fields(this, reason);
7216 this->seen_ = false;
7220 // Look for a use of a complete type within another type. This is
7221 // used to check that we don't try to use a type within itself.
7223 class Find_type_use : public Traverse
7226 Find_type_use(Named_type* find_type)
7227 : Traverse(traverse_types),
7228 find_type_(find_type), found_(false)
7231 // Whether we found the type.
7234 { return this->found_; }
7241 // The type we are looking for.
7242 Named_type* find_type_;
7243 // Whether we found the type.
7247 // Check for FIND_TYPE in TYPE.
7250 Find_type_use::type(Type* type)
7252 if (type->named_type() != NULL && this->find_type_ == type->named_type())
7254 this->found_ = true;
7255 return TRAVERSE_EXIT;
7258 // It's OK if we see a reference to the type in any type which is
7259 // essentially a pointer: a pointer, a slice, a function, a map, or
7261 if (type->points_to() != NULL
7262 || type->is_slice_type()
7263 || type->function_type() != NULL
7264 || type->map_type() != NULL
7265 || type->channel_type() != NULL)
7266 return TRAVERSE_SKIP_COMPONENTS;
7268 // For an interface, a reference to the type in a method type should
7269 // be ignored, but we have to consider direct inheritance. When
7270 // this is called, there may be cases of direct inheritance
7271 // represented as a method with no name.
7272 if (type->interface_type() != NULL)
7274 const Typed_identifier_list* methods = type->interface_type()->methods();
7275 if (methods != NULL)
7277 for (Typed_identifier_list::const_iterator p = methods->begin();
7278 p != methods->end();
7281 if (p->name().empty())
7283 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
7284 return TRAVERSE_EXIT;
7288 return TRAVERSE_SKIP_COMPONENTS;
7291 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
7292 // to convert TYPE to the backend representation before we convert
7294 if (type->named_type() != NULL)
7296 switch (type->base()->classification())
7298 case Type::TYPE_ERROR:
7299 case Type::TYPE_BOOLEAN:
7300 case Type::TYPE_INTEGER:
7301 case Type::TYPE_FLOAT:
7302 case Type::TYPE_COMPLEX:
7303 case Type::TYPE_STRING:
7304 case Type::TYPE_NIL:
7307 case Type::TYPE_ARRAY:
7308 case Type::TYPE_STRUCT:
7309 this->find_type_->add_dependency(type->named_type());
7312 case Type::TYPE_VOID:
7313 case Type::TYPE_SINK:
7314 case Type::TYPE_FUNCTION:
7315 case Type::TYPE_POINTER:
7316 case Type::TYPE_CALL_MULTIPLE_RESULT:
7317 case Type::TYPE_MAP:
7318 case Type::TYPE_CHANNEL:
7319 case Type::TYPE_INTERFACE:
7320 case Type::TYPE_NAMED:
7321 case Type::TYPE_FORWARD:
7327 return TRAVERSE_CONTINUE;
7330 // Verify that a named type does not refer to itself.
7333 Named_type::do_verify()
7335 Find_type_use find(this);
7336 Type::traverse(this->type_, &find);
7339 error_at(this->location_, "invalid recursive type %qs",
7340 this->message_name().c_str());
7341 this->is_error_ = true;
7345 // Check whether any of the local methods overloads an existing
7346 // struct field or interface method. We don't need to check the
7347 // list of methods against itself: that is handled by the Bindings
7349 if (this->local_methods_ != NULL)
7351 Struct_type* st = this->type_->struct_type();
7352 bool found_dup = false;
7355 for (Bindings::const_declarations_iterator p =
7356 this->local_methods_->begin_declarations();
7357 p != this->local_methods_->end_declarations();
7360 const std::string& name(p->first);
7361 if (st != NULL && st->find_local_field(name, NULL) != NULL)
7363 error_at(p->second->location(),
7364 "method %qs redeclares struct field name",
7365 Gogo::message_name(name).c_str());
7377 // Return whether this type is or contains a pointer.
7380 Named_type::do_has_pointer() const
7385 bool ret = this->type_->has_pointer();
7386 this->seen_ = false;
7390 // Return whether comparisons for this type can use the identity
7394 Named_type::do_compare_is_identity() const
7399 bool ret = this->type_->compare_is_identity();
7400 this->seen_ = false;
7404 // Return a hash code. This is used for method lookup. We simply
7405 // hash on the name itself.
7408 Named_type::do_hash_for_method(Gogo* gogo) const
7410 const std::string& name(this->named_object()->name());
7411 unsigned int ret = Type::hash_string(name, 0);
7413 // GOGO will be NULL here when called from Type_hash_identical.
7414 // That is OK because that is only used for internal hash tables
7415 // where we are going to be comparing named types for equality. In
7416 // other cases, which are cases where the runtime is going to
7417 // compare hash codes to see if the types are the same, we need to
7418 // include the package prefix and name in the hash.
7419 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
7421 const Package* package = this->named_object()->package();
7422 if (package == NULL)
7424 ret = Type::hash_string(gogo->unique_prefix(), ret);
7425 ret = Type::hash_string(gogo->package_name(), ret);
7429 ret = Type::hash_string(package->unique_prefix(), ret);
7430 ret = Type::hash_string(package->name(), ret);
7437 // Convert a named type to the backend representation. In order to
7438 // get dependencies right, we fill in a dummy structure for this type,
7439 // then convert all the dependencies, then complete this type. When
7440 // this function is complete, the size of the type is known.
7443 Named_type::convert(Gogo* gogo)
7445 if (this->is_error_ || this->is_converted_)
7448 this->create_placeholder(gogo);
7450 // Convert all the dependencies. If they refer indirectly back to
7451 // this type, they will pick up the intermediate tree we just
7453 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
7454 p != this->dependencies_.end();
7456 (*p)->convert(gogo);
7458 // Complete this type.
7459 Btype* bt = this->named_btype_;
7460 Type* base = this->type_->base();
7461 switch (base->classification())
7478 // The size of these types is already correct. We don't worry
7479 // about filling them in until later, when we also track
7480 // circular references.
7485 std::vector<Backend::Btyped_identifier> bfields;
7486 get_backend_struct_fields(gogo, base->struct_type()->fields(),
7488 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
7489 bt = gogo->backend()->error_type();
7494 // Slice types were completed in create_placeholder.
7495 if (!base->is_slice_type())
7497 Btype* bet = base->array_type()->get_backend_element(gogo);
7498 Bexpression* blen = base->array_type()->get_backend_length(gogo);
7499 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
7500 bt = gogo->backend()->error_type();
7504 case TYPE_INTERFACE:
7505 // Interface types were completed in create_placeholder.
7513 case TYPE_CALL_MULTIPLE_RESULT:
7519 this->named_btype_ = bt;
7520 this->is_converted_ = true;
7523 // Create the placeholder for a named type. This is the first step in
7524 // converting to the backend representation.
7527 Named_type::create_placeholder(Gogo* gogo)
7529 if (this->is_error_)
7530 this->named_btype_ = gogo->backend()->error_type();
7532 if (this->named_btype_ != NULL)
7535 // Create the structure for this type. Note that because we call
7536 // base() here, we don't attempt to represent a named type defined
7537 // as another named type. Instead both named types will point to
7538 // different base representations.
7539 Type* base = this->type_->base();
7541 bool set_name = true;
7542 switch (base->classification())
7545 this->is_error_ = true;
7546 this->named_btype_ = gogo->backend()->error_type();
7556 // These are simple basic types, we can just create them
7558 bt = Type::get_named_base_btype(gogo, base);
7563 // All maps and channels have the same backend representation.
7564 bt = Type::get_named_base_btype(gogo, base);
7570 bool for_function = base->classification() == TYPE_FUNCTION;
7571 bt = gogo->backend()->placeholder_pointer_type(this->name(),
7579 bt = gogo->backend()->placeholder_struct_type(this->name(),
7585 if (base->is_slice_type())
7586 bt = gogo->backend()->placeholder_struct_type(this->name(),
7589 bt = gogo->backend()->placeholder_array_type(this->name(),
7594 case TYPE_INTERFACE:
7595 if (base->interface_type()->is_empty())
7596 bt = Interface_type::get_backend_empty_interface_type(gogo);
7599 bt = gogo->backend()->placeholder_struct_type(this->name(),
7607 case TYPE_CALL_MULTIPLE_RESULT:
7614 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
7616 this->named_btype_ = bt;
7618 if (base->is_slice_type())
7620 // We do not record slices as dependencies of other types,
7621 // because we can fill them in completely here with the final
7623 std::vector<Backend::Btyped_identifier> bfields;
7624 get_backend_slice_fields(gogo, base->array_type(), &bfields);
7625 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
7626 this->named_btype_ = gogo->backend()->error_type();
7628 else if (base->interface_type() != NULL
7629 && !base->interface_type()->is_empty())
7631 // We do not record interfaces as dependencies of other types,
7632 // because we can fill them in completely here with the final
7634 std::vector<Backend::Btyped_identifier> bfields;
7635 get_backend_interface_fields(gogo, base->interface_type(), &bfields);
7636 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
7637 this->named_btype_ = gogo->backend()->error_type();
7641 // Get a tree for a named type.
7644 Named_type::do_get_backend(Gogo* gogo)
7646 if (this->is_error_)
7647 return gogo->backend()->error_type();
7649 Btype* bt = this->named_btype_;
7651 if (!gogo->named_types_are_converted())
7653 // We have not completed converting named types. NAMED_BTYPE_
7654 // is a placeholder and we shouldn't do anything further.
7658 // We don't build dependencies for types whose sizes do not
7659 // change or are not relevant, so we may see them here while
7660 // converting types.
7661 this->create_placeholder(gogo);
7662 bt = this->named_btype_;
7663 go_assert(bt != NULL);
7667 // We are not converting types. This should only be called if the
7668 // type has already been converted.
7669 if (!this->is_converted_)
7671 go_assert(saw_errors());
7672 return gogo->backend()->error_type();
7675 go_assert(bt != NULL);
7677 // Complete the tree.
7678 Type* base = this->type_->base();
7680 switch (base->classification())
7683 return gogo->backend()->error_type();
7696 case TYPE_INTERFACE:
7700 // Don't build a circular data structure. GENERIC can't handle
7702 if (this->seen_in_get_backend_)
7704 this->is_circular_ = true;
7705 return gogo->backend()->circular_pointer_type(bt, true);
7707 this->seen_in_get_backend_ = true;
7708 bt1 = Type::get_named_base_btype(gogo, base);
7709 this->seen_in_get_backend_ = false;
7710 if (this->is_circular_)
7711 bt1 = gogo->backend()->circular_pointer_type(bt, true);
7712 if (!gogo->backend()->set_placeholder_function_type(bt, bt1))
7713 bt = gogo->backend()->error_type();
7717 // Don't build a circular data structure. GENERIC can't handle
7719 if (this->seen_in_get_backend_)
7721 this->is_circular_ = true;
7722 return gogo->backend()->circular_pointer_type(bt, false);
7724 this->seen_in_get_backend_ = true;
7725 bt1 = Type::get_named_base_btype(gogo, base);
7726 this->seen_in_get_backend_ = false;
7727 if (this->is_circular_)
7728 bt1 = gogo->backend()->circular_pointer_type(bt, false);
7729 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
7730 bt = gogo->backend()->error_type();
7735 case TYPE_CALL_MULTIPLE_RESULT:
7744 // Build a type descriptor for a named type.
7747 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7749 // If NAME is not NULL, then we don't really want the type
7750 // descriptor for this type; we want the descriptor for the
7751 // underlying type, giving it the name NAME.
7752 return this->named_type_descriptor(gogo, this->type_,
7753 name == NULL ? this : name);
7756 // Add to the reflection string. This is used mostly for the name of
7757 // the type used in a type descriptor, not for actual reflection
7761 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
7763 if (!Linemap::is_predeclared_location(this->location()))
7765 const Package* package = this->named_object_->package();
7766 if (package != NULL)
7767 ret->append(package->name());
7769 ret->append(gogo->package_name());
7770 ret->push_back('.');
7772 if (this->in_function_ != NULL)
7774 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
7775 ret->push_back('$');
7777 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
7780 // Get the mangled name.
7783 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7785 Named_object* no = this->named_object_;
7787 if (Linemap::is_predeclared_location(this->location()))
7788 go_assert(this->in_function_ == NULL);
7791 const std::string& unique_prefix(no->package() == NULL
7792 ? gogo->unique_prefix()
7793 : no->package()->unique_prefix());
7794 const std::string& package_name(no->package() == NULL
7795 ? gogo->package_name()
7796 : no->package()->name());
7797 name = unique_prefix;
7798 name.append(1, '.');
7799 name.append(package_name);
7800 name.append(1, '.');
7801 if (this->in_function_ != NULL)
7803 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
7804 name.append(1, '$');
7807 name.append(Gogo::unpack_hidden_name(no->name()));
7809 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
7814 // Export the type. This is called to export a global type.
7817 Named_type::export_named_type(Export* exp, const std::string&) const
7819 // We don't need to write the name of the type here, because it will
7820 // be written by Export::write_type anyhow.
7821 exp->write_c_string("type ");
7822 exp->write_type(this);
7823 exp->write_c_string(";\n");
7826 // Import a named type.
7829 Named_type::import_named_type(Import* imp, Named_type** ptype)
7831 imp->require_c_string("type ");
7832 Type *type = imp->read_type();
7833 *ptype = type->named_type();
7834 go_assert(*ptype != NULL);
7835 imp->require_c_string(";\n");
7838 // Export the type when it is referenced by another type. In this
7839 // case Export::export_type will already have issued the name.
7842 Named_type::do_export(Export* exp) const
7844 exp->write_type(this->type_);
7846 // To save space, we only export the methods directly attached to
7848 Bindings* methods = this->local_methods_;
7849 if (methods == NULL)
7852 exp->write_c_string("\n");
7853 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
7854 p != methods->end_definitions();
7857 exp->write_c_string(" ");
7858 (*p)->export_named_object(exp);
7861 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
7862 p != methods->end_declarations();
7865 if (p->second->is_function_declaration())
7867 exp->write_c_string(" ");
7868 p->second->export_named_object(exp);
7873 // Make a named type.
7876 Type::make_named_type(Named_object* named_object, Type* type,
7879 return new Named_type(named_object, type, location);
7882 // Finalize the methods for TYPE. It will be a named type or a struct
7883 // type. This sets *ALL_METHODS to the list of methods, and builds
7884 // all required stubs.
7887 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
7888 Methods** all_methods)
7890 *all_methods = NULL;
7891 Types_seen types_seen;
7892 Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen,
7894 Type::build_stub_methods(gogo, type, *all_methods, location);
7897 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
7898 // build up the struct field indexes as we go. DEPTH is the depth of
7899 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
7900 // adding these methods for an anonymous field with pointer type.
7901 // NEEDS_STUB_METHOD is true if we need to use a stub method which
7902 // calls the real method. TYPES_SEEN is used to avoid infinite
7906 Type::add_methods_for_type(const Type* type,
7907 const Method::Field_indexes* field_indexes,
7909 bool is_embedded_pointer,
7910 bool needs_stub_method,
7911 Types_seen* types_seen,
7914 // Pointer types may not have methods.
7915 if (type->points_to() != NULL)
7918 const Named_type* nt = type->named_type();
7921 std::pair<Types_seen::iterator, bool> ins = types_seen->insert(nt);
7927 Type::add_local_methods_for_type(nt, field_indexes, depth,
7928 is_embedded_pointer, needs_stub_method,
7931 Type::add_embedded_methods_for_type(type, field_indexes, depth,
7932 is_embedded_pointer, needs_stub_method,
7933 types_seen, methods);
7935 // If we are called with depth > 0, then we are looking at an
7936 // anonymous field of a struct. If such a field has interface type,
7937 // then we need to add the interface methods. We don't want to add
7938 // them when depth == 0, because we will already handle them
7939 // following the usual rules for an interface type.
7941 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
7944 // Add the local methods for the named type NT to *METHODS. The
7945 // parameters are as for add_methods_to_type.
7948 Type::add_local_methods_for_type(const Named_type* nt,
7949 const Method::Field_indexes* field_indexes,
7951 bool is_embedded_pointer,
7952 bool needs_stub_method,
7955 const Bindings* local_methods = nt->local_methods();
7956 if (local_methods == NULL)
7959 if (*methods == NULL)
7960 *methods = new Methods();
7962 for (Bindings::const_declarations_iterator p =
7963 local_methods->begin_declarations();
7964 p != local_methods->end_declarations();
7967 Named_object* no = p->second;
7968 bool is_value_method = (is_embedded_pointer
7969 || !Type::method_expects_pointer(no));
7970 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
7972 || (depth > 0 && is_value_method)));
7973 if (!(*methods)->insert(no->name(), m))
7978 // Add the embedded methods for TYPE to *METHODS. These are the
7979 // methods attached to anonymous fields. The parameters are as for
7980 // add_methods_to_type.
7983 Type::add_embedded_methods_for_type(const Type* type,
7984 const Method::Field_indexes* field_indexes,
7986 bool is_embedded_pointer,
7987 bool needs_stub_method,
7988 Types_seen* types_seen,
7991 // Look for anonymous fields in TYPE. TYPE has fields if it is a
7993 const Struct_type* st = type->struct_type();
7997 const Struct_field_list* fields = st->fields();
8002 for (Struct_field_list::const_iterator pf = fields->begin();
8003 pf != fields->end();
8006 if (!pf->is_anonymous())
8009 Type* ftype = pf->type();
8010 bool is_pointer = false;
8011 if (ftype->points_to() != NULL)
8013 ftype = ftype->points_to();
8016 Named_type* fnt = ftype->named_type();
8019 // This is an error, but it will be diagnosed elsewhere.
8023 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
8024 sub_field_indexes->next = field_indexes;
8025 sub_field_indexes->field_index = i;
8027 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
8028 (is_embedded_pointer || is_pointer),
8037 // If TYPE is an interface type, then add its method to *METHODS.
8038 // This is for interface methods attached to an anonymous field. The
8039 // parameters are as for add_methods_for_type.
8042 Type::add_interface_methods_for_type(const Type* type,
8043 const Method::Field_indexes* field_indexes,
8047 const Interface_type* it = type->interface_type();
8051 const Typed_identifier_list* imethods = it->methods();
8052 if (imethods == NULL)
8055 if (*methods == NULL)
8056 *methods = new Methods();
8058 for (Typed_identifier_list::const_iterator pm = imethods->begin();
8059 pm != imethods->end();
8062 Function_type* fntype = pm->type()->function_type();
8065 // This is an error, but it should be reported elsewhere
8066 // when we look at the methods for IT.
8069 go_assert(!fntype->is_method());
8070 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
8071 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
8072 field_indexes, depth);
8073 if (!(*methods)->insert(pm->name(), m))
8078 // Build stub methods for TYPE as needed. METHODS is the set of
8079 // methods for the type. A stub method may be needed when a type
8080 // inherits a method from an anonymous field. When we need the
8081 // address of the method, as in a type descriptor, we need to build a
8082 // little stub which does the required field dereferences and jumps to
8083 // the real method. LOCATION is the location of the type definition.
8086 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
8089 if (methods == NULL)
8091 for (Methods::const_iterator p = methods->begin();
8092 p != methods->end();
8095 Method* m = p->second;
8096 if (m->is_ambiguous() || !m->needs_stub_method())
8099 const std::string& name(p->first);
8101 // Build a stub method.
8103 const Function_type* fntype = m->type();
8105 static unsigned int counter;
8107 snprintf(buf, sizeof buf, "$this%u", counter);
8110 Type* receiver_type = const_cast<Type*>(type);
8111 if (!m->is_value_method())
8112 receiver_type = Type::make_pointer_type(receiver_type);
8113 Location receiver_location = m->receiver_location();
8114 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
8117 const Typed_identifier_list* fnparams = fntype->parameters();
8118 Typed_identifier_list* stub_params;
8119 if (fnparams == NULL || fnparams->empty())
8123 // We give each stub parameter a unique name.
8124 stub_params = new Typed_identifier_list();
8125 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
8126 pp != fnparams->end();
8130 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
8131 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
8137 const Typed_identifier_list* fnresults = fntype->results();
8138 Typed_identifier_list* stub_results;
8139 if (fnresults == NULL || fnresults->empty())
8140 stub_results = NULL;
8143 // We create the result parameters without any names, since
8144 // we won't refer to them.
8145 stub_results = new Typed_identifier_list();
8146 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
8147 pr != fnresults->end();
8149 stub_results->push_back(Typed_identifier("", pr->type(),
8153 Function_type* stub_type = Type::make_function_type(receiver,
8156 fntype->location());
8157 if (fntype->is_varargs())
8158 stub_type->set_is_varargs();
8160 // We only create the function in the package which creates the
8162 const Package* package;
8163 if (type->named_type() == NULL)
8166 package = type->named_type()->named_object()->package();
8168 if (package != NULL)
8169 stub = Named_object::make_function_declaration(name, package,
8170 stub_type, location);
8173 stub = gogo->start_function(name, stub_type, false,
8174 fntype->location());
8175 Type::build_one_stub_method(gogo, m, buf, stub_params,
8176 fntype->is_varargs(), location);
8177 gogo->finish_function(fntype->location());
8180 m->set_stub_object(stub);
8184 // Build a stub method which adjusts the receiver as required to call
8185 // METHOD. RECEIVER_NAME is the name we used for the receiver.
8186 // PARAMS is the list of function parameters.
8189 Type::build_one_stub_method(Gogo* gogo, Method* method,
8190 const char* receiver_name,
8191 const Typed_identifier_list* params,
8195 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
8196 go_assert(receiver_object != NULL);
8198 Expression* expr = Expression::make_var_reference(receiver_object, location);
8199 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
8200 if (expr->type()->points_to() == NULL)
8201 expr = Expression::make_unary(OPERATOR_AND, expr, location);
8203 Expression_list* arguments;
8204 if (params == NULL || params->empty())
8208 arguments = new Expression_list();
8209 for (Typed_identifier_list::const_iterator p = params->begin();
8213 Named_object* param = gogo->lookup(p->name(), NULL);
8214 go_assert(param != NULL);
8215 Expression* param_ref = Expression::make_var_reference(param,
8217 arguments->push_back(param_ref);
8221 Expression* func = method->bind_method(expr, location);
8222 go_assert(func != NULL);
8223 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
8225 call->set_hidden_fields_are_ok();
8226 size_t count = call->result_count();
8228 gogo->add_statement(Statement::make_statement(call, true));
8231 Expression_list* retvals = new Expression_list();
8233 retvals->push_back(call);
8236 for (size_t i = 0; i < count; ++i)
8237 retvals->push_back(Expression::make_call_result(call, i));
8239 Return_statement* retstat = Statement::make_return_statement(retvals,
8242 // We can return values with hidden fields from a stub. This is
8243 // necessary if the method is itself hidden.
8244 retstat->set_hidden_fields_are_ok();
8246 gogo->add_statement(retstat);
8250 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
8251 // in reverse order.
8254 Type::apply_field_indexes(Expression* expr,
8255 const Method::Field_indexes* field_indexes,
8258 if (field_indexes == NULL)
8260 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
8261 Struct_type* stype = expr->type()->deref()->struct_type();
8262 go_assert(stype != NULL
8263 && field_indexes->field_index < stype->field_count());
8264 if (expr->type()->struct_type() == NULL)
8266 go_assert(expr->type()->points_to() != NULL);
8267 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
8268 go_assert(expr->type()->struct_type() == stype);
8270 return Expression::make_field_reference(expr, field_indexes->field_index,
8274 // Return whether NO is a method for which the receiver is a pointer.
8277 Type::method_expects_pointer(const Named_object* no)
8279 const Function_type *fntype;
8280 if (no->is_function())
8281 fntype = no->func_value()->type();
8282 else if (no->is_function_declaration())
8283 fntype = no->func_declaration_value()->type();
8286 return fntype->receiver()->type()->points_to() != NULL;
8289 // Given a set of methods for a type, METHODS, return the method NAME,
8290 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
8291 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
8292 // but is ambiguous (and return NULL).
8295 Type::method_function(const Methods* methods, const std::string& name,
8298 if (is_ambiguous != NULL)
8299 *is_ambiguous = false;
8300 if (methods == NULL)
8302 Methods::const_iterator p = methods->find(name);
8303 if (p == methods->end())
8305 Method* m = p->second;
8306 if (m->is_ambiguous())
8308 if (is_ambiguous != NULL)
8309 *is_ambiguous = true;
8315 // Look for field or method NAME for TYPE. Return an Expression for
8316 // the field or method bound to EXPR. If there is no such field or
8317 // method, give an appropriate error and return an error expression.
8320 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
8321 const std::string& name,
8324 if (type->deref()->is_error_type())
8325 return Expression::make_error(location);
8327 const Named_type* nt = type->deref()->named_type();
8328 const Struct_type* st = type->deref()->struct_type();
8329 const Interface_type* it = type->interface_type();
8331 // If this is a pointer to a pointer, then it is possible that the
8332 // pointed-to type has methods.
8336 && type->points_to() != NULL
8337 && type->points_to()->points_to() != NULL)
8339 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
8340 type = type->points_to();
8341 if (type->deref()->is_error_type())
8342 return Expression::make_error(location);
8343 nt = type->points_to()->named_type();
8344 st = type->points_to()->struct_type();
8347 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
8348 || expr->is_addressable());
8349 std::vector<const Named_type*> seen;
8350 bool is_method = false;
8351 bool found_pointer_method = false;
8354 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
8355 &seen, NULL, &is_method,
8356 &found_pointer_method, &ambig1, &ambig2))
8361 go_assert(st != NULL);
8362 if (type->struct_type() == NULL)
8364 go_assert(type->points_to() != NULL);
8365 expr = Expression::make_unary(OPERATOR_MULT, expr,
8367 go_assert(expr->type()->struct_type() == st);
8369 ret = st->field_reference(expr, name, location);
8371 else if (it != NULL && it->find_method(name) != NULL)
8372 ret = Expression::make_interface_field_reference(expr, name,
8378 m = nt->method_function(name, NULL);
8379 else if (st != NULL)
8380 m = st->method_function(name, NULL);
8383 go_assert(m != NULL);
8384 if (!m->is_value_method() && expr->type()->points_to() == NULL)
8385 expr = Expression::make_unary(OPERATOR_AND, expr, location);
8386 ret = m->bind_method(expr, location);
8388 go_assert(ret != NULL);
8393 if (!ambig1.empty())
8394 error_at(location, "%qs is ambiguous via %qs and %qs",
8395 Gogo::message_name(name).c_str(), ambig1.c_str(),
8397 else if (found_pointer_method)
8398 error_at(location, "method requires a pointer");
8399 else if (nt == NULL && st == NULL && it == NULL)
8401 ("reference to field %qs in object which "
8402 "has no fields or methods"),
8403 Gogo::message_name(name).c_str());
8407 if (!Gogo::is_hidden_name(name))
8408 is_unexported = false;
8411 std::string unpacked = Gogo::unpack_hidden_name(name);
8413 is_unexported = Type::is_unexported_field_or_method(gogo, type,
8418 error_at(location, "reference to unexported field or method %qs",
8419 Gogo::message_name(name).c_str());
8421 error_at(location, "reference to undefined field or method %qs",
8422 Gogo::message_name(name).c_str());
8424 return Expression::make_error(location);
8428 // Look in TYPE for a field or method named NAME, return true if one
8429 // is found. This looks through embedded anonymous fields and handles
8430 // ambiguity. If a method is found, sets *IS_METHOD to true;
8431 // otherwise, if a field is found, set it to false. If
8432 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
8433 // whose address can not be taken. SEEN is used to avoid infinite
8434 // recursion on invalid types.
8436 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
8437 // method we couldn't use because it requires a pointer. LEVEL is
8438 // used for recursive calls, and can be NULL for a non-recursive call.
8439 // When this function returns false because it finds that the name is
8440 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
8441 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
8442 // will be unchanged.
8444 // This function just returns whether or not there is a field or
8445 // method, and whether it is a field or method. It doesn't build an
8446 // expression to refer to it. If it is a method, we then look in the
8447 // list of all methods for the type. If it is a field, the search has
8448 // to be done again, looking only for fields, and building up the
8449 // expression as we go.
8452 Type::find_field_or_method(const Type* type,
8453 const std::string& name,
8454 bool receiver_can_be_pointer,
8455 std::vector<const Named_type*>* seen,
8458 bool* found_pointer_method,
8459 std::string* ambig1,
8460 std::string* ambig2)
8462 // Named types can have locally defined methods.
8463 const Named_type* nt = type->named_type();
8464 if (nt == NULL && type->points_to() != NULL)
8465 nt = type->points_to()->named_type();
8468 Named_object* no = nt->find_local_method(name);
8471 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
8477 // Record that we have found a pointer method in order to
8478 // give a better error message if we don't find anything
8480 *found_pointer_method = true;
8483 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
8489 // We've already seen this type when searching for methods.
8495 // Interface types can have methods.
8496 const Interface_type* it = type->interface_type();
8497 if (it != NULL && it->find_method(name) != NULL)
8503 // Struct types can have fields. They can also inherit fields and
8504 // methods from anonymous fields.
8505 const Struct_type* st = type->deref()->struct_type();
8508 const Struct_field_list* fields = st->fields();
8513 seen->push_back(nt);
8515 int found_level = 0;
8516 bool found_is_method = false;
8517 std::string found_ambig1;
8518 std::string found_ambig2;
8519 const Struct_field* found_parent = NULL;
8520 for (Struct_field_list::const_iterator pf = fields->begin();
8521 pf != fields->end();
8524 if (pf->is_field_name(name))
8532 if (!pf->is_anonymous())
8535 if (pf->type()->deref()->is_error_type()
8536 || pf->type()->deref()->is_undefined())
8539 Named_type* fnt = pf->type()->named_type();
8541 fnt = pf->type()->deref()->named_type();
8542 go_assert(fnt != NULL);
8544 int sublevel = level == NULL ? 1 : *level + 1;
8546 std::string subambig1;
8547 std::string subambig2;
8548 bool subfound = Type::find_field_or_method(fnt,
8550 receiver_can_be_pointer,
8554 found_pointer_method,
8559 if (!subambig1.empty())
8561 // The name was found via this field, but is ambiguous.
8562 // if the ambiguity is lower or at the same level as
8563 // anything else we have already found, then we want to
8564 // pass the ambiguity back to the caller.
8565 if (found_level == 0 || sublevel <= found_level)
8567 found_ambig1 = (Gogo::message_name(pf->field_name())
8569 found_ambig2 = (Gogo::message_name(pf->field_name())
8571 found_level = sublevel;
8577 // The name was found via this field. Use the level to see
8578 // if we want to use this one, or whether it introduces an
8580 if (found_level == 0 || sublevel < found_level)
8582 found_level = sublevel;
8583 found_is_method = sub_is_method;
8584 found_ambig1.clear();
8585 found_ambig2.clear();
8586 found_parent = &*pf;
8588 else if (sublevel > found_level)
8590 else if (found_ambig1.empty())
8592 // We found an ambiguity.
8593 go_assert(found_parent != NULL);
8594 found_ambig1 = Gogo::message_name(found_parent->field_name());
8595 found_ambig2 = Gogo::message_name(pf->field_name());
8599 // We found an ambiguity, but we already know of one.
8600 // Just report the earlier one.
8605 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
8606 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
8607 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
8608 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
8613 if (found_level == 0)
8615 else if (!found_ambig1.empty())
8617 go_assert(!found_ambig1.empty());
8618 ambig1->assign(found_ambig1);
8619 ambig2->assign(found_ambig2);
8621 *level = found_level;
8627 *level = found_level;
8628 *is_method = found_is_method;
8633 // Return whether NAME is an unexported field or method for TYPE.
8636 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
8637 const std::string& name,
8638 std::vector<const Named_type*>* seen)
8640 const Named_type* nt = type->named_type();
8642 nt = type->deref()->named_type();
8645 if (nt->is_unexported_local_method(gogo, name))
8648 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
8654 // We've already seen this type.
8660 const Interface_type* it = type->interface_type();
8661 if (it != NULL && it->is_unexported_method(gogo, name))
8664 type = type->deref();
8666 const Struct_type* st = type->struct_type();
8667 if (st != NULL && st->is_unexported_local_field(gogo, name))
8673 const Struct_field_list* fields = st->fields();
8678 seen->push_back(nt);
8680 for (Struct_field_list::const_iterator pf = fields->begin();
8681 pf != fields->end();
8684 if (pf->is_anonymous()
8685 && !pf->type()->deref()->is_error_type()
8686 && !pf->type()->deref()->is_undefined())
8688 Named_type* subtype = pf->type()->named_type();
8689 if (subtype == NULL)
8690 subtype = pf->type()->deref()->named_type();
8691 if (subtype == NULL)
8693 // This is an error, but it will be diagnosed elsewhere.
8696 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
8711 // Class Forward_declaration.
8713 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
8714 : Type(TYPE_FORWARD),
8715 named_object_(named_object->resolve()), warned_(false)
8717 go_assert(this->named_object_->is_unknown()
8718 || this->named_object_->is_type_declaration());
8721 // Return the named object.
8724 Forward_declaration_type::named_object()
8726 return this->named_object_->resolve();
8730 Forward_declaration_type::named_object() const
8732 return this->named_object_->resolve();
8735 // Return the name of the forward declared type.
8738 Forward_declaration_type::name() const
8740 return this->named_object()->name();
8743 // Warn about a use of a type which has been declared but not defined.
8746 Forward_declaration_type::warn() const
8748 Named_object* no = this->named_object_->resolve();
8749 if (no->is_unknown())
8751 // The name was not defined anywhere.
8754 error_at(this->named_object_->location(),
8755 "use of undefined type %qs",
8756 no->message_name().c_str());
8757 this->warned_ = true;
8760 else if (no->is_type_declaration())
8762 // The name was seen as a type, but the type was never defined.
8763 if (no->type_declaration_value()->using_type())
8765 error_at(this->named_object_->location(),
8766 "use of undefined type %qs",
8767 no->message_name().c_str());
8768 this->warned_ = true;
8773 // The name was defined, but not as a type.
8776 error_at(this->named_object_->location(), "expected type");
8777 this->warned_ = true;
8782 // Get the base type of a declaration. This gives an error if the
8783 // type has not yet been defined.
8786 Forward_declaration_type::real_type()
8788 if (this->is_defined())
8789 return this->named_object()->type_value();
8793 return Type::make_error_type();
8798 Forward_declaration_type::real_type() const
8800 if (this->is_defined())
8801 return this->named_object()->type_value();
8805 return Type::make_error_type();
8809 // Return whether the base type is defined.
8812 Forward_declaration_type::is_defined() const
8814 return this->named_object()->is_type();
8817 // Add a method. This is used when methods are defined before the
8821 Forward_declaration_type::add_method(const std::string& name,
8824 Named_object* no = this->named_object();
8825 if (no->is_unknown())
8826 no->declare_as_type();
8827 return no->type_declaration_value()->add_method(name, function);
8830 // Add a method declaration. This is used when methods are declared
8834 Forward_declaration_type::add_method_declaration(const std::string& name,
8835 Function_type* type,
8838 Named_object* no = this->named_object();
8839 if (no->is_unknown())
8840 no->declare_as_type();
8841 Type_declaration* td = no->type_declaration_value();
8842 return td->add_method_declaration(name, type, location);
8848 Forward_declaration_type::do_traverse(Traverse* traverse)
8850 if (this->is_defined()
8851 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
8852 return TRAVERSE_EXIT;
8853 return TRAVERSE_CONTINUE;
8856 // Get the backend representation for the type.
8859 Forward_declaration_type::do_get_backend(Gogo* gogo)
8861 if (this->is_defined())
8862 return Type::get_named_base_btype(gogo, this->real_type());
8865 return gogo->backend()->error_type();
8867 // We represent an undefined type as a struct with no fields. That
8868 // should work fine for the backend, since the same case can arise
8870 std::vector<Backend::Btyped_identifier> fields;
8871 Btype* bt = gogo->backend()->struct_type(fields);
8872 return gogo->backend()->named_type(this->name(), bt,
8873 this->named_object()->location());
8876 // Build a type descriptor for a forwarded type.
8879 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8881 Location ploc = Linemap::predeclared_location();
8882 if (!this->is_defined())
8883 return Expression::make_nil(ploc);
8886 Type* t = this->real_type();
8888 return this->named_type_descriptor(gogo, t, name);
8890 return Expression::make_type_descriptor(t, ploc);
8894 // The reflection string.
8897 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
8899 this->append_reflection(this->real_type(), gogo, ret);
8902 // The mangled name.
8905 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8907 if (this->is_defined())
8908 this->append_mangled_name(this->real_type(), gogo, ret);
8911 const Named_object* no = this->named_object();
8913 if (no->package() == NULL)
8914 name = gogo->package_name();
8916 name = no->package()->name();
8918 name += Gogo::unpack_hidden_name(no->name());
8920 snprintf(buf, sizeof buf, "N%u_",
8921 static_cast<unsigned int>(name.length()));
8927 // Export a forward declaration. This can happen when a defined type
8928 // refers to a type which is only declared (and is presumably defined
8929 // in some other file in the same package).
8932 Forward_declaration_type::do_export(Export*) const
8934 // If there is a base type, that should be exported instead of this.
8935 go_assert(!this->is_defined());
8937 // We don't output anything.
8940 // Make a forward declaration.
8943 Type::make_forward_declaration(Named_object* named_object)
8945 return new Forward_declaration_type(named_object);
8948 // Class Typed_identifier_list.
8950 // Sort the entries by name.
8952 struct Typed_identifier_list_sort
8956 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
8957 { return t1.name() < t2.name(); }
8961 Typed_identifier_list::sort_by_name()
8963 std::sort(this->entries_.begin(), this->entries_.end(),
8964 Typed_identifier_list_sort());
8970 Typed_identifier_list::traverse(Traverse* traverse)
8972 for (Typed_identifier_list::const_iterator p = this->begin();
8976 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
8977 return TRAVERSE_EXIT;
8979 return TRAVERSE_CONTINUE;
8984 Typed_identifier_list*
8985 Typed_identifier_list::copy() const
8987 Typed_identifier_list* ret = new Typed_identifier_list();
8988 for (Typed_identifier_list::const_iterator p = this->begin();
8991 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));