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),
41 type_descriptor_decl_(NULL_TREE)
49 // Get the base type for a type--skip names and forward declarations.
54 switch (this->classification_)
57 return this->named_type()->named_base();
59 return this->forward_declaration_type()->real_type()->base();
68 switch (this->classification_)
71 return this->named_type()->named_base();
73 return this->forward_declaration_type()->real_type()->base();
79 // Skip defined forward declarations.
85 Forward_declaration_type* ftype = t->forward_declaration_type();
86 while (ftype != NULL && ftype->is_defined())
88 t = ftype->real_type();
89 ftype = t->forward_declaration_type();
95 Type::forwarded() const
98 const Forward_declaration_type* ftype = t->forward_declaration_type();
99 while (ftype != NULL && ftype->is_defined())
101 t = ftype->real_type();
102 ftype = t->forward_declaration_type();
107 // If this is a named type, return it. Otherwise, return NULL.
112 return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
116 Type::named_type() const
118 return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
121 // Return true if this type is not defined.
124 Type::is_undefined() const
126 return this->forwarded()->forward_declaration_type() != NULL;
129 // Return true if this is a basic type: a type which is not composed
130 // of other types, and is not void.
133 Type::is_basic_type() const
135 switch (this->classification_)
158 return this->base()->is_basic_type();
165 // Return true if this is an abstract type.
168 Type::is_abstract() const
170 switch (this->classification())
173 return this->integer_type()->is_abstract();
175 return this->float_type()->is_abstract();
177 return this->complex_type()->is_abstract();
179 return this->is_abstract_string_type();
181 return this->is_abstract_boolean_type();
187 // Return a non-abstract version of an abstract type.
190 Type::make_non_abstract_type()
192 go_assert(this->is_abstract());
193 switch (this->classification())
196 return Type::lookup_integer_type("int");
198 return Type::lookup_float_type("float64");
200 return Type::lookup_complex_type("complex128");
202 return Type::lookup_string_type();
204 return Type::lookup_bool_type();
210 // Return true if this is an error type. Don't give an error if we
211 // try to dereference an undefined forwarding type, as this is called
212 // in the parser when the type may legitimately be undefined.
215 Type::is_error_type() const
217 const Type* t = this->forwarded();
218 // Note that we return false for an undefined forward type.
219 switch (t->classification_)
224 return t->named_type()->is_named_error_type();
230 // If this is a pointer type, return the type to which it points.
231 // Otherwise, return NULL.
234 Type::points_to() const
236 const Pointer_type* ptype = this->convert<const Pointer_type,
238 return ptype == NULL ? NULL : ptype->points_to();
241 // Return whether this is an open array type.
244 Type::is_open_array_type() const
246 return this->array_type() != NULL && this->array_type()->length() == NULL;
249 // Return whether this is the predeclared constant nil being used as a
253 Type::is_nil_constant_as_type() const
255 const Type* t = this->forwarded();
256 if (t->forward_declaration_type() != NULL)
258 const Named_object* no = t->forward_declaration_type()->named_object();
259 if (no->is_unknown())
260 no = no->unknown_value()->real_named_object();
263 && no->const_value()->expr()->is_nil_expression())
272 Type::traverse(Type* type, Traverse* traverse)
274 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
275 || (traverse->traverse_mask()
276 & Traverse::traverse_expressions) != 0);
277 if (traverse->remember_type(type))
279 // We have already traversed this type.
280 return TRAVERSE_CONTINUE;
282 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
284 int t = traverse->type(type);
285 if (t == TRAVERSE_EXIT)
286 return TRAVERSE_EXIT;
287 else if (t == TRAVERSE_SKIP_COMPONENTS)
288 return TRAVERSE_CONTINUE;
290 // An array type has an expression which we need to traverse if
291 // traverse_expressions is set.
292 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
293 return TRAVERSE_EXIT;
294 return TRAVERSE_CONTINUE;
297 // Default implementation for do_traverse for child class.
300 Type::do_traverse(Traverse*)
302 return TRAVERSE_CONTINUE;
305 // Return whether two types are identical. If ERRORS_ARE_IDENTICAL,
306 // then return true for all erroneous types; this is used to avoid
307 // cascading errors. If REASON is not NULL, optionally set *REASON to
308 // the reason the types are not identical.
311 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
314 if (t1 == NULL || t2 == NULL)
316 // Something is wrong.
317 return errors_are_identical ? true : t1 == t2;
320 // Skip defined forward declarations.
321 t1 = t1->forwarded();
322 t2 = t2->forwarded();
327 // An undefined forward declaration is an error.
328 if (t1->forward_declaration_type() != NULL
329 || t2->forward_declaration_type() != NULL)
330 return errors_are_identical;
332 // Avoid cascading errors with error types.
333 if (t1->is_error_type() || t2->is_error_type())
335 if (errors_are_identical)
337 return t1->is_error_type() && t2->is_error_type();
340 // Get a good reason for the sink type. Note that the sink type on
341 // the left hand side of an assignment is handled in are_assignable.
342 if (t1->is_sink_type() || t2->is_sink_type())
345 *reason = "invalid use of _";
349 // A named type is only identical to itself.
350 if (t1->named_type() != NULL || t2->named_type() != NULL)
353 // Check type shapes.
354 if (t1->classification() != t2->classification())
357 switch (t1->classification())
363 // These types are always identical.
367 return t1->integer_type()->is_identical(t2->integer_type());
370 return t1->float_type()->is_identical(t2->float_type());
373 return t1->complex_type()->is_identical(t2->complex_type());
376 return t1->function_type()->is_identical(t2->function_type(),
378 errors_are_identical,
382 return Type::are_identical(t1->points_to(), t2->points_to(),
383 errors_are_identical, reason);
386 return t1->struct_type()->is_identical(t2->struct_type(),
387 errors_are_identical);
390 return t1->array_type()->is_identical(t2->array_type(),
391 errors_are_identical);
394 return t1->map_type()->is_identical(t2->map_type(),
395 errors_are_identical);
398 return t1->channel_type()->is_identical(t2->channel_type(),
399 errors_are_identical);
402 return t1->interface_type()->is_identical(t2->interface_type(),
403 errors_are_identical);
405 case TYPE_CALL_MULTIPLE_RESULT:
407 *reason = "invalid use of multiple value function call";
415 // Return true if it's OK to have a binary operation with types LHS
416 // and RHS. This is not used for shifts or comparisons.
419 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
421 if (Type::are_identical(lhs, rhs, true, NULL))
424 // A constant of abstract bool type may be mixed with any bool type.
425 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
426 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
429 // A constant of abstract string type may be mixed with any string
431 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
432 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
438 // A constant of abstract integer, float, or complex type may be
439 // mixed with an integer, float, or complex type.
440 if ((rhs->is_abstract()
441 && (rhs->integer_type() != NULL
442 || rhs->float_type() != NULL
443 || rhs->complex_type() != NULL)
444 && (lhs->integer_type() != NULL
445 || lhs->float_type() != NULL
446 || lhs->complex_type() != NULL))
447 || (lhs->is_abstract()
448 && (lhs->integer_type() != NULL
449 || lhs->float_type() != NULL
450 || lhs->complex_type() != NULL)
451 && (rhs->integer_type() != NULL
452 || rhs->float_type() != NULL
453 || rhs->complex_type() != NULL)))
456 // The nil type may be compared to a pointer, an interface type, a
457 // slice type, a channel type, a map type, or a function type.
458 if (lhs->is_nil_type()
459 && (rhs->points_to() != NULL
460 || rhs->interface_type() != NULL
461 || rhs->is_open_array_type()
462 || rhs->map_type() != NULL
463 || rhs->channel_type() != NULL
464 || rhs->function_type() != NULL))
466 if (rhs->is_nil_type()
467 && (lhs->points_to() != NULL
468 || lhs->interface_type() != NULL
469 || lhs->is_open_array_type()
470 || lhs->map_type() != NULL
471 || lhs->channel_type() != NULL
472 || lhs->function_type() != NULL))
478 // Return true if a value with type RHS may be assigned to a variable
479 // with type LHS. If CHECK_HIDDEN_FIELDS is true, check whether any
480 // hidden fields are modified. If REASON is not NULL, set *REASON to
481 // the reason the types are not assignable.
484 Type::are_assignable_check_hidden(const Type* lhs, const Type* rhs,
485 bool check_hidden_fields,
488 // Do some checks first. Make sure the types are defined.
490 && rhs->forwarded()->forward_declaration_type() == NULL
491 && rhs->is_void_type())
494 *reason = "non-value used as value";
498 if (lhs != NULL && lhs->forwarded()->forward_declaration_type() == NULL)
500 // Any value may be assigned to the blank identifier.
501 if (lhs->is_sink_type())
504 // All fields of a struct must be exported, or the assignment
505 // must be in the same package.
506 if (check_hidden_fields
508 && rhs->forwarded()->forward_declaration_type() == NULL)
510 if (lhs->has_hidden_fields(NULL, reason)
511 || rhs->has_hidden_fields(NULL, reason))
516 // Identical types are assignable.
517 if (Type::are_identical(lhs, rhs, true, reason))
520 // The types are assignable if they have identical underlying types
521 // and either LHS or RHS is not a named type.
522 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
523 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
524 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
527 // The types are assignable if LHS is an interface type and RHS
528 // implements the required methods.
529 const Interface_type* lhs_interface_type = lhs->interface_type();
530 if (lhs_interface_type != NULL)
532 if (lhs_interface_type->implements_interface(rhs, reason))
534 const Interface_type* rhs_interface_type = rhs->interface_type();
535 if (rhs_interface_type != NULL
536 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
541 // The type are assignable if RHS is a bidirectional channel type,
542 // LHS is a channel type, they have identical element types, and
543 // either LHS or RHS is not a named type.
544 if (lhs->channel_type() != NULL
545 && rhs->channel_type() != NULL
546 && rhs->channel_type()->may_send()
547 && rhs->channel_type()->may_receive()
548 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
549 && Type::are_identical(lhs->channel_type()->element_type(),
550 rhs->channel_type()->element_type(),
555 // The nil type may be assigned to a pointer, function, slice, map,
556 // channel, or interface type.
557 if (rhs->is_nil_type()
558 && (lhs->points_to() != NULL
559 || lhs->function_type() != NULL
560 || lhs->is_open_array_type()
561 || lhs->map_type() != NULL
562 || lhs->channel_type() != NULL
563 || lhs->interface_type() != NULL))
566 // An untyped numeric constant may be assigned to a numeric type if
567 // it is representable in that type.
568 if ((rhs->is_abstract()
569 && (rhs->integer_type() != NULL
570 || rhs->float_type() != NULL
571 || rhs->complex_type() != NULL))
572 && (lhs->integer_type() != NULL
573 || lhs->float_type() != NULL
574 || lhs->complex_type() != NULL))
577 // Give some better error messages.
578 if (reason != NULL && reason->empty())
580 if (rhs->interface_type() != NULL)
581 reason->assign(_("need explicit conversion"));
582 else if (rhs->is_call_multiple_result_type())
583 reason->assign(_("multiple value function call in "
584 "single value context"));
585 else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
587 size_t len = (lhs->named_type()->name().length()
588 + rhs->named_type()->name().length()
590 char* buf = new char[len];
591 snprintf(buf, len, _("cannot use type %s as type %s"),
592 rhs->named_type()->message_name().c_str(),
593 lhs->named_type()->message_name().c_str());
602 // Return true if a value with type RHS may be assigned to a variable
603 // with type LHS. If REASON is not NULL, set *REASON to the reason
604 // the types are not assignable.
607 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
609 return Type::are_assignable_check_hidden(lhs, rhs, true, reason);
612 // Like are_assignable but don't check for hidden fields.
615 Type::are_assignable_hidden_ok(const Type* lhs, const Type* rhs,
618 return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
621 // Return true if a value with type RHS may be converted to type LHS.
622 // If REASON is not NULL, set *REASON to the reason the types are not
626 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
628 // The types are convertible if they are assignable.
629 if (Type::are_assignable(lhs, rhs, reason))
632 // The types are convertible if they have identical underlying
634 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
635 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
638 // The types are convertible if they are both unnamed pointer types
639 // and their pointer base types have identical underlying types.
640 if (lhs->named_type() == NULL
641 && rhs->named_type() == NULL
642 && lhs->points_to() != NULL
643 && rhs->points_to() != NULL
644 && (lhs->points_to()->named_type() != NULL
645 || rhs->points_to()->named_type() != NULL)
646 && Type::are_identical(lhs->points_to()->base(),
647 rhs->points_to()->base(),
652 // Integer and floating point types are convertible to each other.
653 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
654 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
657 // Complex types are convertible to each other.
658 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
661 // An integer, or []byte, or []int, may be converted to a string.
662 if (lhs->is_string_type())
664 if (rhs->integer_type() != NULL)
666 if (rhs->is_open_array_type() && rhs->named_type() == NULL)
668 const Type* e = rhs->array_type()->element_type()->forwarded();
669 if (e->integer_type() != NULL
670 && (e == Type::lookup_integer_type("uint8")
671 || e == Type::lookup_integer_type("int")))
676 // A string may be converted to []byte or []int.
677 if (rhs->is_string_type()
678 && lhs->is_open_array_type()
679 && lhs->named_type() == NULL)
681 const Type* e = lhs->array_type()->element_type()->forwarded();
682 if (e->integer_type() != NULL
683 && (e == Type::lookup_integer_type("uint8")
684 || e == Type::lookup_integer_type("int")))
688 // An unsafe.Pointer type may be converted to any pointer type or to
689 // uintptr, and vice-versa.
690 if (lhs->is_unsafe_pointer_type()
691 && (rhs->points_to() != NULL
692 || (rhs->integer_type() != NULL
693 && rhs->forwarded() == Type::lookup_integer_type("uintptr"))))
695 if (rhs->is_unsafe_pointer_type()
696 && (lhs->points_to() != NULL
697 || (lhs->integer_type() != NULL
698 && lhs->forwarded() == Type::lookup_integer_type("uintptr"))))
701 // Give a better error message.
705 *reason = "invalid type conversion";
708 std::string s = "invalid type conversion (";
718 // Return whether this type has any hidden fields. This is only a
719 // possibility for a few types.
722 Type::has_hidden_fields(const Named_type* within, std::string* reason) const
724 switch (this->forwarded()->classification_)
727 return this->named_type()->named_type_has_hidden_fields(reason);
729 return this->struct_type()->struct_has_hidden_fields(within, reason);
731 return this->array_type()->array_has_hidden_fields(within, reason);
737 // Return a hash code for the type to be used for method lookup.
740 Type::hash_for_method(Gogo* gogo) const
742 unsigned int ret = 0;
743 if (this->classification_ != TYPE_FORWARD)
744 ret += this->classification_;
745 return ret + this->do_hash_for_method(gogo);
748 // Default implementation of do_hash_for_method. This is appropriate
749 // for types with no subfields.
752 Type::do_hash_for_method(Gogo*) const
757 // Return a hash code for a string, given a starting hash.
760 Type::hash_string(const std::string& s, unsigned int h)
762 const char* p = s.data();
763 size_t len = s.length();
764 for (; len > 0; --len)
772 // Default check for the expression passed to make. Any type which
773 // may be used with make implements its own version of this.
776 Type::do_check_make_expression(Expression_list*, source_location)
781 // Return whether an expression has an integer value. Report an error
782 // if not. This is used when handling calls to the predeclared make
786 Type::check_int_value(Expression* e, const char* errmsg,
787 source_location location)
789 if (e->type()->integer_type() != NULL)
792 // Check for a floating point constant with integer value.
797 if (e->float_constant_value(fval, &dummy) && mpfr_integer_p(fval))
804 mpfr_clear_overflow();
805 mpfr_clear_erangeflag();
806 mpfr_get_z(ival, fval, GMP_RNDN);
807 if (!mpfr_overflow_p()
808 && !mpfr_erangeflag_p()
809 && mpz_sgn(ival) >= 0)
811 Named_type* ntype = Type::lookup_integer_type("int");
812 Integer_type* inttype = ntype->integer_type();
814 mpz_init_set_ui(max, 1);
815 mpz_mul_2exp(max, max, inttype->bits() - 1);
816 ok = mpz_cmp(ival, max) < 0;
830 error_at(location, "%s", errmsg);
834 // A hash table mapping unnamed types to the backend representation of
837 Type::Type_btypes Type::type_btypes;
839 // Return a tree representing this type.
842 Type::get_backend(Gogo* gogo)
844 if (this->btype_ != NULL)
847 if (this->forward_declaration_type() != NULL
848 || this->named_type() != NULL)
849 return this->get_btype_without_hash(gogo);
851 if (this->is_error_type())
852 return gogo->backend()->error_type();
854 // To avoid confusing the backend, translate all identical Go types
855 // to the same backend representation. We use a hash table to do
856 // that. There is no need to use the hash table for named types, as
857 // named types are only identical to themselves.
859 std::pair<Type*, Btype*> val(this, NULL);
860 std::pair<Type_btypes::iterator, bool> ins =
861 Type::type_btypes.insert(val);
862 if (!ins.second && ins.first->second != NULL)
864 if (gogo != NULL && gogo->named_types_are_converted())
865 this->btype_ = ins.first->second;
866 return ins.first->second;
869 Btype* bt = this->get_btype_without_hash(gogo);
871 if (ins.first->second == NULL)
872 ins.first->second = bt;
875 // We have already created a backend representation for this
876 // type. This can happen when an unnamed type is defined using
877 // a named type which in turns uses an identical unnamed type.
878 // Use the tree we created earlier and ignore the one we just
880 bt = ins.first->second;
881 if (gogo == NULL || !gogo->named_types_are_converted())
889 // Return the backend representation for a type without looking in the
890 // hash table for identical types. This is used for named types,
891 // since a named type is never identical to any other type.
894 Type::get_btype_without_hash(Gogo* gogo)
896 if (this->btype_ == NULL)
898 Btype* bt = this->do_get_backend(gogo);
900 // For a recursive function or pointer type, we will temporarily
901 // return a circular pointer type during the recursion. We
902 // don't want to record that for a forwarding type, as it may
904 if (this->forward_declaration_type() != NULL
905 && gogo->backend()->is_circular_pointer_type(bt))
908 if (gogo == NULL || !gogo->named_types_are_converted())
916 // Any type which supports the builtin make function must implement
920 Type::do_make_expression_tree(Translate_context*, Expression_list*,
926 // Return a pointer to the type descriptor for this type.
929 Type::type_descriptor_pointer(Gogo* gogo)
931 Type* t = this->forwarded();
932 if (t->type_descriptor_decl_ == NULL_TREE)
934 Expression* e = t->do_type_descriptor(gogo, NULL);
935 gogo->build_type_descriptor_decl(t, e, &t->type_descriptor_decl_);
936 go_assert(t->type_descriptor_decl_ != NULL_TREE
937 && (t->type_descriptor_decl_ == error_mark_node
938 || DECL_P(t->type_descriptor_decl_)));
940 if (t->type_descriptor_decl_ == error_mark_node)
941 return error_mark_node;
942 return build_fold_addr_expr(t->type_descriptor_decl_);
945 // Return a composite literal for a type descriptor.
948 Type::type_descriptor(Gogo* gogo, Type* type)
950 return type->do_type_descriptor(gogo, NULL);
953 // Return a composite literal for a type descriptor with a name.
956 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
958 go_assert(name != NULL && type->named_type() != name);
959 return type->do_type_descriptor(gogo, name);
962 // Make a builtin struct type from a list of fields. The fields are
963 // pairs of a name and a type.
966 Type::make_builtin_struct_type(int nfields, ...)
969 va_start(ap, nfields);
971 source_location bloc = BUILTINS_LOCATION;
972 Struct_field_list* sfl = new Struct_field_list();
973 for (int i = 0; i < nfields; i++)
975 const char* field_name = va_arg(ap, const char *);
976 Type* type = va_arg(ap, Type*);
977 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
982 return Type::make_struct_type(sfl, bloc);
985 // A list of builtin named types.
987 std::vector<Named_type*> Type::named_builtin_types;
989 // Make a builtin named type.
992 Type::make_builtin_named_type(const char* name, Type* type)
994 source_location bloc = BUILTINS_LOCATION;
995 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
996 Named_type* ret = no->type_value();
997 Type::named_builtin_types.push_back(ret);
1001 // Convert the named builtin types.
1004 Type::convert_builtin_named_types(Gogo* gogo)
1006 for (std::vector<Named_type*>::const_iterator p =
1007 Type::named_builtin_types.begin();
1008 p != Type::named_builtin_types.end();
1011 bool r = (*p)->verify();
1013 (*p)->convert(gogo);
1017 // Return the type of a type descriptor. We should really tie this to
1018 // runtime.Type rather than copying it. This must match commonType in
1019 // libgo/go/runtime/type.go.
1022 Type::make_type_descriptor_type()
1027 source_location bloc = BUILTINS_LOCATION;
1029 Type* uint8_type = Type::lookup_integer_type("uint8");
1030 Type* uint32_type = Type::lookup_integer_type("uint32");
1031 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1032 Type* string_type = Type::lookup_string_type();
1033 Type* pointer_string_type = Type::make_pointer_type(string_type);
1035 // This is an unnamed version of unsafe.Pointer. Perhaps we
1036 // should use the named version instead, although that would
1037 // require us to create the unsafe package if it has not been
1038 // imported. It probably doesn't matter.
1039 Type* void_type = Type::make_void_type();
1040 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1042 // Forward declaration for the type descriptor type.
1043 Named_object* named_type_descriptor_type =
1044 Named_object::make_type_declaration("commonType", NULL, bloc);
1045 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1046 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1048 // The type of a method on a concrete type.
1049 Struct_type* method_type =
1050 Type::make_builtin_struct_type(5,
1051 "name", pointer_string_type,
1052 "pkgPath", pointer_string_type,
1053 "mtyp", pointer_type_descriptor_type,
1054 "typ", pointer_type_descriptor_type,
1055 "tfn", unsafe_pointer_type);
1056 Named_type* named_method_type =
1057 Type::make_builtin_named_type("method", method_type);
1059 // Information for types with a name or methods.
1060 Type* slice_named_method_type =
1061 Type::make_array_type(named_method_type, NULL);
1062 Struct_type* uncommon_type =
1063 Type::make_builtin_struct_type(3,
1064 "name", pointer_string_type,
1065 "pkgPath", pointer_string_type,
1066 "methods", slice_named_method_type);
1067 Named_type* named_uncommon_type =
1068 Type::make_builtin_named_type("uncommonType", uncommon_type);
1070 Type* pointer_uncommon_type =
1071 Type::make_pointer_type(named_uncommon_type);
1073 // The type descriptor type.
1075 Typed_identifier_list* params = new Typed_identifier_list();
1076 params->push_back(Typed_identifier("", unsafe_pointer_type, bloc));
1077 params->push_back(Typed_identifier("", uintptr_type, bloc));
1079 Typed_identifier_list* results = new Typed_identifier_list();
1080 results->push_back(Typed_identifier("", uintptr_type, bloc));
1082 Type* hashfn_type = Type::make_function_type(NULL, params, results, bloc);
1084 params = new Typed_identifier_list();
1085 params->push_back(Typed_identifier("", unsafe_pointer_type, bloc));
1086 params->push_back(Typed_identifier("", unsafe_pointer_type, bloc));
1087 params->push_back(Typed_identifier("", uintptr_type, bloc));
1089 results = new Typed_identifier_list();
1090 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1092 Type* equalfn_type = Type::make_function_type(NULL, params, results,
1095 Struct_type* type_descriptor_type =
1096 Type::make_builtin_struct_type(10,
1098 "align", uint8_type,
1099 "fieldAlign", uint8_type,
1100 "size", uintptr_type,
1101 "hash", uint32_type,
1102 "hashfn", hashfn_type,
1103 "equalfn", equalfn_type,
1104 "string", pointer_string_type,
1105 "", pointer_uncommon_type,
1107 pointer_type_descriptor_type);
1109 Named_type* named = Type::make_builtin_named_type("commonType",
1110 type_descriptor_type);
1112 named_type_descriptor_type->set_type_value(named);
1120 // Make the type of a pointer to a type descriptor as represented in
1124 Type::make_type_descriptor_ptr_type()
1128 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1132 // Return the names of runtime functions which compute a hash code for
1133 // this type and which compare whether two values of this type are
1137 Type::type_functions(const char** hash_fn, const char** equal_fn) const
1139 switch (this->base()->classification())
1141 case Type::TYPE_ERROR:
1142 case Type::TYPE_VOID:
1143 case Type::TYPE_NIL:
1144 // These types can not be hashed or compared.
1145 *hash_fn = "__go_type_hash_error";
1146 *equal_fn = "__go_type_equal_error";
1149 case Type::TYPE_BOOLEAN:
1150 case Type::TYPE_INTEGER:
1151 case Type::TYPE_FLOAT:
1152 case Type::TYPE_COMPLEX:
1153 case Type::TYPE_POINTER:
1154 case Type::TYPE_FUNCTION:
1155 case Type::TYPE_MAP:
1156 case Type::TYPE_CHANNEL:
1157 *hash_fn = "__go_type_hash_identity";
1158 *equal_fn = "__go_type_equal_identity";
1161 case Type::TYPE_STRING:
1162 *hash_fn = "__go_type_hash_string";
1163 *equal_fn = "__go_type_equal_string";
1166 case Type::TYPE_STRUCT:
1167 case Type::TYPE_ARRAY:
1168 // These types can not be hashed or compared.
1169 *hash_fn = "__go_type_hash_error";
1170 *equal_fn = "__go_type_equal_error";
1173 case Type::TYPE_INTERFACE:
1174 if (this->interface_type()->is_empty())
1176 *hash_fn = "__go_type_hash_empty_interface";
1177 *equal_fn = "__go_type_equal_empty_interface";
1181 *hash_fn = "__go_type_hash_interface";
1182 *equal_fn = "__go_type_equal_interface";
1186 case Type::TYPE_NAMED:
1187 case Type::TYPE_FORWARD:
1195 // Return a composite literal for the type descriptor for a plain type
1196 // of kind RUNTIME_TYPE_KIND named NAME.
1199 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
1200 Named_type* name, const Methods* methods,
1201 bool only_value_methods)
1203 source_location bloc = BUILTINS_LOCATION;
1205 Type* td_type = Type::make_type_descriptor_type();
1206 const Struct_field_list* fields = td_type->struct_type()->fields();
1208 Expression_list* vals = new Expression_list();
1211 Struct_field_list::const_iterator p = fields->begin();
1212 go_assert(p->field_name() == "Kind");
1214 mpz_init_set_ui(iv, runtime_type_kind);
1215 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1218 go_assert(p->field_name() == "align");
1219 Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT;
1220 vals->push_back(Expression::make_type_info(this, type_info));
1223 go_assert(p->field_name() == "fieldAlign");
1224 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
1225 vals->push_back(Expression::make_type_info(this, type_info));
1228 go_assert(p->field_name() == "size");
1229 type_info = Expression::TYPE_INFO_SIZE;
1230 vals->push_back(Expression::make_type_info(this, type_info));
1233 go_assert(p->field_name() == "hash");
1234 mpz_set_ui(iv, this->hash_for_method(gogo));
1235 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1237 const char* hash_fn;
1238 const char* equal_fn;
1239 this->type_functions(&hash_fn, &equal_fn);
1242 go_assert(p->field_name() == "hashfn");
1243 Function_type* fntype = p->type()->function_type();
1244 Named_object* no = Named_object::make_function_declaration(hash_fn, NULL,
1247 no->func_declaration_value()->set_asm_name(hash_fn);
1248 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
1251 go_assert(p->field_name() == "equalfn");
1252 fntype = p->type()->function_type();
1253 no = Named_object::make_function_declaration(equal_fn, NULL, fntype, bloc);
1254 no->func_declaration_value()->set_asm_name(equal_fn);
1255 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
1258 go_assert(p->field_name() == "string");
1259 Expression* s = Expression::make_string((name != NULL
1260 ? name->reflection(gogo)
1261 : this->reflection(gogo)),
1263 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1266 go_assert(p->field_name() == "uncommonType");
1267 if (name == NULL && methods == NULL)
1268 vals->push_back(Expression::make_nil(bloc));
1271 if (methods == NULL)
1272 methods = name->methods();
1273 vals->push_back(this->uncommon_type_constructor(gogo,
1276 only_value_methods));
1280 go_assert(p->field_name() == "ptrToThis");
1282 vals->push_back(Expression::make_nil(bloc));
1285 Type* pt = Type::make_pointer_type(name);
1286 vals->push_back(Expression::make_type_descriptor(pt, bloc));
1290 go_assert(p == fields->end());
1294 return Expression::make_struct_composite_literal(td_type, vals, bloc);
1297 // Return a composite literal for the uncommon type information for
1298 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
1299 // struct. If name is not NULL, it is the name of the type. If
1300 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
1301 // is true if only value methods should be included. At least one of
1302 // NAME and METHODS must not be NULL.
1305 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
1306 Named_type* name, const Methods* methods,
1307 bool only_value_methods) const
1309 source_location bloc = BUILTINS_LOCATION;
1311 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
1313 Expression_list* vals = new Expression_list();
1316 Struct_field_list::const_iterator p = fields->begin();
1317 go_assert(p->field_name() == "name");
1320 go_assert(p->field_name() == "pkgPath");
1324 vals->push_back(Expression::make_nil(bloc));
1325 vals->push_back(Expression::make_nil(bloc));
1329 Named_object* no = name->named_object();
1330 std::string n = Gogo::unpack_hidden_name(no->name());
1331 Expression* s = Expression::make_string(n, bloc);
1332 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1334 if (name->is_builtin())
1335 vals->push_back(Expression::make_nil(bloc));
1338 const Package* package = no->package();
1339 const std::string& unique_prefix(package == NULL
1340 ? gogo->unique_prefix()
1341 : package->unique_prefix());
1342 const std::string& package_name(package == NULL
1343 ? gogo->package_name()
1345 n.assign(unique_prefix);
1347 n.append(package_name);
1348 if (name->in_function() != NULL)
1351 n.append(Gogo::unpack_hidden_name(name->in_function()->name()));
1353 s = Expression::make_string(n, bloc);
1354 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1359 go_assert(p->field_name() == "methods");
1360 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
1361 only_value_methods));
1364 go_assert(p == fields->end());
1366 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
1368 return Expression::make_unary(OPERATOR_AND, r, bloc);
1371 // Sort methods by name.
1377 operator()(const std::pair<std::string, const Method*>& m1,
1378 const std::pair<std::string, const Method*>& m2) const
1379 { return m1.first < m2.first; }
1382 // Return a composite literal for the type method table for this type.
1383 // METHODS_TYPE is the type of the table, and is a slice type.
1384 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
1385 // then only value methods are used.
1388 Type::methods_constructor(Gogo* gogo, Type* methods_type,
1389 const Methods* methods,
1390 bool only_value_methods) const
1392 source_location bloc = BUILTINS_LOCATION;
1394 std::vector<std::pair<std::string, const Method*> > smethods;
1395 if (methods != NULL)
1397 smethods.reserve(methods->count());
1398 for (Methods::const_iterator p = methods->begin();
1399 p != methods->end();
1402 if (p->second->is_ambiguous())
1404 if (only_value_methods && !p->second->is_value_method())
1406 smethods.push_back(std::make_pair(p->first, p->second));
1410 if (smethods.empty())
1411 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
1413 std::sort(smethods.begin(), smethods.end(), Sort_methods());
1415 Type* method_type = methods_type->array_type()->element_type();
1417 Expression_list* vals = new Expression_list();
1418 vals->reserve(smethods.size());
1419 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
1421 p != smethods.end();
1423 vals->push_back(this->method_constructor(gogo, method_type, p->first,
1424 p->second, only_value_methods));
1426 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
1429 // Return a composite literal for a single method. METHOD_TYPE is the
1430 // type of the entry. METHOD_NAME is the name of the method and M is
1431 // the method information.
1434 Type::method_constructor(Gogo*, Type* method_type,
1435 const std::string& method_name,
1437 bool only_value_methods) const
1439 source_location bloc = BUILTINS_LOCATION;
1441 const Struct_field_list* fields = method_type->struct_type()->fields();
1443 Expression_list* vals = new Expression_list();
1446 Struct_field_list::const_iterator p = fields->begin();
1447 go_assert(p->field_name() == "name");
1448 const std::string n = Gogo::unpack_hidden_name(method_name);
1449 Expression* s = Expression::make_string(n, bloc);
1450 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1453 go_assert(p->field_name() == "pkgPath");
1454 if (!Gogo::is_hidden_name(method_name))
1455 vals->push_back(Expression::make_nil(bloc));
1458 s = Expression::make_string(Gogo::hidden_name_prefix(method_name), bloc);
1459 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1462 Named_object* no = (m->needs_stub_method()
1464 : m->named_object());
1466 Function_type* mtype;
1467 if (no->is_function())
1468 mtype = no->func_value()->type();
1470 mtype = no->func_declaration_value()->type();
1471 go_assert(mtype->is_method());
1472 Type* nonmethod_type = mtype->copy_without_receiver();
1475 go_assert(p->field_name() == "mtyp");
1476 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
1479 go_assert(p->field_name() == "typ");
1480 if (!only_value_methods && m->is_value_method())
1482 // This is a value method on a pointer type. Change the type of
1483 // the method to use a pointer receiver. The implementation
1484 // always uses a pointer receiver anyhow.
1485 Type* rtype = mtype->receiver()->type();
1486 Type* prtype = Type::make_pointer_type(rtype);
1487 Typed_identifier* receiver =
1488 new Typed_identifier(mtype->receiver()->name(), prtype,
1489 mtype->receiver()->location());
1490 mtype = Type::make_function_type(receiver,
1491 (mtype->parameters() == NULL
1493 : mtype->parameters()->copy()),
1494 (mtype->results() == NULL
1496 : mtype->results()->copy()),
1499 vals->push_back(Expression::make_type_descriptor(mtype, bloc));
1502 go_assert(p->field_name() == "tfn");
1503 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
1506 go_assert(p == fields->end());
1508 return Expression::make_struct_composite_literal(method_type, vals, bloc);
1511 // Return a composite literal for the type descriptor of a plain type.
1512 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
1513 // NULL, it is the name to use as well as the list of methods.
1516 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
1519 return this->type_descriptor_constructor(gogo, runtime_type_kind,
1523 // Return the type reflection string for this type.
1526 Type::reflection(Gogo* gogo) const
1530 // The do_reflection virtual function should set RET to the
1531 // reflection string.
1532 this->do_reflection(gogo, &ret);
1537 // Return a mangled name for the type.
1540 Type::mangled_name(Gogo* gogo) const
1544 // The do_mangled_name virtual function should set RET to the
1545 // mangled name. For a composite type it should append a code for
1546 // the composition and then call do_mangled_name on the components.
1547 this->do_mangled_name(gogo, &ret);
1552 // Default function to export a type.
1555 Type::do_export(Export*) const
1563 Type::import_type(Import* imp)
1565 if (imp->match_c_string("("))
1566 return Function_type::do_import(imp);
1567 else if (imp->match_c_string("*"))
1568 return Pointer_type::do_import(imp);
1569 else if (imp->match_c_string("struct "))
1570 return Struct_type::do_import(imp);
1571 else if (imp->match_c_string("["))
1572 return Array_type::do_import(imp);
1573 else if (imp->match_c_string("map "))
1574 return Map_type::do_import(imp);
1575 else if (imp->match_c_string("chan "))
1576 return Channel_type::do_import(imp);
1577 else if (imp->match_c_string("interface"))
1578 return Interface_type::do_import(imp);
1581 error_at(imp->location(), "import error: expected type");
1582 return Type::make_error_type();
1586 // A type used to indicate a parsing error. This exists to simplify
1587 // later error detection.
1589 class Error_type : public Type
1598 do_get_backend(Gogo* gogo)
1599 { return gogo->backend()->error_type(); }
1602 do_type_descriptor(Gogo*, Named_type*)
1603 { return Expression::make_error(BUILTINS_LOCATION); }
1606 do_reflection(Gogo*, std::string*) const
1607 { go_assert(saw_errors()); }
1610 do_mangled_name(Gogo*, std::string* ret) const
1611 { ret->push_back('E'); }
1615 Type::make_error_type()
1617 static Error_type singleton_error_type;
1618 return &singleton_error_type;
1623 class Void_type : public Type
1632 do_get_backend(Gogo* gogo)
1633 { return gogo->backend()->void_type(); }
1636 do_type_descriptor(Gogo*, Named_type*)
1637 { go_unreachable(); }
1640 do_reflection(Gogo*, std::string*) const
1644 do_mangled_name(Gogo*, std::string* ret) const
1645 { ret->push_back('v'); }
1649 Type::make_void_type()
1651 static Void_type singleton_void_type;
1652 return &singleton_void_type;
1655 // The boolean type.
1657 class Boolean_type : public Type
1661 : Type(TYPE_BOOLEAN)
1666 do_get_backend(Gogo* gogo)
1667 { return gogo->backend()->bool_type(); }
1670 do_type_descriptor(Gogo*, Named_type* name);
1672 // We should not be asked for the reflection string of a basic type.
1674 do_reflection(Gogo*, std::string* ret) const
1675 { ret->append("bool"); }
1678 do_mangled_name(Gogo*, std::string* ret) const
1679 { ret->push_back('b'); }
1682 // Make the type descriptor.
1685 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
1688 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
1691 Named_object* no = gogo->lookup_global("bool");
1692 go_assert(no != NULL);
1693 return Type::type_descriptor(gogo, no->type_value());
1698 Type::make_boolean_type()
1700 static Boolean_type boolean_type;
1701 return &boolean_type;
1704 // The named type "bool".
1706 static Named_type* named_bool_type;
1708 // Get the named type "bool".
1711 Type::lookup_bool_type()
1713 return named_bool_type;
1716 // Make the named type "bool".
1719 Type::make_named_bool_type()
1721 Type* bool_type = Type::make_boolean_type();
1722 Named_object* named_object = Named_object::make_type("bool", NULL,
1725 Named_type* named_type = named_object->type_value();
1726 named_bool_type = named_type;
1730 // Class Integer_type.
1732 Integer_type::Named_integer_types Integer_type::named_integer_types;
1734 // Create a new integer type. Non-abstract integer types always have
1738 Integer_type::create_integer_type(const char* name, bool is_unsigned,
1739 int bits, int runtime_type_kind)
1741 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
1743 std::string sname(name);
1744 Named_object* named_object = Named_object::make_type(sname, NULL,
1747 Named_type* named_type = named_object->type_value();
1748 std::pair<Named_integer_types::iterator, bool> ins =
1749 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
1750 go_assert(ins.second);
1754 // Look up an existing integer type.
1757 Integer_type::lookup_integer_type(const char* name)
1759 Named_integer_types::const_iterator p =
1760 Integer_type::named_integer_types.find(name);
1761 go_assert(p != Integer_type::named_integer_types.end());
1765 // Create a new abstract integer type.
1768 Integer_type::create_abstract_integer_type()
1770 static Integer_type* abstract_type;
1771 if (abstract_type == NULL)
1772 abstract_type = new Integer_type(true, false, INT_TYPE_SIZE,
1773 RUNTIME_TYPE_KIND_INT);
1774 return abstract_type;
1777 // Integer type compatibility.
1780 Integer_type::is_identical(const Integer_type* t) const
1782 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
1784 return this->is_abstract_ == t->is_abstract_;
1790 Integer_type::do_hash_for_method(Gogo*) const
1792 return ((this->bits_ << 4)
1793 + ((this->is_unsigned_ ? 1 : 0) << 8)
1794 + ((this->is_abstract_ ? 1 : 0) << 9));
1797 // Convert an Integer_type to the backend representation.
1800 Integer_type::do_get_backend(Gogo* gogo)
1802 if (this->is_abstract_)
1804 go_assert(saw_errors());
1805 return gogo->backend()->error_type();
1807 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
1810 // The type descriptor for an integer type. Integer types are always
1814 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
1816 go_assert(name != NULL);
1817 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
1820 // We should not be asked for the reflection string of a basic type.
1823 Integer_type::do_reflection(Gogo*, std::string*) const
1825 go_assert(saw_errors());
1831 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
1834 snprintf(buf, sizeof buf, "i%s%s%de",
1835 this->is_abstract_ ? "a" : "",
1836 this->is_unsigned_ ? "u" : "",
1841 // Make an integer type.
1844 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
1845 int runtime_type_kind)
1847 return Integer_type::create_integer_type(name, is_unsigned, bits,
1851 // Make an abstract integer type.
1854 Type::make_abstract_integer_type()
1856 return Integer_type::create_abstract_integer_type();
1859 // Look up an integer type.
1862 Type::lookup_integer_type(const char* name)
1864 return Integer_type::lookup_integer_type(name);
1867 // Class Float_type.
1869 Float_type::Named_float_types Float_type::named_float_types;
1871 // Create a new float type. Non-abstract float types always have
1875 Float_type::create_float_type(const char* name, int bits,
1876 int runtime_type_kind)
1878 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
1879 std::string sname(name);
1880 Named_object* named_object = Named_object::make_type(sname, NULL, float_type,
1882 Named_type* named_type = named_object->type_value();
1883 std::pair<Named_float_types::iterator, bool> ins =
1884 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
1885 go_assert(ins.second);
1889 // Look up an existing float type.
1892 Float_type::lookup_float_type(const char* name)
1894 Named_float_types::const_iterator p =
1895 Float_type::named_float_types.find(name);
1896 go_assert(p != Float_type::named_float_types.end());
1900 // Create a new abstract float type.
1903 Float_type::create_abstract_float_type()
1905 static Float_type* abstract_type;
1906 if (abstract_type == NULL)
1907 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
1908 return abstract_type;
1911 // Whether this type is identical with T.
1914 Float_type::is_identical(const Float_type* t) const
1916 if (this->bits_ != t->bits_)
1918 return this->is_abstract_ == t->is_abstract_;
1924 Float_type::do_hash_for_method(Gogo*) const
1926 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
1929 // Convert to the backend representation.
1932 Float_type::do_get_backend(Gogo* gogo)
1934 return gogo->backend()->float_type(this->bits_);
1937 // The type descriptor for a float type. Float types are always named.
1940 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
1942 go_assert(name != NULL);
1943 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
1946 // We should not be asked for the reflection string of a basic type.
1949 Float_type::do_reflection(Gogo*, std::string*) const
1951 go_assert(saw_errors());
1957 Float_type::do_mangled_name(Gogo*, std::string* ret) const
1960 snprintf(buf, sizeof buf, "f%s%de",
1961 this->is_abstract_ ? "a" : "",
1966 // Make a floating point type.
1969 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
1971 return Float_type::create_float_type(name, bits, runtime_type_kind);
1974 // Make an abstract float type.
1977 Type::make_abstract_float_type()
1979 return Float_type::create_abstract_float_type();
1982 // Look up a float type.
1985 Type::lookup_float_type(const char* name)
1987 return Float_type::lookup_float_type(name);
1990 // Class Complex_type.
1992 Complex_type::Named_complex_types Complex_type::named_complex_types;
1994 // Create a new complex type. Non-abstract complex types always have
1998 Complex_type::create_complex_type(const char* name, int bits,
1999 int runtime_type_kind)
2001 Complex_type* complex_type = new Complex_type(false, bits,
2003 std::string sname(name);
2004 Named_object* named_object = Named_object::make_type(sname, NULL,
2007 Named_type* named_type = named_object->type_value();
2008 std::pair<Named_complex_types::iterator, bool> ins =
2009 Complex_type::named_complex_types.insert(std::make_pair(sname,
2011 go_assert(ins.second);
2015 // Look up an existing complex type.
2018 Complex_type::lookup_complex_type(const char* name)
2020 Named_complex_types::const_iterator p =
2021 Complex_type::named_complex_types.find(name);
2022 go_assert(p != Complex_type::named_complex_types.end());
2026 // Create a new abstract complex type.
2029 Complex_type::create_abstract_complex_type()
2031 static Complex_type* abstract_type;
2032 if (abstract_type == NULL)
2033 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
2034 return abstract_type;
2037 // Whether this type is identical with T.
2040 Complex_type::is_identical(const Complex_type *t) const
2042 if (this->bits_ != t->bits_)
2044 return this->is_abstract_ == t->is_abstract_;
2050 Complex_type::do_hash_for_method(Gogo*) const
2052 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2055 // Convert to the backend representation.
2058 Complex_type::do_get_backend(Gogo* gogo)
2060 return gogo->backend()->complex_type(this->bits_);
2063 // The type descriptor for a complex type. Complex types are always
2067 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2069 go_assert(name != NULL);
2070 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2073 // We should not be asked for the reflection string of a basic type.
2076 Complex_type::do_reflection(Gogo*, std::string*) const
2078 go_assert(saw_errors());
2084 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
2087 snprintf(buf, sizeof buf, "c%s%de",
2088 this->is_abstract_ ? "a" : "",
2093 // Make a complex type.
2096 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
2098 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
2101 // Make an abstract complex type.
2104 Type::make_abstract_complex_type()
2106 return Complex_type::create_abstract_complex_type();
2109 // Look up a complex type.
2112 Type::lookup_complex_type(const char* name)
2114 return Complex_type::lookup_complex_type(name);
2117 // Class String_type.
2119 // Convert String_type to the backend representation. A string is a
2120 // struct with two fields: a pointer to the characters and a length.
2123 String_type::do_get_backend(Gogo* gogo)
2125 static Btype* backend_string_type;
2126 if (backend_string_type == NULL)
2128 std::vector<Backend::Btyped_identifier> fields(2);
2130 Type* b = gogo->lookup_global("byte")->type_value();
2131 Type* pb = Type::make_pointer_type(b);
2132 fields[0].name = "__data";
2133 fields[0].btype = pb->get_backend(gogo);
2134 fields[0].location = UNKNOWN_LOCATION;
2136 Type* int_type = Type::lookup_integer_type("int");
2137 fields[1].name = "__length";
2138 fields[1].btype = int_type->get_backend(gogo);
2139 fields[1].location = UNKNOWN_LOCATION;
2141 backend_string_type = gogo->backend()->struct_type(fields);
2143 return backend_string_type;
2146 // Return a tree for the length of STRING.
2149 String_type::length_tree(Gogo*, tree string)
2151 tree string_type = TREE_TYPE(string);
2152 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2153 tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type));
2154 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)),
2156 return fold_build3(COMPONENT_REF, integer_type_node, string,
2157 length_field, NULL_TREE);
2160 // Return a tree for a pointer to the bytes of STRING.
2163 String_type::bytes_tree(Gogo*, tree string)
2165 tree string_type = TREE_TYPE(string);
2166 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2167 tree bytes_field = TYPE_FIELDS(string_type);
2168 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)),
2170 return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string,
2171 bytes_field, NULL_TREE);
2174 // The type descriptor for the string type.
2177 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2180 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
2183 Named_object* no = gogo->lookup_global("string");
2184 go_assert(no != NULL);
2185 return Type::type_descriptor(gogo, no->type_value());
2189 // We should not be asked for the reflection string of a basic type.
2192 String_type::do_reflection(Gogo*, std::string* ret) const
2194 ret->append("string");
2197 // Mangled name of a string type.
2200 String_type::do_mangled_name(Gogo*, std::string* ret) const
2202 ret->push_back('z');
2205 // Make a string type.
2208 Type::make_string_type()
2210 static String_type string_type;
2211 return &string_type;
2214 // The named type "string".
2216 static Named_type* named_string_type;
2218 // Get the named type "string".
2221 Type::lookup_string_type()
2223 return named_string_type;
2226 // Make the named type string.
2229 Type::make_named_string_type()
2231 Type* string_type = Type::make_string_type();
2232 Named_object* named_object = Named_object::make_type("string", NULL,
2235 Named_type* named_type = named_object->type_value();
2236 named_string_type = named_type;
2240 // The sink type. This is the type of the blank identifier _. Any
2241 // type may be assigned to it.
2243 class Sink_type : public Type
2252 do_get_backend(Gogo*)
2253 { go_unreachable(); }
2256 do_type_descriptor(Gogo*, Named_type*)
2257 { go_unreachable(); }
2260 do_reflection(Gogo*, std::string*) const
2261 { go_unreachable(); }
2264 do_mangled_name(Gogo*, std::string*) const
2265 { go_unreachable(); }
2268 // Make the sink type.
2271 Type::make_sink_type()
2273 static Sink_type sink_type;
2277 // Class Function_type.
2282 Function_type::do_traverse(Traverse* traverse)
2284 if (this->receiver_ != NULL
2285 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
2286 return TRAVERSE_EXIT;
2287 if (this->parameters_ != NULL
2288 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
2289 return TRAVERSE_EXIT;
2290 if (this->results_ != NULL
2291 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
2292 return TRAVERSE_EXIT;
2293 return TRAVERSE_CONTINUE;
2296 // Returns whether T is a valid redeclaration of this type. If this
2297 // returns false, and REASON is not NULL, *REASON may be set to a
2298 // brief explanation of why it returned false.
2301 Function_type::is_valid_redeclaration(const Function_type* t,
2302 std::string* reason) const
2304 if (!this->is_identical(t, false, true, reason))
2307 // A redeclaration of a function is required to use the same names
2308 // for the receiver and parameters.
2309 if (this->receiver() != NULL
2310 && this->receiver()->name() != t->receiver()->name()
2311 && this->receiver()->name() != Import::import_marker
2312 && t->receiver()->name() != Import::import_marker)
2315 *reason = "receiver name changed";
2319 const Typed_identifier_list* parms1 = this->parameters();
2320 const Typed_identifier_list* parms2 = t->parameters();
2323 Typed_identifier_list::const_iterator p1 = parms1->begin();
2324 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
2325 p2 != parms2->end();
2328 if (p1->name() != p2->name()
2329 && p1->name() != Import::import_marker
2330 && p2->name() != Import::import_marker)
2333 *reason = "parameter name changed";
2337 // This is called at parse time, so we may have unknown
2339 Type* t1 = p1->type()->forwarded();
2340 Type* t2 = p2->type()->forwarded();
2342 && t1->forward_declaration_type() != NULL
2343 && (t2->forward_declaration_type() == NULL
2344 || (t1->forward_declaration_type()->named_object()
2345 != t2->forward_declaration_type()->named_object())))
2350 const Typed_identifier_list* results1 = this->results();
2351 const Typed_identifier_list* results2 = t->results();
2352 if (results1 != NULL)
2354 Typed_identifier_list::const_iterator res1 = results1->begin();
2355 for (Typed_identifier_list::const_iterator res2 = results2->begin();
2356 res2 != results2->end();
2359 if (res1->name() != res2->name()
2360 && res1->name() != Import::import_marker
2361 && res2->name() != Import::import_marker)
2364 *reason = "result name changed";
2368 // This is called at parse time, so we may have unknown
2370 Type* t1 = res1->type()->forwarded();
2371 Type* t2 = res2->type()->forwarded();
2373 && t1->forward_declaration_type() != NULL
2374 && (t2->forward_declaration_type() == NULL
2375 || (t1->forward_declaration_type()->named_object()
2376 != t2->forward_declaration_type()->named_object())))
2384 // Check whether T is the same as this type.
2387 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
2388 bool errors_are_identical,
2389 std::string* reason) const
2391 if (!ignore_receiver)
2393 const Typed_identifier* r1 = this->receiver();
2394 const Typed_identifier* r2 = t->receiver();
2395 if ((r1 != NULL) != (r2 != NULL))
2398 *reason = _("different receiver types");
2403 if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
2406 if (reason != NULL && !reason->empty())
2407 *reason = "receiver: " + *reason;
2413 const Typed_identifier_list* parms1 = this->parameters();
2414 const Typed_identifier_list* parms2 = t->parameters();
2415 if ((parms1 != NULL) != (parms2 != NULL))
2418 *reason = _("different number of parameters");
2423 Typed_identifier_list::const_iterator p1 = parms1->begin();
2424 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
2425 p2 != parms2->end();
2428 if (p1 == parms1->end())
2431 *reason = _("different number of parameters");
2435 if (!Type::are_identical(p1->type(), p2->type(),
2436 errors_are_identical, NULL))
2439 *reason = _("different parameter types");
2443 if (p1 != parms1->end())
2446 *reason = _("different number of parameters");
2451 if (this->is_varargs() != t->is_varargs())
2454 *reason = _("different varargs");
2458 const Typed_identifier_list* results1 = this->results();
2459 const Typed_identifier_list* results2 = t->results();
2460 if ((results1 != NULL) != (results2 != NULL))
2463 *reason = _("different number of results");
2466 if (results1 != NULL)
2468 Typed_identifier_list::const_iterator res1 = results1->begin();
2469 for (Typed_identifier_list::const_iterator res2 = results2->begin();
2470 res2 != results2->end();
2473 if (res1 == results1->end())
2476 *reason = _("different number of results");
2480 if (!Type::are_identical(res1->type(), res2->type(),
2481 errors_are_identical, NULL))
2484 *reason = _("different result types");
2488 if (res1 != results1->end())
2491 *reason = _("different number of results");
2502 Function_type::do_hash_for_method(Gogo* gogo) const
2504 unsigned int ret = 0;
2505 // We ignore the receiver type for hash codes, because we need to
2506 // get the same hash code for a method in an interface and a method
2507 // declared for a type. The former will not have a receiver.
2508 if (this->parameters_ != NULL)
2511 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
2512 p != this->parameters_->end();
2514 ret += p->type()->hash_for_method(gogo) << shift;
2516 if (this->results_ != NULL)
2519 for (Typed_identifier_list::const_iterator p = this->results_->begin();
2520 p != this->results_->end();
2522 ret += p->type()->hash_for_method(gogo) << shift;
2524 if (this->is_varargs_)
2530 // Get the backend representation for a function type.
2533 Function_type::get_function_backend(Gogo* gogo)
2535 Backend::Btyped_identifier breceiver;
2536 if (this->receiver_ != NULL)
2538 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
2540 // We always pass the address of the receiver parameter, in
2541 // order to make interface calls work with unknown types.
2542 Type* rtype = this->receiver_->type();
2543 if (rtype->points_to() == NULL)
2544 rtype = Type::make_pointer_type(rtype);
2545 breceiver.btype = rtype->get_backend(gogo);
2546 breceiver.location = this->receiver_->location();
2549 std::vector<Backend::Btyped_identifier> bparameters;
2550 if (this->parameters_ != NULL)
2552 bparameters.resize(this->parameters_->size());
2554 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
2555 p != this->parameters_->end();
2558 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
2559 bparameters[i].btype = p->type()->get_backend(gogo);
2560 bparameters[i].location = p->location();
2562 go_assert(i == bparameters.size());
2565 std::vector<Backend::Btyped_identifier> bresults;
2566 if (this->results_ != NULL)
2568 bresults.resize(this->results_->size());
2570 for (Typed_identifier_list::const_iterator p = this->results_->begin();
2571 p != this->results_->end();
2574 bresults[i].name = Gogo::unpack_hidden_name(p->name());
2575 bresults[i].btype = p->type()->get_backend(gogo);
2576 bresults[i].location = p->location();
2578 go_assert(i == bresults.size());
2581 return gogo->backend()->function_type(breceiver, bparameters, bresults,
2585 // A hash table mapping function types to their backend placeholders.
2587 Function_type::Placeholders Function_type::placeholders;
2589 // Get the backend representation for a function type. If we are
2590 // still converting types, and this types has multiple results, return
2591 // a placeholder instead. We do this because for multiple results we
2592 // build a struct, and we need to make sure that all the types in the
2593 // struct are valid before we create the struct.
2596 Function_type::do_get_backend(Gogo* gogo)
2598 if (!gogo->named_types_are_converted()
2599 && this->results_ != NULL
2600 && this->results_->size() > 1)
2602 Btype* placeholder =
2603 gogo->backend()->placeholder_pointer_type("", this->location(), true);
2604 Function_type::placeholders.push_back(std::make_pair(this, placeholder));
2607 return this->get_function_backend(gogo);
2610 // Convert function types after all named types are converted.
2613 Function_type::convert_types(Gogo* gogo)
2615 for (Placeholders::const_iterator p = Function_type::placeholders.begin();
2616 p != Function_type::placeholders.end();
2619 Btype* bt = p->first->get_function_backend(gogo);
2620 if (!gogo->backend()->set_placeholder_function_type(p->second, bt))
2621 go_assert(saw_errors());
2625 // The type of a function type descriptor.
2628 Function_type::make_function_type_descriptor_type()
2633 Type* tdt = Type::make_type_descriptor_type();
2634 Type* ptdt = Type::make_type_descriptor_ptr_type();
2636 Type* bool_type = Type::lookup_bool_type();
2638 Type* slice_type = Type::make_array_type(ptdt, NULL);
2640 Struct_type* s = Type::make_builtin_struct_type(4,
2642 "dotdotdot", bool_type,
2646 ret = Type::make_builtin_named_type("FuncType", s);
2652 // The type descriptor for a function type.
2655 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2657 source_location bloc = BUILTINS_LOCATION;
2659 Type* ftdt = Function_type::make_function_type_descriptor_type();
2661 const Struct_field_list* fields = ftdt->struct_type()->fields();
2663 Expression_list* vals = new Expression_list();
2666 Struct_field_list::const_iterator p = fields->begin();
2667 go_assert(p->field_name() == "commonType");
2668 vals->push_back(this->type_descriptor_constructor(gogo,
2669 RUNTIME_TYPE_KIND_FUNC,
2673 go_assert(p->field_name() == "dotdotdot");
2674 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
2677 go_assert(p->field_name() == "in");
2678 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
2679 this->parameters()));
2682 go_assert(p->field_name() == "out");
2683 vals->push_back(this->type_descriptor_params(p->type(), NULL,
2687 go_assert(p == fields->end());
2689 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
2692 // Return a composite literal for the parameters or results of a type
2696 Function_type::type_descriptor_params(Type* params_type,
2697 const Typed_identifier* receiver,
2698 const Typed_identifier_list* params)
2700 source_location bloc = BUILTINS_LOCATION;
2702 if (receiver == NULL && params == NULL)
2703 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
2705 Expression_list* vals = new Expression_list();
2706 vals->reserve((params == NULL ? 0 : params->size())
2707 + (receiver != NULL ? 1 : 0));
2709 if (receiver != NULL)
2710 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
2714 for (Typed_identifier_list::const_iterator p = params->begin();
2717 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
2720 return Expression::make_slice_composite_literal(params_type, vals, bloc);
2723 // The reflection string.
2726 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
2728 // FIXME: Turn this off until we straighten out the type of the
2729 // struct field used in a go statement which calls a method.
2730 // go_assert(this->receiver_ == NULL);
2732 ret->append("func");
2734 if (this->receiver_ != NULL)
2736 ret->push_back('(');
2737 this->append_reflection(this->receiver_->type(), gogo, ret);
2738 ret->push_back(')');
2741 ret->push_back('(');
2742 const Typed_identifier_list* params = this->parameters();
2745 bool is_varargs = this->is_varargs_;
2746 for (Typed_identifier_list::const_iterator p = params->begin();
2750 if (p != params->begin())
2752 if (!is_varargs || p + 1 != params->end())
2753 this->append_reflection(p->type(), gogo, ret);
2757 this->append_reflection(p->type()->array_type()->element_type(),
2762 ret->push_back(')');
2764 const Typed_identifier_list* results = this->results();
2765 if (results != NULL && !results->empty())
2767 if (results->size() == 1)
2768 ret->push_back(' ');
2771 for (Typed_identifier_list::const_iterator p = results->begin();
2772 p != results->end();
2775 if (p != results->begin())
2777 this->append_reflection(p->type(), gogo, ret);
2779 if (results->size() > 1)
2780 ret->push_back(')');
2787 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
2789 ret->push_back('F');
2791 if (this->receiver_ != NULL)
2793 ret->push_back('m');
2794 this->append_mangled_name(this->receiver_->type(), gogo, ret);
2797 const Typed_identifier_list* params = this->parameters();
2800 ret->push_back('p');
2801 for (Typed_identifier_list::const_iterator p = params->begin();
2804 this->append_mangled_name(p->type(), gogo, ret);
2805 if (this->is_varargs_)
2806 ret->push_back('V');
2807 ret->push_back('e');
2810 const Typed_identifier_list* results = this->results();
2811 if (results != NULL)
2813 ret->push_back('r');
2814 for (Typed_identifier_list::const_iterator p = results->begin();
2815 p != results->end();
2817 this->append_mangled_name(p->type(), gogo, ret);
2818 ret->push_back('e');
2821 ret->push_back('e');
2824 // Export a function type.
2827 Function_type::do_export(Export* exp) const
2829 // We don't write out the receiver. The only function types which
2830 // should have a receiver are the ones associated with explicitly
2831 // defined methods. For those the receiver type is written out by
2832 // Function::export_func.
2834 exp->write_c_string("(");
2836 if (this->parameters_ != NULL)
2838 bool is_varargs = this->is_varargs_;
2839 for (Typed_identifier_list::const_iterator p =
2840 this->parameters_->begin();
2841 p != this->parameters_->end();
2847 exp->write_c_string(", ");
2848 if (!is_varargs || p + 1 != this->parameters_->end())
2849 exp->write_type(p->type());
2852 exp->write_c_string("...");
2853 exp->write_type(p->type()->array_type()->element_type());
2857 exp->write_c_string(")");
2859 const Typed_identifier_list* results = this->results_;
2860 if (results != NULL)
2862 exp->write_c_string(" ");
2863 if (results->size() == 1)
2864 exp->write_type(results->begin()->type());
2868 exp->write_c_string("(");
2869 for (Typed_identifier_list::const_iterator p = results->begin();
2870 p != results->end();
2876 exp->write_c_string(", ");
2877 exp->write_type(p->type());
2879 exp->write_c_string(")");
2884 // Import a function type.
2887 Function_type::do_import(Import* imp)
2889 imp->require_c_string("(");
2890 Typed_identifier_list* parameters;
2891 bool is_varargs = false;
2892 if (imp->peek_char() == ')')
2896 parameters = new Typed_identifier_list();
2899 if (imp->match_c_string("..."))
2905 Type* ptype = imp->read_type();
2907 ptype = Type::make_array_type(ptype, NULL);
2908 parameters->push_back(Typed_identifier(Import::import_marker,
2909 ptype, imp->location()));
2910 if (imp->peek_char() != ',')
2912 go_assert(!is_varargs);
2913 imp->require_c_string(", ");
2916 imp->require_c_string(")");
2918 Typed_identifier_list* results;
2919 if (imp->peek_char() != ' ')
2924 results = new Typed_identifier_list;
2925 if (imp->peek_char() != '(')
2927 Type* rtype = imp->read_type();
2928 results->push_back(Typed_identifier(Import::import_marker, rtype,
2936 Type* rtype = imp->read_type();
2937 results->push_back(Typed_identifier(Import::import_marker,
2938 rtype, imp->location()));
2939 if (imp->peek_char() != ',')
2941 imp->require_c_string(", ");
2943 imp->require_c_string(")");
2947 Function_type* ret = Type::make_function_type(NULL, parameters, results,
2950 ret->set_is_varargs();
2954 // Make a copy of a function type without a receiver.
2957 Function_type::copy_without_receiver() const
2959 go_assert(this->is_method());
2960 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
2963 if (this->is_varargs())
2964 ret->set_is_varargs();
2965 if (this->is_builtin())
2966 ret->set_is_builtin();
2970 // Make a copy of a function type with a receiver.
2973 Function_type::copy_with_receiver(Type* receiver_type) const
2975 go_assert(!this->is_method());
2976 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
2978 return Type::make_function_type(receiver, this->parameters_,
2979 this->results_, this->location_);
2982 // Make a function type.
2985 Type::make_function_type(Typed_identifier* receiver,
2986 Typed_identifier_list* parameters,
2987 Typed_identifier_list* results,
2988 source_location location)
2990 return new Function_type(receiver, parameters, results, location);
2993 // Class Pointer_type.
2998 Pointer_type::do_traverse(Traverse* traverse)
3000 return Type::traverse(this->to_type_, traverse);
3006 Pointer_type::do_hash_for_method(Gogo* gogo) const
3008 return this->to_type_->hash_for_method(gogo) << 4;
3011 // The tree for a pointer type.
3014 Pointer_type::do_get_backend(Gogo* gogo)
3016 Btype* to_btype = this->to_type_->get_backend(gogo);
3017 return gogo->backend()->pointer_type(to_btype);
3020 // The type of a pointer type descriptor.
3023 Pointer_type::make_pointer_type_descriptor_type()
3028 Type* tdt = Type::make_type_descriptor_type();
3029 Type* ptdt = Type::make_type_descriptor_ptr_type();
3031 Struct_type* s = Type::make_builtin_struct_type(2,
3035 ret = Type::make_builtin_named_type("PtrType", s);
3041 // The type descriptor for a pointer type.
3044 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3046 if (this->is_unsafe_pointer_type())
3048 go_assert(name != NULL);
3049 return this->plain_type_descriptor(gogo,
3050 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
3055 source_location bloc = BUILTINS_LOCATION;
3057 const Methods* methods;
3058 Type* deref = this->points_to();
3059 if (deref->named_type() != NULL)
3060 methods = deref->named_type()->methods();
3061 else if (deref->struct_type() != NULL)
3062 methods = deref->struct_type()->methods();
3066 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
3068 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
3070 Expression_list* vals = new Expression_list();
3073 Struct_field_list::const_iterator p = fields->begin();
3074 go_assert(p->field_name() == "commonType");
3075 vals->push_back(this->type_descriptor_constructor(gogo,
3076 RUNTIME_TYPE_KIND_PTR,
3077 name, methods, false));
3080 go_assert(p->field_name() == "elem");
3081 vals->push_back(Expression::make_type_descriptor(deref, bloc));
3083 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
3087 // Reflection string.
3090 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
3092 ret->push_back('*');
3093 this->append_reflection(this->to_type_, gogo, ret);
3099 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3101 ret->push_back('p');
3102 this->append_mangled_name(this->to_type_, gogo, ret);
3108 Pointer_type::do_export(Export* exp) const
3110 exp->write_c_string("*");
3111 if (this->is_unsafe_pointer_type())
3112 exp->write_c_string("any");
3114 exp->write_type(this->to_type_);
3120 Pointer_type::do_import(Import* imp)
3122 imp->require_c_string("*");
3123 if (imp->match_c_string("any"))
3126 return Type::make_pointer_type(Type::make_void_type());
3128 Type* to = imp->read_type();
3129 return Type::make_pointer_type(to);
3132 // Make a pointer type.
3135 Type::make_pointer_type(Type* to_type)
3137 typedef Unordered_map(Type*, Pointer_type*) Hashtable;
3138 static Hashtable pointer_types;
3139 Hashtable::const_iterator p = pointer_types.find(to_type);
3140 if (p != pointer_types.end())
3142 Pointer_type* ret = new Pointer_type(to_type);
3143 pointer_types[to_type] = ret;
3147 // The nil type. We use a special type for nil because it is not the
3148 // same as any other type. In C term nil has type void*, but there is
3149 // no such type in Go.
3151 class Nil_type : public Type
3160 do_get_backend(Gogo* gogo)
3161 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
3164 do_type_descriptor(Gogo*, Named_type*)
3165 { go_unreachable(); }
3168 do_reflection(Gogo*, std::string*) const
3169 { go_unreachable(); }
3172 do_mangled_name(Gogo*, std::string* ret) const
3173 { ret->push_back('n'); }
3176 // Make the nil type.
3179 Type::make_nil_type()
3181 static Nil_type singleton_nil_type;
3182 return &singleton_nil_type;
3185 // The type of a function call which returns multiple values. This is
3186 // really a struct, but we don't want to confuse a function call which
3187 // returns a struct with a function call which returns multiple
3190 class Call_multiple_result_type : public Type
3193 Call_multiple_result_type(Call_expression* call)
3194 : Type(TYPE_CALL_MULTIPLE_RESULT),
3200 do_has_pointer() const
3202 go_assert(saw_errors());
3207 do_get_backend(Gogo* gogo)
3209 go_assert(saw_errors());
3210 return gogo->backend()->error_type();
3214 do_type_descriptor(Gogo*, Named_type*)
3216 go_assert(saw_errors());
3217 return Expression::make_error(UNKNOWN_LOCATION);
3221 do_reflection(Gogo*, std::string*) const
3222 { go_assert(saw_errors()); }
3225 do_mangled_name(Gogo*, std::string*) const
3226 { go_assert(saw_errors()); }
3229 // The expression being called.
3230 Call_expression* call_;
3233 // Make a call result type.
3236 Type::make_call_multiple_result_type(Call_expression* call)
3238 return new Call_multiple_result_type(call);
3241 // Class Struct_field.
3243 // Get the name of a field.
3246 Struct_field::field_name() const
3248 const std::string& name(this->typed_identifier_.name());
3253 // This is called during parsing, before anything is lowered, so
3254 // we have to be pretty careful to avoid dereferencing an
3255 // unknown type name.
3256 Type* t = this->typed_identifier_.type();
3258 if (t->classification() == Type::TYPE_POINTER)
3261 Pointer_type* ptype = static_cast<Pointer_type*>(t);
3262 dt = ptype->points_to();
3264 if (dt->forward_declaration_type() != NULL)
3265 return dt->forward_declaration_type()->name();
3266 else if (dt->named_type() != NULL)
3267 return dt->named_type()->name();
3268 else if (t->is_error_type() || dt->is_error_type())
3270 static const std::string error_string = "*error*";
3271 return error_string;
3275 // Avoid crashing in the erroneous case where T is named but
3278 if (t->forward_declaration_type() != NULL)
3279 return t->forward_declaration_type()->name();
3280 else if (t->named_type() != NULL)
3281 return t->named_type()->name();
3288 // Class Struct_type.
3293 Struct_type::do_traverse(Traverse* traverse)
3295 Struct_field_list* fields = this->fields_;
3298 for (Struct_field_list::iterator p = fields->begin();
3302 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
3303 return TRAVERSE_EXIT;
3306 return TRAVERSE_CONTINUE;
3309 // Verify that the struct type is complete and valid.
3312 Struct_type::do_verify()
3314 Struct_field_list* fields = this->fields_;
3318 for (Struct_field_list::iterator p = fields->begin();
3322 Type* t = p->type();
3323 if (t->is_undefined())
3325 error_at(p->location(), "struct field type is incomplete");
3326 p->set_type(Type::make_error_type());
3329 else if (p->is_anonymous())
3331 if (t->named_type() != NULL && t->points_to() != NULL)
3333 error_at(p->location(), "embedded type may not be a pointer");
3334 p->set_type(Type::make_error_type());
3337 if (t->points_to() != NULL
3338 && t->points_to()->interface_type() != NULL)
3340 error_at(p->location(),
3341 "embedded type may not be pointer to interface");
3342 p->set_type(Type::make_error_type());
3350 // Whether this contains a pointer.
3353 Struct_type::do_has_pointer() const
3355 const Struct_field_list* fields = this->fields();
3358 for (Struct_field_list::const_iterator p = fields->begin();
3362 if (p->type()->has_pointer())
3368 // Whether this type is identical to T.
3371 Struct_type::is_identical(const Struct_type* t,
3372 bool errors_are_identical) const
3374 const Struct_field_list* fields1 = this->fields();
3375 const Struct_field_list* fields2 = t->fields();
3376 if (fields1 == NULL || fields2 == NULL)
3377 return fields1 == fields2;
3378 Struct_field_list::const_iterator pf2 = fields2->begin();
3379 for (Struct_field_list::const_iterator pf1 = fields1->begin();
3380 pf1 != fields1->end();
3383 if (pf2 == fields2->end())
3385 if (pf1->field_name() != pf2->field_name())
3387 if (pf1->is_anonymous() != pf2->is_anonymous()
3388 || !Type::are_identical(pf1->type(), pf2->type(),
3389 errors_are_identical, NULL))
3391 if (!pf1->has_tag())
3398 if (!pf2->has_tag())
3400 if (pf1->tag() != pf2->tag())
3404 if (pf2 != fields2->end())
3409 // Whether this struct type has any hidden fields.
3412 Struct_type::struct_has_hidden_fields(const Named_type* within,
3413 std::string* reason) const
3415 const Struct_field_list* fields = this->fields();
3418 const Package* within_package = (within == NULL
3420 : within->named_object()->package());
3421 for (Struct_field_list::const_iterator pf = fields->begin();
3422 pf != fields->end();
3425 if (within_package != NULL
3426 && !pf->is_anonymous()
3427 && Gogo::is_hidden_name(pf->field_name()))
3431 std::string within_name = within->named_object()->message_name();
3432 std::string name = Gogo::message_name(pf->field_name());
3433 size_t bufsize = 200 + within_name.length() + name.length();
3434 char* buf = new char[bufsize];
3435 snprintf(buf, bufsize,
3436 _("implicit assignment of %s%s%s hidden field %s%s%s"),
3437 open_quote, within_name.c_str(), close_quote,
3438 open_quote, name.c_str(), close_quote);
3439 reason->assign(buf);
3445 if (pf->type()->has_hidden_fields(within, reason))
3455 Struct_type::do_hash_for_method(Gogo* gogo) const
3457 unsigned int ret = 0;
3458 if (this->fields() != NULL)
3460 for (Struct_field_list::const_iterator pf = this->fields()->begin();
3461 pf != this->fields()->end();
3463 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
3468 // Find the local field NAME.
3471 Struct_type::find_local_field(const std::string& name,
3472 unsigned int *pindex) const
3474 const Struct_field_list* fields = this->fields_;
3478 for (Struct_field_list::const_iterator pf = fields->begin();
3479 pf != fields->end();
3482 if (pf->field_name() == name)
3492 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
3494 Field_reference_expression*
3495 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
3496 source_location location) const
3499 return this->field_reference_depth(struct_expr, name, location, NULL,
3503 // Return an expression for a field, along with the depth at which it
3506 Field_reference_expression*
3507 Struct_type::field_reference_depth(Expression* struct_expr,
3508 const std::string& name,
3509 source_location location,
3510 Saw_named_type* saw,
3511 unsigned int* depth) const
3513 const Struct_field_list* fields = this->fields_;
3517 // Look for a field with this name.
3519 for (Struct_field_list::const_iterator pf = fields->begin();
3520 pf != fields->end();
3523 if (pf->field_name() == name)
3526 return Expression::make_field_reference(struct_expr, i, location);
3530 // Look for an anonymous field which contains a field with this
3532 unsigned int found_depth = 0;
3533 Field_reference_expression* ret = NULL;
3535 for (Struct_field_list::const_iterator pf = fields->begin();
3536 pf != fields->end();
3539 if (!pf->is_anonymous())
3542 Struct_type* st = pf->type()->deref()->struct_type();
3546 Saw_named_type* hold_saw = saw;
3547 Saw_named_type saw_here;
3548 Named_type* nt = pf->type()->named_type();
3550 nt = pf->type()->deref()->named_type();
3554 for (q = saw; q != NULL; q = q->next)
3558 // If this is an error, it will be reported
3565 saw_here.next = saw;
3570 // Look for a reference using a NULL struct expression. If we
3571 // find one, fill in the struct expression with a reference to
3573 unsigned int subdepth;
3574 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
3584 if (ret == NULL || subdepth < found_depth)
3589 found_depth = subdepth;
3590 Expression* here = Expression::make_field_reference(struct_expr, i,
3592 if (pf->type()->points_to() != NULL)
3593 here = Expression::make_unary(OPERATOR_MULT, here, location);
3594 while (sub->expr() != NULL)
3596 sub = sub->expr()->deref()->field_reference_expression();
3597 go_assert(sub != NULL);
3599 sub->set_struct_expression(here);
3601 else if (subdepth > found_depth)
3605 // We do not handle ambiguity here--it should be handled by
3606 // Type::bind_field_or_method.
3614 *depth = found_depth + 1;
3619 // Return the total number of fields, including embedded fields.
3622 Struct_type::total_field_count() const
3624 if (this->fields_ == NULL)
3626 unsigned int ret = 0;
3627 for (Struct_field_list::const_iterator pf = this->fields_->begin();
3628 pf != this->fields_->end();
3631 if (!pf->is_anonymous() || pf->type()->deref()->struct_type() == NULL)
3634 ret += pf->type()->struct_type()->total_field_count();
3639 // Return whether NAME is an unexported field, for better error reporting.
3642 Struct_type::is_unexported_local_field(Gogo* gogo,
3643 const std::string& name) const
3645 const Struct_field_list* fields = this->fields_;
3648 for (Struct_field_list::const_iterator pf = fields->begin();
3649 pf != fields->end();
3652 const std::string& field_name(pf->field_name());
3653 if (Gogo::is_hidden_name(field_name)
3654 && name == Gogo::unpack_hidden_name(field_name)
3655 && gogo->pack_hidden_name(name, false) != field_name)
3662 // Finalize the methods of an unnamed struct.
3665 Struct_type::finalize_methods(Gogo* gogo)
3667 if (this->all_methods_ != NULL)
3669 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
3672 // Return the method NAME, or NULL if there isn't one or if it is
3673 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
3677 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
3679 return Type::method_function(this->all_methods_, name, is_ambiguous);
3682 // Convert struct fields to the backend representation. This is not
3683 // declared in types.h so that types.h doesn't have to #include
3687 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
3688 std::vector<Backend::Btyped_identifier>* bfields)
3690 bfields->resize(fields->size());
3692 for (Struct_field_list::const_iterator p = fields->begin();
3696 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
3697 (*bfields)[i].btype = p->type()->get_backend(gogo);
3698 (*bfields)[i].location = p->location();
3700 go_assert(i == fields->size());
3703 // Get the tree for a struct type.
3706 Struct_type::do_get_backend(Gogo* gogo)
3708 std::vector<Backend::Btyped_identifier> bfields;
3709 get_backend_struct_fields(gogo, this->fields_, &bfields);
3710 return gogo->backend()->struct_type(bfields);
3713 // The type of a struct type descriptor.
3716 Struct_type::make_struct_type_descriptor_type()
3721 Type* tdt = Type::make_type_descriptor_type();
3722 Type* ptdt = Type::make_type_descriptor_ptr_type();
3724 Type* uintptr_type = Type::lookup_integer_type("uintptr");
3725 Type* string_type = Type::lookup_string_type();
3726 Type* pointer_string_type = Type::make_pointer_type(string_type);
3729 Type::make_builtin_struct_type(5,
3730 "name", pointer_string_type,
3731 "pkgPath", pointer_string_type,
3733 "tag", pointer_string_type,
3734 "offset", uintptr_type);
3735 Type* nsf = Type::make_builtin_named_type("structField", sf);
3737 Type* slice_type = Type::make_array_type(nsf, NULL);
3739 Struct_type* s = Type::make_builtin_struct_type(2,
3741 "fields", slice_type);
3743 ret = Type::make_builtin_named_type("StructType", s);
3749 // Build a type descriptor for a struct type.
3752 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3754 source_location bloc = BUILTINS_LOCATION;
3756 Type* stdt = Struct_type::make_struct_type_descriptor_type();
3758 const Struct_field_list* fields = stdt->struct_type()->fields();
3760 Expression_list* vals = new Expression_list();
3763 const Methods* methods = this->methods();
3764 // A named struct should not have methods--the methods should attach
3765 // to the named type.
3766 go_assert(methods == NULL || name == NULL);
3768 Struct_field_list::const_iterator ps = fields->begin();
3769 go_assert(ps->field_name() == "commonType");
3770 vals->push_back(this->type_descriptor_constructor(gogo,
3771 RUNTIME_TYPE_KIND_STRUCT,
3772 name, methods, true));
3775 go_assert(ps->field_name() == "fields");
3777 Expression_list* elements = new Expression_list();
3778 elements->reserve(this->fields_->size());
3779 Type* element_type = ps->type()->array_type()->element_type();
3780 for (Struct_field_list::const_iterator pf = this->fields_->begin();
3781 pf != this->fields_->end();
3784 const Struct_field_list* f = element_type->struct_type()->fields();
3786 Expression_list* fvals = new Expression_list();
3789 Struct_field_list::const_iterator q = f->begin();
3790 go_assert(q->field_name() == "name");
3791 if (pf->is_anonymous())
3792 fvals->push_back(Expression::make_nil(bloc));
3795 std::string n = Gogo::unpack_hidden_name(pf->field_name());
3796 Expression* s = Expression::make_string(n, bloc);
3797 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3801 go_assert(q->field_name() == "pkgPath");
3802 if (!Gogo::is_hidden_name(pf->field_name()))
3803 fvals->push_back(Expression::make_nil(bloc));
3806 std::string n = Gogo::hidden_name_prefix(pf->field_name());
3807 Expression* s = Expression::make_string(n, bloc);
3808 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3812 go_assert(q->field_name() == "typ");
3813 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
3816 go_assert(q->field_name() == "tag");
3818 fvals->push_back(Expression::make_nil(bloc));
3821 Expression* s = Expression::make_string(pf->tag(), bloc);
3822 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3826 go_assert(q->field_name() == "offset");
3827 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
3829 Expression* v = Expression::make_struct_composite_literal(element_type,
3831 elements->push_back(v);
3834 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
3837 return Expression::make_struct_composite_literal(stdt, vals, bloc);
3840 // Reflection string.
3843 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
3845 ret->append("struct { ");
3847 for (Struct_field_list::const_iterator p = this->fields_->begin();
3848 p != this->fields_->end();
3851 if (p != this->fields_->begin())
3853 if (p->is_anonymous())
3854 ret->push_back('?');
3856 ret->append(Gogo::unpack_hidden_name(p->field_name()));
3857 ret->push_back(' ');
3858 this->append_reflection(p->type(), gogo, ret);
3862 const std::string& tag(p->tag());
3864 for (std::string::const_iterator p = tag.begin();
3869 ret->append("\\x00");
3870 else if (*p == '\n')
3872 else if (*p == '\t')
3875 ret->append("\\\"");
3876 else if (*p == '\\')
3877 ret->append("\\\\");
3881 ret->push_back('"');
3891 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3893 ret->push_back('S');
3895 const Struct_field_list* fields = this->fields_;
3898 for (Struct_field_list::const_iterator p = fields->begin();
3902 if (p->is_anonymous())
3906 std::string n = Gogo::unpack_hidden_name(p->field_name());
3908 snprintf(buf, sizeof buf, "%u_",
3909 static_cast<unsigned int>(n.length()));
3913 this->append_mangled_name(p->type(), gogo, ret);
3916 const std::string& tag(p->tag());
3918 for (std::string::const_iterator p = tag.begin();
3922 if (ISALNUM(*p) || *p == '_')
3927 snprintf(buf, sizeof buf, ".%x.",
3928 static_cast<unsigned int>(*p));
3933 snprintf(buf, sizeof buf, "T%u_",
3934 static_cast<unsigned int>(out.length()));
3941 ret->push_back('e');
3947 Struct_type::do_export(Export* exp) const
3949 exp->write_c_string("struct { ");
3950 const Struct_field_list* fields = this->fields_;
3951 go_assert(fields != NULL);
3952 for (Struct_field_list::const_iterator p = fields->begin();
3956 if (p->is_anonymous())
3957 exp->write_string("? ");
3960 exp->write_string(p->field_name());
3961 exp->write_c_string(" ");
3963 exp->write_type(p->type());
3967 exp->write_c_string(" ");
3968 Expression* expr = Expression::make_string(p->tag(),
3970 expr->export_expression(exp);
3974 exp->write_c_string("; ");
3976 exp->write_c_string("}");
3982 Struct_type::do_import(Import* imp)
3984 imp->require_c_string("struct { ");
3985 Struct_field_list* fields = new Struct_field_list;
3986 if (imp->peek_char() != '}')
3991 if (imp->match_c_string("? "))
3995 name = imp->read_identifier();
3996 imp->require_c_string(" ");
3998 Type* ftype = imp->read_type();
4000 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
4002 if (imp->peek_char() == ' ')
4005 Expression* expr = Expression::import_expression(imp);
4006 String_expression* sexpr = expr->string_expression();
4007 go_assert(sexpr != NULL);
4008 sf.set_tag(sexpr->val());
4012 imp->require_c_string("; ");
4013 fields->push_back(sf);
4014 if (imp->peek_char() == '}')
4018 imp->require_c_string("}");
4020 return Type::make_struct_type(fields, imp->location());
4023 // Make a struct type.
4026 Type::make_struct_type(Struct_field_list* fields,
4027 source_location location)
4029 return new Struct_type(fields, location);
4032 // Class Array_type.
4034 // Whether two array types are identical.
4037 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
4039 if (!Type::are_identical(this->element_type(), t->element_type(),
4040 errors_are_identical, NULL))
4043 Expression* l1 = this->length();
4044 Expression* l2 = t->length();
4046 // Slices of the same element type are identical.
4047 if (l1 == NULL && l2 == NULL)
4050 // Arrays of the same element type are identical if they have the
4052 if (l1 != NULL && l2 != NULL)
4057 // Try to determine the lengths. If we can't, assume the arrays
4058 // are not identical.
4066 if (l1->integer_constant_value(true, v1, &type1)
4067 && l2->integer_constant_value(true, v2, &type2))
4068 ret = mpz_cmp(v1, v2) == 0;
4074 // Otherwise the arrays are not identical.
4081 Array_type::do_traverse(Traverse* traverse)
4083 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
4084 return TRAVERSE_EXIT;
4085 if (this->length_ != NULL
4086 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
4087 return TRAVERSE_EXIT;
4088 return TRAVERSE_CONTINUE;
4091 // Check that the length is valid.
4094 Array_type::verify_length()
4096 if (this->length_ == NULL)
4099 Type_context context(Type::lookup_integer_type("int"), false);
4100 this->length_->determine_type(&context);
4102 if (!this->length_->is_constant())
4104 error_at(this->length_->location(), "array bound is not constant");
4111 if (!this->length_->integer_constant_value(true, val, &vt))
4115 if (!this->length_->float_constant_value(fval, &vt))
4117 if (this->length_->type()->integer_type() != NULL
4118 || this->length_->type()->float_type() != NULL)
4119 error_at(this->length_->location(),
4120 "array bound is not constant");
4122 error_at(this->length_->location(),
4123 "array bound is not numeric");
4128 if (!mpfr_integer_p(fval))
4130 error_at(this->length_->location(),
4131 "array bound truncated to integer");
4137 mpfr_get_z(val, fval, GMP_RNDN);
4141 if (mpz_sgn(val) < 0)
4143 error_at(this->length_->location(), "negative array bound");
4148 Type* int_type = Type::lookup_integer_type("int");
4149 int tbits = int_type->integer_type()->bits();
4150 int vbits = mpz_sizeinbase(val, 2);
4151 if (vbits + 1 > tbits)
4153 error_at(this->length_->location(), "array bound overflows");
4166 Array_type::do_verify()
4168 if (!this->verify_length())
4170 this->length_ = Expression::make_error(this->length_->location());
4176 // Array type hash code.
4179 Array_type::do_hash_for_method(Gogo* gogo) const
4181 // There is no very convenient way to get a hash code for the
4183 return this->element_type_->hash_for_method(gogo) + 1;
4186 // See if the expression passed to make is suitable. The first
4187 // argument is required, and gives the length. An optional second
4188 // argument is permitted for the capacity.
4191 Array_type::do_check_make_expression(Expression_list* args,
4192 source_location location)
4194 go_assert(this->length_ == NULL);
4195 if (args == NULL || args->empty())
4197 error_at(location, "length required when allocating a slice");
4200 else if (args->size() > 2)
4202 error_at(location, "too many expressions passed to make");
4207 if (!Type::check_int_value(args->front(),
4208 _("bad length when making slice"), location))
4211 if (args->size() > 1)
4213 if (!Type::check_int_value(args->back(),
4214 _("bad capacity when making slice"),
4223 // Get a tree for the length of a fixed array. The length may be
4224 // computed using a function call, so we must only evaluate it once.
4227 Array_type::get_length_tree(Gogo* gogo)
4229 go_assert(this->length_ != NULL);
4230 if (this->length_tree_ == NULL_TREE)
4235 if (this->length_->integer_constant_value(true, val, &t))
4238 t = Type::lookup_integer_type("int");
4239 else if (t->is_abstract())
4240 t = t->make_non_abstract_type();
4241 tree tt = type_to_tree(t->get_backend(gogo));
4242 this->length_tree_ = Expression::integer_constant_tree(val, tt);
4249 // Make up a translation context for the array length
4250 // expression. FIXME: This won't work in general.
4251 Translate_context context(gogo, NULL, NULL, NULL);
4252 tree len = this->length_->get_tree(&context);
4253 if (len != error_mark_node)
4255 len = convert_to_integer(integer_type_node, len);
4256 len = save_expr(len);
4258 this->length_tree_ = len;
4261 return this->length_tree_;
4264 // Get the backend representation of the fields of a slice. This is
4265 // not declared in types.h so that types.h doesn't have to #include
4268 // We use int for the count and capacity fields. This matches 6g.
4269 // The language more or less assumes that we can't allocate space of a
4270 // size which does not fit in int.
4273 get_backend_slice_fields(Gogo* gogo, Array_type* type,
4274 std::vector<Backend::Btyped_identifier>* bfields)
4278 Type* pet = Type::make_pointer_type(type->element_type());
4279 Btype* pbet = pet->get_backend(gogo);
4281 Backend::Btyped_identifier* p = &(*bfields)[0];
4282 p->name = "__values";
4284 p->location = UNKNOWN_LOCATION;
4286 Type* int_type = Type::lookup_integer_type("int");
4289 p->name = "__count";
4290 p->btype = int_type->get_backend(gogo);
4291 p->location = UNKNOWN_LOCATION;
4294 p->name = "__capacity";
4295 p->btype = int_type->get_backend(gogo);
4296 p->location = UNKNOWN_LOCATION;
4299 // Get a tree for the type of this array. A fixed array is simply
4300 // represented as ARRAY_TYPE with the appropriate index--i.e., it is
4301 // just like an array in C. An open array is a struct with three
4302 // fields: a data pointer, the length, and the capacity.
4305 Array_type::do_get_backend(Gogo* gogo)
4307 if (this->length_ == NULL)
4309 std::vector<Backend::Btyped_identifier> bfields;
4310 get_backend_slice_fields(gogo, this, &bfields);
4311 return gogo->backend()->struct_type(bfields);
4315 Btype* element = this->get_backend_element(gogo);
4316 Bexpression* len = this->get_backend_length(gogo);
4317 return gogo->backend()->array_type(element, len);
4321 // Return the backend representation of the element type.
4323 Array_type::get_backend_element(Gogo* gogo)
4325 return this->element_type_->get_backend(gogo);
4328 // Return the backend representation of the length.
4331 Array_type::get_backend_length(Gogo* gogo)
4333 return tree_to_expr(this->get_length_tree(gogo));
4336 // Handle the builtin make function for a slice.
4339 Array_type::do_make_expression_tree(Translate_context* context,
4340 Expression_list* args,
4341 source_location location)
4343 go_assert(this->length_ == NULL);
4345 Gogo* gogo = context->gogo();
4346 tree type_tree = type_to_tree(this->get_backend(gogo));
4347 if (type_tree == error_mark_node)
4348 return error_mark_node;
4350 tree values_field = TYPE_FIELDS(type_tree);
4351 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(values_field)),
4354 tree count_field = DECL_CHAIN(values_field);
4355 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(count_field)),
4358 tree element_type_tree = type_to_tree(this->element_type_->get_backend(gogo));
4359 if (element_type_tree == error_mark_node)
4360 return error_mark_node;
4361 tree element_size_tree = TYPE_SIZE_UNIT(element_type_tree);
4363 // The first argument is the number of elements, the optional second
4364 // argument is the capacity.
4365 go_assert(args != NULL && args->size() >= 1 && args->size() <= 2);
4367 tree length_tree = args->front()->get_tree(context);
4368 if (length_tree == error_mark_node)
4369 return error_mark_node;
4370 if (!DECL_P(length_tree))
4371 length_tree = save_expr(length_tree);
4372 if (!INTEGRAL_TYPE_P(TREE_TYPE(length_tree)))
4373 length_tree = convert_to_integer(TREE_TYPE(count_field), length_tree);
4375 tree bad_index = Expression::check_bounds(length_tree,
4376 TREE_TYPE(count_field),
4377 NULL_TREE, location);
4379 length_tree = fold_convert_loc(location, TREE_TYPE(count_field), length_tree);
4381 if (args->size() == 1)
4382 capacity_tree = length_tree;
4385 capacity_tree = args->back()->get_tree(context);
4386 if (capacity_tree == error_mark_node)
4387 return error_mark_node;
4388 if (!DECL_P(capacity_tree))
4389 capacity_tree = save_expr(capacity_tree);
4390 if (!INTEGRAL_TYPE_P(TREE_TYPE(capacity_tree)))
4391 capacity_tree = convert_to_integer(TREE_TYPE(count_field),
4394 bad_index = Expression::check_bounds(capacity_tree,
4395 TREE_TYPE(count_field),
4396 bad_index, location);
4398 tree chktype = (((TYPE_SIZE(TREE_TYPE(capacity_tree))
4399 > TYPE_SIZE(TREE_TYPE(length_tree)))
4400 || ((TYPE_SIZE(TREE_TYPE(capacity_tree))
4401 == TYPE_SIZE(TREE_TYPE(length_tree)))
4402 && TYPE_UNSIGNED(TREE_TYPE(capacity_tree))))
4403 ? TREE_TYPE(capacity_tree)
4404 : TREE_TYPE(length_tree));
4405 tree chk = fold_build2_loc(location, LT_EXPR, boolean_type_node,
4406 fold_convert_loc(location, chktype,
4408 fold_convert_loc(location, chktype,
4410 if (bad_index == NULL_TREE)
4413 bad_index = fold_build2_loc(location, TRUTH_OR_EXPR, boolean_type_node,
4416 capacity_tree = fold_convert_loc(location, TREE_TYPE(count_field),
4420 tree size_tree = fold_build2_loc(location, MULT_EXPR, sizetype,
4422 fold_convert_loc(location, sizetype,
4425 tree chk = fold_build2_loc(location, TRUTH_AND_EXPR, boolean_type_node,
4426 fold_build2_loc(location, GT_EXPR,
4428 fold_convert_loc(location,
4432 fold_build2_loc(location, LT_EXPR,
4434 size_tree, element_size_tree));
4435 if (bad_index == NULL_TREE)
4438 bad_index = fold_build2_loc(location, TRUTH_OR_EXPR, boolean_type_node,
4441 tree space = context->gogo()->allocate_memory(this->element_type_,
4442 size_tree, location);
4444 space = fold_convert(TREE_TYPE(values_field), space);
4446 if (bad_index != NULL_TREE && bad_index != boolean_false_node)
4448 tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_SLICE_OUT_OF_BOUNDS,
4450 space = build2(COMPOUND_EXPR, TREE_TYPE(space),
4451 build3(COND_EXPR, void_type_node,
4452 bad_index, crash, NULL_TREE),
4456 return gogo->slice_constructor(type_tree, space, length_tree, capacity_tree);
4459 // Return a tree for a pointer to the values in ARRAY.
4462 Array_type::value_pointer_tree(Gogo*, tree array) const
4465 if (this->length() != NULL)
4468 ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))),
4469 build_fold_addr_expr(array));
4474 tree field = TYPE_FIELDS(TREE_TYPE(array));
4475 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
4477 ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field,
4480 if (TREE_CONSTANT(array))
4481 TREE_CONSTANT(ret) = 1;
4485 // Return a tree for the length of the array ARRAY which has this
4489 Array_type::length_tree(Gogo* gogo, tree array)
4491 if (this->length_ != NULL)
4493 if (TREE_CODE(array) == SAVE_EXPR)
4494 return fold_convert(integer_type_node, this->get_length_tree(gogo));
4496 return omit_one_operand(integer_type_node,
4497 this->get_length_tree(gogo), array);
4500 // This is an open array. We need to read the length field.
4502 tree type = TREE_TYPE(array);
4503 go_assert(TREE_CODE(type) == RECORD_TYPE);
4505 tree field = DECL_CHAIN(TYPE_FIELDS(type));
4506 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
4508 tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
4509 if (TREE_CONSTANT(array))
4510 TREE_CONSTANT(ret) = 1;
4514 // Return a tree for the capacity of the array ARRAY which has this
4518 Array_type::capacity_tree(Gogo* gogo, tree array)
4520 if (this->length_ != NULL)
4521 return omit_one_operand(sizetype, this->get_length_tree(gogo), array);
4523 // This is an open array. We need to read the capacity field.
4525 tree type = TREE_TYPE(array);
4526 go_assert(TREE_CODE(type) == RECORD_TYPE);
4528 tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type)));
4529 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
4531 return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
4537 Array_type::do_export(Export* exp) const
4539 exp->write_c_string("[");
4540 if (this->length_ != NULL)
4541 this->length_->export_expression(exp);
4542 exp->write_c_string("] ");
4543 exp->write_type(this->element_type_);
4549 Array_type::do_import(Import* imp)
4551 imp->require_c_string("[");
4553 if (imp->peek_char() == ']')
4556 length = Expression::import_expression(imp);
4557 imp->require_c_string("] ");
4558 Type* element_type = imp->read_type();
4559 return Type::make_array_type(element_type, length);
4562 // The type of an array type descriptor.
4565 Array_type::make_array_type_descriptor_type()
4570 Type* tdt = Type::make_type_descriptor_type();
4571 Type* ptdt = Type::make_type_descriptor_ptr_type();
4573 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4576 Type::make_builtin_struct_type(4,
4580 "len", uintptr_type);
4582 ret = Type::make_builtin_named_type("ArrayType", sf);
4588 // The type of an slice type descriptor.
4591 Array_type::make_slice_type_descriptor_type()
4596 Type* tdt = Type::make_type_descriptor_type();
4597 Type* ptdt = Type::make_type_descriptor_ptr_type();
4600 Type::make_builtin_struct_type(2,
4604 ret = Type::make_builtin_named_type("SliceType", sf);
4610 // Build a type descriptor for an array/slice type.
4613 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4615 if (this->length_ != NULL)
4616 return this->array_type_descriptor(gogo, name);
4618 return this->slice_type_descriptor(gogo, name);
4621 // Build a type descriptor for an array type.
4624 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
4626 source_location bloc = BUILTINS_LOCATION;
4628 Type* atdt = Array_type::make_array_type_descriptor_type();
4630 const Struct_field_list* fields = atdt->struct_type()->fields();
4632 Expression_list* vals = new Expression_list();
4635 Struct_field_list::const_iterator p = fields->begin();
4636 go_assert(p->field_name() == "commonType");
4637 vals->push_back(this->type_descriptor_constructor(gogo,
4638 RUNTIME_TYPE_KIND_ARRAY,
4642 go_assert(p->field_name() == "elem");
4643 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
4646 go_assert(p->field_name() == "slice");
4647 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
4648 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
4651 go_assert(p->field_name() == "len");
4652 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
4655 go_assert(p == fields->end());
4657 return Expression::make_struct_composite_literal(atdt, vals, bloc);
4660 // Build a type descriptor for a slice type.
4663 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
4665 source_location bloc = BUILTINS_LOCATION;
4667 Type* stdt = Array_type::make_slice_type_descriptor_type();
4669 const Struct_field_list* fields = stdt->struct_type()->fields();
4671 Expression_list* vals = new Expression_list();
4674 Struct_field_list::const_iterator p = fields->begin();
4675 go_assert(p->field_name() == "commonType");
4676 vals->push_back(this->type_descriptor_constructor(gogo,
4677 RUNTIME_TYPE_KIND_SLICE,
4681 go_assert(p->field_name() == "elem");
4682 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
4685 go_assert(p == fields->end());
4687 return Expression::make_struct_composite_literal(stdt, vals, bloc);
4690 // Reflection string.
4693 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
4695 ret->push_back('[');
4696 if (this->length_ != NULL)
4701 if (!this->length_->integer_constant_value(true, val, &type))
4702 error_at(this->length_->location(),
4703 "array length must be integer constant expression");
4704 else if (mpz_cmp_si(val, 0) < 0)
4705 error_at(this->length_->location(), "array length is negative");
4706 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
4707 error_at(this->length_->location(), "array length is too large");
4711 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
4716 ret->push_back(']');
4718 this->append_reflection(this->element_type_, gogo, ret);
4724 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4726 ret->push_back('A');
4727 this->append_mangled_name(this->element_type_, gogo, ret);
4728 if (this->length_ != NULL)
4733 if (!this->length_->integer_constant_value(true, val, &type))
4734 error_at(this->length_->location(),
4735 "array length must be integer constant expression");
4736 else if (mpz_cmp_si(val, 0) < 0)
4737 error_at(this->length_->location(), "array length is negative");
4738 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
4739 error_at(this->length_->location(), "array size is too large");
4743 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
4748 ret->push_back('e');
4751 // Make an array type.
4754 Type::make_array_type(Type* element_type, Expression* length)
4756 return new Array_type(element_type, length);
4764 Map_type::do_traverse(Traverse* traverse)
4766 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
4767 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
4768 return TRAVERSE_EXIT;
4769 return TRAVERSE_CONTINUE;
4772 // Check that the map type is OK.
4775 Map_type::do_verify()
4777 if (this->key_type_->struct_type() != NULL
4778 || this->key_type_->array_type() != NULL)
4780 error_at(this->location_, "invalid map key type");
4786 // Whether two map types are identical.
4789 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
4791 return (Type::are_identical(this->key_type(), t->key_type(),
4792 errors_are_identical, NULL)
4793 && Type::are_identical(this->val_type(), t->val_type(),
4794 errors_are_identical, NULL));
4800 Map_type::do_hash_for_method(Gogo* gogo) const
4802 return (this->key_type_->hash_for_method(gogo)
4803 + this->val_type_->hash_for_method(gogo)
4807 // Check that a call to the builtin make function is valid. For a map
4808 // the optional argument is the number of spaces to preallocate for
4812 Map_type::do_check_make_expression(Expression_list* args,
4813 source_location location)
4815 if (args != NULL && !args->empty())
4817 if (!Type::check_int_value(args->front(), _("bad size when making map"),
4820 else if (args->size() > 1)
4822 error_at(location, "too many arguments when making map");
4829 // Get the backend representation for a map type. A map type is
4830 // represented as a pointer to a struct. The struct is __go_map in
4834 Map_type::do_get_backend(Gogo* gogo)
4836 static Btype* backend_map_type;
4837 if (backend_map_type == NULL)
4839 std::vector<Backend::Btyped_identifier> bfields(4);
4841 Type* pdt = Type::make_type_descriptor_ptr_type();
4842 bfields[0].name = "__descriptor";
4843 bfields[0].btype = pdt->get_backend(gogo);
4844 bfields[0].location = BUILTINS_LOCATION;
4846 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4847 bfields[1].name = "__element_count";
4848 bfields[1].btype = uintptr_type->get_backend(gogo);
4849 bfields[1].location = BUILTINS_LOCATION;
4851 bfields[2].name = "__bucket_count";
4852 bfields[2].btype = bfields[1].btype;
4853 bfields[2].location = BUILTINS_LOCATION;
4855 Btype* bvt = gogo->backend()->void_type();
4856 Btype* bpvt = gogo->backend()->pointer_type(bvt);
4857 Btype* bppvt = gogo->backend()->pointer_type(bpvt);
4858 bfields[3].name = "__buckets";
4859 bfields[3].btype = bppvt;
4860 bfields[3].location = BUILTINS_LOCATION;
4862 Btype *bt = gogo->backend()->struct_type(bfields);
4863 bt = gogo->backend()->named_type("__go_map", bt, BUILTINS_LOCATION);
4864 backend_map_type = gogo->backend()->pointer_type(bt);
4866 return backend_map_type;
4869 // Return an expression for a newly allocated map.
4872 Map_type::do_make_expression_tree(Translate_context* context,
4873 Expression_list* args,
4874 source_location location)
4876 tree bad_index = NULL_TREE;
4879 if (args == NULL || args->empty())
4880 expr_tree = size_zero_node;
4883 expr_tree = args->front()->get_tree(context);
4884 if (expr_tree == error_mark_node)
4885 return error_mark_node;
4886 if (!DECL_P(expr_tree))
4887 expr_tree = save_expr(expr_tree);
4888 if (!INTEGRAL_TYPE_P(TREE_TYPE(expr_tree)))
4889 expr_tree = convert_to_integer(sizetype, expr_tree);
4890 bad_index = Expression::check_bounds(expr_tree, sizetype, bad_index,
4894 tree map_type = type_to_tree(this->get_backend(context->gogo()));
4896 static tree new_map_fndecl;
4897 tree ret = Gogo::call_builtin(&new_map_fndecl,
4902 TREE_TYPE(TYPE_FIELDS(TREE_TYPE(map_type))),
4903 context->gogo()->map_descriptor(this),
4906 if (ret == error_mark_node)
4907 return error_mark_node;
4908 // This can panic if the capacity is out of range.
4909 TREE_NOTHROW(new_map_fndecl) = 0;
4911 if (bad_index == NULL_TREE)
4915 tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_MAP_OUT_OF_BOUNDS,
4917 return build2(COMPOUND_EXPR, TREE_TYPE(ret),
4918 build3(COND_EXPR, void_type_node,
4919 bad_index, crash, NULL_TREE),
4924 // The type of a map type descriptor.
4927 Map_type::make_map_type_descriptor_type()
4932 Type* tdt = Type::make_type_descriptor_type();
4933 Type* ptdt = Type::make_type_descriptor_ptr_type();
4936 Type::make_builtin_struct_type(3,
4941 ret = Type::make_builtin_named_type("MapType", sf);
4947 // Build a type descriptor for a map type.
4950 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4952 source_location bloc = BUILTINS_LOCATION;
4954 Type* mtdt = Map_type::make_map_type_descriptor_type();
4956 const Struct_field_list* fields = mtdt->struct_type()->fields();
4958 Expression_list* vals = new Expression_list();
4961 Struct_field_list::const_iterator p = fields->begin();
4962 go_assert(p->field_name() == "commonType");
4963 vals->push_back(this->type_descriptor_constructor(gogo,
4964 RUNTIME_TYPE_KIND_MAP,
4968 go_assert(p->field_name() == "key");
4969 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
4972 go_assert(p->field_name() == "elem");
4973 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
4976 go_assert(p == fields->end());
4978 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
4981 // Reflection string for a map.
4984 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
4986 ret->append("map[");
4987 this->append_reflection(this->key_type_, gogo, ret);
4989 this->append_reflection(this->val_type_, gogo, ret);
4992 // Mangled name for a map.
4995 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4997 ret->push_back('M');
4998 this->append_mangled_name(this->key_type_, gogo, ret);
5000 this->append_mangled_name(this->val_type_, gogo, ret);
5003 // Export a map type.
5006 Map_type::do_export(Export* exp) const
5008 exp->write_c_string("map [");
5009 exp->write_type(this->key_type_);
5010 exp->write_c_string("] ");
5011 exp->write_type(this->val_type_);
5014 // Import a map type.
5017 Map_type::do_import(Import* imp)
5019 imp->require_c_string("map [");
5020 Type* key_type = imp->read_type();
5021 imp->require_c_string("] ");
5022 Type* val_type = imp->read_type();
5023 return Type::make_map_type(key_type, val_type, imp->location());
5029 Type::make_map_type(Type* key_type, Type* val_type, source_location location)
5031 return new Map_type(key_type, val_type, location);
5034 // Class Channel_type.
5039 Channel_type::do_hash_for_method(Gogo* gogo) const
5041 unsigned int ret = 0;
5042 if (this->may_send_)
5044 if (this->may_receive_)
5046 if (this->element_type_ != NULL)
5047 ret += this->element_type_->hash_for_method(gogo) << 2;
5051 // Whether this type is the same as T.
5054 Channel_type::is_identical(const Channel_type* t,
5055 bool errors_are_identical) const
5057 if (!Type::are_identical(this->element_type(), t->element_type(),
5058 errors_are_identical, NULL))
5060 return (this->may_send_ == t->may_send_
5061 && this->may_receive_ == t->may_receive_);
5064 // Check whether the parameters for a call to the builtin function
5065 // make are OK for a channel. A channel can take an optional single
5066 // parameter which is the buffer size.
5069 Channel_type::do_check_make_expression(Expression_list* args,
5070 source_location location)
5072 if (args != NULL && !args->empty())
5074 if (!Type::check_int_value(args->front(),
5075 _("bad buffer size when making channel"),
5078 else if (args->size() > 1)
5080 error_at(location, "too many arguments when making channel");
5087 // Return the tree for a channel type. A channel is a pointer to a
5088 // __go_channel struct. The __go_channel struct is defined in
5089 // libgo/runtime/channel.h.
5092 Channel_type::do_get_backend(Gogo* gogo)
5094 static Btype* backend_channel_type;
5095 if (backend_channel_type == NULL)
5097 std::vector<Backend::Btyped_identifier> bfields;
5098 Btype* bt = gogo->backend()->struct_type(bfields);
5099 bt = gogo->backend()->named_type("__go_channel", bt, BUILTINS_LOCATION);
5100 backend_channel_type = gogo->backend()->pointer_type(bt);
5102 return backend_channel_type;
5105 // Handle the builtin function make for a channel.
5108 Channel_type::do_make_expression_tree(Translate_context* context,
5109 Expression_list* args,
5110 source_location location)
5112 Gogo* gogo = context->gogo();
5113 tree channel_type = type_to_tree(this->get_backend(gogo));
5115 Type* ptdt = Type::make_type_descriptor_ptr_type();
5116 tree element_type_descriptor =
5117 this->element_type_->type_descriptor_pointer(gogo);
5119 tree bad_index = NULL_TREE;
5122 if (args == NULL || args->empty())
5123 expr_tree = size_zero_node;
5126 expr_tree = args->front()->get_tree(context);
5127 if (expr_tree == error_mark_node)
5128 return error_mark_node;
5129 if (!DECL_P(expr_tree))
5130 expr_tree = save_expr(expr_tree);
5131 if (!INTEGRAL_TYPE_P(TREE_TYPE(expr_tree)))
5132 expr_tree = convert_to_integer(sizetype, expr_tree);
5133 bad_index = Expression::check_bounds(expr_tree, sizetype, bad_index,
5137 static tree new_channel_fndecl;
5138 tree ret = Gogo::call_builtin(&new_channel_fndecl,
5143 type_to_tree(ptdt->get_backend(gogo)),
5144 element_type_descriptor,
5147 if (ret == error_mark_node)
5148 return error_mark_node;
5149 // This can panic if the capacity is out of range.
5150 TREE_NOTHROW(new_channel_fndecl) = 0;
5152 if (bad_index == NULL_TREE)
5156 tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_CHAN_OUT_OF_BOUNDS,
5158 return build2(COMPOUND_EXPR, TREE_TYPE(ret),
5159 build3(COND_EXPR, void_type_node,
5160 bad_index, crash, NULL_TREE),
5165 // Build a type descriptor for a channel type.
5168 Channel_type::make_chan_type_descriptor_type()
5173 Type* tdt = Type::make_type_descriptor_type();
5174 Type* ptdt = Type::make_type_descriptor_ptr_type();
5176 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5179 Type::make_builtin_struct_type(3,
5182 "dir", uintptr_type);
5184 ret = Type::make_builtin_named_type("ChanType", sf);
5190 // Build a type descriptor for a map type.
5193 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5195 source_location bloc = BUILTINS_LOCATION;
5197 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
5199 const Struct_field_list* fields = ctdt->struct_type()->fields();
5201 Expression_list* vals = new Expression_list();
5204 Struct_field_list::const_iterator p = fields->begin();
5205 go_assert(p->field_name() == "commonType");
5206 vals->push_back(this->type_descriptor_constructor(gogo,
5207 RUNTIME_TYPE_KIND_CHAN,
5211 go_assert(p->field_name() == "elem");
5212 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5215 go_assert(p->field_name() == "dir");
5216 // These bits must match the ones in libgo/runtime/go-type.h.
5218 if (this->may_receive_)
5220 if (this->may_send_)
5223 mpz_init_set_ui(iv, val);
5224 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
5228 go_assert(p == fields->end());
5230 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
5233 // Reflection string.
5236 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
5238 if (!this->may_send_)
5240 ret->append("chan");
5241 if (!this->may_receive_)
5243 ret->push_back(' ');
5244 this->append_reflection(this->element_type_, gogo, ret);
5250 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5252 ret->push_back('C');
5253 this->append_mangled_name(this->element_type_, gogo, ret);
5254 if (this->may_send_)
5255 ret->push_back('s');
5256 if (this->may_receive_)
5257 ret->push_back('r');
5258 ret->push_back('e');
5264 Channel_type::do_export(Export* exp) const
5266 exp->write_c_string("chan ");
5267 if (this->may_send_ && !this->may_receive_)
5268 exp->write_c_string("-< ");
5269 else if (this->may_receive_ && !this->may_send_)
5270 exp->write_c_string("<- ");
5271 exp->write_type(this->element_type_);
5277 Channel_type::do_import(Import* imp)
5279 imp->require_c_string("chan ");
5283 if (imp->match_c_string("-< "))
5287 may_receive = false;
5289 else if (imp->match_c_string("<- "))
5301 Type* element_type = imp->read_type();
5303 return Type::make_channel_type(may_send, may_receive, element_type);
5306 // Make a new channel type.
5309 Type::make_channel_type(bool send, bool receive, Type* element_type)
5311 return new Channel_type(send, receive, element_type);
5314 // Class Interface_type.
5319 Interface_type::do_traverse(Traverse* traverse)
5321 if (this->methods_ == NULL)
5322 return TRAVERSE_CONTINUE;
5323 return this->methods_->traverse(traverse);
5326 // Finalize the methods. This handles interface inheritance.
5329 Interface_type::finalize_methods()
5331 if (this->methods_ == NULL)
5333 std::vector<Named_type*> seen;
5334 bool is_recursive = false;
5337 while (from < this->methods_->size())
5339 const Typed_identifier* p = &this->methods_->at(from);
5340 if (!p->name().empty())
5343 for (i = 0; i < to; ++i)
5345 if (this->methods_->at(i).name() == p->name())
5347 error_at(p->location(), "duplicate method %qs",
5348 Gogo::message_name(p->name()).c_str());
5355 this->methods_->set(to, *p);
5362 Interface_type* it = p->type()->interface_type();
5365 error_at(p->location(), "interface contains embedded non-interface");
5373 error_at(p->location(), "invalid recursive interface");
5374 is_recursive = true;
5380 Named_type* nt = p->type()->named_type();
5383 std::vector<Named_type*>::const_iterator q;
5384 for (q = seen.begin(); q != seen.end(); ++q)
5388 error_at(p->location(), "inherited interface loop");
5392 if (q != seen.end())
5400 const Typed_identifier_list* methods = it->methods();
5401 if (methods == NULL)
5406 for (Typed_identifier_list::const_iterator q = methods->begin();
5407 q != methods->end();
5410 if (q->name().empty())
5412 if (q->type()->forwarded() == p->type()->forwarded())
5413 error_at(p->location(), "interface inheritance loop");
5417 for (i = from + 1; i < this->methods_->size(); ++i)
5419 const Typed_identifier* r = &this->methods_->at(i);
5420 if (r->name().empty()
5421 && r->type()->forwarded() == q->type()->forwarded())
5423 error_at(p->location(),
5424 "inherited interface listed twice");
5428 if (i == this->methods_->size())
5429 this->methods_->push_back(Typed_identifier(q->name(),
5434 else if (this->find_method(q->name()) == NULL)
5435 this->methods_->push_back(Typed_identifier(q->name(), q->type(),
5440 error_at(p->location(), "inherited method %qs is ambiguous",
5441 Gogo::message_name(q->name()).c_str());
5448 delete this->methods_;
5449 this->methods_ = NULL;
5453 this->methods_->resize(to);
5454 this->methods_->sort_by_name();
5458 // Return the method NAME, or NULL.
5460 const Typed_identifier*
5461 Interface_type::find_method(const std::string& name) const
5463 if (this->methods_ == NULL)
5465 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5466 p != this->methods_->end();
5468 if (p->name() == name)
5473 // Return the method index.
5476 Interface_type::method_index(const std::string& name) const
5478 go_assert(this->methods_ != NULL);
5480 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5481 p != this->methods_->end();
5483 if (p->name() == name)
5488 // Return whether NAME is an unexported method, for better error
5492 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
5494 if (this->methods_ == NULL)
5496 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5497 p != this->methods_->end();
5500 const std::string& method_name(p->name());
5501 if (Gogo::is_hidden_name(method_name)
5502 && name == Gogo::unpack_hidden_name(method_name)
5503 && gogo->pack_hidden_name(name, false) != method_name)
5509 // Whether this type is identical with T.
5512 Interface_type::is_identical(const Interface_type* t,
5513 bool errors_are_identical) const
5515 // We require the same methods with the same types. The methods
5516 // have already been sorted.
5517 if (this->methods() == NULL || t->methods() == NULL)
5518 return this->methods() == t->methods();
5520 Typed_identifier_list::const_iterator p1 = this->methods()->begin();
5521 for (Typed_identifier_list::const_iterator p2 = t->methods()->begin();
5522 p2 != t->methods()->end();
5525 if (p1 == this->methods()->end())
5527 if (p1->name() != p2->name()
5528 || !Type::are_identical(p1->type(), p2->type(),
5529 errors_are_identical, NULL))
5532 if (p1 != this->methods()->end())
5537 // Whether we can assign the interface type T to this type. The types
5538 // are known to not be identical. An interface assignment is only
5539 // permitted if T is known to implement all methods in THIS.
5540 // Otherwise a type guard is required.
5543 Interface_type::is_compatible_for_assign(const Interface_type* t,
5544 std::string* reason) const
5546 if (this->methods() == NULL)
5548 for (Typed_identifier_list::const_iterator p = this->methods()->begin();
5549 p != this->methods()->end();
5552 const Typed_identifier* m = t->find_method(p->name());
5558 snprintf(buf, sizeof buf,
5559 _("need explicit conversion; missing method %s%s%s"),
5560 open_quote, Gogo::message_name(p->name()).c_str(),
5562 reason->assign(buf);
5567 std::string subreason;
5568 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
5572 std::string n = Gogo::message_name(p->name());
5573 size_t len = 100 + n.length() + subreason.length();
5574 char* buf = new char[len];
5575 if (subreason.empty())
5576 snprintf(buf, len, _("incompatible type for method %s%s%s"),
5577 open_quote, n.c_str(), close_quote);
5580 _("incompatible type for method %s%s%s (%s)"),
5581 open_quote, n.c_str(), close_quote,
5583 reason->assign(buf);
5596 Interface_type::do_hash_for_method(Gogo* gogo) const
5598 unsigned int ret = 0;
5599 if (this->methods_ != NULL)
5601 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5602 p != this->methods_->end();
5605 ret = Type::hash_string(p->name(), ret);
5606 ret += p->type()->hash_for_method(gogo);
5613 // Return true if T implements the interface. If it does not, and
5614 // REASON is not NULL, set *REASON to a useful error message.
5617 Interface_type::implements_interface(const Type* t, std::string* reason) const
5619 if (this->methods_ == NULL)
5622 bool is_pointer = false;
5623 const Named_type* nt = t->named_type();
5624 const Struct_type* st = t->struct_type();
5625 // If we start with a named type, we don't dereference it to find
5629 const Type* pt = t->points_to();
5632 // If T is a pointer to a named type, then we need to look at
5633 // the type to which it points.
5635 nt = pt->named_type();
5636 st = pt->struct_type();
5640 // If we have a named type, get the methods from it rather than from
5645 // Only named and struct types have methods.
5646 if (nt == NULL && st == NULL)
5650 if (t->points_to() != NULL
5651 && t->points_to()->interface_type() != NULL)
5652 reason->assign(_("pointer to interface type has no methods"));
5654 reason->assign(_("type has no methods"));
5659 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
5663 if (t->points_to() != NULL
5664 && t->points_to()->interface_type() != NULL)
5665 reason->assign(_("pointer to interface type has no methods"));
5667 reason->assign(_("type has no methods"));
5672 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5673 p != this->methods_->end();
5676 bool is_ambiguous = false;
5677 Method* m = (nt != NULL
5678 ? nt->method_function(p->name(), &is_ambiguous)
5679 : st->method_function(p->name(), &is_ambiguous));
5684 std::string n = Gogo::message_name(p->name());
5685 size_t len = n.length() + 100;
5686 char* buf = new char[len];
5688 snprintf(buf, len, _("ambiguous method %s%s%s"),
5689 open_quote, n.c_str(), close_quote);
5691 snprintf(buf, len, _("missing method %s%s%s"),
5692 open_quote, n.c_str(), close_quote);
5693 reason->assign(buf);
5699 Function_type *p_fn_type = p->type()->function_type();
5700 Function_type* m_fn_type = m->type()->function_type();
5701 go_assert(p_fn_type != NULL && m_fn_type != NULL);
5702 std::string subreason;
5703 if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
5707 std::string n = Gogo::message_name(p->name());
5708 size_t len = 100 + n.length() + subreason.length();
5709 char* buf = new char[len];
5710 if (subreason.empty())
5711 snprintf(buf, len, _("incompatible type for method %s%s%s"),
5712 open_quote, n.c_str(), close_quote);
5715 _("incompatible type for method %s%s%s (%s)"),
5716 open_quote, n.c_str(), close_quote,
5718 reason->assign(buf);
5724 if (!is_pointer && !m->is_value_method())
5728 std::string n = Gogo::message_name(p->name());
5729 size_t len = 100 + n.length();
5730 char* buf = new char[len];
5731 snprintf(buf, len, _("method %s%s%s requires a pointer"),
5732 open_quote, n.c_str(), close_quote);
5733 reason->assign(buf);
5743 // Return the backend representation of the empty interface type. We
5744 // use the same struct for all empty interfaces.
5747 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
5749 static Btype* empty_interface_type;
5750 if (empty_interface_type == NULL)
5752 std::vector<Backend::Btyped_identifier> bfields(2);
5754 Type* pdt = Type::make_type_descriptor_ptr_type();
5755 bfields[0].name = "__type_descriptor";
5756 bfields[0].btype = pdt->get_backend(gogo);
5757 bfields[0].location = UNKNOWN_LOCATION;
5759 Type* vt = Type::make_pointer_type(Type::make_void_type());
5760 bfields[1].name = "__object";
5761 bfields[1].btype = vt->get_backend(gogo);
5762 bfields[1].location = UNKNOWN_LOCATION;
5764 empty_interface_type = gogo->backend()->struct_type(bfields);
5766 return empty_interface_type;
5769 // Return the fields of a non-empty interface type. This is not
5770 // declared in types.h so that types.h doesn't have to #include
5774 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
5775 std::vector<Backend::Btyped_identifier>* bfields)
5777 source_location loc = type->location();
5779 std::vector<Backend::Btyped_identifier> mfields(type->methods()->size() + 1);
5781 Type* pdt = Type::make_type_descriptor_ptr_type();
5782 mfields[0].name = "__type_descriptor";
5783 mfields[0].btype = pdt->get_backend(gogo);
5784 mfields[0].location = loc;
5786 std::string last_name = "";
5788 for (Typed_identifier_list::const_iterator p = type->methods()->begin();
5789 p != type->methods()->end();
5792 mfields[i].name = Gogo::unpack_hidden_name(p->name());
5793 mfields[i].btype = p->type()->get_backend(gogo);
5794 mfields[i].location = loc;
5795 // Sanity check: the names should be sorted.
5796 go_assert(p->name() > last_name);
5797 last_name = p->name();
5800 Btype* methods = gogo->backend()->struct_type(mfields);
5804 (*bfields)[0].name = "__methods";
5805 (*bfields)[0].btype = gogo->backend()->pointer_type(methods);
5806 (*bfields)[0].location = loc;
5808 Type* vt = Type::make_pointer_type(Type::make_void_type());
5809 (*bfields)[1].name = "__object";
5810 (*bfields)[1].btype = vt->get_backend(gogo);
5811 (*bfields)[1].location = UNKNOWN_LOCATION;
5814 // Return a tree for an interface type. An interface is a pointer to
5815 // a struct. The struct has three fields. The first field is a
5816 // pointer to the type descriptor for the dynamic type of the object.
5817 // The second field is a pointer to a table of methods for the
5818 // interface to be used with the object. The third field is the value
5819 // of the object itself.
5822 Interface_type::do_get_backend(Gogo* gogo)
5824 if (this->methods_ == NULL)
5825 return Interface_type::get_backend_empty_interface_type(gogo);
5828 std::vector<Backend::Btyped_identifier> bfields;
5829 get_backend_interface_fields(gogo, this, &bfields);
5830 return gogo->backend()->struct_type(bfields);
5834 // The type of an interface type descriptor.
5837 Interface_type::make_interface_type_descriptor_type()
5842 Type* tdt = Type::make_type_descriptor_type();
5843 Type* ptdt = Type::make_type_descriptor_ptr_type();
5845 Type* string_type = Type::lookup_string_type();
5846 Type* pointer_string_type = Type::make_pointer_type(string_type);
5849 Type::make_builtin_struct_type(3,
5850 "name", pointer_string_type,
5851 "pkgPath", pointer_string_type,
5854 Type* nsm = Type::make_builtin_named_type("imethod", sm);
5856 Type* slice_nsm = Type::make_array_type(nsm, NULL);
5858 Struct_type* s = Type::make_builtin_struct_type(2,
5860 "methods", slice_nsm);
5862 ret = Type::make_builtin_named_type("InterfaceType", s);
5868 // Build a type descriptor for an interface type.
5871 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5873 source_location bloc = BUILTINS_LOCATION;
5875 Type* itdt = Interface_type::make_interface_type_descriptor_type();
5877 const Struct_field_list* ifields = itdt->struct_type()->fields();
5879 Expression_list* ivals = new Expression_list();
5882 Struct_field_list::const_iterator pif = ifields->begin();
5883 go_assert(pif->field_name() == "commonType");
5884 ivals->push_back(this->type_descriptor_constructor(gogo,
5885 RUNTIME_TYPE_KIND_INTERFACE,
5889 go_assert(pif->field_name() == "methods");
5891 Expression_list* methods = new Expression_list();
5892 if (this->methods_ != NULL && !this->methods_->empty())
5894 Type* elemtype = pif->type()->array_type()->element_type();
5896 methods->reserve(this->methods_->size());
5897 for (Typed_identifier_list::const_iterator pm = this->methods_->begin();
5898 pm != this->methods_->end();
5901 const Struct_field_list* mfields = elemtype->struct_type()->fields();
5903 Expression_list* mvals = new Expression_list();
5906 Struct_field_list::const_iterator pmf = mfields->begin();
5907 go_assert(pmf->field_name() == "name");
5908 std::string s = Gogo::unpack_hidden_name(pm->name());
5909 Expression* e = Expression::make_string(s, bloc);
5910 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
5913 go_assert(pmf->field_name() == "pkgPath");
5914 if (!Gogo::is_hidden_name(pm->name()))
5915 mvals->push_back(Expression::make_nil(bloc));
5918 s = Gogo::hidden_name_prefix(pm->name());
5919 e = Expression::make_string(s, bloc);
5920 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
5924 go_assert(pmf->field_name() == "typ");
5925 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
5928 go_assert(pmf == mfields->end());
5930 e = Expression::make_struct_composite_literal(elemtype, mvals,
5932 methods->push_back(e);
5936 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
5940 go_assert(pif == ifields->end());
5942 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
5945 // Reflection string.
5948 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
5950 ret->append("interface {");
5951 if (this->methods_ != NULL)
5953 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5954 p != this->methods_->end();
5957 if (p != this->methods_->begin())
5959 ret->push_back(' ');
5960 if (!Gogo::is_hidden_name(p->name()))
5961 ret->append(p->name());
5964 // This matches what the gc compiler does.
5965 std::string prefix = Gogo::hidden_name_prefix(p->name());
5966 ret->append(prefix.substr(prefix.find('.') + 1));
5967 ret->push_back('.');
5968 ret->append(Gogo::unpack_hidden_name(p->name()));
5970 std::string sub = p->type()->reflection(gogo);
5971 go_assert(sub.compare(0, 4, "func") == 0);
5972 sub = sub.substr(4);
5982 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5984 ret->push_back('I');
5986 const Typed_identifier_list* methods = this->methods_;
5987 if (methods != NULL)
5989 for (Typed_identifier_list::const_iterator p = methods->begin();
5990 p != methods->end();
5993 std::string n = Gogo::unpack_hidden_name(p->name());
5995 snprintf(buf, sizeof buf, "%u_",
5996 static_cast<unsigned int>(n.length()));
5999 this->append_mangled_name(p->type(), gogo, ret);
6003 ret->push_back('e');
6009 Interface_type::do_export(Export* exp) const
6011 exp->write_c_string("interface { ");
6013 const Typed_identifier_list* methods = this->methods_;
6014 if (methods != NULL)
6016 for (Typed_identifier_list::const_iterator pm = methods->begin();
6017 pm != methods->end();
6020 exp->write_string(pm->name());
6021 exp->write_c_string(" (");
6023 const Function_type* fntype = pm->type()->function_type();
6026 const Typed_identifier_list* parameters = fntype->parameters();
6027 if (parameters != NULL)
6029 bool is_varargs = fntype->is_varargs();
6030 for (Typed_identifier_list::const_iterator pp =
6031 parameters->begin();
6032 pp != parameters->end();
6038 exp->write_c_string(", ");
6039 if (!is_varargs || pp + 1 != parameters->end())
6040 exp->write_type(pp->type());
6043 exp->write_c_string("...");
6044 Type *pptype = pp->type();
6045 exp->write_type(pptype->array_type()->element_type());
6050 exp->write_c_string(")");
6052 const Typed_identifier_list* results = fntype->results();
6053 if (results != NULL)
6055 exp->write_c_string(" ");
6056 if (results->size() == 1)
6057 exp->write_type(results->begin()->type());
6061 exp->write_c_string("(");
6062 for (Typed_identifier_list::const_iterator p =
6064 p != results->end();
6070 exp->write_c_string(", ");
6071 exp->write_type(p->type());
6073 exp->write_c_string(")");
6077 exp->write_c_string("; ");
6081 exp->write_c_string("}");
6084 // Import an interface type.
6087 Interface_type::do_import(Import* imp)
6089 imp->require_c_string("interface { ");
6091 Typed_identifier_list* methods = new Typed_identifier_list;
6092 while (imp->peek_char() != '}')
6094 std::string name = imp->read_identifier();
6095 imp->require_c_string(" (");
6097 Typed_identifier_list* parameters;
6098 bool is_varargs = false;
6099 if (imp->peek_char() == ')')
6103 parameters = new Typed_identifier_list;
6106 if (imp->match_c_string("..."))
6112 Type* ptype = imp->read_type();
6114 ptype = Type::make_array_type(ptype, NULL);
6115 parameters->push_back(Typed_identifier(Import::import_marker,
6116 ptype, imp->location()));
6117 if (imp->peek_char() != ',')
6119 go_assert(!is_varargs);
6120 imp->require_c_string(", ");
6123 imp->require_c_string(")");
6125 Typed_identifier_list* results;
6126 if (imp->peek_char() != ' ')
6130 results = new Typed_identifier_list;
6132 if (imp->peek_char() != '(')
6134 Type* rtype = imp->read_type();
6135 results->push_back(Typed_identifier(Import::import_marker,
6136 rtype, imp->location()));
6143 Type* rtype = imp->read_type();
6144 results->push_back(Typed_identifier(Import::import_marker,
6145 rtype, imp->location()));
6146 if (imp->peek_char() != ',')
6148 imp->require_c_string(", ");
6150 imp->require_c_string(")");
6154 Function_type* fntype = Type::make_function_type(NULL, parameters,
6158 fntype->set_is_varargs();
6159 methods->push_back(Typed_identifier(name, fntype, imp->location()));
6161 imp->require_c_string("; ");
6164 imp->require_c_string("}");
6166 if (methods->empty())
6172 return Type::make_interface_type(methods, imp->location());
6175 // Make an interface type.
6178 Type::make_interface_type(Typed_identifier_list* methods,
6179 source_location location)
6181 return new Interface_type(methods, location);
6186 // Bind a method to an object.
6189 Method::bind_method(Expression* expr, source_location location) const
6191 if (this->stub_ == NULL)
6193 // When there is no stub object, the binding is determined by
6195 return this->do_bind_method(expr, location);
6198 Expression* func = Expression::make_func_reference(this->stub_, NULL,
6200 return Expression::make_bound_method(expr, func, location);
6203 // Return the named object associated with a method. This may only be
6204 // called after methods are finalized.
6207 Method::named_object() const
6209 if (this->stub_ != NULL)
6211 return this->do_named_object();
6214 // Class Named_method.
6216 // The type of the method.
6219 Named_method::do_type() const
6221 if (this->named_object_->is_function())
6222 return this->named_object_->func_value()->type();
6223 else if (this->named_object_->is_function_declaration())
6224 return this->named_object_->func_declaration_value()->type();
6229 // Return the location of the method receiver.
6232 Named_method::do_receiver_location() const
6234 return this->do_type()->receiver()->location();
6237 // Bind a method to an object.
6240 Named_method::do_bind_method(Expression* expr, source_location location) const
6242 Expression* func = Expression::make_func_reference(this->named_object_, NULL,
6244 Bound_method_expression* bme = Expression::make_bound_method(expr, func,
6246 // If this is not a local method, and it does not use a stub, then
6247 // the real method expects a different type. We need to cast the
6249 if (this->depth() > 0 && !this->needs_stub_method())
6251 Function_type* ftype = this->do_type();
6252 go_assert(ftype->is_method());
6253 Type* frtype = ftype->receiver()->type();
6254 bme->set_first_argument_type(frtype);
6259 // Class Interface_method.
6261 // Bind a method to an object.
6264 Interface_method::do_bind_method(Expression* expr,
6265 source_location location) const
6267 return Expression::make_interface_field_reference(expr, this->name_,
6273 // Insert a new method. Return true if it was inserted, false
6277 Methods::insert(const std::string& name, Method* m)
6279 std::pair<Method_map::iterator, bool> ins =
6280 this->methods_.insert(std::make_pair(name, m));
6285 Method* old_method = ins.first->second;
6286 if (m->depth() < old_method->depth())
6289 ins.first->second = m;
6294 if (m->depth() == old_method->depth())
6295 old_method->set_is_ambiguous();
6301 // Return the number of unambiguous methods.
6304 Methods::count() const
6307 for (Method_map::const_iterator p = this->methods_.begin();
6308 p != this->methods_.end();
6310 if (!p->second->is_ambiguous())
6315 // Class Named_type.
6317 // Return the name of the type.
6320 Named_type::name() const
6322 return this->named_object_->name();
6325 // Return the name of the type to use in an error message.
6328 Named_type::message_name() const
6330 return this->named_object_->message_name();
6333 // Return the base type for this type. We have to be careful about
6334 // circular type definitions, which are invalid but may be seen here.
6337 Named_type::named_base()
6339 if (this->seen_ > 0)
6342 Type* ret = this->type_->base();
6348 Named_type::named_base() const
6350 if (this->seen_ > 0)
6353 const Type* ret = this->type_->base();
6358 // Return whether this is an error type. We have to be careful about
6359 // circular type definitions, which are invalid but may be seen here.
6362 Named_type::is_named_error_type() const
6364 if (this->seen_ > 0)
6367 bool ret = this->type_->is_error_type();
6372 // Add a method to this type.
6375 Named_type::add_method(const std::string& name, Function* function)
6377 if (this->local_methods_ == NULL)
6378 this->local_methods_ = new Bindings(NULL);
6379 return this->local_methods_->add_function(name, NULL, function);
6382 // Add a method declaration to this type.
6385 Named_type::add_method_declaration(const std::string& name, Package* package,
6386 Function_type* type,
6387 source_location location)
6389 if (this->local_methods_ == NULL)
6390 this->local_methods_ = new Bindings(NULL);
6391 return this->local_methods_->add_function_declaration(name, package, type,
6395 // Add an existing method to this type.
6398 Named_type::add_existing_method(Named_object* no)
6400 if (this->local_methods_ == NULL)
6401 this->local_methods_ = new Bindings(NULL);
6402 this->local_methods_->add_named_object(no);
6405 // Look for a local method NAME, and returns its named object, or NULL
6409 Named_type::find_local_method(const std::string& name) const
6411 if (this->local_methods_ == NULL)
6413 return this->local_methods_->lookup(name);
6416 // Return whether NAME is an unexported field or method, for better
6420 Named_type::is_unexported_local_method(Gogo* gogo,
6421 const std::string& name) const
6423 Bindings* methods = this->local_methods_;
6424 if (methods != NULL)
6426 for (Bindings::const_declarations_iterator p =
6427 methods->begin_declarations();
6428 p != methods->end_declarations();
6431 if (Gogo::is_hidden_name(p->first)
6432 && name == Gogo::unpack_hidden_name(p->first)
6433 && gogo->pack_hidden_name(name, false) != p->first)
6440 // Build the complete list of methods for this type, which means
6441 // recursively including all methods for anonymous fields. Create all
6445 Named_type::finalize_methods(Gogo* gogo)
6447 if (this->all_methods_ != NULL)
6450 if (this->local_methods_ != NULL
6451 && (this->points_to() != NULL || this->interface_type() != NULL))
6453 const Bindings* lm = this->local_methods_;
6454 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
6455 p != lm->end_declarations();
6457 error_at(p->second->location(),
6458 "invalid pointer or interface receiver type");
6459 delete this->local_methods_;
6460 this->local_methods_ = NULL;
6464 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6467 // Return the method NAME, or NULL if there isn't one or if it is
6468 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6472 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
6474 return Type::method_function(this->all_methods_, name, is_ambiguous);
6477 // Return a pointer to the interface method table for this type for
6478 // the interface INTERFACE. IS_POINTER is true if this is for a
6482 Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface,
6485 go_assert(!interface->is_empty());
6487 Interface_method_tables** pimt = (is_pointer
6488 ? &this->interface_method_tables_
6489 : &this->pointer_interface_method_tables_);
6492 *pimt = new Interface_method_tables(5);
6494 std::pair<const Interface_type*, tree> val(interface, NULL_TREE);
6495 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
6499 // This is a new entry in the hash table.
6500 go_assert(ins.first->second == NULL_TREE);
6501 ins.first->second = gogo->interface_method_table_for_type(interface,
6506 tree decl = ins.first->second;
6507 if (decl == error_mark_node)
6508 return error_mark_node;
6509 go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL);
6510 return build_fold_addr_expr(decl);
6513 // Return whether a named type has any hidden fields.
6516 Named_type::named_type_has_hidden_fields(std::string* reason) const
6518 if (this->seen_ > 0)
6521 bool ret = this->type_->has_hidden_fields(this, reason);
6526 // Look for a use of a complete type within another type. This is
6527 // used to check that we don't try to use a type within itself.
6529 class Find_type_use : public Traverse
6532 Find_type_use(Named_type* find_type)
6533 : Traverse(traverse_types),
6534 find_type_(find_type), found_(false)
6537 // Whether we found the type.
6540 { return this->found_; }
6547 // The type we are looking for.
6548 Named_type* find_type_;
6549 // Whether we found the type.
6553 // Check for FIND_TYPE in TYPE.
6556 Find_type_use::type(Type* type)
6558 if (type->named_type() != NULL && this->find_type_ == type->named_type())
6560 this->found_ = true;
6561 return TRAVERSE_EXIT;
6564 // It's OK if we see a reference to the type in any type which is
6565 // essentially a pointer: a pointer, a slice, a function, a map, or
6567 if (type->points_to() != NULL
6568 || type->is_open_array_type()
6569 || type->function_type() != NULL
6570 || type->map_type() != NULL
6571 || type->channel_type() != NULL)
6572 return TRAVERSE_SKIP_COMPONENTS;
6574 // For an interface, a reference to the type in a method type should
6575 // be ignored, but we have to consider direct inheritance. When
6576 // this is called, there may be cases of direct inheritance
6577 // represented as a method with no name.
6578 if (type->interface_type() != NULL)
6580 const Typed_identifier_list* methods = type->interface_type()->methods();
6581 if (methods != NULL)
6583 for (Typed_identifier_list::const_iterator p = methods->begin();
6584 p != methods->end();
6587 if (p->name().empty())
6589 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
6590 return TRAVERSE_EXIT;
6594 return TRAVERSE_SKIP_COMPONENTS;
6597 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
6598 // to convert TYPE to the backend representation before we convert
6600 if (type->named_type() != NULL)
6602 switch (type->base()->classification())
6604 case Type::TYPE_ERROR:
6605 case Type::TYPE_BOOLEAN:
6606 case Type::TYPE_INTEGER:
6607 case Type::TYPE_FLOAT:
6608 case Type::TYPE_COMPLEX:
6609 case Type::TYPE_STRING:
6610 case Type::TYPE_NIL:
6613 case Type::TYPE_ARRAY:
6614 case Type::TYPE_STRUCT:
6615 this->find_type_->add_dependency(type->named_type());
6618 case Type::TYPE_VOID:
6619 case Type::TYPE_SINK:
6620 case Type::TYPE_FUNCTION:
6621 case Type::TYPE_POINTER:
6622 case Type::TYPE_CALL_MULTIPLE_RESULT:
6623 case Type::TYPE_MAP:
6624 case Type::TYPE_CHANNEL:
6625 case Type::TYPE_INTERFACE:
6626 case Type::TYPE_NAMED:
6627 case Type::TYPE_FORWARD:
6633 return TRAVERSE_CONTINUE;
6636 // Verify that a named type does not refer to itself.
6639 Named_type::do_verify()
6641 Find_type_use find(this);
6642 Type::traverse(this->type_, &find);
6645 error_at(this->location_, "invalid recursive type %qs",
6646 this->message_name().c_str());
6647 this->is_error_ = true;
6651 // Check whether any of the local methods overloads an existing
6652 // struct field or interface method. We don't need to check the
6653 // list of methods against itself: that is handled by the Bindings
6655 if (this->local_methods_ != NULL)
6657 Struct_type* st = this->type_->struct_type();
6658 bool found_dup = false;
6661 for (Bindings::const_declarations_iterator p =
6662 this->local_methods_->begin_declarations();
6663 p != this->local_methods_->end_declarations();
6666 const std::string& name(p->first);
6667 if (st != NULL && st->find_local_field(name, NULL) != NULL)
6669 error_at(p->second->location(),
6670 "method %qs redeclares struct field name",
6671 Gogo::message_name(name).c_str());
6683 // Return whether this type is or contains a pointer.
6686 Named_type::do_has_pointer() const
6688 if (this->seen_ > 0)
6691 bool ret = this->type_->has_pointer();
6696 // Return a hash code. This is used for method lookup. We simply
6697 // hash on the name itself.
6700 Named_type::do_hash_for_method(Gogo* gogo) const
6702 const std::string& name(this->named_object()->name());
6703 unsigned int ret = Type::hash_string(name, 0);
6705 // GOGO will be NULL here when called from Type_hash_identical.
6706 // That is OK because that is only used for internal hash tables
6707 // where we are going to be comparing named types for equality. In
6708 // other cases, which are cases where the runtime is going to
6709 // compare hash codes to see if the types are the same, we need to
6710 // include the package prefix and name in the hash.
6711 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
6713 const Package* package = this->named_object()->package();
6714 if (package == NULL)
6716 ret = Type::hash_string(gogo->unique_prefix(), ret);
6717 ret = Type::hash_string(gogo->package_name(), ret);
6721 ret = Type::hash_string(package->unique_prefix(), ret);
6722 ret = Type::hash_string(package->name(), ret);
6729 // Convert a named type to the backend representation. In order to
6730 // get dependencies right, we fill in a dummy structure for this type,
6731 // then convert all the dependencies, then complete this type. When
6732 // this function is complete, the size of the type is known.
6735 Named_type::convert(Gogo* gogo)
6737 if (this->is_error_ || this->is_converted_)
6740 this->create_placeholder(gogo);
6742 // Convert all the dependencies. If they refer indirectly back to
6743 // this type, they will pick up the intermediate tree we just
6745 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
6746 p != this->dependencies_.end();
6748 (*p)->convert(gogo);
6750 // Complete this type.
6751 Btype* bt = this->named_btype_;
6752 Type* base = this->type_->base();
6753 switch (base->classification())
6770 // The size of these types is already correct. We don't worry
6771 // about filling them in until later, when we also track
6772 // circular references.
6777 std::vector<Backend::Btyped_identifier> bfields;
6778 get_backend_struct_fields(gogo, base->struct_type()->fields(),
6780 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6781 bt = gogo->backend()->error_type();
6786 // Slice types were completed in create_placeholder.
6787 if (!base->is_open_array_type())
6789 Btype* bet = base->array_type()->get_backend_element(gogo);
6790 Bexpression* blen = base->array_type()->get_backend_length(gogo);
6791 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
6792 bt = gogo->backend()->error_type();
6796 case TYPE_INTERFACE:
6797 // Interface types were completed in create_placeholder.
6805 case TYPE_CALL_MULTIPLE_RESULT:
6811 this->named_btype_ = bt;
6812 this->is_converted_ = true;
6815 // Create the placeholder for a named type. This is the first step in
6816 // converting to the backend representation.
6819 Named_type::create_placeholder(Gogo* gogo)
6821 if (this->is_error_)
6822 this->named_btype_ = gogo->backend()->error_type();
6824 if (this->named_btype_ != NULL)
6827 // Create the structure for this type. Note that because we call
6828 // base() here, we don't attempt to represent a named type defined
6829 // as another named type. Instead both named types will point to
6830 // different base representations.
6831 Type* base = this->type_->base();
6833 bool set_name = true;
6834 switch (base->classification())
6837 this->is_error_ = true;
6838 this->named_btype_ = gogo->backend()->error_type();
6848 // These are simple basic types, we can just create them
6850 bt = Type::get_named_base_btype(gogo, base);
6855 // All maps and channels have the same backend representation.
6856 bt = Type::get_named_base_btype(gogo, base);
6862 bool for_function = base->classification() == TYPE_FUNCTION;
6863 bt = gogo->backend()->placeholder_pointer_type(this->name(),
6871 bt = gogo->backend()->placeholder_struct_type(this->name(),
6877 if (base->is_open_array_type())
6878 bt = gogo->backend()->placeholder_struct_type(this->name(),
6881 bt = gogo->backend()->placeholder_array_type(this->name(),
6886 case TYPE_INTERFACE:
6887 if (base->interface_type()->is_empty())
6888 bt = Interface_type::get_backend_empty_interface_type(gogo);
6891 bt = gogo->backend()->placeholder_struct_type(this->name(),
6899 case TYPE_CALL_MULTIPLE_RESULT:
6906 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
6908 this->named_btype_ = bt;
6910 if (base->is_open_array_type())
6912 // We do not record slices as dependencies of other types,
6913 // because we can fill them in completely here with the final
6915 std::vector<Backend::Btyped_identifier> bfields;
6916 get_backend_slice_fields(gogo, base->array_type(), &bfields);
6917 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6918 this->named_btype_ = gogo->backend()->error_type();
6920 else if (base->interface_type() != NULL
6921 && !base->interface_type()->is_empty())
6923 // We do not record interfaces as dependencies of other types,
6924 // because we can fill them in completely here with the final
6926 std::vector<Backend::Btyped_identifier> bfields;
6927 get_backend_interface_fields(gogo, base->interface_type(), &bfields);
6928 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6929 this->named_btype_ = gogo->backend()->error_type();
6933 // Get a tree for a named type.
6936 Named_type::do_get_backend(Gogo* gogo)
6938 if (this->is_error_)
6939 return gogo->backend()->error_type();
6941 Btype* bt = this->named_btype_;
6943 if (!gogo->named_types_are_converted())
6945 // We have not completed converting named types. NAMED_BTYPE_
6946 // is a placeholder and we shouldn't do anything further.
6950 // We don't build dependencies for types whose sizes do not
6951 // change or are not relevant, so we may see them here while
6952 // converting types.
6953 this->create_placeholder(gogo);
6954 bt = this->named_btype_;
6955 go_assert(bt != NULL);
6959 // We are not converting types. This should only be called if the
6960 // type has already been converted.
6961 if (!this->is_converted_)
6963 go_assert(saw_errors());
6964 return gogo->backend()->error_type();
6967 go_assert(bt != NULL);
6969 // Complete the tree.
6970 Type* base = this->type_->base();
6972 switch (base->classification())
6975 return gogo->backend()->error_type();
6988 case TYPE_INTERFACE:
6992 // Don't build a circular data structure. GENERIC can't handle
6994 if (this->seen_ > 0)
6996 this->is_circular_ = true;
6997 return gogo->backend()->circular_pointer_type(bt, true);
7000 bt1 = Type::get_named_base_btype(gogo, base);
7002 if (this->is_circular_)
7003 bt1 = gogo->backend()->circular_pointer_type(bt, true);
7004 if (!gogo->backend()->set_placeholder_function_type(bt, bt1))
7005 bt = gogo->backend()->error_type();
7009 // Don't build a circular data structure. GENERIC can't handle
7011 if (this->seen_ > 0)
7013 this->is_circular_ = true;
7014 return gogo->backend()->circular_pointer_type(bt, false);
7017 bt1 = Type::get_named_base_btype(gogo, base);
7019 if (this->is_circular_)
7020 bt1 = gogo->backend()->circular_pointer_type(bt, false);
7021 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
7022 bt = gogo->backend()->error_type();
7027 case TYPE_CALL_MULTIPLE_RESULT:
7036 // Build a type descriptor for a named type.
7039 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7041 // If NAME is not NULL, then we don't really want the type
7042 // descriptor for this type; we want the descriptor for the
7043 // underlying type, giving it the name NAME.
7044 return this->named_type_descriptor(gogo, this->type_,
7045 name == NULL ? this : name);
7048 // Add to the reflection string. This is used mostly for the name of
7049 // the type used in a type descriptor, not for actual reflection
7053 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
7055 if (this->location() != BUILTINS_LOCATION)
7057 const Package* package = this->named_object_->package();
7058 if (package != NULL)
7059 ret->append(package->name());
7061 ret->append(gogo->package_name());
7062 ret->push_back('.');
7064 if (this->in_function_ != NULL)
7066 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
7067 ret->push_back('$');
7069 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
7072 // Get the mangled name.
7075 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7077 Named_object* no = this->named_object_;
7079 if (this->location() == BUILTINS_LOCATION)
7080 go_assert(this->in_function_ == NULL);
7083 const std::string& unique_prefix(no->package() == NULL
7084 ? gogo->unique_prefix()
7085 : no->package()->unique_prefix());
7086 const std::string& package_name(no->package() == NULL
7087 ? gogo->package_name()
7088 : no->package()->name());
7089 name = unique_prefix;
7090 name.append(1, '.');
7091 name.append(package_name);
7092 name.append(1, '.');
7093 if (this->in_function_ != NULL)
7095 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
7096 name.append(1, '$');
7099 name.append(Gogo::unpack_hidden_name(no->name()));
7101 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
7106 // Export the type. This is called to export a global type.
7109 Named_type::export_named_type(Export* exp, const std::string&) const
7111 // We don't need to write the name of the type here, because it will
7112 // be written by Export::write_type anyhow.
7113 exp->write_c_string("type ");
7114 exp->write_type(this);
7115 exp->write_c_string(";\n");
7118 // Import a named type.
7121 Named_type::import_named_type(Import* imp, Named_type** ptype)
7123 imp->require_c_string("type ");
7124 Type *type = imp->read_type();
7125 *ptype = type->named_type();
7126 go_assert(*ptype != NULL);
7127 imp->require_c_string(";\n");
7130 // Export the type when it is referenced by another type. In this
7131 // case Export::export_type will already have issued the name.
7134 Named_type::do_export(Export* exp) const
7136 exp->write_type(this->type_);
7138 // To save space, we only export the methods directly attached to
7140 Bindings* methods = this->local_methods_;
7141 if (methods == NULL)
7144 exp->write_c_string("\n");
7145 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
7146 p != methods->end_definitions();
7149 exp->write_c_string(" ");
7150 (*p)->export_named_object(exp);
7153 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
7154 p != methods->end_declarations();
7157 if (p->second->is_function_declaration())
7159 exp->write_c_string(" ");
7160 p->second->export_named_object(exp);
7165 // Make a named type.
7168 Type::make_named_type(Named_object* named_object, Type* type,
7169 source_location location)
7171 return new Named_type(named_object, type, location);
7174 // Finalize the methods for TYPE. It will be a named type or a struct
7175 // type. This sets *ALL_METHODS to the list of methods, and builds
7176 // all required stubs.
7179 Type::finalize_methods(Gogo* gogo, const Type* type, source_location location,
7180 Methods** all_methods)
7182 *all_methods = NULL;
7183 Types_seen types_seen;
7184 Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen,
7186 Type::build_stub_methods(gogo, type, *all_methods, location);
7189 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
7190 // build up the struct field indexes as we go. DEPTH is the depth of
7191 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
7192 // adding these methods for an anonymous field with pointer type.
7193 // NEEDS_STUB_METHOD is true if we need to use a stub method which
7194 // calls the real method. TYPES_SEEN is used to avoid infinite
7198 Type::add_methods_for_type(const Type* type,
7199 const Method::Field_indexes* field_indexes,
7201 bool is_embedded_pointer,
7202 bool needs_stub_method,
7203 Types_seen* types_seen,
7206 // Pointer types may not have methods.
7207 if (type->points_to() != NULL)
7210 const Named_type* nt = type->named_type();
7213 std::pair<Types_seen::iterator, bool> ins = types_seen->insert(nt);
7219 Type::add_local_methods_for_type(nt, field_indexes, depth,
7220 is_embedded_pointer, needs_stub_method,
7223 Type::add_embedded_methods_for_type(type, field_indexes, depth,
7224 is_embedded_pointer, needs_stub_method,
7225 types_seen, methods);
7227 // If we are called with depth > 0, then we are looking at an
7228 // anonymous field of a struct. If such a field has interface type,
7229 // then we need to add the interface methods. We don't want to add
7230 // them when depth == 0, because we will already handle them
7231 // following the usual rules for an interface type.
7233 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
7236 // Add the local methods for the named type NT to *METHODS. The
7237 // parameters are as for add_methods_to_type.
7240 Type::add_local_methods_for_type(const Named_type* nt,
7241 const Method::Field_indexes* field_indexes,
7243 bool is_embedded_pointer,
7244 bool needs_stub_method,
7247 const Bindings* local_methods = nt->local_methods();
7248 if (local_methods == NULL)
7251 if (*methods == NULL)
7252 *methods = new Methods();
7254 for (Bindings::const_declarations_iterator p =
7255 local_methods->begin_declarations();
7256 p != local_methods->end_declarations();
7259 Named_object* no = p->second;
7260 bool is_value_method = (is_embedded_pointer
7261 || !Type::method_expects_pointer(no));
7262 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
7264 || (depth > 0 && is_value_method)));
7265 if (!(*methods)->insert(no->name(), m))
7270 // Add the embedded methods for TYPE to *METHODS. These are the
7271 // methods attached to anonymous fields. The parameters are as for
7272 // add_methods_to_type.
7275 Type::add_embedded_methods_for_type(const Type* type,
7276 const Method::Field_indexes* field_indexes,
7278 bool is_embedded_pointer,
7279 bool needs_stub_method,
7280 Types_seen* types_seen,
7283 // Look for anonymous fields in TYPE. TYPE has fields if it is a
7285 const Struct_type* st = type->struct_type();
7289 const Struct_field_list* fields = st->fields();
7294 for (Struct_field_list::const_iterator pf = fields->begin();
7295 pf != fields->end();
7298 if (!pf->is_anonymous())
7301 Type* ftype = pf->type();
7302 bool is_pointer = false;
7303 if (ftype->points_to() != NULL)
7305 ftype = ftype->points_to();
7308 Named_type* fnt = ftype->named_type();
7311 // This is an error, but it will be diagnosed elsewhere.
7315 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
7316 sub_field_indexes->next = field_indexes;
7317 sub_field_indexes->field_index = i;
7319 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
7320 (is_embedded_pointer || is_pointer),
7329 // If TYPE is an interface type, then add its method to *METHODS.
7330 // This is for interface methods attached to an anonymous field. The
7331 // parameters are as for add_methods_for_type.
7334 Type::add_interface_methods_for_type(const Type* type,
7335 const Method::Field_indexes* field_indexes,
7339 const Interface_type* it = type->interface_type();
7343 const Typed_identifier_list* imethods = it->methods();
7344 if (imethods == NULL)
7347 if (*methods == NULL)
7348 *methods = new Methods();
7350 for (Typed_identifier_list::const_iterator pm = imethods->begin();
7351 pm != imethods->end();
7354 Function_type* fntype = pm->type()->function_type();
7357 // This is an error, but it should be reported elsewhere
7358 // when we look at the methods for IT.
7361 go_assert(!fntype->is_method());
7362 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
7363 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
7364 field_indexes, depth);
7365 if (!(*methods)->insert(pm->name(), m))
7370 // Build stub methods for TYPE as needed. METHODS is the set of
7371 // methods for the type. A stub method may be needed when a type
7372 // inherits a method from an anonymous field. When we need the
7373 // address of the method, as in a type descriptor, we need to build a
7374 // little stub which does the required field dereferences and jumps to
7375 // the real method. LOCATION is the location of the type definition.
7378 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
7379 source_location location)
7381 if (methods == NULL)
7383 for (Methods::const_iterator p = methods->begin();
7384 p != methods->end();
7387 Method* m = p->second;
7388 if (m->is_ambiguous() || !m->needs_stub_method())
7391 const std::string& name(p->first);
7393 // Build a stub method.
7395 const Function_type* fntype = m->type();
7397 static unsigned int counter;
7399 snprintf(buf, sizeof buf, "$this%u", counter);
7402 Type* receiver_type = const_cast<Type*>(type);
7403 if (!m->is_value_method())
7404 receiver_type = Type::make_pointer_type(receiver_type);
7405 source_location receiver_location = m->receiver_location();
7406 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
7409 const Typed_identifier_list* fnparams = fntype->parameters();
7410 Typed_identifier_list* stub_params;
7411 if (fnparams == NULL || fnparams->empty())
7415 // We give each stub parameter a unique name.
7416 stub_params = new Typed_identifier_list();
7417 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
7418 pp != fnparams->end();
7422 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
7423 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
7429 const Typed_identifier_list* fnresults = fntype->results();
7430 Typed_identifier_list* stub_results;
7431 if (fnresults == NULL || fnresults->empty())
7432 stub_results = NULL;
7435 // We create the result parameters without any names, since
7436 // we won't refer to them.
7437 stub_results = new Typed_identifier_list();
7438 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
7439 pr != fnresults->end();
7441 stub_results->push_back(Typed_identifier("", pr->type(),
7445 Function_type* stub_type = Type::make_function_type(receiver,
7448 fntype->location());
7449 if (fntype->is_varargs())
7450 stub_type->set_is_varargs();
7452 // We only create the function in the package which creates the
7454 const Package* package;
7455 if (type->named_type() == NULL)
7458 package = type->named_type()->named_object()->package();
7460 if (package != NULL)
7461 stub = Named_object::make_function_declaration(name, package,
7462 stub_type, location);
7465 stub = gogo->start_function(name, stub_type, false,
7466 fntype->location());
7467 Type::build_one_stub_method(gogo, m, buf, stub_params,
7468 fntype->is_varargs(), location);
7469 gogo->finish_function(fntype->location());
7472 m->set_stub_object(stub);
7476 // Build a stub method which adjusts the receiver as required to call
7477 // METHOD. RECEIVER_NAME is the name we used for the receiver.
7478 // PARAMS is the list of function parameters.
7481 Type::build_one_stub_method(Gogo* gogo, Method* method,
7482 const char* receiver_name,
7483 const Typed_identifier_list* params,
7485 source_location location)
7487 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
7488 go_assert(receiver_object != NULL);
7490 Expression* expr = Expression::make_var_reference(receiver_object, location);
7491 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
7492 if (expr->type()->points_to() == NULL)
7493 expr = Expression::make_unary(OPERATOR_AND, expr, location);
7495 Expression_list* arguments;
7496 if (params == NULL || params->empty())
7500 arguments = new Expression_list();
7501 for (Typed_identifier_list::const_iterator p = params->begin();
7505 Named_object* param = gogo->lookup(p->name(), NULL);
7506 go_assert(param != NULL);
7507 Expression* param_ref = Expression::make_var_reference(param,
7509 arguments->push_back(param_ref);
7513 Expression* func = method->bind_method(expr, location);
7514 go_assert(func != NULL);
7515 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
7517 size_t count = call->result_count();
7519 gogo->add_statement(Statement::make_statement(call));
7522 Expression_list* retvals = new Expression_list();
7524 retvals->push_back(call);
7527 for (size_t i = 0; i < count; ++i)
7528 retvals->push_back(Expression::make_call_result(call, i));
7530 Statement* retstat = Statement::make_return_statement(retvals, location);
7531 gogo->add_statement(retstat);
7535 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
7536 // in reverse order.
7539 Type::apply_field_indexes(Expression* expr,
7540 const Method::Field_indexes* field_indexes,
7541 source_location location)
7543 if (field_indexes == NULL)
7545 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
7546 Struct_type* stype = expr->type()->deref()->struct_type();
7547 go_assert(stype != NULL
7548 && field_indexes->field_index < stype->field_count());
7549 if (expr->type()->struct_type() == NULL)
7551 go_assert(expr->type()->points_to() != NULL);
7552 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
7553 go_assert(expr->type()->struct_type() == stype);
7555 return Expression::make_field_reference(expr, field_indexes->field_index,
7559 // Return whether NO is a method for which the receiver is a pointer.
7562 Type::method_expects_pointer(const Named_object* no)
7564 const Function_type *fntype;
7565 if (no->is_function())
7566 fntype = no->func_value()->type();
7567 else if (no->is_function_declaration())
7568 fntype = no->func_declaration_value()->type();
7571 return fntype->receiver()->type()->points_to() != NULL;
7574 // Given a set of methods for a type, METHODS, return the method NAME,
7575 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
7576 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
7577 // but is ambiguous (and return NULL).
7580 Type::method_function(const Methods* methods, const std::string& name,
7583 if (is_ambiguous != NULL)
7584 *is_ambiguous = false;
7585 if (methods == NULL)
7587 Methods::const_iterator p = methods->find(name);
7588 if (p == methods->end())
7590 Method* m = p->second;
7591 if (m->is_ambiguous())
7593 if (is_ambiguous != NULL)
7594 *is_ambiguous = true;
7600 // Look for field or method NAME for TYPE. Return an Expression for
7601 // the field or method bound to EXPR. If there is no such field or
7602 // method, give an appropriate error and return an error expression.
7605 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
7606 const std::string& name,
7607 source_location location)
7609 if (type->deref()->is_error_type())
7610 return Expression::make_error(location);
7612 const Named_type* nt = type->deref()->named_type();
7613 const Struct_type* st = type->deref()->struct_type();
7614 const Interface_type* it = type->interface_type();
7616 // If this is a pointer to a pointer, then it is possible that the
7617 // pointed-to type has methods.
7621 && type->points_to() != NULL
7622 && type->points_to()->points_to() != NULL)
7624 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
7625 type = type->points_to();
7626 if (type->deref()->is_error_type())
7627 return Expression::make_error(location);
7628 nt = type->points_to()->named_type();
7629 st = type->points_to()->struct_type();
7632 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
7633 || expr->is_addressable());
7634 std::vector<const Named_type*> seen;
7635 bool is_method = false;
7636 bool found_pointer_method = false;
7639 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
7640 &seen, NULL, &is_method,
7641 &found_pointer_method, &ambig1, &ambig2))
7646 go_assert(st != NULL);
7647 if (type->struct_type() == NULL)
7649 go_assert(type->points_to() != NULL);
7650 expr = Expression::make_unary(OPERATOR_MULT, expr,
7652 go_assert(expr->type()->struct_type() == st);
7654 ret = st->field_reference(expr, name, location);
7656 else if (it != NULL && it->find_method(name) != NULL)
7657 ret = Expression::make_interface_field_reference(expr, name,
7663 m = nt->method_function(name, NULL);
7664 else if (st != NULL)
7665 m = st->method_function(name, NULL);
7668 go_assert(m != NULL);
7669 if (!m->is_value_method() && expr->type()->points_to() == NULL)
7670 expr = Expression::make_unary(OPERATOR_AND, expr, location);
7671 ret = m->bind_method(expr, location);
7673 go_assert(ret != NULL);
7678 if (!ambig1.empty())
7679 error_at(location, "%qs is ambiguous via %qs and %qs",
7680 Gogo::message_name(name).c_str(),
7681 Gogo::message_name(ambig1).c_str(),
7682 Gogo::message_name(ambig2).c_str());
7683 else if (found_pointer_method)
7684 error_at(location, "method requires a pointer");
7685 else if (nt == NULL && st == NULL && it == NULL)
7687 ("reference to field %qs in object which "
7688 "has no fields or methods"),
7689 Gogo::message_name(name).c_str());
7693 if (!Gogo::is_hidden_name(name))
7694 is_unexported = false;
7697 std::string unpacked = Gogo::unpack_hidden_name(name);
7699 is_unexported = Type::is_unexported_field_or_method(gogo, type,
7704 error_at(location, "reference to unexported field or method %qs",
7705 Gogo::message_name(name).c_str());
7707 error_at(location, "reference to undefined field or method %qs",
7708 Gogo::message_name(name).c_str());
7710 return Expression::make_error(location);
7714 // Look in TYPE for a field or method named NAME, return true if one
7715 // is found. This looks through embedded anonymous fields and handles
7716 // ambiguity. If a method is found, sets *IS_METHOD to true;
7717 // otherwise, if a field is found, set it to false. If
7718 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
7719 // whose address can not be taken. SEEN is used to avoid infinite
7720 // recursion on invalid types.
7722 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
7723 // method we couldn't use because it requires a pointer. LEVEL is
7724 // used for recursive calls, and can be NULL for a non-recursive call.
7725 // When this function returns false because it finds that the name is
7726 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
7727 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
7728 // will be unchanged.
7730 // This function just returns whether or not there is a field or
7731 // method, and whether it is a field or method. It doesn't build an
7732 // expression to refer to it. If it is a method, we then look in the
7733 // list of all methods for the type. If it is a field, the search has
7734 // to be done again, looking only for fields, and building up the
7735 // expression as we go.
7738 Type::find_field_or_method(const Type* type,
7739 const std::string& name,
7740 bool receiver_can_be_pointer,
7741 std::vector<const Named_type*>* seen,
7744 bool* found_pointer_method,
7745 std::string* ambig1,
7746 std::string* ambig2)
7748 // Named types can have locally defined methods.
7749 const Named_type* nt = type->named_type();
7750 if (nt == NULL && type->points_to() != NULL)
7751 nt = type->points_to()->named_type();
7754 Named_object* no = nt->find_local_method(name);
7757 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
7763 // Record that we have found a pointer method in order to
7764 // give a better error message if we don't find anything
7766 *found_pointer_method = true;
7769 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
7775 // We've already seen this type when searching for methods.
7781 // Interface types can have methods.
7782 const Interface_type* it = type->interface_type();
7783 if (it != NULL && it->find_method(name) != NULL)
7789 // Struct types can have fields. They can also inherit fields and
7790 // methods from anonymous fields.
7791 const Struct_type* st = type->deref()->struct_type();
7794 const Struct_field_list* fields = st->fields();
7799 seen->push_back(nt);
7801 int found_level = 0;
7802 bool found_is_method = false;
7803 std::string found_ambig1;
7804 std::string found_ambig2;
7805 const Struct_field* found_parent = NULL;
7806 for (Struct_field_list::const_iterator pf = fields->begin();
7807 pf != fields->end();
7810 if (pf->field_name() == name)
7818 if (!pf->is_anonymous())
7821 if (pf->type()->deref()->is_error_type()
7822 || pf->type()->deref()->is_undefined())
7825 Named_type* fnt = pf->type()->named_type();
7827 fnt = pf->type()->deref()->named_type();
7828 go_assert(fnt != NULL);
7830 int sublevel = level == NULL ? 1 : *level + 1;
7832 std::string subambig1;
7833 std::string subambig2;
7834 bool subfound = Type::find_field_or_method(fnt,
7836 receiver_can_be_pointer,
7840 found_pointer_method,
7845 if (!subambig1.empty())
7847 // The name was found via this field, but is ambiguous.
7848 // if the ambiguity is lower or at the same level as
7849 // anything else we have already found, then we want to
7850 // pass the ambiguity back to the caller.
7851 if (found_level == 0 || sublevel <= found_level)
7853 found_ambig1 = pf->field_name() + '.' + subambig1;
7854 found_ambig2 = pf->field_name() + '.' + subambig2;
7855 found_level = sublevel;
7861 // The name was found via this field. Use the level to see
7862 // if we want to use this one, or whether it introduces an
7864 if (found_level == 0 || sublevel < found_level)
7866 found_level = sublevel;
7867 found_is_method = sub_is_method;
7868 found_ambig1.clear();
7869 found_ambig2.clear();
7870 found_parent = &*pf;
7872 else if (sublevel > found_level)
7874 else if (found_ambig1.empty())
7876 // We found an ambiguity.
7877 go_assert(found_parent != NULL);
7878 found_ambig1 = found_parent->field_name();
7879 found_ambig2 = pf->field_name();
7883 // We found an ambiguity, but we already know of one.
7884 // Just report the earlier one.
7889 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
7890 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
7891 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
7892 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
7897 if (found_level == 0)
7899 else if (!found_ambig1.empty())
7901 go_assert(!found_ambig1.empty());
7902 ambig1->assign(found_ambig1);
7903 ambig2->assign(found_ambig2);
7905 *level = found_level;
7911 *level = found_level;
7912 *is_method = found_is_method;
7917 // Return whether NAME is an unexported field or method for TYPE.
7920 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
7921 const std::string& name,
7922 std::vector<const Named_type*>* seen)
7924 const Named_type* nt = type->named_type();
7926 nt = type->deref()->named_type();
7929 if (nt->is_unexported_local_method(gogo, name))
7932 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
7938 // We've already seen this type.
7944 const Interface_type* it = type->interface_type();
7945 if (it != NULL && it->is_unexported_method(gogo, name))
7948 type = type->deref();
7950 const Struct_type* st = type->struct_type();
7951 if (st != NULL && st->is_unexported_local_field(gogo, name))
7957 const Struct_field_list* fields = st->fields();
7962 seen->push_back(nt);
7964 for (Struct_field_list::const_iterator pf = fields->begin();
7965 pf != fields->end();
7968 if (pf->is_anonymous()
7969 && !pf->type()->deref()->is_error_type()
7970 && !pf->type()->deref()->is_undefined())
7972 Named_type* subtype = pf->type()->named_type();
7973 if (subtype == NULL)
7974 subtype = pf->type()->deref()->named_type();
7975 if (subtype == NULL)
7977 // This is an error, but it will be diagnosed elsewhere.
7980 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
7995 // Class Forward_declaration.
7997 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
7998 : Type(TYPE_FORWARD),
7999 named_object_(named_object->resolve()), warned_(false)
8001 go_assert(this->named_object_->is_unknown()
8002 || this->named_object_->is_type_declaration());
8005 // Return the named object.
8008 Forward_declaration_type::named_object()
8010 return this->named_object_->resolve();
8014 Forward_declaration_type::named_object() const
8016 return this->named_object_->resolve();
8019 // Return the name of the forward declared type.
8022 Forward_declaration_type::name() const
8024 return this->named_object()->name();
8027 // Warn about a use of a type which has been declared but not defined.
8030 Forward_declaration_type::warn() const
8032 Named_object* no = this->named_object_->resolve();
8033 if (no->is_unknown())
8035 // The name was not defined anywhere.
8038 error_at(this->named_object_->location(),
8039 "use of undefined type %qs",
8040 no->message_name().c_str());
8041 this->warned_ = true;
8044 else if (no->is_type_declaration())
8046 // The name was seen as a type, but the type was never defined.
8047 if (no->type_declaration_value()->using_type())
8049 error_at(this->named_object_->location(),
8050 "use of undefined type %qs",
8051 no->message_name().c_str());
8052 this->warned_ = true;
8057 // The name was defined, but not as a type.
8060 error_at(this->named_object_->location(), "expected type");
8061 this->warned_ = true;
8066 // Get the base type of a declaration. This gives an error if the
8067 // type has not yet been defined.
8070 Forward_declaration_type::real_type()
8072 if (this->is_defined())
8073 return this->named_object()->type_value();
8077 return Type::make_error_type();
8082 Forward_declaration_type::real_type() const
8084 if (this->is_defined())
8085 return this->named_object()->type_value();
8089 return Type::make_error_type();
8093 // Return whether the base type is defined.
8096 Forward_declaration_type::is_defined() const
8098 return this->named_object()->is_type();
8101 // Add a method. This is used when methods are defined before the
8105 Forward_declaration_type::add_method(const std::string& name,
8108 Named_object* no = this->named_object();
8109 if (no->is_unknown())
8110 no->declare_as_type();
8111 return no->type_declaration_value()->add_method(name, function);
8114 // Add a method declaration. This is used when methods are declared
8118 Forward_declaration_type::add_method_declaration(const std::string& name,
8119 Function_type* type,
8120 source_location location)
8122 Named_object* no = this->named_object();
8123 if (no->is_unknown())
8124 no->declare_as_type();
8125 Type_declaration* td = no->type_declaration_value();
8126 return td->add_method_declaration(name, type, location);
8132 Forward_declaration_type::do_traverse(Traverse* traverse)
8134 if (this->is_defined()
8135 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
8136 return TRAVERSE_EXIT;
8137 return TRAVERSE_CONTINUE;
8140 // Get the backend representation for the type.
8143 Forward_declaration_type::do_get_backend(Gogo* gogo)
8145 if (this->is_defined())
8146 return Type::get_named_base_btype(gogo, this->real_type());
8149 return gogo->backend()->error_type();
8151 // We represent an undefined type as a struct with no fields. That
8152 // should work fine for the backend, since the same case can arise
8154 std::vector<Backend::Btyped_identifier> fields;
8155 Btype* bt = gogo->backend()->struct_type(fields);
8156 return gogo->backend()->named_type(this->name(), bt,
8157 this->named_object()->location());
8160 // Build a type descriptor for a forwarded type.
8163 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8165 if (!this->is_defined())
8166 return Expression::make_nil(BUILTINS_LOCATION);
8169 Type* t = this->real_type();
8171 return this->named_type_descriptor(gogo, t, name);
8173 return Expression::make_type_descriptor(t, BUILTINS_LOCATION);
8177 // The reflection string.
8180 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
8182 this->append_reflection(this->real_type(), gogo, ret);
8185 // The mangled name.
8188 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8190 if (this->is_defined())
8191 this->append_mangled_name(this->real_type(), gogo, ret);
8194 const Named_object* no = this->named_object();
8196 if (no->package() == NULL)
8197 name = gogo->package_name();
8199 name = no->package()->name();
8201 name += Gogo::unpack_hidden_name(no->name());
8203 snprintf(buf, sizeof buf, "N%u_",
8204 static_cast<unsigned int>(name.length()));
8210 // Export a forward declaration. This can happen when a defined type
8211 // refers to a type which is only declared (and is presumably defined
8212 // in some other file in the same package).
8215 Forward_declaration_type::do_export(Export*) const
8217 // If there is a base type, that should be exported instead of this.
8218 go_assert(!this->is_defined());
8220 // We don't output anything.
8223 // Make a forward declaration.
8226 Type::make_forward_declaration(Named_object* named_object)
8228 return new Forward_declaration_type(named_object);
8231 // Class Typed_identifier_list.
8233 // Sort the entries by name.
8235 struct Typed_identifier_list_sort
8239 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
8240 { return t1.name() < t2.name(); }
8244 Typed_identifier_list::sort_by_name()
8246 std::sort(this->entries_.begin(), this->entries_.end(),
8247 Typed_identifier_list_sort());
8253 Typed_identifier_list::traverse(Traverse* traverse)
8255 for (Typed_identifier_list::const_iterator p = this->begin();
8259 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
8260 return TRAVERSE_EXIT;
8262 return TRAVERSE_CONTINUE;
8267 Typed_identifier_list*
8268 Typed_identifier_list::copy() const
8270 Typed_identifier_list* ret = new Typed_identifier_list();
8271 for (Typed_identifier_list::const_iterator p = this->begin();
8274 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));