1 // types.cc -- Go frontend types.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
11 #ifndef ENABLE_BUILD_WITH_CXX
23 #ifndef ENABLE_BUILD_WITH_CXX
30 #include "expressions.h"
31 #include "statements.h"
39 Type::Type(Type_classification classification)
40 : classification_(classification), btype_(NULL), type_descriptor_var_(NULL)
48 // Get the base type for a type--skip names and forward declarations.
53 switch (this->classification_)
56 return this->named_type()->named_base();
58 return this->forward_declaration_type()->real_type()->base();
67 switch (this->classification_)
70 return this->named_type()->named_base();
72 return this->forward_declaration_type()->real_type()->base();
78 // Skip defined forward declarations.
84 Forward_declaration_type* ftype = t->forward_declaration_type();
85 while (ftype != NULL && ftype->is_defined())
87 t = ftype->real_type();
88 ftype = t->forward_declaration_type();
94 Type::forwarded() const
97 const Forward_declaration_type* ftype = t->forward_declaration_type();
98 while (ftype != NULL && ftype->is_defined())
100 t = ftype->real_type();
101 ftype = t->forward_declaration_type();
106 // If this is a named type, return it. Otherwise, return NULL.
111 return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
115 Type::named_type() const
117 return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
120 // Return true if this type is not defined.
123 Type::is_undefined() const
125 return this->forwarded()->forward_declaration_type() != NULL;
128 // Return true if this is a basic type: a type which is not composed
129 // of other types, and is not void.
132 Type::is_basic_type() const
134 switch (this->classification_)
157 return this->base()->is_basic_type();
164 // Return true if this is an abstract type.
167 Type::is_abstract() const
169 switch (this->classification())
172 return this->integer_type()->is_abstract();
174 return this->float_type()->is_abstract();
176 return this->complex_type()->is_abstract();
178 return this->is_abstract_string_type();
180 return this->is_abstract_boolean_type();
186 // Return a non-abstract version of an abstract type.
189 Type::make_non_abstract_type()
191 go_assert(this->is_abstract());
192 switch (this->classification())
195 return Type::lookup_integer_type("int");
197 return Type::lookup_float_type("float64");
199 return Type::lookup_complex_type("complex128");
201 return Type::lookup_string_type();
203 return Type::lookup_bool_type();
209 // Return true if this is an error type. Don't give an error if we
210 // try to dereference an undefined forwarding type, as this is called
211 // in the parser when the type may legitimately be undefined.
214 Type::is_error_type() const
216 const Type* t = this->forwarded();
217 // Note that we return false for an undefined forward type.
218 switch (t->classification_)
223 return t->named_type()->is_named_error_type();
229 // If this is a pointer type, return the type to which it points.
230 // Otherwise, return NULL.
233 Type::points_to() const
235 const Pointer_type* ptype = this->convert<const Pointer_type,
237 return ptype == NULL ? NULL : ptype->points_to();
240 // Return whether this is an open array type.
243 Type::is_slice_type() const
245 return this->array_type() != NULL && this->array_type()->length() == NULL;
248 // Return whether this is the predeclared constant nil being used as a
252 Type::is_nil_constant_as_type() const
254 const Type* t = this->forwarded();
255 if (t->forward_declaration_type() != NULL)
257 const Named_object* no = t->forward_declaration_type()->named_object();
258 if (no->is_unknown())
259 no = no->unknown_value()->real_named_object();
262 && no->const_value()->expr()->is_nil_expression())
271 Type::traverse(Type* type, Traverse* traverse)
273 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
274 || (traverse->traverse_mask()
275 & Traverse::traverse_expressions) != 0);
276 if (traverse->remember_type(type))
278 // We have already traversed this type.
279 return TRAVERSE_CONTINUE;
281 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
283 int t = traverse->type(type);
284 if (t == TRAVERSE_EXIT)
285 return TRAVERSE_EXIT;
286 else if (t == TRAVERSE_SKIP_COMPONENTS)
287 return TRAVERSE_CONTINUE;
289 // An array type has an expression which we need to traverse if
290 // traverse_expressions is set.
291 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
292 return TRAVERSE_EXIT;
293 return TRAVERSE_CONTINUE;
296 // Default implementation for do_traverse for child class.
299 Type::do_traverse(Traverse*)
301 return TRAVERSE_CONTINUE;
304 // Return whether two types are identical. If ERRORS_ARE_IDENTICAL,
305 // then return true for all erroneous types; this is used to avoid
306 // cascading errors. If REASON is not NULL, optionally set *REASON to
307 // the reason the types are not identical.
310 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
313 if (t1 == NULL || t2 == NULL)
315 // Something is wrong.
316 return errors_are_identical ? true : t1 == t2;
319 // Skip defined forward declarations.
320 t1 = t1->forwarded();
321 t2 = t2->forwarded();
326 // An undefined forward declaration is an error.
327 if (t1->forward_declaration_type() != NULL
328 || t2->forward_declaration_type() != NULL)
329 return errors_are_identical;
331 // Avoid cascading errors with error types.
332 if (t1->is_error_type() || t2->is_error_type())
334 if (errors_are_identical)
336 return t1->is_error_type() && t2->is_error_type();
339 // Get a good reason for the sink type. Note that the sink type on
340 // the left hand side of an assignment is handled in are_assignable.
341 if (t1->is_sink_type() || t2->is_sink_type())
344 *reason = "invalid use of _";
348 // A named type is only identical to itself.
349 if (t1->named_type() != NULL || t2->named_type() != NULL)
352 // Check type shapes.
353 if (t1->classification() != t2->classification())
356 switch (t1->classification())
362 // These types are always identical.
366 return t1->integer_type()->is_identical(t2->integer_type());
369 return t1->float_type()->is_identical(t2->float_type());
372 return t1->complex_type()->is_identical(t2->complex_type());
375 return t1->function_type()->is_identical(t2->function_type(),
377 errors_are_identical,
381 return Type::are_identical(t1->points_to(), t2->points_to(),
382 errors_are_identical, reason);
385 return t1->struct_type()->is_identical(t2->struct_type(),
386 errors_are_identical);
389 return t1->array_type()->is_identical(t2->array_type(),
390 errors_are_identical);
393 return t1->map_type()->is_identical(t2->map_type(),
394 errors_are_identical);
397 return t1->channel_type()->is_identical(t2->channel_type(),
398 errors_are_identical);
401 return t1->interface_type()->is_identical(t2->interface_type(),
402 errors_are_identical);
404 case TYPE_CALL_MULTIPLE_RESULT:
406 *reason = "invalid use of multiple value function call";
414 // Return true if it's OK to have a binary operation with types LHS
415 // and RHS. This is not used for shifts or comparisons.
418 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
420 if (Type::are_identical(lhs, rhs, true, NULL))
423 // A constant of abstract bool type may be mixed with any bool type.
424 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
425 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
428 // A constant of abstract string type may be mixed with any string
430 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
431 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
437 // A constant of abstract integer, float, or complex type may be
438 // mixed with an integer, float, or complex type.
439 if ((rhs->is_abstract()
440 && (rhs->integer_type() != NULL
441 || rhs->float_type() != NULL
442 || rhs->complex_type() != NULL)
443 && (lhs->integer_type() != NULL
444 || lhs->float_type() != NULL
445 || lhs->complex_type() != NULL))
446 || (lhs->is_abstract()
447 && (lhs->integer_type() != NULL
448 || lhs->float_type() != NULL
449 || lhs->complex_type() != NULL)
450 && (rhs->integer_type() != NULL
451 || rhs->float_type() != NULL
452 || rhs->complex_type() != NULL)))
455 // The nil type may be compared to a pointer, an interface type, a
456 // slice type, a channel type, a map type, or a function type.
457 if (lhs->is_nil_type()
458 && (rhs->points_to() != NULL
459 || rhs->interface_type() != NULL
460 || rhs->is_slice_type()
461 || rhs->map_type() != NULL
462 || rhs->channel_type() != NULL
463 || rhs->function_type() != NULL))
465 if (rhs->is_nil_type()
466 && (lhs->points_to() != NULL
467 || lhs->interface_type() != NULL
468 || lhs->is_slice_type()
469 || lhs->map_type() != NULL
470 || lhs->channel_type() != NULL
471 || lhs->function_type() != NULL))
477 // Return true if a value with type RHS may be assigned to a variable
478 // with type LHS. If CHECK_HIDDEN_FIELDS is true, check whether any
479 // hidden fields are modified. If REASON is not NULL, set *REASON to
480 // the reason the types are not assignable.
483 Type::are_assignable_check_hidden(const Type* lhs, const Type* rhs,
484 bool check_hidden_fields,
487 // Do some checks first. Make sure the types are defined.
489 && rhs->forwarded()->forward_declaration_type() == NULL
490 && rhs->is_void_type())
493 *reason = "non-value used as value";
497 if (lhs != NULL && lhs->forwarded()->forward_declaration_type() == NULL)
499 // Any value may be assigned to the blank identifier.
500 if (lhs->is_sink_type())
503 // All fields of a struct must be exported, or the assignment
504 // must be in the same package.
505 if (check_hidden_fields
507 && rhs->forwarded()->forward_declaration_type() == NULL)
509 if (lhs->has_hidden_fields(NULL, reason)
510 || rhs->has_hidden_fields(NULL, reason))
515 // Identical types are assignable.
516 if (Type::are_identical(lhs, rhs, true, reason))
519 // The types are assignable if they have identical underlying types
520 // and either LHS or RHS is not a named type.
521 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
522 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
523 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
526 // The types are assignable if LHS is an interface type and RHS
527 // implements the required methods.
528 const Interface_type* lhs_interface_type = lhs->interface_type();
529 if (lhs_interface_type != NULL)
531 if (lhs_interface_type->implements_interface(rhs, reason))
533 const Interface_type* rhs_interface_type = rhs->interface_type();
534 if (rhs_interface_type != NULL
535 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
540 // The type are assignable if RHS is a bidirectional channel type,
541 // LHS is a channel type, they have identical element types, and
542 // either LHS or RHS is not a named type.
543 if (lhs->channel_type() != NULL
544 && rhs->channel_type() != NULL
545 && rhs->channel_type()->may_send()
546 && rhs->channel_type()->may_receive()
547 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
548 && Type::are_identical(lhs->channel_type()->element_type(),
549 rhs->channel_type()->element_type(),
554 // The nil type may be assigned to a pointer, function, slice, map,
555 // channel, or interface type.
556 if (rhs->is_nil_type()
557 && (lhs->points_to() != NULL
558 || lhs->function_type() != NULL
559 || lhs->is_slice_type()
560 || lhs->map_type() != NULL
561 || lhs->channel_type() != NULL
562 || lhs->interface_type() != NULL))
565 // An untyped numeric constant may be assigned to a numeric type if
566 // it is representable in that type.
567 if ((rhs->is_abstract()
568 && (rhs->integer_type() != NULL
569 || rhs->float_type() != NULL
570 || rhs->complex_type() != NULL))
571 && (lhs->integer_type() != NULL
572 || lhs->float_type() != NULL
573 || lhs->complex_type() != NULL))
576 // Give some better error messages.
577 if (reason != NULL && reason->empty())
579 if (rhs->interface_type() != NULL)
580 reason->assign(_("need explicit conversion"));
581 else if (rhs->is_call_multiple_result_type())
582 reason->assign(_("multiple value function call in "
583 "single value context"));
584 else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
586 size_t len = (lhs->named_type()->name().length()
587 + rhs->named_type()->name().length()
589 char* buf = new char[len];
590 snprintf(buf, len, _("cannot use type %s as type %s"),
591 rhs->named_type()->message_name().c_str(),
592 lhs->named_type()->message_name().c_str());
601 // Return true if a value with type RHS may be assigned to a variable
602 // with type LHS. If REASON is not NULL, set *REASON to the reason
603 // the types are not assignable.
606 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
608 return Type::are_assignable_check_hidden(lhs, rhs, true, reason);
611 // Like are_assignable but don't check for hidden fields.
614 Type::are_assignable_hidden_ok(const Type* lhs, const Type* rhs,
617 return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
620 // Return true if a value with type RHS may be converted to type LHS.
621 // If REASON is not NULL, set *REASON to the reason the types are not
625 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
627 // The types are convertible if they are assignable.
628 if (Type::are_assignable(lhs, rhs, reason))
631 // The types are convertible if they have identical underlying
633 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
634 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
637 // The types are convertible if they are both unnamed pointer types
638 // and their pointer base types have identical underlying types.
639 if (lhs->named_type() == NULL
640 && rhs->named_type() == NULL
641 && lhs->points_to() != NULL
642 && rhs->points_to() != NULL
643 && (lhs->points_to()->named_type() != NULL
644 || rhs->points_to()->named_type() != NULL)
645 && Type::are_identical(lhs->points_to()->base(),
646 rhs->points_to()->base(),
651 // Integer and floating point types are convertible to each other.
652 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
653 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
656 // Complex types are convertible to each other.
657 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
660 // An integer, or []byte, or []int, may be converted to a string.
661 if (lhs->is_string_type())
663 if (rhs->integer_type() != NULL)
665 if (rhs->is_slice_type() && rhs->named_type() == NULL)
667 const Type* e = rhs->array_type()->element_type()->forwarded();
668 if (e->integer_type() != NULL
669 && (e == Type::lookup_integer_type("uint8")
670 || e == Type::lookup_integer_type("int")))
675 // A string may be converted to []byte or []int.
676 if (rhs->is_string_type()
677 && lhs->is_slice_type()
678 && lhs->named_type() == NULL)
680 const Type* e = lhs->array_type()->element_type()->forwarded();
681 if (e->integer_type() != NULL
682 && (e == Type::lookup_integer_type("uint8")
683 || e == Type::lookup_integer_type("int")))
687 // An unsafe.Pointer type may be converted to any pointer type or to
688 // uintptr, and vice-versa.
689 if (lhs->is_unsafe_pointer_type()
690 && (rhs->points_to() != NULL
691 || (rhs->integer_type() != NULL
692 && rhs->forwarded() == Type::lookup_integer_type("uintptr"))))
694 if (rhs->is_unsafe_pointer_type()
695 && (lhs->points_to() != NULL
696 || (lhs->integer_type() != NULL
697 && lhs->forwarded() == Type::lookup_integer_type("uintptr"))))
700 // Give a better error message.
704 *reason = "invalid type conversion";
707 std::string s = "invalid type conversion (";
717 // Return whether this type has any hidden fields. This is only a
718 // possibility for a few types.
721 Type::has_hidden_fields(const Named_type* within, std::string* reason) const
723 switch (this->forwarded()->classification_)
726 return this->named_type()->named_type_has_hidden_fields(reason);
728 return this->struct_type()->struct_has_hidden_fields(within, reason);
730 return this->array_type()->array_has_hidden_fields(within, reason);
736 // Return a hash code for the type to be used for method lookup.
739 Type::hash_for_method(Gogo* gogo) const
741 unsigned int ret = 0;
742 if (this->classification_ != TYPE_FORWARD)
743 ret += this->classification_;
744 return ret + this->do_hash_for_method(gogo);
747 // Default implementation of do_hash_for_method. This is appropriate
748 // for types with no subfields.
751 Type::do_hash_for_method(Gogo*) const
756 // Return a hash code for a string, given a starting hash.
759 Type::hash_string(const std::string& s, unsigned int h)
761 const char* p = s.data();
762 size_t len = s.length();
763 for (; len > 0; --len)
771 // A hash table mapping unnamed types to the backend representation of
774 Type::Type_btypes Type::type_btypes;
776 // Return a tree representing this type.
779 Type::get_backend(Gogo* gogo)
781 if (this->btype_ != NULL)
784 if (this->forward_declaration_type() != NULL
785 || this->named_type() != NULL)
786 return this->get_btype_without_hash(gogo);
788 if (this->is_error_type())
789 return gogo->backend()->error_type();
791 // To avoid confusing the backend, translate all identical Go types
792 // to the same backend representation. We use a hash table to do
793 // that. There is no need to use the hash table for named types, as
794 // named types are only identical to themselves.
796 std::pair<Type*, Btype*> val(this, NULL);
797 std::pair<Type_btypes::iterator, bool> ins =
798 Type::type_btypes.insert(val);
799 if (!ins.second && ins.first->second != NULL)
801 if (gogo != NULL && gogo->named_types_are_converted())
802 this->btype_ = ins.first->second;
803 return ins.first->second;
806 Btype* bt = this->get_btype_without_hash(gogo);
808 if (ins.first->second == NULL)
809 ins.first->second = bt;
812 // We have already created a backend representation for this
813 // type. This can happen when an unnamed type is defined using
814 // a named type which in turns uses an identical unnamed type.
815 // Use the tree we created earlier and ignore the one we just
817 bt = ins.first->second;
818 if (gogo == NULL || !gogo->named_types_are_converted())
826 // Return the backend representation for a type without looking in the
827 // hash table for identical types. This is used for named types,
828 // since a named type is never identical to any other type.
831 Type::get_btype_without_hash(Gogo* gogo)
833 if (this->btype_ == NULL)
835 Btype* bt = this->do_get_backend(gogo);
837 // For a recursive function or pointer type, we will temporarily
838 // return a circular pointer type during the recursion. We
839 // don't want to record that for a forwarding type, as it may
841 if (this->forward_declaration_type() != NULL
842 && gogo->backend()->is_circular_pointer_type(bt))
845 if (gogo == NULL || !gogo->named_types_are_converted())
853 // Return a pointer to the type descriptor for this type.
856 Type::type_descriptor_pointer(Gogo* gogo, Location location)
858 Type* t = this->forwarded();
859 if (t->type_descriptor_var_ == NULL)
861 t->make_type_descriptor_var(gogo);
862 go_assert(t->type_descriptor_var_ != NULL);
864 tree var_tree = var_to_tree(t->type_descriptor_var_);
865 if (var_tree == error_mark_node)
866 return error_mark_node;
867 return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
870 // A mapping from unnamed types to type descriptor variables.
872 Type::Type_descriptor_vars Type::type_descriptor_vars;
874 // Build the type descriptor for this type.
877 Type::make_type_descriptor_var(Gogo* gogo)
879 go_assert(this->type_descriptor_var_ == NULL);
881 Named_type* nt = this->named_type();
883 // We can have multiple instances of unnamed types, but we only want
884 // to emit the type descriptor once. We use a hash table. This is
885 // not necessary for named types, as they are unique, and we store
886 // the type descriptor in the type itself.
887 Bvariable** phash = NULL;
890 Bvariable* bvnull = NULL;
891 std::pair<Type_descriptor_vars::iterator, bool> ins =
892 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
895 // We've already build a type descriptor for this type.
896 this->type_descriptor_var_ = ins.first->second;
899 phash = &ins.first->second;
902 std::string var_name;
904 var_name = this->unnamed_type_descriptor_var_name(gogo);
906 var_name = this->type_descriptor_var_name(gogo);
908 // Build the contents of the type descriptor.
909 Expression* initializer = this->do_type_descriptor(gogo, NULL);
911 Btype* initializer_btype = initializer->type()->get_backend(gogo);
913 // See if this type descriptor is defined in a different package.
914 bool is_defined_elsewhere = false;
917 if (nt->named_object()->package() != NULL)
919 // This is a named type defined in a different package. The
920 // type descriptor should be defined in that package.
921 is_defined_elsewhere = true;
926 if (this->points_to() != NULL
927 && this->points_to()->named_type() != NULL
928 && this->points_to()->named_type()->named_object()->package() != NULL)
930 // This is an unnamed pointer to a named type defined in a
931 // different package. The descriptor should be defined in
933 is_defined_elsewhere = true;
937 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
939 if (is_defined_elsewhere)
941 this->type_descriptor_var_ =
942 gogo->backend()->immutable_struct_reference(var_name,
946 *phash = this->type_descriptor_var_;
950 // See if this type descriptor can appear in multiple packages.
951 bool is_common = false;
954 // We create the descriptor for a builtin type whenever we need
956 is_common = nt->is_builtin();
960 // This is an unnamed type. The descriptor could be defined in
961 // any package where it is needed, and the linker will pick one
962 // descriptor to keep.
966 // We are going to build the type descriptor in this package. We
967 // must create the variable before we convert the initializer to the
968 // backend representation, because the initializer may refer to the
969 // type descriptor of this type. By setting type_descriptor_var_ we
970 // ensure that type_descriptor_pointer will work if called while
971 // converting INITIALIZER.
973 this->type_descriptor_var_ =
974 gogo->backend()->immutable_struct(var_name, is_common, initializer_btype,
977 *phash = this->type_descriptor_var_;
979 Translate_context context(gogo, NULL, NULL, NULL);
980 context.set_is_const();
981 Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
983 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
985 initializer_btype, loc,
989 // Return the name of the type descriptor variable for an unnamed
993 Type::unnamed_type_descriptor_var_name(Gogo* gogo)
995 return "__go_td_" + this->mangled_name(gogo);
998 // Return the name of the type descriptor variable for a named type.
1001 Type::type_descriptor_var_name(Gogo* gogo)
1003 Named_type* nt = this->named_type();
1004 Named_object* no = nt->named_object();
1005 const Named_object* in_function = nt->in_function();
1006 std::string ret = "__go_tdn_";
1007 if (nt->is_builtin())
1008 go_assert(in_function == NULL);
1011 const std::string& unique_prefix(no->package() == NULL
1012 ? gogo->unique_prefix()
1013 : no->package()->unique_prefix());
1014 const std::string& package_name(no->package() == NULL
1015 ? gogo->package_name()
1016 : no->package()->name());
1017 ret.append(unique_prefix);
1019 ret.append(package_name);
1021 if (in_function != NULL)
1023 ret.append(Gogo::unpack_hidden_name(in_function->name()));
1027 ret.append(no->name());
1031 // Return a composite literal for a type descriptor.
1034 Type::type_descriptor(Gogo* gogo, Type* type)
1036 return type->do_type_descriptor(gogo, NULL);
1039 // Return a composite literal for a type descriptor with a name.
1042 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1044 go_assert(name != NULL && type->named_type() != name);
1045 return type->do_type_descriptor(gogo, name);
1048 // Make a builtin struct type from a list of fields. The fields are
1049 // pairs of a name and a type.
1052 Type::make_builtin_struct_type(int nfields, ...)
1055 va_start(ap, nfields);
1057 Location bloc = Linemap::predeclared_location();
1058 Struct_field_list* sfl = new Struct_field_list();
1059 for (int i = 0; i < nfields; i++)
1061 const char* field_name = va_arg(ap, const char *);
1062 Type* type = va_arg(ap, Type*);
1063 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1068 return Type::make_struct_type(sfl, bloc);
1071 // A list of builtin named types.
1073 std::vector<Named_type*> Type::named_builtin_types;
1075 // Make a builtin named type.
1078 Type::make_builtin_named_type(const char* name, Type* type)
1080 Location bloc = Linemap::predeclared_location();
1081 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1082 Named_type* ret = no->type_value();
1083 Type::named_builtin_types.push_back(ret);
1087 // Convert the named builtin types.
1090 Type::convert_builtin_named_types(Gogo* gogo)
1092 for (std::vector<Named_type*>::const_iterator p =
1093 Type::named_builtin_types.begin();
1094 p != Type::named_builtin_types.end();
1097 bool r = (*p)->verify();
1099 (*p)->convert(gogo);
1103 // Return the type of a type descriptor. We should really tie this to
1104 // runtime.Type rather than copying it. This must match commonType in
1105 // libgo/go/runtime/type.go.
1108 Type::make_type_descriptor_type()
1113 Location bloc = Linemap::predeclared_location();
1115 Type* uint8_type = Type::lookup_integer_type("uint8");
1116 Type* uint32_type = Type::lookup_integer_type("uint32");
1117 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1118 Type* string_type = Type::lookup_string_type();
1119 Type* pointer_string_type = Type::make_pointer_type(string_type);
1121 // This is an unnamed version of unsafe.Pointer. Perhaps we
1122 // should use the named version instead, although that would
1123 // require us to create the unsafe package if it has not been
1124 // imported. It probably doesn't matter.
1125 Type* void_type = Type::make_void_type();
1126 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1128 // Forward declaration for the type descriptor type.
1129 Named_object* named_type_descriptor_type =
1130 Named_object::make_type_declaration("commonType", NULL, bloc);
1131 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1132 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1134 // The type of a method on a concrete type.
1135 Struct_type* method_type =
1136 Type::make_builtin_struct_type(5,
1137 "name", pointer_string_type,
1138 "pkgPath", pointer_string_type,
1139 "mtyp", pointer_type_descriptor_type,
1140 "typ", pointer_type_descriptor_type,
1141 "tfn", unsafe_pointer_type);
1142 Named_type* named_method_type =
1143 Type::make_builtin_named_type("method", method_type);
1145 // Information for types with a name or methods.
1146 Type* slice_named_method_type =
1147 Type::make_array_type(named_method_type, NULL);
1148 Struct_type* uncommon_type =
1149 Type::make_builtin_struct_type(3,
1150 "name", pointer_string_type,
1151 "pkgPath", pointer_string_type,
1152 "methods", slice_named_method_type);
1153 Named_type* named_uncommon_type =
1154 Type::make_builtin_named_type("uncommonType", uncommon_type);
1156 Type* pointer_uncommon_type =
1157 Type::make_pointer_type(named_uncommon_type);
1159 // The type descriptor type.
1161 Typed_identifier_list* params = new Typed_identifier_list();
1162 params->push_back(Typed_identifier("", unsafe_pointer_type, bloc));
1163 params->push_back(Typed_identifier("", uintptr_type, bloc));
1165 Typed_identifier_list* results = new Typed_identifier_list();
1166 results->push_back(Typed_identifier("", uintptr_type, bloc));
1168 Type* hashfn_type = Type::make_function_type(NULL, params, results, bloc);
1170 params = new Typed_identifier_list();
1171 params->push_back(Typed_identifier("", unsafe_pointer_type, bloc));
1172 params->push_back(Typed_identifier("", unsafe_pointer_type, bloc));
1173 params->push_back(Typed_identifier("", uintptr_type, bloc));
1175 results = new Typed_identifier_list();
1176 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1178 Type* equalfn_type = Type::make_function_type(NULL, params, results,
1181 Struct_type* type_descriptor_type =
1182 Type::make_builtin_struct_type(10,
1184 "align", uint8_type,
1185 "fieldAlign", uint8_type,
1186 "size", uintptr_type,
1187 "hash", uint32_type,
1188 "hashfn", hashfn_type,
1189 "equalfn", equalfn_type,
1190 "string", pointer_string_type,
1191 "", pointer_uncommon_type,
1193 pointer_type_descriptor_type);
1195 Named_type* named = Type::make_builtin_named_type("commonType",
1196 type_descriptor_type);
1198 named_type_descriptor_type->set_type_value(named);
1206 // Make the type of a pointer to a type descriptor as represented in
1210 Type::make_type_descriptor_ptr_type()
1214 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1218 // Return the names of runtime functions which compute a hash code for
1219 // this type and which compare whether two values of this type are
1223 Type::type_functions(const char** hash_fn, const char** equal_fn) const
1225 switch (this->base()->classification())
1227 case Type::TYPE_ERROR:
1228 case Type::TYPE_VOID:
1229 case Type::TYPE_NIL:
1230 // These types can not be hashed or compared.
1231 *hash_fn = "__go_type_hash_error";
1232 *equal_fn = "__go_type_equal_error";
1235 case Type::TYPE_BOOLEAN:
1236 case Type::TYPE_INTEGER:
1237 case Type::TYPE_FLOAT:
1238 case Type::TYPE_COMPLEX:
1239 case Type::TYPE_POINTER:
1240 case Type::TYPE_FUNCTION:
1241 case Type::TYPE_MAP:
1242 case Type::TYPE_CHANNEL:
1243 *hash_fn = "__go_type_hash_identity";
1244 *equal_fn = "__go_type_equal_identity";
1247 case Type::TYPE_STRING:
1248 *hash_fn = "__go_type_hash_string";
1249 *equal_fn = "__go_type_equal_string";
1252 case Type::TYPE_STRUCT:
1253 case Type::TYPE_ARRAY:
1254 // These types can not be hashed or compared.
1255 *hash_fn = "__go_type_hash_error";
1256 *equal_fn = "__go_type_equal_error";
1259 case Type::TYPE_INTERFACE:
1260 if (this->interface_type()->is_empty())
1262 *hash_fn = "__go_type_hash_empty_interface";
1263 *equal_fn = "__go_type_equal_empty_interface";
1267 *hash_fn = "__go_type_hash_interface";
1268 *equal_fn = "__go_type_equal_interface";
1272 case Type::TYPE_NAMED:
1273 case Type::TYPE_FORWARD:
1281 // Return a composite literal for the type descriptor for a plain type
1282 // of kind RUNTIME_TYPE_KIND named NAME.
1285 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
1286 Named_type* name, const Methods* methods,
1287 bool only_value_methods)
1289 Location bloc = Linemap::predeclared_location();
1291 Type* td_type = Type::make_type_descriptor_type();
1292 const Struct_field_list* fields = td_type->struct_type()->fields();
1294 Expression_list* vals = new Expression_list();
1297 if (!this->has_pointer())
1298 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
1299 Struct_field_list::const_iterator p = fields->begin();
1300 go_assert(p->is_field_name("Kind"));
1302 mpz_init_set_ui(iv, runtime_type_kind);
1303 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1306 go_assert(p->is_field_name("align"));
1307 Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT;
1308 vals->push_back(Expression::make_type_info(this, type_info));
1311 go_assert(p->is_field_name("fieldAlign"));
1312 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
1313 vals->push_back(Expression::make_type_info(this, type_info));
1316 go_assert(p->is_field_name("size"));
1317 type_info = Expression::TYPE_INFO_SIZE;
1318 vals->push_back(Expression::make_type_info(this, type_info));
1321 go_assert(p->is_field_name("hash"));
1322 mpz_set_ui(iv, this->hash_for_method(gogo));
1323 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1325 const char* hash_fn;
1326 const char* equal_fn;
1327 this->type_functions(&hash_fn, &equal_fn);
1330 go_assert(p->is_field_name("hashfn"));
1331 Function_type* fntype = p->type()->function_type();
1332 Named_object* no = Named_object::make_function_declaration(hash_fn, NULL,
1335 no->func_declaration_value()->set_asm_name(hash_fn);
1336 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
1339 go_assert(p->is_field_name("equalfn"));
1340 fntype = p->type()->function_type();
1341 no = Named_object::make_function_declaration(equal_fn, NULL, fntype, bloc);
1342 no->func_declaration_value()->set_asm_name(equal_fn);
1343 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
1346 go_assert(p->is_field_name("string"));
1347 Expression* s = Expression::make_string((name != NULL
1348 ? name->reflection(gogo)
1349 : this->reflection(gogo)),
1351 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1354 go_assert(p->is_field_name("uncommonType"));
1355 if (name == NULL && methods == NULL)
1356 vals->push_back(Expression::make_nil(bloc));
1359 if (methods == NULL)
1360 methods = name->methods();
1361 vals->push_back(this->uncommon_type_constructor(gogo,
1364 only_value_methods));
1368 go_assert(p->is_field_name("ptrToThis"));
1370 vals->push_back(Expression::make_nil(bloc));
1373 Type* pt = Type::make_pointer_type(name);
1374 vals->push_back(Expression::make_type_descriptor(pt, bloc));
1378 go_assert(p == fields->end());
1382 return Expression::make_struct_composite_literal(td_type, vals, bloc);
1385 // Return a composite literal for the uncommon type information for
1386 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
1387 // struct. If name is not NULL, it is the name of the type. If
1388 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
1389 // is true if only value methods should be included. At least one of
1390 // NAME and METHODS must not be NULL.
1393 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
1394 Named_type* name, const Methods* methods,
1395 bool only_value_methods) const
1397 Location bloc = Linemap::predeclared_location();
1399 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
1401 Expression_list* vals = new Expression_list();
1404 Struct_field_list::const_iterator p = fields->begin();
1405 go_assert(p->is_field_name("name"));
1408 go_assert(p->is_field_name("pkgPath"));
1412 vals->push_back(Expression::make_nil(bloc));
1413 vals->push_back(Expression::make_nil(bloc));
1417 Named_object* no = name->named_object();
1418 std::string n = Gogo::unpack_hidden_name(no->name());
1419 Expression* s = Expression::make_string(n, bloc);
1420 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1422 if (name->is_builtin())
1423 vals->push_back(Expression::make_nil(bloc));
1426 const Package* package = no->package();
1427 const std::string& unique_prefix(package == NULL
1428 ? gogo->unique_prefix()
1429 : package->unique_prefix());
1430 const std::string& package_name(package == NULL
1431 ? gogo->package_name()
1433 n.assign(unique_prefix);
1435 n.append(package_name);
1436 if (name->in_function() != NULL)
1439 n.append(Gogo::unpack_hidden_name(name->in_function()->name()));
1441 s = Expression::make_string(n, bloc);
1442 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1447 go_assert(p->is_field_name("methods"));
1448 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
1449 only_value_methods));
1452 go_assert(p == fields->end());
1454 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
1456 return Expression::make_unary(OPERATOR_AND, r, bloc);
1459 // Sort methods by name.
1465 operator()(const std::pair<std::string, const Method*>& m1,
1466 const std::pair<std::string, const Method*>& m2) const
1467 { return m1.first < m2.first; }
1470 // Return a composite literal for the type method table for this type.
1471 // METHODS_TYPE is the type of the table, and is a slice type.
1472 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
1473 // then only value methods are used.
1476 Type::methods_constructor(Gogo* gogo, Type* methods_type,
1477 const Methods* methods,
1478 bool only_value_methods) const
1480 Location bloc = Linemap::predeclared_location();
1482 std::vector<std::pair<std::string, const Method*> > smethods;
1483 if (methods != NULL)
1485 smethods.reserve(methods->count());
1486 for (Methods::const_iterator p = methods->begin();
1487 p != methods->end();
1490 if (p->second->is_ambiguous())
1492 if (only_value_methods && !p->second->is_value_method())
1494 smethods.push_back(std::make_pair(p->first, p->second));
1498 if (smethods.empty())
1499 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
1501 std::sort(smethods.begin(), smethods.end(), Sort_methods());
1503 Type* method_type = methods_type->array_type()->element_type();
1505 Expression_list* vals = new Expression_list();
1506 vals->reserve(smethods.size());
1507 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
1509 p != smethods.end();
1511 vals->push_back(this->method_constructor(gogo, method_type, p->first,
1512 p->second, only_value_methods));
1514 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
1517 // Return a composite literal for a single method. METHOD_TYPE is the
1518 // type of the entry. METHOD_NAME is the name of the method and M is
1519 // the method information.
1522 Type::method_constructor(Gogo*, Type* method_type,
1523 const std::string& method_name,
1525 bool only_value_methods) const
1527 Location bloc = Linemap::predeclared_location();
1529 const Struct_field_list* fields = method_type->struct_type()->fields();
1531 Expression_list* vals = new Expression_list();
1534 Struct_field_list::const_iterator p = fields->begin();
1535 go_assert(p->is_field_name("name"));
1536 const std::string n = Gogo::unpack_hidden_name(method_name);
1537 Expression* s = Expression::make_string(n, bloc);
1538 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1541 go_assert(p->is_field_name("pkgPath"));
1542 if (!Gogo::is_hidden_name(method_name))
1543 vals->push_back(Expression::make_nil(bloc));
1546 s = Expression::make_string(Gogo::hidden_name_prefix(method_name), bloc);
1547 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1550 Named_object* no = (m->needs_stub_method()
1552 : m->named_object());
1554 Function_type* mtype;
1555 if (no->is_function())
1556 mtype = no->func_value()->type();
1558 mtype = no->func_declaration_value()->type();
1559 go_assert(mtype->is_method());
1560 Type* nonmethod_type = mtype->copy_without_receiver();
1563 go_assert(p->is_field_name("mtyp"));
1564 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
1567 go_assert(p->is_field_name("typ"));
1568 if (!only_value_methods && m->is_value_method())
1570 // This is a value method on a pointer type. Change the type of
1571 // the method to use a pointer receiver. The implementation
1572 // always uses a pointer receiver anyhow.
1573 Type* rtype = mtype->receiver()->type();
1574 Type* prtype = Type::make_pointer_type(rtype);
1575 Typed_identifier* receiver =
1576 new Typed_identifier(mtype->receiver()->name(), prtype,
1577 mtype->receiver()->location());
1578 mtype = Type::make_function_type(receiver,
1579 (mtype->parameters() == NULL
1581 : mtype->parameters()->copy()),
1582 (mtype->results() == NULL
1584 : mtype->results()->copy()),
1587 vals->push_back(Expression::make_type_descriptor(mtype, bloc));
1590 go_assert(p->is_field_name("tfn"));
1591 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
1594 go_assert(p == fields->end());
1596 return Expression::make_struct_composite_literal(method_type, vals, bloc);
1599 // Return a composite literal for the type descriptor of a plain type.
1600 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
1601 // NULL, it is the name to use as well as the list of methods.
1604 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
1607 return this->type_descriptor_constructor(gogo, runtime_type_kind,
1611 // Return the type reflection string for this type.
1614 Type::reflection(Gogo* gogo) const
1618 // The do_reflection virtual function should set RET to the
1619 // reflection string.
1620 this->do_reflection(gogo, &ret);
1625 // Return a mangled name for the type.
1628 Type::mangled_name(Gogo* gogo) const
1632 // The do_mangled_name virtual function should set RET to the
1633 // mangled name. For a composite type it should append a code for
1634 // the composition and then call do_mangled_name on the components.
1635 this->do_mangled_name(gogo, &ret);
1640 // Default function to export a type.
1643 Type::do_export(Export*) const
1651 Type::import_type(Import* imp)
1653 if (imp->match_c_string("("))
1654 return Function_type::do_import(imp);
1655 else if (imp->match_c_string("*"))
1656 return Pointer_type::do_import(imp);
1657 else if (imp->match_c_string("struct "))
1658 return Struct_type::do_import(imp);
1659 else if (imp->match_c_string("["))
1660 return Array_type::do_import(imp);
1661 else if (imp->match_c_string("map "))
1662 return Map_type::do_import(imp);
1663 else if (imp->match_c_string("chan "))
1664 return Channel_type::do_import(imp);
1665 else if (imp->match_c_string("interface"))
1666 return Interface_type::do_import(imp);
1669 error_at(imp->location(), "import error: expected type");
1670 return Type::make_error_type();
1674 // A type used to indicate a parsing error. This exists to simplify
1675 // later error detection.
1677 class Error_type : public Type
1686 do_get_backend(Gogo* gogo)
1687 { return gogo->backend()->error_type(); }
1690 do_type_descriptor(Gogo*, Named_type*)
1691 { return Expression::make_error(Linemap::predeclared_location()); }
1694 do_reflection(Gogo*, std::string*) const
1695 { go_assert(saw_errors()); }
1698 do_mangled_name(Gogo*, std::string* ret) const
1699 { ret->push_back('E'); }
1703 Type::make_error_type()
1705 static Error_type singleton_error_type;
1706 return &singleton_error_type;
1711 class Void_type : public Type
1720 do_get_backend(Gogo* gogo)
1721 { return gogo->backend()->void_type(); }
1724 do_type_descriptor(Gogo*, Named_type*)
1725 { go_unreachable(); }
1728 do_reflection(Gogo*, std::string*) const
1732 do_mangled_name(Gogo*, std::string* ret) const
1733 { ret->push_back('v'); }
1737 Type::make_void_type()
1739 static Void_type singleton_void_type;
1740 return &singleton_void_type;
1743 // The boolean type.
1745 class Boolean_type : public Type
1749 : Type(TYPE_BOOLEAN)
1754 do_get_backend(Gogo* gogo)
1755 { return gogo->backend()->bool_type(); }
1758 do_type_descriptor(Gogo*, Named_type* name);
1760 // We should not be asked for the reflection string of a basic type.
1762 do_reflection(Gogo*, std::string* ret) const
1763 { ret->append("bool"); }
1766 do_mangled_name(Gogo*, std::string* ret) const
1767 { ret->push_back('b'); }
1770 // Make the type descriptor.
1773 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
1776 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
1779 Named_object* no = gogo->lookup_global("bool");
1780 go_assert(no != NULL);
1781 return Type::type_descriptor(gogo, no->type_value());
1786 Type::make_boolean_type()
1788 static Boolean_type boolean_type;
1789 return &boolean_type;
1792 // The named type "bool".
1794 static Named_type* named_bool_type;
1796 // Get the named type "bool".
1799 Type::lookup_bool_type()
1801 return named_bool_type;
1804 // Make the named type "bool".
1807 Type::make_named_bool_type()
1809 Type* bool_type = Type::make_boolean_type();
1810 Named_object* named_object =
1811 Named_object::make_type("bool", NULL, bool_type,
1812 Linemap::predeclared_location());
1813 Named_type* named_type = named_object->type_value();
1814 named_bool_type = named_type;
1818 // Class Integer_type.
1820 Integer_type::Named_integer_types Integer_type::named_integer_types;
1822 // Create a new integer type. Non-abstract integer types always have
1826 Integer_type::create_integer_type(const char* name, bool is_unsigned,
1827 int bits, int runtime_type_kind)
1829 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
1831 std::string sname(name);
1832 Named_object* named_object =
1833 Named_object::make_type(sname, NULL, integer_type,
1834 Linemap::predeclared_location());
1835 Named_type* named_type = named_object->type_value();
1836 std::pair<Named_integer_types::iterator, bool> ins =
1837 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
1838 go_assert(ins.second);
1842 // Look up an existing integer type.
1845 Integer_type::lookup_integer_type(const char* name)
1847 Named_integer_types::const_iterator p =
1848 Integer_type::named_integer_types.find(name);
1849 go_assert(p != Integer_type::named_integer_types.end());
1853 // Create a new abstract integer type.
1856 Integer_type::create_abstract_integer_type()
1858 static Integer_type* abstract_type;
1859 if (abstract_type == NULL)
1860 abstract_type = new Integer_type(true, false, INT_TYPE_SIZE,
1861 RUNTIME_TYPE_KIND_INT);
1862 return abstract_type;
1865 // Integer type compatibility.
1868 Integer_type::is_identical(const Integer_type* t) const
1870 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
1872 return this->is_abstract_ == t->is_abstract_;
1878 Integer_type::do_hash_for_method(Gogo*) const
1880 return ((this->bits_ << 4)
1881 + ((this->is_unsigned_ ? 1 : 0) << 8)
1882 + ((this->is_abstract_ ? 1 : 0) << 9));
1885 // Convert an Integer_type to the backend representation.
1888 Integer_type::do_get_backend(Gogo* gogo)
1890 if (this->is_abstract_)
1892 go_assert(saw_errors());
1893 return gogo->backend()->error_type();
1895 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
1898 // The type descriptor for an integer type. Integer types are always
1902 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
1904 go_assert(name != NULL);
1905 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
1908 // We should not be asked for the reflection string of a basic type.
1911 Integer_type::do_reflection(Gogo*, std::string*) const
1913 go_assert(saw_errors());
1919 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
1922 snprintf(buf, sizeof buf, "i%s%s%de",
1923 this->is_abstract_ ? "a" : "",
1924 this->is_unsigned_ ? "u" : "",
1929 // Make an integer type.
1932 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
1933 int runtime_type_kind)
1935 return Integer_type::create_integer_type(name, is_unsigned, bits,
1939 // Make an abstract integer type.
1942 Type::make_abstract_integer_type()
1944 return Integer_type::create_abstract_integer_type();
1947 // Look up an integer type.
1950 Type::lookup_integer_type(const char* name)
1952 return Integer_type::lookup_integer_type(name);
1955 // Class Float_type.
1957 Float_type::Named_float_types Float_type::named_float_types;
1959 // Create a new float type. Non-abstract float types always have
1963 Float_type::create_float_type(const char* name, int bits,
1964 int runtime_type_kind)
1966 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
1967 std::string sname(name);
1968 Named_object* named_object =
1969 Named_object::make_type(sname, NULL, float_type,
1970 Linemap::predeclared_location());
1971 Named_type* named_type = named_object->type_value();
1972 std::pair<Named_float_types::iterator, bool> ins =
1973 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
1974 go_assert(ins.second);
1978 // Look up an existing float type.
1981 Float_type::lookup_float_type(const char* name)
1983 Named_float_types::const_iterator p =
1984 Float_type::named_float_types.find(name);
1985 go_assert(p != Float_type::named_float_types.end());
1989 // Create a new abstract float type.
1992 Float_type::create_abstract_float_type()
1994 static Float_type* abstract_type;
1995 if (abstract_type == NULL)
1996 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
1997 return abstract_type;
2000 // Whether this type is identical with T.
2003 Float_type::is_identical(const Float_type* t) const
2005 if (this->bits_ != t->bits_)
2007 return this->is_abstract_ == t->is_abstract_;
2013 Float_type::do_hash_for_method(Gogo*) const
2015 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2018 // Convert to the backend representation.
2021 Float_type::do_get_backend(Gogo* gogo)
2023 return gogo->backend()->float_type(this->bits_);
2026 // The type descriptor for a float type. Float types are always named.
2029 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2031 go_assert(name != NULL);
2032 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2035 // We should not be asked for the reflection string of a basic type.
2038 Float_type::do_reflection(Gogo*, std::string*) const
2040 go_assert(saw_errors());
2046 Float_type::do_mangled_name(Gogo*, std::string* ret) const
2049 snprintf(buf, sizeof buf, "f%s%de",
2050 this->is_abstract_ ? "a" : "",
2055 // Make a floating point type.
2058 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
2060 return Float_type::create_float_type(name, bits, runtime_type_kind);
2063 // Make an abstract float type.
2066 Type::make_abstract_float_type()
2068 return Float_type::create_abstract_float_type();
2071 // Look up a float type.
2074 Type::lookup_float_type(const char* name)
2076 return Float_type::lookup_float_type(name);
2079 // Class Complex_type.
2081 Complex_type::Named_complex_types Complex_type::named_complex_types;
2083 // Create a new complex type. Non-abstract complex types always have
2087 Complex_type::create_complex_type(const char* name, int bits,
2088 int runtime_type_kind)
2090 Complex_type* complex_type = new Complex_type(false, bits,
2092 std::string sname(name);
2093 Named_object* named_object =
2094 Named_object::make_type(sname, NULL, complex_type,
2095 Linemap::predeclared_location());
2096 Named_type* named_type = named_object->type_value();
2097 std::pair<Named_complex_types::iterator, bool> ins =
2098 Complex_type::named_complex_types.insert(std::make_pair(sname,
2100 go_assert(ins.second);
2104 // Look up an existing complex type.
2107 Complex_type::lookup_complex_type(const char* name)
2109 Named_complex_types::const_iterator p =
2110 Complex_type::named_complex_types.find(name);
2111 go_assert(p != Complex_type::named_complex_types.end());
2115 // Create a new abstract complex type.
2118 Complex_type::create_abstract_complex_type()
2120 static Complex_type* abstract_type;
2121 if (abstract_type == NULL)
2122 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
2123 return abstract_type;
2126 // Whether this type is identical with T.
2129 Complex_type::is_identical(const Complex_type *t) const
2131 if (this->bits_ != t->bits_)
2133 return this->is_abstract_ == t->is_abstract_;
2139 Complex_type::do_hash_for_method(Gogo*) const
2141 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2144 // Convert to the backend representation.
2147 Complex_type::do_get_backend(Gogo* gogo)
2149 return gogo->backend()->complex_type(this->bits_);
2152 // The type descriptor for a complex type. Complex types are always
2156 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2158 go_assert(name != NULL);
2159 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2162 // We should not be asked for the reflection string of a basic type.
2165 Complex_type::do_reflection(Gogo*, std::string*) const
2167 go_assert(saw_errors());
2173 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
2176 snprintf(buf, sizeof buf, "c%s%de",
2177 this->is_abstract_ ? "a" : "",
2182 // Make a complex type.
2185 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
2187 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
2190 // Make an abstract complex type.
2193 Type::make_abstract_complex_type()
2195 return Complex_type::create_abstract_complex_type();
2198 // Look up a complex type.
2201 Type::lookup_complex_type(const char* name)
2203 return Complex_type::lookup_complex_type(name);
2206 // Class String_type.
2208 // Convert String_type to the backend representation. A string is a
2209 // struct with two fields: a pointer to the characters and a length.
2212 String_type::do_get_backend(Gogo* gogo)
2214 static Btype* backend_string_type;
2215 if (backend_string_type == NULL)
2217 std::vector<Backend::Btyped_identifier> fields(2);
2219 Type* b = gogo->lookup_global("byte")->type_value();
2220 Type* pb = Type::make_pointer_type(b);
2221 fields[0].name = "__data";
2222 fields[0].btype = pb->get_backend(gogo);
2223 fields[0].location = Linemap::predeclared_location();
2225 Type* int_type = Type::lookup_integer_type("int");
2226 fields[1].name = "__length";
2227 fields[1].btype = int_type->get_backend(gogo);
2228 fields[1].location = fields[0].location;
2230 backend_string_type = gogo->backend()->struct_type(fields);
2232 return backend_string_type;
2235 // Return a tree for the length of STRING.
2238 String_type::length_tree(Gogo*, tree string)
2240 tree string_type = TREE_TYPE(string);
2241 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2242 tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type));
2243 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)),
2245 return fold_build3(COMPONENT_REF, integer_type_node, string,
2246 length_field, NULL_TREE);
2249 // Return a tree for a pointer to the bytes of STRING.
2252 String_type::bytes_tree(Gogo*, tree string)
2254 tree string_type = TREE_TYPE(string);
2255 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2256 tree bytes_field = TYPE_FIELDS(string_type);
2257 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)),
2259 return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string,
2260 bytes_field, NULL_TREE);
2263 // The type descriptor for the string type.
2266 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2269 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
2272 Named_object* no = gogo->lookup_global("string");
2273 go_assert(no != NULL);
2274 return Type::type_descriptor(gogo, no->type_value());
2278 // We should not be asked for the reflection string of a basic type.
2281 String_type::do_reflection(Gogo*, std::string* ret) const
2283 ret->append("string");
2286 // Mangled name of a string type.
2289 String_type::do_mangled_name(Gogo*, std::string* ret) const
2291 ret->push_back('z');
2294 // Make a string type.
2297 Type::make_string_type()
2299 static String_type string_type;
2300 return &string_type;
2303 // The named type "string".
2305 static Named_type* named_string_type;
2307 // Get the named type "string".
2310 Type::lookup_string_type()
2312 return named_string_type;
2315 // Make the named type string.
2318 Type::make_named_string_type()
2320 Type* string_type = Type::make_string_type();
2321 Named_object* named_object =
2322 Named_object::make_type("string", NULL, string_type,
2323 Linemap::predeclared_location());
2324 Named_type* named_type = named_object->type_value();
2325 named_string_type = named_type;
2329 // The sink type. This is the type of the blank identifier _. Any
2330 // type may be assigned to it.
2332 class Sink_type : public Type
2341 do_get_backend(Gogo*)
2342 { go_unreachable(); }
2345 do_type_descriptor(Gogo*, Named_type*)
2346 { go_unreachable(); }
2349 do_reflection(Gogo*, std::string*) const
2350 { go_unreachable(); }
2353 do_mangled_name(Gogo*, std::string*) const
2354 { go_unreachable(); }
2357 // Make the sink type.
2360 Type::make_sink_type()
2362 static Sink_type sink_type;
2366 // Class Function_type.
2371 Function_type::do_traverse(Traverse* traverse)
2373 if (this->receiver_ != NULL
2374 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
2375 return TRAVERSE_EXIT;
2376 if (this->parameters_ != NULL
2377 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
2378 return TRAVERSE_EXIT;
2379 if (this->results_ != NULL
2380 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
2381 return TRAVERSE_EXIT;
2382 return TRAVERSE_CONTINUE;
2385 // Returns whether T is a valid redeclaration of this type. If this
2386 // returns false, and REASON is not NULL, *REASON may be set to a
2387 // brief explanation of why it returned false.
2390 Function_type::is_valid_redeclaration(const Function_type* t,
2391 std::string* reason) const
2393 if (!this->is_identical(t, false, true, reason))
2396 // A redeclaration of a function is required to use the same names
2397 // for the receiver and parameters.
2398 if (this->receiver() != NULL
2399 && this->receiver()->name() != t->receiver()->name()
2400 && this->receiver()->name() != Import::import_marker
2401 && t->receiver()->name() != Import::import_marker)
2404 *reason = "receiver name changed";
2408 const Typed_identifier_list* parms1 = this->parameters();
2409 const Typed_identifier_list* parms2 = t->parameters();
2412 Typed_identifier_list::const_iterator p1 = parms1->begin();
2413 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
2414 p2 != parms2->end();
2417 if (p1->name() != p2->name()
2418 && p1->name() != Import::import_marker
2419 && p2->name() != Import::import_marker)
2422 *reason = "parameter name changed";
2426 // This is called at parse time, so we may have unknown
2428 Type* t1 = p1->type()->forwarded();
2429 Type* t2 = p2->type()->forwarded();
2431 && t1->forward_declaration_type() != NULL
2432 && (t2->forward_declaration_type() == NULL
2433 || (t1->forward_declaration_type()->named_object()
2434 != t2->forward_declaration_type()->named_object())))
2439 const Typed_identifier_list* results1 = this->results();
2440 const Typed_identifier_list* results2 = t->results();
2441 if (results1 != NULL)
2443 Typed_identifier_list::const_iterator res1 = results1->begin();
2444 for (Typed_identifier_list::const_iterator res2 = results2->begin();
2445 res2 != results2->end();
2448 if (res1->name() != res2->name()
2449 && res1->name() != Import::import_marker
2450 && res2->name() != Import::import_marker)
2453 *reason = "result name changed";
2457 // This is called at parse time, so we may have unknown
2459 Type* t1 = res1->type()->forwarded();
2460 Type* t2 = res2->type()->forwarded();
2462 && t1->forward_declaration_type() != NULL
2463 && (t2->forward_declaration_type() == NULL
2464 || (t1->forward_declaration_type()->named_object()
2465 != t2->forward_declaration_type()->named_object())))
2473 // Check whether T is the same as this type.
2476 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
2477 bool errors_are_identical,
2478 std::string* reason) const
2480 if (!ignore_receiver)
2482 const Typed_identifier* r1 = this->receiver();
2483 const Typed_identifier* r2 = t->receiver();
2484 if ((r1 != NULL) != (r2 != NULL))
2487 *reason = _("different receiver types");
2492 if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
2495 if (reason != NULL && !reason->empty())
2496 *reason = "receiver: " + *reason;
2502 const Typed_identifier_list* parms1 = this->parameters();
2503 const Typed_identifier_list* parms2 = t->parameters();
2504 if ((parms1 != NULL) != (parms2 != NULL))
2507 *reason = _("different number of parameters");
2512 Typed_identifier_list::const_iterator p1 = parms1->begin();
2513 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
2514 p2 != parms2->end();
2517 if (p1 == parms1->end())
2520 *reason = _("different number of parameters");
2524 if (!Type::are_identical(p1->type(), p2->type(),
2525 errors_are_identical, NULL))
2528 *reason = _("different parameter types");
2532 if (p1 != parms1->end())
2535 *reason = _("different number of parameters");
2540 if (this->is_varargs() != t->is_varargs())
2543 *reason = _("different varargs");
2547 const Typed_identifier_list* results1 = this->results();
2548 const Typed_identifier_list* results2 = t->results();
2549 if ((results1 != NULL) != (results2 != NULL))
2552 *reason = _("different number of results");
2555 if (results1 != NULL)
2557 Typed_identifier_list::const_iterator res1 = results1->begin();
2558 for (Typed_identifier_list::const_iterator res2 = results2->begin();
2559 res2 != results2->end();
2562 if (res1 == results1->end())
2565 *reason = _("different number of results");
2569 if (!Type::are_identical(res1->type(), res2->type(),
2570 errors_are_identical, NULL))
2573 *reason = _("different result types");
2577 if (res1 != results1->end())
2580 *reason = _("different number of results");
2591 Function_type::do_hash_for_method(Gogo* gogo) const
2593 unsigned int ret = 0;
2594 // We ignore the receiver type for hash codes, because we need to
2595 // get the same hash code for a method in an interface and a method
2596 // declared for a type. The former will not have a receiver.
2597 if (this->parameters_ != NULL)
2600 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
2601 p != this->parameters_->end();
2603 ret += p->type()->hash_for_method(gogo) << shift;
2605 if (this->results_ != NULL)
2608 for (Typed_identifier_list::const_iterator p = this->results_->begin();
2609 p != this->results_->end();
2611 ret += p->type()->hash_for_method(gogo) << shift;
2613 if (this->is_varargs_)
2619 // Get the backend representation for a function type.
2622 Function_type::get_function_backend(Gogo* gogo)
2624 Backend::Btyped_identifier breceiver;
2625 if (this->receiver_ != NULL)
2627 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
2629 // We always pass the address of the receiver parameter, in
2630 // order to make interface calls work with unknown types.
2631 Type* rtype = this->receiver_->type();
2632 if (rtype->points_to() == NULL)
2633 rtype = Type::make_pointer_type(rtype);
2634 breceiver.btype = rtype->get_backend(gogo);
2635 breceiver.location = this->receiver_->location();
2638 std::vector<Backend::Btyped_identifier> bparameters;
2639 if (this->parameters_ != NULL)
2641 bparameters.resize(this->parameters_->size());
2643 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
2644 p != this->parameters_->end();
2647 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
2648 bparameters[i].btype = p->type()->get_backend(gogo);
2649 bparameters[i].location = p->location();
2651 go_assert(i == bparameters.size());
2654 std::vector<Backend::Btyped_identifier> bresults;
2655 if (this->results_ != NULL)
2657 bresults.resize(this->results_->size());
2659 for (Typed_identifier_list::const_iterator p = this->results_->begin();
2660 p != this->results_->end();
2663 bresults[i].name = Gogo::unpack_hidden_name(p->name());
2664 bresults[i].btype = p->type()->get_backend(gogo);
2665 bresults[i].location = p->location();
2667 go_assert(i == bresults.size());
2670 return gogo->backend()->function_type(breceiver, bparameters, bresults,
2674 // A hash table mapping function types to their backend placeholders.
2676 Function_type::Placeholders Function_type::placeholders;
2678 // Get the backend representation for a function type. If we are
2679 // still converting types, and this types has multiple results, return
2680 // a placeholder instead. We do this because for multiple results we
2681 // build a struct, and we need to make sure that all the types in the
2682 // struct are valid before we create the struct.
2685 Function_type::do_get_backend(Gogo* gogo)
2687 if (!gogo->named_types_are_converted()
2688 && this->results_ != NULL
2689 && this->results_->size() > 1)
2691 Btype* placeholder =
2692 gogo->backend()->placeholder_pointer_type("", this->location(), true);
2693 Function_type::placeholders.push_back(std::make_pair(this, placeholder));
2696 return this->get_function_backend(gogo);
2699 // Convert function types after all named types are converted.
2702 Function_type::convert_types(Gogo* gogo)
2704 for (Placeholders::const_iterator p = Function_type::placeholders.begin();
2705 p != Function_type::placeholders.end();
2708 Btype* bt = p->first->get_function_backend(gogo);
2709 if (!gogo->backend()->set_placeholder_function_type(p->second, bt))
2710 go_assert(saw_errors());
2714 // The type of a function type descriptor.
2717 Function_type::make_function_type_descriptor_type()
2722 Type* tdt = Type::make_type_descriptor_type();
2723 Type* ptdt = Type::make_type_descriptor_ptr_type();
2725 Type* bool_type = Type::lookup_bool_type();
2727 Type* slice_type = Type::make_array_type(ptdt, NULL);
2729 Struct_type* s = Type::make_builtin_struct_type(4,
2731 "dotdotdot", bool_type,
2735 ret = Type::make_builtin_named_type("FuncType", s);
2741 // The type descriptor for a function type.
2744 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2746 Location bloc = Linemap::predeclared_location();
2748 Type* ftdt = Function_type::make_function_type_descriptor_type();
2750 const Struct_field_list* fields = ftdt->struct_type()->fields();
2752 Expression_list* vals = new Expression_list();
2755 Struct_field_list::const_iterator p = fields->begin();
2756 go_assert(p->is_field_name("commonType"));
2757 vals->push_back(this->type_descriptor_constructor(gogo,
2758 RUNTIME_TYPE_KIND_FUNC,
2762 go_assert(p->is_field_name("dotdotdot"));
2763 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
2766 go_assert(p->is_field_name("in"));
2767 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
2768 this->parameters()));
2771 go_assert(p->is_field_name("out"));
2772 vals->push_back(this->type_descriptor_params(p->type(), NULL,
2776 go_assert(p == fields->end());
2778 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
2781 // Return a composite literal for the parameters or results of a type
2785 Function_type::type_descriptor_params(Type* params_type,
2786 const Typed_identifier* receiver,
2787 const Typed_identifier_list* params)
2789 Location bloc = Linemap::predeclared_location();
2791 if (receiver == NULL && params == NULL)
2792 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
2794 Expression_list* vals = new Expression_list();
2795 vals->reserve((params == NULL ? 0 : params->size())
2796 + (receiver != NULL ? 1 : 0));
2798 if (receiver != NULL)
2799 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
2803 for (Typed_identifier_list::const_iterator p = params->begin();
2806 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
2809 return Expression::make_slice_composite_literal(params_type, vals, bloc);
2812 // The reflection string.
2815 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
2817 // FIXME: Turn this off until we straighten out the type of the
2818 // struct field used in a go statement which calls a method.
2819 // go_assert(this->receiver_ == NULL);
2821 ret->append("func");
2823 if (this->receiver_ != NULL)
2825 ret->push_back('(');
2826 this->append_reflection(this->receiver_->type(), gogo, ret);
2827 ret->push_back(')');
2830 ret->push_back('(');
2831 const Typed_identifier_list* params = this->parameters();
2834 bool is_varargs = this->is_varargs_;
2835 for (Typed_identifier_list::const_iterator p = params->begin();
2839 if (p != params->begin())
2841 if (!is_varargs || p + 1 != params->end())
2842 this->append_reflection(p->type(), gogo, ret);
2846 this->append_reflection(p->type()->array_type()->element_type(),
2851 ret->push_back(')');
2853 const Typed_identifier_list* results = this->results();
2854 if (results != NULL && !results->empty())
2856 if (results->size() == 1)
2857 ret->push_back(' ');
2860 for (Typed_identifier_list::const_iterator p = results->begin();
2861 p != results->end();
2864 if (p != results->begin())
2866 this->append_reflection(p->type(), gogo, ret);
2868 if (results->size() > 1)
2869 ret->push_back(')');
2876 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
2878 ret->push_back('F');
2880 if (this->receiver_ != NULL)
2882 ret->push_back('m');
2883 this->append_mangled_name(this->receiver_->type(), gogo, ret);
2886 const Typed_identifier_list* params = this->parameters();
2889 ret->push_back('p');
2890 for (Typed_identifier_list::const_iterator p = params->begin();
2893 this->append_mangled_name(p->type(), gogo, ret);
2894 if (this->is_varargs_)
2895 ret->push_back('V');
2896 ret->push_back('e');
2899 const Typed_identifier_list* results = this->results();
2900 if (results != NULL)
2902 ret->push_back('r');
2903 for (Typed_identifier_list::const_iterator p = results->begin();
2904 p != results->end();
2906 this->append_mangled_name(p->type(), gogo, ret);
2907 ret->push_back('e');
2910 ret->push_back('e');
2913 // Export a function type.
2916 Function_type::do_export(Export* exp) const
2918 // We don't write out the receiver. The only function types which
2919 // should have a receiver are the ones associated with explicitly
2920 // defined methods. For those the receiver type is written out by
2921 // Function::export_func.
2923 exp->write_c_string("(");
2925 if (this->parameters_ != NULL)
2927 bool is_varargs = this->is_varargs_;
2928 for (Typed_identifier_list::const_iterator p =
2929 this->parameters_->begin();
2930 p != this->parameters_->end();
2936 exp->write_c_string(", ");
2937 if (!is_varargs || p + 1 != this->parameters_->end())
2938 exp->write_type(p->type());
2941 exp->write_c_string("...");
2942 exp->write_type(p->type()->array_type()->element_type());
2946 exp->write_c_string(")");
2948 const Typed_identifier_list* results = this->results_;
2949 if (results != NULL)
2951 exp->write_c_string(" ");
2952 if (results->size() == 1)
2953 exp->write_type(results->begin()->type());
2957 exp->write_c_string("(");
2958 for (Typed_identifier_list::const_iterator p = results->begin();
2959 p != results->end();
2965 exp->write_c_string(", ");
2966 exp->write_type(p->type());
2968 exp->write_c_string(")");
2973 // Import a function type.
2976 Function_type::do_import(Import* imp)
2978 imp->require_c_string("(");
2979 Typed_identifier_list* parameters;
2980 bool is_varargs = false;
2981 if (imp->peek_char() == ')')
2985 parameters = new Typed_identifier_list();
2988 if (imp->match_c_string("..."))
2994 Type* ptype = imp->read_type();
2996 ptype = Type::make_array_type(ptype, NULL);
2997 parameters->push_back(Typed_identifier(Import::import_marker,
2998 ptype, imp->location()));
2999 if (imp->peek_char() != ',')
3001 go_assert(!is_varargs);
3002 imp->require_c_string(", ");
3005 imp->require_c_string(")");
3007 Typed_identifier_list* results;
3008 if (imp->peek_char() != ' ')
3013 results = new Typed_identifier_list;
3014 if (imp->peek_char() != '(')
3016 Type* rtype = imp->read_type();
3017 results->push_back(Typed_identifier(Import::import_marker, rtype,
3025 Type* rtype = imp->read_type();
3026 results->push_back(Typed_identifier(Import::import_marker,
3027 rtype, imp->location()));
3028 if (imp->peek_char() != ',')
3030 imp->require_c_string(", ");
3032 imp->require_c_string(")");
3036 Function_type* ret = Type::make_function_type(NULL, parameters, results,
3039 ret->set_is_varargs();
3043 // Make a copy of a function type without a receiver.
3046 Function_type::copy_without_receiver() const
3048 go_assert(this->is_method());
3049 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
3052 if (this->is_varargs())
3053 ret->set_is_varargs();
3054 if (this->is_builtin())
3055 ret->set_is_builtin();
3059 // Make a copy of a function type with a receiver.
3062 Function_type::copy_with_receiver(Type* receiver_type) const
3064 go_assert(!this->is_method());
3065 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
3067 return Type::make_function_type(receiver, this->parameters_,
3068 this->results_, this->location_);
3071 // Make a function type.
3074 Type::make_function_type(Typed_identifier* receiver,
3075 Typed_identifier_list* parameters,
3076 Typed_identifier_list* results,
3079 return new Function_type(receiver, parameters, results, location);
3082 // Class Pointer_type.
3087 Pointer_type::do_traverse(Traverse* traverse)
3089 return Type::traverse(this->to_type_, traverse);
3095 Pointer_type::do_hash_for_method(Gogo* gogo) const
3097 return this->to_type_->hash_for_method(gogo) << 4;
3100 // The tree for a pointer type.
3103 Pointer_type::do_get_backend(Gogo* gogo)
3105 Btype* to_btype = this->to_type_->get_backend(gogo);
3106 return gogo->backend()->pointer_type(to_btype);
3109 // The type of a pointer type descriptor.
3112 Pointer_type::make_pointer_type_descriptor_type()
3117 Type* tdt = Type::make_type_descriptor_type();
3118 Type* ptdt = Type::make_type_descriptor_ptr_type();
3120 Struct_type* s = Type::make_builtin_struct_type(2,
3124 ret = Type::make_builtin_named_type("PtrType", s);
3130 // The type descriptor for a pointer type.
3133 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3135 if (this->is_unsafe_pointer_type())
3137 go_assert(name != NULL);
3138 return this->plain_type_descriptor(gogo,
3139 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
3144 Location bloc = Linemap::predeclared_location();
3146 const Methods* methods;
3147 Type* deref = this->points_to();
3148 if (deref->named_type() != NULL)
3149 methods = deref->named_type()->methods();
3150 else if (deref->struct_type() != NULL)
3151 methods = deref->struct_type()->methods();
3155 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
3157 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
3159 Expression_list* vals = new Expression_list();
3162 Struct_field_list::const_iterator p = fields->begin();
3163 go_assert(p->is_field_name("commonType"));
3164 vals->push_back(this->type_descriptor_constructor(gogo,
3165 RUNTIME_TYPE_KIND_PTR,
3166 name, methods, false));
3169 go_assert(p->is_field_name("elem"));
3170 vals->push_back(Expression::make_type_descriptor(deref, bloc));
3172 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
3176 // Reflection string.
3179 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
3181 ret->push_back('*');
3182 this->append_reflection(this->to_type_, gogo, ret);
3188 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3190 ret->push_back('p');
3191 this->append_mangled_name(this->to_type_, gogo, ret);
3197 Pointer_type::do_export(Export* exp) const
3199 exp->write_c_string("*");
3200 if (this->is_unsafe_pointer_type())
3201 exp->write_c_string("any");
3203 exp->write_type(this->to_type_);
3209 Pointer_type::do_import(Import* imp)
3211 imp->require_c_string("*");
3212 if (imp->match_c_string("any"))
3215 return Type::make_pointer_type(Type::make_void_type());
3217 Type* to = imp->read_type();
3218 return Type::make_pointer_type(to);
3221 // Make a pointer type.
3224 Type::make_pointer_type(Type* to_type)
3226 typedef Unordered_map(Type*, Pointer_type*) Hashtable;
3227 static Hashtable pointer_types;
3228 Hashtable::const_iterator p = pointer_types.find(to_type);
3229 if (p != pointer_types.end())
3231 Pointer_type* ret = new Pointer_type(to_type);
3232 pointer_types[to_type] = ret;
3236 // The nil type. We use a special type for nil because it is not the
3237 // same as any other type. In C term nil has type void*, but there is
3238 // no such type in Go.
3240 class Nil_type : public Type
3249 do_get_backend(Gogo* gogo)
3250 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
3253 do_type_descriptor(Gogo*, Named_type*)
3254 { go_unreachable(); }
3257 do_reflection(Gogo*, std::string*) const
3258 { go_unreachable(); }
3261 do_mangled_name(Gogo*, std::string* ret) const
3262 { ret->push_back('n'); }
3265 // Make the nil type.
3268 Type::make_nil_type()
3270 static Nil_type singleton_nil_type;
3271 return &singleton_nil_type;
3274 // The type of a function call which returns multiple values. This is
3275 // really a struct, but we don't want to confuse a function call which
3276 // returns a struct with a function call which returns multiple
3279 class Call_multiple_result_type : public Type
3282 Call_multiple_result_type(Call_expression* call)
3283 : Type(TYPE_CALL_MULTIPLE_RESULT),
3289 do_has_pointer() const
3291 go_assert(saw_errors());
3296 do_get_backend(Gogo* gogo)
3298 go_assert(saw_errors());
3299 return gogo->backend()->error_type();
3303 do_type_descriptor(Gogo*, Named_type*)
3305 go_assert(saw_errors());
3306 return Expression::make_error(Linemap::unknown_location());
3310 do_reflection(Gogo*, std::string*) const
3311 { go_assert(saw_errors()); }
3314 do_mangled_name(Gogo*, std::string*) const
3315 { go_assert(saw_errors()); }
3318 // The expression being called.
3319 Call_expression* call_;
3322 // Make a call result type.
3325 Type::make_call_multiple_result_type(Call_expression* call)
3327 return new Call_multiple_result_type(call);
3330 // Class Struct_field.
3332 // Get the name of a field.
3335 Struct_field::field_name() const
3337 const std::string& name(this->typed_identifier_.name());
3342 // This is called during parsing, before anything is lowered, so
3343 // we have to be pretty careful to avoid dereferencing an
3344 // unknown type name.
3345 Type* t = this->typed_identifier_.type();
3347 if (t->classification() == Type::TYPE_POINTER)
3350 Pointer_type* ptype = static_cast<Pointer_type*>(t);
3351 dt = ptype->points_to();
3353 if (dt->forward_declaration_type() != NULL)
3354 return dt->forward_declaration_type()->name();
3355 else if (dt->named_type() != NULL)
3356 return dt->named_type()->name();
3357 else if (t->is_error_type() || dt->is_error_type())
3359 static const std::string error_string = "*error*";
3360 return error_string;
3364 // Avoid crashing in the erroneous case where T is named but
3367 if (t->forward_declaration_type() != NULL)
3368 return t->forward_declaration_type()->name();
3369 else if (t->named_type() != NULL)
3370 return t->named_type()->name();
3377 // Return whether this field is named NAME.
3380 Struct_field::is_field_name(const std::string& name) const
3382 const std::string& me(this->typed_identifier_.name());
3387 Type* t = this->typed_identifier_.type();
3388 if (t->points_to() != NULL)
3390 Named_type* nt = t->named_type();
3391 if (nt != NULL && nt->name() == name)
3394 // This is a horrible hack caused by the fact that we don't pack
3395 // the names of builtin types. FIXME.
3398 && nt->name() == Gogo::unpack_hidden_name(name))
3405 // Class Struct_type.
3410 Struct_type::do_traverse(Traverse* traverse)
3412 Struct_field_list* fields = this->fields_;
3415 for (Struct_field_list::iterator p = fields->begin();
3419 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
3420 return TRAVERSE_EXIT;
3423 return TRAVERSE_CONTINUE;
3426 // Verify that the struct type is complete and valid.
3429 Struct_type::do_verify()
3431 Struct_field_list* fields = this->fields_;
3435 for (Struct_field_list::iterator p = fields->begin();
3439 Type* t = p->type();
3440 if (t->is_undefined())
3442 error_at(p->location(), "struct field type is incomplete");
3443 p->set_type(Type::make_error_type());
3446 else if (p->is_anonymous())
3448 if (t->named_type() != NULL && t->points_to() != NULL)
3450 error_at(p->location(), "embedded type may not be a pointer");
3451 p->set_type(Type::make_error_type());
3454 if (t->points_to() != NULL
3455 && t->points_to()->interface_type() != NULL)
3457 error_at(p->location(),
3458 "embedded type may not be pointer to interface");
3459 p->set_type(Type::make_error_type());
3467 // Whether this contains a pointer.
3470 Struct_type::do_has_pointer() const
3472 const Struct_field_list* fields = this->fields();
3475 for (Struct_field_list::const_iterator p = fields->begin();
3479 if (p->type()->has_pointer())
3485 // Whether this type is identical to T.
3488 Struct_type::is_identical(const Struct_type* t,
3489 bool errors_are_identical) const
3491 const Struct_field_list* fields1 = this->fields();
3492 const Struct_field_list* fields2 = t->fields();
3493 if (fields1 == NULL || fields2 == NULL)
3494 return fields1 == fields2;
3495 Struct_field_list::const_iterator pf2 = fields2->begin();
3496 for (Struct_field_list::const_iterator pf1 = fields1->begin();
3497 pf1 != fields1->end();
3500 if (pf2 == fields2->end())
3502 if (pf1->field_name() != pf2->field_name())
3504 if (pf1->is_anonymous() != pf2->is_anonymous()
3505 || !Type::are_identical(pf1->type(), pf2->type(),
3506 errors_are_identical, NULL))
3508 if (!pf1->has_tag())
3515 if (!pf2->has_tag())
3517 if (pf1->tag() != pf2->tag())
3521 if (pf2 != fields2->end())
3526 // Whether this struct type has any hidden fields.
3529 Struct_type::struct_has_hidden_fields(const Named_type* within,
3530 std::string* reason) const
3532 const Struct_field_list* fields = this->fields();
3535 const Package* within_package = (within == NULL
3537 : within->named_object()->package());
3538 for (Struct_field_list::const_iterator pf = fields->begin();
3539 pf != fields->end();
3542 if (within_package != NULL
3543 && !pf->is_anonymous()
3544 && Gogo::is_hidden_name(pf->field_name()))
3548 std::string within_name = within->named_object()->message_name();
3549 std::string name = Gogo::message_name(pf->field_name());
3550 size_t bufsize = 200 + within_name.length() + name.length();
3551 char* buf = new char[bufsize];
3552 snprintf(buf, bufsize,
3553 _("implicit assignment of %s%s%s hidden field %s%s%s"),
3554 open_quote, within_name.c_str(), close_quote,
3555 open_quote, name.c_str(), close_quote);
3556 reason->assign(buf);
3562 if (pf->type()->has_hidden_fields(within, reason))
3572 Struct_type::do_hash_for_method(Gogo* gogo) const
3574 unsigned int ret = 0;
3575 if (this->fields() != NULL)
3577 for (Struct_field_list::const_iterator pf = this->fields()->begin();
3578 pf != this->fields()->end();
3580 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
3585 // Find the local field NAME.
3588 Struct_type::find_local_field(const std::string& name,
3589 unsigned int *pindex) const
3591 const Struct_field_list* fields = this->fields_;
3595 for (Struct_field_list::const_iterator pf = fields->begin();
3596 pf != fields->end();
3599 if (pf->is_field_name(name))
3609 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
3611 Field_reference_expression*
3612 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
3613 Location location) const
3616 return this->field_reference_depth(struct_expr, name, location, NULL,
3620 // Return an expression for a field, along with the depth at which it
3623 Field_reference_expression*
3624 Struct_type::field_reference_depth(Expression* struct_expr,
3625 const std::string& name,
3627 Saw_named_type* saw,
3628 unsigned int* depth) const
3630 const Struct_field_list* fields = this->fields_;
3634 // Look for a field with this name.
3636 for (Struct_field_list::const_iterator pf = fields->begin();
3637 pf != fields->end();
3640 if (pf->is_field_name(name))
3643 return Expression::make_field_reference(struct_expr, i, location);
3647 // Look for an anonymous field which contains a field with this
3649 unsigned int found_depth = 0;
3650 Field_reference_expression* ret = NULL;
3652 for (Struct_field_list::const_iterator pf = fields->begin();
3653 pf != fields->end();
3656 if (!pf->is_anonymous())
3659 Struct_type* st = pf->type()->deref()->struct_type();
3663 Saw_named_type* hold_saw = saw;
3664 Saw_named_type saw_here;
3665 Named_type* nt = pf->type()->named_type();
3667 nt = pf->type()->deref()->named_type();
3671 for (q = saw; q != NULL; q = q->next)
3675 // If this is an error, it will be reported
3682 saw_here.next = saw;
3687 // Look for a reference using a NULL struct expression. If we
3688 // find one, fill in the struct expression with a reference to
3690 unsigned int subdepth;
3691 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
3701 if (ret == NULL || subdepth < found_depth)
3706 found_depth = subdepth;
3707 Expression* here = Expression::make_field_reference(struct_expr, i,
3709 if (pf->type()->points_to() != NULL)
3710 here = Expression::make_unary(OPERATOR_MULT, here, location);
3711 while (sub->expr() != NULL)
3713 sub = sub->expr()->deref()->field_reference_expression();
3714 go_assert(sub != NULL);
3716 sub->set_struct_expression(here);
3718 else if (subdepth > found_depth)
3722 // We do not handle ambiguity here--it should be handled by
3723 // Type::bind_field_or_method.
3731 *depth = found_depth + 1;
3736 // Return the total number of fields, including embedded fields.
3739 Struct_type::total_field_count() const
3741 if (this->fields_ == NULL)
3743 unsigned int ret = 0;
3744 for (Struct_field_list::const_iterator pf = this->fields_->begin();
3745 pf != this->fields_->end();
3748 if (!pf->is_anonymous() || pf->type()->deref()->struct_type() == NULL)
3751 ret += pf->type()->struct_type()->total_field_count();
3756 // Return whether NAME is an unexported field, for better error reporting.
3759 Struct_type::is_unexported_local_field(Gogo* gogo,
3760 const std::string& name) const
3762 const Struct_field_list* fields = this->fields_;
3765 for (Struct_field_list::const_iterator pf = fields->begin();
3766 pf != fields->end();
3769 const std::string& field_name(pf->field_name());
3770 if (Gogo::is_hidden_name(field_name)
3771 && name == Gogo::unpack_hidden_name(field_name)
3772 && gogo->pack_hidden_name(name, false) != field_name)
3779 // Finalize the methods of an unnamed struct.
3782 Struct_type::finalize_methods(Gogo* gogo)
3784 if (this->all_methods_ != NULL)
3786 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
3789 // Return the method NAME, or NULL if there isn't one or if it is
3790 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
3794 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
3796 return Type::method_function(this->all_methods_, name, is_ambiguous);
3799 // Convert struct fields to the backend representation. This is not
3800 // declared in types.h so that types.h doesn't have to #include
3804 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
3805 std::vector<Backend::Btyped_identifier>* bfields)
3807 bfields->resize(fields->size());
3809 for (Struct_field_list::const_iterator p = fields->begin();
3813 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
3814 (*bfields)[i].btype = p->type()->get_backend(gogo);
3815 (*bfields)[i].location = p->location();
3817 go_assert(i == fields->size());
3820 // Get the tree for a struct type.
3823 Struct_type::do_get_backend(Gogo* gogo)
3825 std::vector<Backend::Btyped_identifier> bfields;
3826 get_backend_struct_fields(gogo, this->fields_, &bfields);
3827 return gogo->backend()->struct_type(bfields);
3830 // The type of a struct type descriptor.
3833 Struct_type::make_struct_type_descriptor_type()
3838 Type* tdt = Type::make_type_descriptor_type();
3839 Type* ptdt = Type::make_type_descriptor_ptr_type();
3841 Type* uintptr_type = Type::lookup_integer_type("uintptr");
3842 Type* string_type = Type::lookup_string_type();
3843 Type* pointer_string_type = Type::make_pointer_type(string_type);
3846 Type::make_builtin_struct_type(5,
3847 "name", pointer_string_type,
3848 "pkgPath", pointer_string_type,
3850 "tag", pointer_string_type,
3851 "offset", uintptr_type);
3852 Type* nsf = Type::make_builtin_named_type("structField", sf);
3854 Type* slice_type = Type::make_array_type(nsf, NULL);
3856 Struct_type* s = Type::make_builtin_struct_type(2,
3858 "fields", slice_type);
3860 ret = Type::make_builtin_named_type("StructType", s);
3866 // Build a type descriptor for a struct type.
3869 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3871 Location bloc = Linemap::predeclared_location();
3873 Type* stdt = Struct_type::make_struct_type_descriptor_type();
3875 const Struct_field_list* fields = stdt->struct_type()->fields();
3877 Expression_list* vals = new Expression_list();
3880 const Methods* methods = this->methods();
3881 // A named struct should not have methods--the methods should attach
3882 // to the named type.
3883 go_assert(methods == NULL || name == NULL);
3885 Struct_field_list::const_iterator ps = fields->begin();
3886 go_assert(ps->is_field_name("commonType"));
3887 vals->push_back(this->type_descriptor_constructor(gogo,
3888 RUNTIME_TYPE_KIND_STRUCT,
3889 name, methods, true));
3892 go_assert(ps->is_field_name("fields"));
3894 Expression_list* elements = new Expression_list();
3895 elements->reserve(this->fields_->size());
3896 Type* element_type = ps->type()->array_type()->element_type();
3897 for (Struct_field_list::const_iterator pf = this->fields_->begin();
3898 pf != this->fields_->end();
3901 const Struct_field_list* f = element_type->struct_type()->fields();
3903 Expression_list* fvals = new Expression_list();
3906 Struct_field_list::const_iterator q = f->begin();
3907 go_assert(q->is_field_name("name"));
3908 if (pf->is_anonymous())
3909 fvals->push_back(Expression::make_nil(bloc));
3912 std::string n = Gogo::unpack_hidden_name(pf->field_name());
3913 Expression* s = Expression::make_string(n, bloc);
3914 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3918 go_assert(q->is_field_name("pkgPath"));
3919 if (!Gogo::is_hidden_name(pf->field_name()))
3920 fvals->push_back(Expression::make_nil(bloc));
3923 std::string n = Gogo::hidden_name_prefix(pf->field_name());
3924 Expression* s = Expression::make_string(n, bloc);
3925 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3929 go_assert(q->is_field_name("typ"));
3930 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
3933 go_assert(q->is_field_name("tag"));
3935 fvals->push_back(Expression::make_nil(bloc));
3938 Expression* s = Expression::make_string(pf->tag(), bloc);
3939 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3943 go_assert(q->is_field_name("offset"));
3944 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
3946 Expression* v = Expression::make_struct_composite_literal(element_type,
3948 elements->push_back(v);
3951 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
3954 return Expression::make_struct_composite_literal(stdt, vals, bloc);
3957 // Reflection string.
3960 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
3962 ret->append("struct { ");
3964 for (Struct_field_list::const_iterator p = this->fields_->begin();
3965 p != this->fields_->end();
3968 if (p != this->fields_->begin())
3970 if (p->is_anonymous())
3971 ret->push_back('?');
3973 ret->append(Gogo::unpack_hidden_name(p->field_name()));
3974 ret->push_back(' ');
3975 this->append_reflection(p->type(), gogo, ret);
3979 const std::string& tag(p->tag());
3981 for (std::string::const_iterator p = tag.begin();
3986 ret->append("\\x00");
3987 else if (*p == '\n')
3989 else if (*p == '\t')
3992 ret->append("\\\"");
3993 else if (*p == '\\')
3994 ret->append("\\\\");
3998 ret->push_back('"');
4008 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4010 ret->push_back('S');
4012 const Struct_field_list* fields = this->fields_;
4015 for (Struct_field_list::const_iterator p = fields->begin();
4019 if (p->is_anonymous())
4023 std::string n = Gogo::unpack_hidden_name(p->field_name());
4025 snprintf(buf, sizeof buf, "%u_",
4026 static_cast<unsigned int>(n.length()));
4030 this->append_mangled_name(p->type(), gogo, ret);
4033 const std::string& tag(p->tag());
4035 for (std::string::const_iterator p = tag.begin();
4039 if (ISALNUM(*p) || *p == '_')
4044 snprintf(buf, sizeof buf, ".%x.",
4045 static_cast<unsigned int>(*p));
4050 snprintf(buf, sizeof buf, "T%u_",
4051 static_cast<unsigned int>(out.length()));
4058 ret->push_back('e');
4064 Struct_type::do_export(Export* exp) const
4066 exp->write_c_string("struct { ");
4067 const Struct_field_list* fields = this->fields_;
4068 go_assert(fields != NULL);
4069 for (Struct_field_list::const_iterator p = fields->begin();
4073 if (p->is_anonymous())
4074 exp->write_string("? ");
4077 exp->write_string(p->field_name());
4078 exp->write_c_string(" ");
4080 exp->write_type(p->type());
4084 exp->write_c_string(" ");
4086 Expression::make_string(p->tag(), Linemap::predeclared_location());
4087 expr->export_expression(exp);
4091 exp->write_c_string("; ");
4093 exp->write_c_string("}");
4099 Struct_type::do_import(Import* imp)
4101 imp->require_c_string("struct { ");
4102 Struct_field_list* fields = new Struct_field_list;
4103 if (imp->peek_char() != '}')
4108 if (imp->match_c_string("? "))
4112 name = imp->read_identifier();
4113 imp->require_c_string(" ");
4115 Type* ftype = imp->read_type();
4117 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
4119 if (imp->peek_char() == ' ')
4122 Expression* expr = Expression::import_expression(imp);
4123 String_expression* sexpr = expr->string_expression();
4124 go_assert(sexpr != NULL);
4125 sf.set_tag(sexpr->val());
4129 imp->require_c_string("; ");
4130 fields->push_back(sf);
4131 if (imp->peek_char() == '}')
4135 imp->require_c_string("}");
4137 return Type::make_struct_type(fields, imp->location());
4140 // Make a struct type.
4143 Type::make_struct_type(Struct_field_list* fields,
4146 return new Struct_type(fields, location);
4149 // Class Array_type.
4151 // Whether two array types are identical.
4154 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
4156 if (!Type::are_identical(this->element_type(), t->element_type(),
4157 errors_are_identical, NULL))
4160 Expression* l1 = this->length();
4161 Expression* l2 = t->length();
4163 // Slices of the same element type are identical.
4164 if (l1 == NULL && l2 == NULL)
4167 // Arrays of the same element type are identical if they have the
4169 if (l1 != NULL && l2 != NULL)
4174 // Try to determine the lengths. If we can't, assume the arrays
4175 // are not identical.
4183 if (l1->integer_constant_value(true, v1, &type1)
4184 && l2->integer_constant_value(true, v2, &type2))
4185 ret = mpz_cmp(v1, v2) == 0;
4191 // Otherwise the arrays are not identical.
4198 Array_type::do_traverse(Traverse* traverse)
4200 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
4201 return TRAVERSE_EXIT;
4202 if (this->length_ != NULL
4203 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
4204 return TRAVERSE_EXIT;
4205 return TRAVERSE_CONTINUE;
4208 // Check that the length is valid.
4211 Array_type::verify_length()
4213 if (this->length_ == NULL)
4216 Type_context context(Type::lookup_integer_type("int"), false);
4217 this->length_->determine_type(&context);
4219 if (!this->length_->is_constant())
4221 error_at(this->length_->location(), "array bound is not constant");
4228 if (!this->length_->integer_constant_value(true, val, &vt))
4232 if (!this->length_->float_constant_value(fval, &vt))
4234 if (this->length_->type()->integer_type() != NULL
4235 || this->length_->type()->float_type() != NULL)
4236 error_at(this->length_->location(),
4237 "array bound is not constant");
4239 error_at(this->length_->location(),
4240 "array bound is not numeric");
4245 if (!mpfr_integer_p(fval))
4247 error_at(this->length_->location(),
4248 "array bound truncated to integer");
4254 mpfr_get_z(val, fval, GMP_RNDN);
4258 if (mpz_sgn(val) < 0)
4260 error_at(this->length_->location(), "negative array bound");
4265 Type* int_type = Type::lookup_integer_type("int");
4266 int tbits = int_type->integer_type()->bits();
4267 int vbits = mpz_sizeinbase(val, 2);
4268 if (vbits + 1 > tbits)
4270 error_at(this->length_->location(), "array bound overflows");
4283 Array_type::do_verify()
4285 if (!this->verify_length())
4287 this->length_ = Expression::make_error(this->length_->location());
4293 // Array type hash code.
4296 Array_type::do_hash_for_method(Gogo* gogo) const
4298 // There is no very convenient way to get a hash code for the
4300 return this->element_type_->hash_for_method(gogo) + 1;
4303 // Get a tree for the length of a fixed array. The length may be
4304 // computed using a function call, so we must only evaluate it once.
4307 Array_type::get_length_tree(Gogo* gogo)
4309 go_assert(this->length_ != NULL);
4310 if (this->length_tree_ == NULL_TREE)
4315 if (this->length_->integer_constant_value(true, val, &t))
4318 t = Type::lookup_integer_type("int");
4319 else if (t->is_abstract())
4320 t = t->make_non_abstract_type();
4321 tree tt = type_to_tree(t->get_backend(gogo));
4322 this->length_tree_ = Expression::integer_constant_tree(val, tt);
4329 // Make up a translation context for the array length
4330 // expression. FIXME: This won't work in general.
4331 Translate_context context(gogo, NULL, NULL, NULL);
4332 tree len = this->length_->get_tree(&context);
4333 if (len != error_mark_node)
4335 len = convert_to_integer(integer_type_node, len);
4336 len = save_expr(len);
4338 this->length_tree_ = len;
4341 return this->length_tree_;
4344 // Get the backend representation of the fields of a slice. This is
4345 // not declared in types.h so that types.h doesn't have to #include
4348 // We use int for the count and capacity fields. This matches 6g.
4349 // The language more or less assumes that we can't allocate space of a
4350 // size which does not fit in int.
4353 get_backend_slice_fields(Gogo* gogo, Array_type* type,
4354 std::vector<Backend::Btyped_identifier>* bfields)
4358 Type* pet = Type::make_pointer_type(type->element_type());
4359 Btype* pbet = pet->get_backend(gogo);
4360 Location ploc = Linemap::predeclared_location();
4362 Backend::Btyped_identifier* p = &(*bfields)[0];
4363 p->name = "__values";
4367 Type* int_type = Type::lookup_integer_type("int");
4370 p->name = "__count";
4371 p->btype = int_type->get_backend(gogo);
4375 p->name = "__capacity";
4376 p->btype = int_type->get_backend(gogo);
4380 // Get a tree for the type of this array. A fixed array is simply
4381 // represented as ARRAY_TYPE with the appropriate index--i.e., it is
4382 // just like an array in C. An open array is a struct with three
4383 // fields: a data pointer, the length, and the capacity.
4386 Array_type::do_get_backend(Gogo* gogo)
4388 if (this->length_ == NULL)
4390 std::vector<Backend::Btyped_identifier> bfields;
4391 get_backend_slice_fields(gogo, this, &bfields);
4392 return gogo->backend()->struct_type(bfields);
4396 Btype* element = this->get_backend_element(gogo);
4397 Bexpression* len = this->get_backend_length(gogo);
4398 return gogo->backend()->array_type(element, len);
4402 // Return the backend representation of the element type.
4404 Array_type::get_backend_element(Gogo* gogo)
4406 return this->element_type_->get_backend(gogo);
4409 // Return the backend representation of the length.
4412 Array_type::get_backend_length(Gogo* gogo)
4414 return tree_to_expr(this->get_length_tree(gogo));
4417 // Return a tree for a pointer to the values in ARRAY.
4420 Array_type::value_pointer_tree(Gogo*, tree array) const
4423 if (this->length() != NULL)
4426 ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))),
4427 build_fold_addr_expr(array));
4432 tree field = TYPE_FIELDS(TREE_TYPE(array));
4433 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
4435 ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field,
4438 if (TREE_CONSTANT(array))
4439 TREE_CONSTANT(ret) = 1;
4443 // Return a tree for the length of the array ARRAY which has this
4447 Array_type::length_tree(Gogo* gogo, tree array)
4449 if (this->length_ != NULL)
4451 if (TREE_CODE(array) == SAVE_EXPR)
4452 return fold_convert(integer_type_node, this->get_length_tree(gogo));
4454 return omit_one_operand(integer_type_node,
4455 this->get_length_tree(gogo), array);
4458 // This is an open array. We need to read the length field.
4460 tree type = TREE_TYPE(array);
4461 go_assert(TREE_CODE(type) == RECORD_TYPE);
4463 tree field = DECL_CHAIN(TYPE_FIELDS(type));
4464 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
4466 tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
4467 if (TREE_CONSTANT(array))
4468 TREE_CONSTANT(ret) = 1;
4472 // Return a tree for the capacity of the array ARRAY which has this
4476 Array_type::capacity_tree(Gogo* gogo, tree array)
4478 if (this->length_ != NULL)
4479 return omit_one_operand(sizetype, this->get_length_tree(gogo), array);
4481 // This is an open array. We need to read the capacity field.
4483 tree type = TREE_TYPE(array);
4484 go_assert(TREE_CODE(type) == RECORD_TYPE);
4486 tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type)));
4487 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
4489 return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
4495 Array_type::do_export(Export* exp) const
4497 exp->write_c_string("[");
4498 if (this->length_ != NULL)
4499 this->length_->export_expression(exp);
4500 exp->write_c_string("] ");
4501 exp->write_type(this->element_type_);
4507 Array_type::do_import(Import* imp)
4509 imp->require_c_string("[");
4511 if (imp->peek_char() == ']')
4514 length = Expression::import_expression(imp);
4515 imp->require_c_string("] ");
4516 Type* element_type = imp->read_type();
4517 return Type::make_array_type(element_type, length);
4520 // The type of an array type descriptor.
4523 Array_type::make_array_type_descriptor_type()
4528 Type* tdt = Type::make_type_descriptor_type();
4529 Type* ptdt = Type::make_type_descriptor_ptr_type();
4531 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4534 Type::make_builtin_struct_type(4,
4538 "len", uintptr_type);
4540 ret = Type::make_builtin_named_type("ArrayType", sf);
4546 // The type of an slice type descriptor.
4549 Array_type::make_slice_type_descriptor_type()
4554 Type* tdt = Type::make_type_descriptor_type();
4555 Type* ptdt = Type::make_type_descriptor_ptr_type();
4558 Type::make_builtin_struct_type(2,
4562 ret = Type::make_builtin_named_type("SliceType", sf);
4568 // Build a type descriptor for an array/slice type.
4571 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4573 if (this->length_ != NULL)
4574 return this->array_type_descriptor(gogo, name);
4576 return this->slice_type_descriptor(gogo, name);
4579 // Build a type descriptor for an array type.
4582 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
4584 Location bloc = Linemap::predeclared_location();
4586 Type* atdt = Array_type::make_array_type_descriptor_type();
4588 const Struct_field_list* fields = atdt->struct_type()->fields();
4590 Expression_list* vals = new Expression_list();
4593 Struct_field_list::const_iterator p = fields->begin();
4594 go_assert(p->is_field_name("commonType"));
4595 vals->push_back(this->type_descriptor_constructor(gogo,
4596 RUNTIME_TYPE_KIND_ARRAY,
4600 go_assert(p->is_field_name("elem"));
4601 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
4604 go_assert(p->is_field_name("slice"));
4605 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
4606 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
4609 go_assert(p->is_field_name("len"));
4610 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
4613 go_assert(p == fields->end());
4615 return Expression::make_struct_composite_literal(atdt, vals, bloc);
4618 // Build a type descriptor for a slice type.
4621 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
4623 Location bloc = Linemap::predeclared_location();
4625 Type* stdt = Array_type::make_slice_type_descriptor_type();
4627 const Struct_field_list* fields = stdt->struct_type()->fields();
4629 Expression_list* vals = new Expression_list();
4632 Struct_field_list::const_iterator p = fields->begin();
4633 go_assert(p->is_field_name("commonType"));
4634 vals->push_back(this->type_descriptor_constructor(gogo,
4635 RUNTIME_TYPE_KIND_SLICE,
4639 go_assert(p->is_field_name("elem"));
4640 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
4643 go_assert(p == fields->end());
4645 return Expression::make_struct_composite_literal(stdt, vals, bloc);
4648 // Reflection string.
4651 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
4653 ret->push_back('[');
4654 if (this->length_ != NULL)
4659 if (!this->length_->integer_constant_value(true, val, &type))
4660 error_at(this->length_->location(),
4661 "array length must be integer constant expression");
4662 else if (mpz_cmp_si(val, 0) < 0)
4663 error_at(this->length_->location(), "array length is negative");
4664 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
4665 error_at(this->length_->location(), "array length is too large");
4669 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
4674 ret->push_back(']');
4676 this->append_reflection(this->element_type_, gogo, ret);
4682 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4684 ret->push_back('A');
4685 this->append_mangled_name(this->element_type_, gogo, ret);
4686 if (this->length_ != NULL)
4691 if (!this->length_->integer_constant_value(true, val, &type))
4692 error_at(this->length_->location(),
4693 "array length must be integer constant expression");
4694 else if (mpz_cmp_si(val, 0) < 0)
4695 error_at(this->length_->location(), "array length is negative");
4696 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
4697 error_at(this->length_->location(), "array size is too large");
4701 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
4706 ret->push_back('e');
4709 // Make an array type.
4712 Type::make_array_type(Type* element_type, Expression* length)
4714 return new Array_type(element_type, length);
4722 Map_type::do_traverse(Traverse* traverse)
4724 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
4725 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
4726 return TRAVERSE_EXIT;
4727 return TRAVERSE_CONTINUE;
4730 // Check that the map type is OK.
4733 Map_type::do_verify()
4735 if (this->key_type_->struct_type() != NULL
4736 || this->key_type_->array_type() != NULL)
4738 error_at(this->location_, "invalid map key type");
4744 // Whether two map types are identical.
4747 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
4749 return (Type::are_identical(this->key_type(), t->key_type(),
4750 errors_are_identical, NULL)
4751 && Type::are_identical(this->val_type(), t->val_type(),
4752 errors_are_identical, NULL));
4758 Map_type::do_hash_for_method(Gogo* gogo) const
4760 return (this->key_type_->hash_for_method(gogo)
4761 + this->val_type_->hash_for_method(gogo)
4765 // Get the backend representation for a map type. A map type is
4766 // represented as a pointer to a struct. The struct is __go_map in
4770 Map_type::do_get_backend(Gogo* gogo)
4772 static Btype* backend_map_type;
4773 if (backend_map_type == NULL)
4775 std::vector<Backend::Btyped_identifier> bfields(4);
4777 Location bloc = Linemap::predeclared_location();
4779 Type* pdt = Type::make_type_descriptor_ptr_type();
4780 bfields[0].name = "__descriptor";
4781 bfields[0].btype = pdt->get_backend(gogo);
4782 bfields[0].location = bloc;
4784 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4785 bfields[1].name = "__element_count";
4786 bfields[1].btype = uintptr_type->get_backend(gogo);
4787 bfields[1].location = bloc;
4789 bfields[2].name = "__bucket_count";
4790 bfields[2].btype = bfields[1].btype;
4791 bfields[2].location = bloc;
4793 Btype* bvt = gogo->backend()->void_type();
4794 Btype* bpvt = gogo->backend()->pointer_type(bvt);
4795 Btype* bppvt = gogo->backend()->pointer_type(bpvt);
4796 bfields[3].name = "__buckets";
4797 bfields[3].btype = bppvt;
4798 bfields[3].location = bloc;
4800 Btype *bt = gogo->backend()->struct_type(bfields);
4801 bt = gogo->backend()->named_type("__go_map", bt, bloc);
4802 backend_map_type = gogo->backend()->pointer_type(bt);
4804 return backend_map_type;
4807 // The type of a map type descriptor.
4810 Map_type::make_map_type_descriptor_type()
4815 Type* tdt = Type::make_type_descriptor_type();
4816 Type* ptdt = Type::make_type_descriptor_ptr_type();
4819 Type::make_builtin_struct_type(3,
4824 ret = Type::make_builtin_named_type("MapType", sf);
4830 // Build a type descriptor for a map type.
4833 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4835 Location bloc = Linemap::predeclared_location();
4837 Type* mtdt = Map_type::make_map_type_descriptor_type();
4839 const Struct_field_list* fields = mtdt->struct_type()->fields();
4841 Expression_list* vals = new Expression_list();
4844 Struct_field_list::const_iterator p = fields->begin();
4845 go_assert(p->is_field_name("commonType"));
4846 vals->push_back(this->type_descriptor_constructor(gogo,
4847 RUNTIME_TYPE_KIND_MAP,
4851 go_assert(p->is_field_name("key"));
4852 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
4855 go_assert(p->is_field_name("elem"));
4856 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
4859 go_assert(p == fields->end());
4861 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
4864 // A mapping from map types to map descriptors.
4866 Map_type::Map_descriptors Map_type::map_descriptors;
4868 // Build a map descriptor for this type. Return a pointer to it.
4871 Map_type::map_descriptor_pointer(Gogo* gogo, Location location)
4873 Bvariable* bvar = this->map_descriptor(gogo);
4874 tree var_tree = var_to_tree(bvar);
4875 if (var_tree == error_mark_node)
4876 return error_mark_node;
4877 return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
4880 // Build a map descriptor for this type.
4883 Map_type::map_descriptor(Gogo* gogo)
4885 std::pair<Map_type*, Bvariable*> val(this, NULL);
4886 std::pair<Map_type::Map_descriptors::iterator, bool> ins =
4887 Map_type::map_descriptors.insert(val);
4889 return ins.first->second;
4891 Type* key_type = this->key_type_;
4892 Type* val_type = this->val_type_;
4894 // The map entry type is a struct with three fields. Build that
4895 // struct so that we can get the offsets of the key and value within
4896 // a map entry. The first field should technically be a pointer to
4897 // this type itself, but since we only care about field offsets we
4898 // just use pointer to bool.
4899 Type* pbool = Type::make_pointer_type(Type::make_boolean_type());
4900 Struct_type* map_entry_type =
4901 Type::make_builtin_struct_type(3,
4906 Type* map_descriptor_type = Map_type::make_map_descriptor_type();
4908 const Struct_field_list* fields =
4909 map_descriptor_type->struct_type()->fields();
4911 Expression_list* vals = new Expression_list();
4914 Location bloc = Linemap::predeclared_location();
4916 Struct_field_list::const_iterator p = fields->begin();
4918 go_assert(p->is_field_name("__map_descriptor"));
4919 vals->push_back(Expression::make_type_descriptor(this, bloc));
4922 go_assert(p->is_field_name("__entry_size"));
4923 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
4924 vals->push_back(Expression::make_type_info(map_entry_type, type_info));
4926 Struct_field_list::const_iterator pf = map_entry_type->fields()->begin();
4928 go_assert(pf->is_field_name("__key"));
4931 go_assert(p->is_field_name("__key_offset"));
4932 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
4935 go_assert(pf->is_field_name("__val"));
4938 go_assert(p->is_field_name("__val_offset"));
4939 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
4942 go_assert(p == fields->end());
4944 Expression* initializer =
4945 Expression::make_struct_composite_literal(map_descriptor_type, vals, bloc);
4947 std::string mangled_name = "__go_map_" + this->mangled_name(gogo);
4948 Btype* map_descriptor_btype = map_descriptor_type->get_backend(gogo);
4949 Bvariable* bvar = gogo->backend()->immutable_struct(mangled_name, true,
4950 map_descriptor_btype,
4953 Translate_context context(gogo, NULL, NULL, NULL);
4954 context.set_is_const();
4955 Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
4957 gogo->backend()->immutable_struct_set_init(bvar, mangled_name, true,
4958 map_descriptor_btype, bloc,
4961 ins.first->second = bvar;
4965 // Build the type of a map descriptor. This must match the struct
4966 // __go_map_descriptor in libgo/runtime/map.h.
4969 Map_type::make_map_descriptor_type()
4974 Type* ptdt = Type::make_type_descriptor_ptr_type();
4975 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4977 Type::make_builtin_struct_type(4,
4978 "__map_descriptor", ptdt,
4979 "__entry_size", uintptr_type,
4980 "__key_offset", uintptr_type,
4981 "__val_offset", uintptr_type);
4982 ret = Type::make_builtin_named_type("__go_map_descriptor", sf);
4987 // Reflection string for a map.
4990 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
4992 ret->append("map[");
4993 this->append_reflection(this->key_type_, gogo, ret);
4995 this->append_reflection(this->val_type_, gogo, ret);
4998 // Mangled name for a map.
5001 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5003 ret->push_back('M');
5004 this->append_mangled_name(this->key_type_, gogo, ret);
5006 this->append_mangled_name(this->val_type_, gogo, ret);
5009 // Export a map type.
5012 Map_type::do_export(Export* exp) const
5014 exp->write_c_string("map [");
5015 exp->write_type(this->key_type_);
5016 exp->write_c_string("] ");
5017 exp->write_type(this->val_type_);
5020 // Import a map type.
5023 Map_type::do_import(Import* imp)
5025 imp->require_c_string("map [");
5026 Type* key_type = imp->read_type();
5027 imp->require_c_string("] ");
5028 Type* val_type = imp->read_type();
5029 return Type::make_map_type(key_type, val_type, imp->location());
5035 Type::make_map_type(Type* key_type, Type* val_type, Location location)
5037 return new Map_type(key_type, val_type, location);
5040 // Class Channel_type.
5045 Channel_type::do_hash_for_method(Gogo* gogo) const
5047 unsigned int ret = 0;
5048 if (this->may_send_)
5050 if (this->may_receive_)
5052 if (this->element_type_ != NULL)
5053 ret += this->element_type_->hash_for_method(gogo) << 2;
5057 // Whether this type is the same as T.
5060 Channel_type::is_identical(const Channel_type* t,
5061 bool errors_are_identical) const
5063 if (!Type::are_identical(this->element_type(), t->element_type(),
5064 errors_are_identical, NULL))
5066 return (this->may_send_ == t->may_send_
5067 && this->may_receive_ == t->may_receive_);
5070 // Return the tree for a channel type. A channel is a pointer to a
5071 // __go_channel struct. The __go_channel struct is defined in
5072 // libgo/runtime/channel.h.
5075 Channel_type::do_get_backend(Gogo* gogo)
5077 static Btype* backend_channel_type;
5078 if (backend_channel_type == NULL)
5080 std::vector<Backend::Btyped_identifier> bfields;
5081 Btype* bt = gogo->backend()->struct_type(bfields);
5082 bt = gogo->backend()->named_type("__go_channel", bt,
5083 Linemap::predeclared_location());
5084 backend_channel_type = gogo->backend()->pointer_type(bt);
5086 return backend_channel_type;
5089 // Build a type descriptor for a channel type.
5092 Channel_type::make_chan_type_descriptor_type()
5097 Type* tdt = Type::make_type_descriptor_type();
5098 Type* ptdt = Type::make_type_descriptor_ptr_type();
5100 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5103 Type::make_builtin_struct_type(3,
5106 "dir", uintptr_type);
5108 ret = Type::make_builtin_named_type("ChanType", sf);
5114 // Build a type descriptor for a map type.
5117 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5119 Location bloc = Linemap::predeclared_location();
5121 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
5123 const Struct_field_list* fields = ctdt->struct_type()->fields();
5125 Expression_list* vals = new Expression_list();
5128 Struct_field_list::const_iterator p = fields->begin();
5129 go_assert(p->is_field_name("commonType"));
5130 vals->push_back(this->type_descriptor_constructor(gogo,
5131 RUNTIME_TYPE_KIND_CHAN,
5135 go_assert(p->is_field_name("elem"));
5136 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5139 go_assert(p->is_field_name("dir"));
5140 // These bits must match the ones in libgo/runtime/go-type.h.
5142 if (this->may_receive_)
5144 if (this->may_send_)
5147 mpz_init_set_ui(iv, val);
5148 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
5152 go_assert(p == fields->end());
5154 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
5157 // Reflection string.
5160 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
5162 if (!this->may_send_)
5164 ret->append("chan");
5165 if (!this->may_receive_)
5167 ret->push_back(' ');
5168 this->append_reflection(this->element_type_, gogo, ret);
5174 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5176 ret->push_back('C');
5177 this->append_mangled_name(this->element_type_, gogo, ret);
5178 if (this->may_send_)
5179 ret->push_back('s');
5180 if (this->may_receive_)
5181 ret->push_back('r');
5182 ret->push_back('e');
5188 Channel_type::do_export(Export* exp) const
5190 exp->write_c_string("chan ");
5191 if (this->may_send_ && !this->may_receive_)
5192 exp->write_c_string("-< ");
5193 else if (this->may_receive_ && !this->may_send_)
5194 exp->write_c_string("<- ");
5195 exp->write_type(this->element_type_);
5201 Channel_type::do_import(Import* imp)
5203 imp->require_c_string("chan ");
5207 if (imp->match_c_string("-< "))
5211 may_receive = false;
5213 else if (imp->match_c_string("<- "))
5225 Type* element_type = imp->read_type();
5227 return Type::make_channel_type(may_send, may_receive, element_type);
5230 // Make a new channel type.
5233 Type::make_channel_type(bool send, bool receive, Type* element_type)
5235 return new Channel_type(send, receive, element_type);
5238 // Class Interface_type.
5243 Interface_type::do_traverse(Traverse* traverse)
5245 if (this->methods_ == NULL)
5246 return TRAVERSE_CONTINUE;
5247 return this->methods_->traverse(traverse);
5250 // Finalize the methods. This handles interface inheritance.
5253 Interface_type::finalize_methods()
5255 if (this->methods_ == NULL)
5257 std::vector<Named_type*> seen;
5258 bool is_recursive = false;
5261 while (from < this->methods_->size())
5263 const Typed_identifier* p = &this->methods_->at(from);
5264 if (!p->name().empty())
5267 for (i = 0; i < to; ++i)
5269 if (this->methods_->at(i).name() == p->name())
5271 error_at(p->location(), "duplicate method %qs",
5272 Gogo::message_name(p->name()).c_str());
5279 this->methods_->set(to, *p);
5286 Interface_type* it = p->type()->interface_type();
5289 error_at(p->location(), "interface contains embedded non-interface");
5297 error_at(p->location(), "invalid recursive interface");
5298 is_recursive = true;
5304 Named_type* nt = p->type()->named_type();
5307 std::vector<Named_type*>::const_iterator q;
5308 for (q = seen.begin(); q != seen.end(); ++q)
5312 error_at(p->location(), "inherited interface loop");
5316 if (q != seen.end())
5324 const Typed_identifier_list* methods = it->methods();
5325 if (methods == NULL)
5330 for (Typed_identifier_list::const_iterator q = methods->begin();
5331 q != methods->end();
5334 if (q->name().empty())
5336 if (q->type()->forwarded() == p->type()->forwarded())
5337 error_at(p->location(), "interface inheritance loop");
5341 for (i = from + 1; i < this->methods_->size(); ++i)
5343 const Typed_identifier* r = &this->methods_->at(i);
5344 if (r->name().empty()
5345 && r->type()->forwarded() == q->type()->forwarded())
5347 error_at(p->location(),
5348 "inherited interface listed twice");
5352 if (i == this->methods_->size())
5353 this->methods_->push_back(Typed_identifier(q->name(),
5358 else if (this->find_method(q->name()) == NULL)
5359 this->methods_->push_back(Typed_identifier(q->name(), q->type(),
5364 error_at(p->location(), "inherited method %qs is ambiguous",
5365 Gogo::message_name(q->name()).c_str());
5372 delete this->methods_;
5373 this->methods_ = NULL;
5377 this->methods_->resize(to);
5378 this->methods_->sort_by_name();
5382 // Return the method NAME, or NULL.
5384 const Typed_identifier*
5385 Interface_type::find_method(const std::string& name) const
5387 if (this->methods_ == NULL)
5389 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5390 p != this->methods_->end();
5392 if (p->name() == name)
5397 // Return the method index.
5400 Interface_type::method_index(const std::string& name) const
5402 go_assert(this->methods_ != NULL);
5404 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5405 p != this->methods_->end();
5407 if (p->name() == name)
5412 // Return whether NAME is an unexported method, for better error
5416 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
5418 if (this->methods_ == NULL)
5420 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5421 p != this->methods_->end();
5424 const std::string& method_name(p->name());
5425 if (Gogo::is_hidden_name(method_name)
5426 && name == Gogo::unpack_hidden_name(method_name)
5427 && gogo->pack_hidden_name(name, false) != method_name)
5433 // Whether this type is identical with T.
5436 Interface_type::is_identical(const Interface_type* t,
5437 bool errors_are_identical) const
5439 // We require the same methods with the same types. The methods
5440 // have already been sorted.
5441 if (this->methods() == NULL || t->methods() == NULL)
5442 return this->methods() == t->methods();
5444 Typed_identifier_list::const_iterator p1 = this->methods()->begin();
5445 for (Typed_identifier_list::const_iterator p2 = t->methods()->begin();
5446 p2 != t->methods()->end();
5449 if (p1 == this->methods()->end())
5451 if (p1->name() != p2->name()
5452 || !Type::are_identical(p1->type(), p2->type(),
5453 errors_are_identical, NULL))
5456 if (p1 != this->methods()->end())
5461 // Whether we can assign the interface type T to this type. The types
5462 // are known to not be identical. An interface assignment is only
5463 // permitted if T is known to implement all methods in THIS.
5464 // Otherwise a type guard is required.
5467 Interface_type::is_compatible_for_assign(const Interface_type* t,
5468 std::string* reason) const
5470 if (this->methods() == NULL)
5472 for (Typed_identifier_list::const_iterator p = this->methods()->begin();
5473 p != this->methods()->end();
5476 const Typed_identifier* m = t->find_method(p->name());
5482 snprintf(buf, sizeof buf,
5483 _("need explicit conversion; missing method %s%s%s"),
5484 open_quote, Gogo::message_name(p->name()).c_str(),
5486 reason->assign(buf);
5491 std::string subreason;
5492 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
5496 std::string n = Gogo::message_name(p->name());
5497 size_t len = 100 + n.length() + subreason.length();
5498 char* buf = new char[len];
5499 if (subreason.empty())
5500 snprintf(buf, len, _("incompatible type for method %s%s%s"),
5501 open_quote, n.c_str(), close_quote);
5504 _("incompatible type for method %s%s%s (%s)"),
5505 open_quote, n.c_str(), close_quote,
5507 reason->assign(buf);
5520 Interface_type::do_hash_for_method(Gogo* gogo) const
5522 unsigned int ret = 0;
5523 if (this->methods_ != NULL)
5525 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5526 p != this->methods_->end();
5529 ret = Type::hash_string(p->name(), ret);
5530 ret += p->type()->hash_for_method(gogo);
5537 // Return true if T implements the interface. If it does not, and
5538 // REASON is not NULL, set *REASON to a useful error message.
5541 Interface_type::implements_interface(const Type* t, std::string* reason) const
5543 if (this->methods_ == NULL)
5546 bool is_pointer = false;
5547 const Named_type* nt = t->named_type();
5548 const Struct_type* st = t->struct_type();
5549 // If we start with a named type, we don't dereference it to find
5553 const Type* pt = t->points_to();
5556 // If T is a pointer to a named type, then we need to look at
5557 // the type to which it points.
5559 nt = pt->named_type();
5560 st = pt->struct_type();
5564 // If we have a named type, get the methods from it rather than from
5569 // Only named and struct types have methods.
5570 if (nt == NULL && st == NULL)
5574 if (t->points_to() != NULL
5575 && t->points_to()->interface_type() != NULL)
5576 reason->assign(_("pointer to interface type has no methods"));
5578 reason->assign(_("type has no methods"));
5583 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
5587 if (t->points_to() != NULL
5588 && t->points_to()->interface_type() != NULL)
5589 reason->assign(_("pointer to interface type has no methods"));
5591 reason->assign(_("type has no methods"));
5596 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5597 p != this->methods_->end();
5600 bool is_ambiguous = false;
5601 Method* m = (nt != NULL
5602 ? nt->method_function(p->name(), &is_ambiguous)
5603 : st->method_function(p->name(), &is_ambiguous));
5608 std::string n = Gogo::message_name(p->name());
5609 size_t len = n.length() + 100;
5610 char* buf = new char[len];
5612 snprintf(buf, len, _("ambiguous method %s%s%s"),
5613 open_quote, n.c_str(), close_quote);
5615 snprintf(buf, len, _("missing method %s%s%s"),
5616 open_quote, n.c_str(), close_quote);
5617 reason->assign(buf);
5623 Function_type *p_fn_type = p->type()->function_type();
5624 Function_type* m_fn_type = m->type()->function_type();
5625 go_assert(p_fn_type != NULL && m_fn_type != NULL);
5626 std::string subreason;
5627 if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
5631 std::string n = Gogo::message_name(p->name());
5632 size_t len = 100 + n.length() + subreason.length();
5633 char* buf = new char[len];
5634 if (subreason.empty())
5635 snprintf(buf, len, _("incompatible type for method %s%s%s"),
5636 open_quote, n.c_str(), close_quote);
5639 _("incompatible type for method %s%s%s (%s)"),
5640 open_quote, n.c_str(), close_quote,
5642 reason->assign(buf);
5648 if (!is_pointer && !m->is_value_method())
5652 std::string n = Gogo::message_name(p->name());
5653 size_t len = 100 + n.length();
5654 char* buf = new char[len];
5655 snprintf(buf, len, _("method %s%s%s requires a pointer"),
5656 open_quote, n.c_str(), close_quote);
5657 reason->assign(buf);
5667 // Return the backend representation of the empty interface type. We
5668 // use the same struct for all empty interfaces.
5671 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
5673 static Btype* empty_interface_type;
5674 if (empty_interface_type == NULL)
5676 std::vector<Backend::Btyped_identifier> bfields(2);
5678 Location bloc = Linemap::predeclared_location();
5680 Type* pdt = Type::make_type_descriptor_ptr_type();
5681 bfields[0].name = "__type_descriptor";
5682 bfields[0].btype = pdt->get_backend(gogo);
5683 bfields[0].location = bloc;
5685 Type* vt = Type::make_pointer_type(Type::make_void_type());
5686 bfields[1].name = "__object";
5687 bfields[1].btype = vt->get_backend(gogo);
5688 bfields[1].location = bloc;
5690 empty_interface_type = gogo->backend()->struct_type(bfields);
5692 return empty_interface_type;
5695 // Return the fields of a non-empty interface type. This is not
5696 // declared in types.h so that types.h doesn't have to #include
5700 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
5701 std::vector<Backend::Btyped_identifier>* bfields)
5703 Location loc = type->location();
5705 std::vector<Backend::Btyped_identifier> mfields(type->methods()->size() + 1);
5707 Type* pdt = Type::make_type_descriptor_ptr_type();
5708 mfields[0].name = "__type_descriptor";
5709 mfields[0].btype = pdt->get_backend(gogo);
5710 mfields[0].location = loc;
5712 std::string last_name = "";
5714 for (Typed_identifier_list::const_iterator p = type->methods()->begin();
5715 p != type->methods()->end();
5718 mfields[i].name = Gogo::unpack_hidden_name(p->name());
5719 mfields[i].btype = p->type()->get_backend(gogo);
5720 mfields[i].location = loc;
5721 // Sanity check: the names should be sorted.
5722 go_assert(p->name() > last_name);
5723 last_name = p->name();
5726 Btype* methods = gogo->backend()->struct_type(mfields);
5730 (*bfields)[0].name = "__methods";
5731 (*bfields)[0].btype = gogo->backend()->pointer_type(methods);
5732 (*bfields)[0].location = loc;
5734 Type* vt = Type::make_pointer_type(Type::make_void_type());
5735 (*bfields)[1].name = "__object";
5736 (*bfields)[1].btype = vt->get_backend(gogo);
5737 (*bfields)[1].location = Linemap::predeclared_location();
5740 // Return a tree for an interface type. An interface is a pointer to
5741 // a struct. The struct has three fields. The first field is a
5742 // pointer to the type descriptor for the dynamic type of the object.
5743 // The second field is a pointer to a table of methods for the
5744 // interface to be used with the object. The third field is the value
5745 // of the object itself.
5748 Interface_type::do_get_backend(Gogo* gogo)
5750 if (this->methods_ == NULL)
5751 return Interface_type::get_backend_empty_interface_type(gogo);
5754 std::vector<Backend::Btyped_identifier> bfields;
5755 get_backend_interface_fields(gogo, this, &bfields);
5756 return gogo->backend()->struct_type(bfields);
5760 // The type of an interface type descriptor.
5763 Interface_type::make_interface_type_descriptor_type()
5768 Type* tdt = Type::make_type_descriptor_type();
5769 Type* ptdt = Type::make_type_descriptor_ptr_type();
5771 Type* string_type = Type::lookup_string_type();
5772 Type* pointer_string_type = Type::make_pointer_type(string_type);
5775 Type::make_builtin_struct_type(3,
5776 "name", pointer_string_type,
5777 "pkgPath", pointer_string_type,
5780 Type* nsm = Type::make_builtin_named_type("imethod", sm);
5782 Type* slice_nsm = Type::make_array_type(nsm, NULL);
5784 Struct_type* s = Type::make_builtin_struct_type(2,
5786 "methods", slice_nsm);
5788 ret = Type::make_builtin_named_type("InterfaceType", s);
5794 // Build a type descriptor for an interface type.
5797 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5799 Location bloc = Linemap::predeclared_location();
5801 Type* itdt = Interface_type::make_interface_type_descriptor_type();
5803 const Struct_field_list* ifields = itdt->struct_type()->fields();
5805 Expression_list* ivals = new Expression_list();
5808 Struct_field_list::const_iterator pif = ifields->begin();
5809 go_assert(pif->is_field_name("commonType"));
5810 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
5811 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
5815 go_assert(pif->is_field_name("methods"));
5817 Expression_list* methods = new Expression_list();
5818 if (this->methods_ != NULL && !this->methods_->empty())
5820 Type* elemtype = pif->type()->array_type()->element_type();
5822 methods->reserve(this->methods_->size());
5823 for (Typed_identifier_list::const_iterator pm = this->methods_->begin();
5824 pm != this->methods_->end();
5827 const Struct_field_list* mfields = elemtype->struct_type()->fields();
5829 Expression_list* mvals = new Expression_list();
5832 Struct_field_list::const_iterator pmf = mfields->begin();
5833 go_assert(pmf->is_field_name("name"));
5834 std::string s = Gogo::unpack_hidden_name(pm->name());
5835 Expression* e = Expression::make_string(s, bloc);
5836 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
5839 go_assert(pmf->is_field_name("pkgPath"));
5840 if (!Gogo::is_hidden_name(pm->name()))
5841 mvals->push_back(Expression::make_nil(bloc));
5844 s = Gogo::hidden_name_prefix(pm->name());
5845 e = Expression::make_string(s, bloc);
5846 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
5850 go_assert(pmf->is_field_name("typ"));
5851 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
5854 go_assert(pmf == mfields->end());
5856 e = Expression::make_struct_composite_literal(elemtype, mvals,
5858 methods->push_back(e);
5862 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
5866 go_assert(pif == ifields->end());
5868 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
5871 // Reflection string.
5874 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
5876 ret->append("interface {");
5877 if (this->methods_ != NULL)
5879 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5880 p != this->methods_->end();
5883 if (p != this->methods_->begin())
5885 ret->push_back(' ');
5886 if (!Gogo::is_hidden_name(p->name()))
5887 ret->append(p->name());
5890 // This matches what the gc compiler does.
5891 std::string prefix = Gogo::hidden_name_prefix(p->name());
5892 ret->append(prefix.substr(prefix.find('.') + 1));
5893 ret->push_back('.');
5894 ret->append(Gogo::unpack_hidden_name(p->name()));
5896 std::string sub = p->type()->reflection(gogo);
5897 go_assert(sub.compare(0, 4, "func") == 0);
5898 sub = sub.substr(4);
5908 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5910 ret->push_back('I');
5912 const Typed_identifier_list* methods = this->methods_;
5913 if (methods != NULL)
5915 for (Typed_identifier_list::const_iterator p = methods->begin();
5916 p != methods->end();
5919 std::string n = Gogo::unpack_hidden_name(p->name());
5921 snprintf(buf, sizeof buf, "%u_",
5922 static_cast<unsigned int>(n.length()));
5925 this->append_mangled_name(p->type(), gogo, ret);
5929 ret->push_back('e');
5935 Interface_type::do_export(Export* exp) const
5937 exp->write_c_string("interface { ");
5939 const Typed_identifier_list* methods = this->methods_;
5940 if (methods != NULL)
5942 for (Typed_identifier_list::const_iterator pm = methods->begin();
5943 pm != methods->end();
5946 exp->write_string(pm->name());
5947 exp->write_c_string(" (");
5949 const Function_type* fntype = pm->type()->function_type();
5952 const Typed_identifier_list* parameters = fntype->parameters();
5953 if (parameters != NULL)
5955 bool is_varargs = fntype->is_varargs();
5956 for (Typed_identifier_list::const_iterator pp =
5957 parameters->begin();
5958 pp != parameters->end();
5964 exp->write_c_string(", ");
5965 if (!is_varargs || pp + 1 != parameters->end())
5966 exp->write_type(pp->type());
5969 exp->write_c_string("...");
5970 Type *pptype = pp->type();
5971 exp->write_type(pptype->array_type()->element_type());
5976 exp->write_c_string(")");
5978 const Typed_identifier_list* results = fntype->results();
5979 if (results != NULL)
5981 exp->write_c_string(" ");
5982 if (results->size() == 1)
5983 exp->write_type(results->begin()->type());
5987 exp->write_c_string("(");
5988 for (Typed_identifier_list::const_iterator p =
5990 p != results->end();
5996 exp->write_c_string(", ");
5997 exp->write_type(p->type());
5999 exp->write_c_string(")");
6003 exp->write_c_string("; ");
6007 exp->write_c_string("}");
6010 // Import an interface type.
6013 Interface_type::do_import(Import* imp)
6015 imp->require_c_string("interface { ");
6017 Typed_identifier_list* methods = new Typed_identifier_list;
6018 while (imp->peek_char() != '}')
6020 std::string name = imp->read_identifier();
6021 imp->require_c_string(" (");
6023 Typed_identifier_list* parameters;
6024 bool is_varargs = false;
6025 if (imp->peek_char() == ')')
6029 parameters = new Typed_identifier_list;
6032 if (imp->match_c_string("..."))
6038 Type* ptype = imp->read_type();
6040 ptype = Type::make_array_type(ptype, NULL);
6041 parameters->push_back(Typed_identifier(Import::import_marker,
6042 ptype, imp->location()));
6043 if (imp->peek_char() != ',')
6045 go_assert(!is_varargs);
6046 imp->require_c_string(", ");
6049 imp->require_c_string(")");
6051 Typed_identifier_list* results;
6052 if (imp->peek_char() != ' ')
6056 results = new Typed_identifier_list;
6058 if (imp->peek_char() != '(')
6060 Type* rtype = imp->read_type();
6061 results->push_back(Typed_identifier(Import::import_marker,
6062 rtype, imp->location()));
6069 Type* rtype = imp->read_type();
6070 results->push_back(Typed_identifier(Import::import_marker,
6071 rtype, imp->location()));
6072 if (imp->peek_char() != ',')
6074 imp->require_c_string(", ");
6076 imp->require_c_string(")");
6080 Function_type* fntype = Type::make_function_type(NULL, parameters,
6084 fntype->set_is_varargs();
6085 methods->push_back(Typed_identifier(name, fntype, imp->location()));
6087 imp->require_c_string("; ");
6090 imp->require_c_string("}");
6092 if (methods->empty())
6098 return Type::make_interface_type(methods, imp->location());
6101 // Make an interface type.
6104 Type::make_interface_type(Typed_identifier_list* methods,
6107 return new Interface_type(methods, location);
6112 // Bind a method to an object.
6115 Method::bind_method(Expression* expr, Location location) const
6117 if (this->stub_ == NULL)
6119 // When there is no stub object, the binding is determined by
6121 return this->do_bind_method(expr, location);
6123 return Expression::make_bound_method(expr, this->stub_, location);
6126 // Return the named object associated with a method. This may only be
6127 // called after methods are finalized.
6130 Method::named_object() const
6132 if (this->stub_ != NULL)
6134 return this->do_named_object();
6137 // Class Named_method.
6139 // The type of the method.
6142 Named_method::do_type() const
6144 if (this->named_object_->is_function())
6145 return this->named_object_->func_value()->type();
6146 else if (this->named_object_->is_function_declaration())
6147 return this->named_object_->func_declaration_value()->type();
6152 // Return the location of the method receiver.
6155 Named_method::do_receiver_location() const
6157 return this->do_type()->receiver()->location();
6160 // Bind a method to an object.
6163 Named_method::do_bind_method(Expression* expr, Location location) const
6165 Named_object* no = this->named_object_;
6166 Bound_method_expression* bme = Expression::make_bound_method(expr, no,
6168 // If this is not a local method, and it does not use a stub, then
6169 // the real method expects a different type. We need to cast the
6171 if (this->depth() > 0 && !this->needs_stub_method())
6173 Function_type* ftype = this->do_type();
6174 go_assert(ftype->is_method());
6175 Type* frtype = ftype->receiver()->type();
6176 bme->set_first_argument_type(frtype);
6181 // Class Interface_method.
6183 // Bind a method to an object.
6186 Interface_method::do_bind_method(Expression* expr,
6187 Location location) const
6189 return Expression::make_interface_field_reference(expr, this->name_,
6195 // Insert a new method. Return true if it was inserted, false
6199 Methods::insert(const std::string& name, Method* m)
6201 std::pair<Method_map::iterator, bool> ins =
6202 this->methods_.insert(std::make_pair(name, m));
6207 Method* old_method = ins.first->second;
6208 if (m->depth() < old_method->depth())
6211 ins.first->second = m;
6216 if (m->depth() == old_method->depth())
6217 old_method->set_is_ambiguous();
6223 // Return the number of unambiguous methods.
6226 Methods::count() const
6229 for (Method_map::const_iterator p = this->methods_.begin();
6230 p != this->methods_.end();
6232 if (!p->second->is_ambiguous())
6237 // Class Named_type.
6239 // Return the name of the type.
6242 Named_type::name() const
6244 return this->named_object_->name();
6247 // Return the name of the type to use in an error message.
6250 Named_type::message_name() const
6252 return this->named_object_->message_name();
6255 // Return the base type for this type. We have to be careful about
6256 // circular type definitions, which are invalid but may be seen here.
6259 Named_type::named_base()
6264 Type* ret = this->type_->base();
6265 this->seen_ = false;
6270 Named_type::named_base() const
6275 const Type* ret = this->type_->base();
6276 this->seen_ = false;
6280 // Return whether this is an error type. We have to be careful about
6281 // circular type definitions, which are invalid but may be seen here.
6284 Named_type::is_named_error_type() const
6289 bool ret = this->type_->is_error_type();
6290 this->seen_ = false;
6294 // Add a method to this type.
6297 Named_type::add_method(const std::string& name, Function* function)
6299 if (this->local_methods_ == NULL)
6300 this->local_methods_ = new Bindings(NULL);
6301 return this->local_methods_->add_function(name, NULL, function);
6304 // Add a method declaration to this type.
6307 Named_type::add_method_declaration(const std::string& name, Package* package,
6308 Function_type* type,
6311 if (this->local_methods_ == NULL)
6312 this->local_methods_ = new Bindings(NULL);
6313 return this->local_methods_->add_function_declaration(name, package, type,
6317 // Add an existing method to this type.
6320 Named_type::add_existing_method(Named_object* no)
6322 if (this->local_methods_ == NULL)
6323 this->local_methods_ = new Bindings(NULL);
6324 this->local_methods_->add_named_object(no);
6327 // Look for a local method NAME, and returns its named object, or NULL
6331 Named_type::find_local_method(const std::string& name) const
6333 if (this->local_methods_ == NULL)
6335 return this->local_methods_->lookup(name);
6338 // Return whether NAME is an unexported field or method, for better
6342 Named_type::is_unexported_local_method(Gogo* gogo,
6343 const std::string& name) const
6345 Bindings* methods = this->local_methods_;
6346 if (methods != NULL)
6348 for (Bindings::const_declarations_iterator p =
6349 methods->begin_declarations();
6350 p != methods->end_declarations();
6353 if (Gogo::is_hidden_name(p->first)
6354 && name == Gogo::unpack_hidden_name(p->first)
6355 && gogo->pack_hidden_name(name, false) != p->first)
6362 // Build the complete list of methods for this type, which means
6363 // recursively including all methods for anonymous fields. Create all
6367 Named_type::finalize_methods(Gogo* gogo)
6369 if (this->all_methods_ != NULL)
6372 if (this->local_methods_ != NULL
6373 && (this->points_to() != NULL || this->interface_type() != NULL))
6375 const Bindings* lm = this->local_methods_;
6376 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
6377 p != lm->end_declarations();
6379 error_at(p->second->location(),
6380 "invalid pointer or interface receiver type");
6381 delete this->local_methods_;
6382 this->local_methods_ = NULL;
6386 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6389 // Return the method NAME, or NULL if there isn't one or if it is
6390 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6394 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
6396 return Type::method_function(this->all_methods_, name, is_ambiguous);
6399 // Return a pointer to the interface method table for this type for
6400 // the interface INTERFACE. IS_POINTER is true if this is for a
6404 Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface,
6407 go_assert(!interface->is_empty());
6409 Interface_method_tables** pimt = (is_pointer
6410 ? &this->interface_method_tables_
6411 : &this->pointer_interface_method_tables_);
6414 *pimt = new Interface_method_tables(5);
6416 std::pair<const Interface_type*, tree> val(interface, NULL_TREE);
6417 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
6421 // This is a new entry in the hash table.
6422 go_assert(ins.first->second == NULL_TREE);
6423 ins.first->second = gogo->interface_method_table_for_type(interface,
6428 tree decl = ins.first->second;
6429 if (decl == error_mark_node)
6430 return error_mark_node;
6431 go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL);
6432 return build_fold_addr_expr(decl);
6435 // Return whether a named type has any hidden fields.
6438 Named_type::named_type_has_hidden_fields(std::string* reason) const
6443 bool ret = this->type_->has_hidden_fields(this, reason);
6444 this->seen_ = false;
6448 // Look for a use of a complete type within another type. This is
6449 // used to check that we don't try to use a type within itself.
6451 class Find_type_use : public Traverse
6454 Find_type_use(Named_type* find_type)
6455 : Traverse(traverse_types),
6456 find_type_(find_type), found_(false)
6459 // Whether we found the type.
6462 { return this->found_; }
6469 // The type we are looking for.
6470 Named_type* find_type_;
6471 // Whether we found the type.
6475 // Check for FIND_TYPE in TYPE.
6478 Find_type_use::type(Type* type)
6480 if (type->named_type() != NULL && this->find_type_ == type->named_type())
6482 this->found_ = true;
6483 return TRAVERSE_EXIT;
6486 // It's OK if we see a reference to the type in any type which is
6487 // essentially a pointer: a pointer, a slice, a function, a map, or
6489 if (type->points_to() != NULL
6490 || type->is_slice_type()
6491 || type->function_type() != NULL
6492 || type->map_type() != NULL
6493 || type->channel_type() != NULL)
6494 return TRAVERSE_SKIP_COMPONENTS;
6496 // For an interface, a reference to the type in a method type should
6497 // be ignored, but we have to consider direct inheritance. When
6498 // this is called, there may be cases of direct inheritance
6499 // represented as a method with no name.
6500 if (type->interface_type() != NULL)
6502 const Typed_identifier_list* methods = type->interface_type()->methods();
6503 if (methods != NULL)
6505 for (Typed_identifier_list::const_iterator p = methods->begin();
6506 p != methods->end();
6509 if (p->name().empty())
6511 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
6512 return TRAVERSE_EXIT;
6516 return TRAVERSE_SKIP_COMPONENTS;
6519 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
6520 // to convert TYPE to the backend representation before we convert
6522 if (type->named_type() != NULL)
6524 switch (type->base()->classification())
6526 case Type::TYPE_ERROR:
6527 case Type::TYPE_BOOLEAN:
6528 case Type::TYPE_INTEGER:
6529 case Type::TYPE_FLOAT:
6530 case Type::TYPE_COMPLEX:
6531 case Type::TYPE_STRING:
6532 case Type::TYPE_NIL:
6535 case Type::TYPE_ARRAY:
6536 case Type::TYPE_STRUCT:
6537 this->find_type_->add_dependency(type->named_type());
6540 case Type::TYPE_VOID:
6541 case Type::TYPE_SINK:
6542 case Type::TYPE_FUNCTION:
6543 case Type::TYPE_POINTER:
6544 case Type::TYPE_CALL_MULTIPLE_RESULT:
6545 case Type::TYPE_MAP:
6546 case Type::TYPE_CHANNEL:
6547 case Type::TYPE_INTERFACE:
6548 case Type::TYPE_NAMED:
6549 case Type::TYPE_FORWARD:
6555 return TRAVERSE_CONTINUE;
6558 // Verify that a named type does not refer to itself.
6561 Named_type::do_verify()
6563 Find_type_use find(this);
6564 Type::traverse(this->type_, &find);
6567 error_at(this->location_, "invalid recursive type %qs",
6568 this->message_name().c_str());
6569 this->is_error_ = true;
6573 // Check whether any of the local methods overloads an existing
6574 // struct field or interface method. We don't need to check the
6575 // list of methods against itself: that is handled by the Bindings
6577 if (this->local_methods_ != NULL)
6579 Struct_type* st = this->type_->struct_type();
6580 bool found_dup = false;
6583 for (Bindings::const_declarations_iterator p =
6584 this->local_methods_->begin_declarations();
6585 p != this->local_methods_->end_declarations();
6588 const std::string& name(p->first);
6589 if (st != NULL && st->find_local_field(name, NULL) != NULL)
6591 error_at(p->second->location(),
6592 "method %qs redeclares struct field name",
6593 Gogo::message_name(name).c_str());
6605 // Return whether this type is or contains a pointer.
6608 Named_type::do_has_pointer() const
6613 bool ret = this->type_->has_pointer();
6614 this->seen_ = false;
6618 // Return a hash code. This is used for method lookup. We simply
6619 // hash on the name itself.
6622 Named_type::do_hash_for_method(Gogo* gogo) const
6624 const std::string& name(this->named_object()->name());
6625 unsigned int ret = Type::hash_string(name, 0);
6627 // GOGO will be NULL here when called from Type_hash_identical.
6628 // That is OK because that is only used for internal hash tables
6629 // where we are going to be comparing named types for equality. In
6630 // other cases, which are cases where the runtime is going to
6631 // compare hash codes to see if the types are the same, we need to
6632 // include the package prefix and name in the hash.
6633 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
6635 const Package* package = this->named_object()->package();
6636 if (package == NULL)
6638 ret = Type::hash_string(gogo->unique_prefix(), ret);
6639 ret = Type::hash_string(gogo->package_name(), ret);
6643 ret = Type::hash_string(package->unique_prefix(), ret);
6644 ret = Type::hash_string(package->name(), ret);
6651 // Convert a named type to the backend representation. In order to
6652 // get dependencies right, we fill in a dummy structure for this type,
6653 // then convert all the dependencies, then complete this type. When
6654 // this function is complete, the size of the type is known.
6657 Named_type::convert(Gogo* gogo)
6659 if (this->is_error_ || this->is_converted_)
6662 this->create_placeholder(gogo);
6664 // Convert all the dependencies. If they refer indirectly back to
6665 // this type, they will pick up the intermediate tree we just
6667 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
6668 p != this->dependencies_.end();
6670 (*p)->convert(gogo);
6672 // Complete this type.
6673 Btype* bt = this->named_btype_;
6674 Type* base = this->type_->base();
6675 switch (base->classification())
6692 // The size of these types is already correct. We don't worry
6693 // about filling them in until later, when we also track
6694 // circular references.
6699 std::vector<Backend::Btyped_identifier> bfields;
6700 get_backend_struct_fields(gogo, base->struct_type()->fields(),
6702 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6703 bt = gogo->backend()->error_type();
6708 // Slice types were completed in create_placeholder.
6709 if (!base->is_slice_type())
6711 Btype* bet = base->array_type()->get_backend_element(gogo);
6712 Bexpression* blen = base->array_type()->get_backend_length(gogo);
6713 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
6714 bt = gogo->backend()->error_type();
6718 case TYPE_INTERFACE:
6719 // Interface types were completed in create_placeholder.
6727 case TYPE_CALL_MULTIPLE_RESULT:
6733 this->named_btype_ = bt;
6734 this->is_converted_ = true;
6737 // Create the placeholder for a named type. This is the first step in
6738 // converting to the backend representation.
6741 Named_type::create_placeholder(Gogo* gogo)
6743 if (this->is_error_)
6744 this->named_btype_ = gogo->backend()->error_type();
6746 if (this->named_btype_ != NULL)
6749 // Create the structure for this type. Note that because we call
6750 // base() here, we don't attempt to represent a named type defined
6751 // as another named type. Instead both named types will point to
6752 // different base representations.
6753 Type* base = this->type_->base();
6755 bool set_name = true;
6756 switch (base->classification())
6759 this->is_error_ = true;
6760 this->named_btype_ = gogo->backend()->error_type();
6770 // These are simple basic types, we can just create them
6772 bt = Type::get_named_base_btype(gogo, base);
6777 // All maps and channels have the same backend representation.
6778 bt = Type::get_named_base_btype(gogo, base);
6784 bool for_function = base->classification() == TYPE_FUNCTION;
6785 bt = gogo->backend()->placeholder_pointer_type(this->name(),
6793 bt = gogo->backend()->placeholder_struct_type(this->name(),
6799 if (base->is_slice_type())
6800 bt = gogo->backend()->placeholder_struct_type(this->name(),
6803 bt = gogo->backend()->placeholder_array_type(this->name(),
6808 case TYPE_INTERFACE:
6809 if (base->interface_type()->is_empty())
6810 bt = Interface_type::get_backend_empty_interface_type(gogo);
6813 bt = gogo->backend()->placeholder_struct_type(this->name(),
6821 case TYPE_CALL_MULTIPLE_RESULT:
6828 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
6830 this->named_btype_ = bt;
6832 if (base->is_slice_type())
6834 // We do not record slices as dependencies of other types,
6835 // because we can fill them in completely here with the final
6837 std::vector<Backend::Btyped_identifier> bfields;
6838 get_backend_slice_fields(gogo, base->array_type(), &bfields);
6839 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6840 this->named_btype_ = gogo->backend()->error_type();
6842 else if (base->interface_type() != NULL
6843 && !base->interface_type()->is_empty())
6845 // We do not record interfaces as dependencies of other types,
6846 // because we can fill them in completely here with the final
6848 std::vector<Backend::Btyped_identifier> bfields;
6849 get_backend_interface_fields(gogo, base->interface_type(), &bfields);
6850 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6851 this->named_btype_ = gogo->backend()->error_type();
6855 // Get a tree for a named type.
6858 Named_type::do_get_backend(Gogo* gogo)
6860 if (this->is_error_)
6861 return gogo->backend()->error_type();
6863 Btype* bt = this->named_btype_;
6865 if (!gogo->named_types_are_converted())
6867 // We have not completed converting named types. NAMED_BTYPE_
6868 // is a placeholder and we shouldn't do anything further.
6872 // We don't build dependencies for types whose sizes do not
6873 // change or are not relevant, so we may see them here while
6874 // converting types.
6875 this->create_placeholder(gogo);
6876 bt = this->named_btype_;
6877 go_assert(bt != NULL);
6881 // We are not converting types. This should only be called if the
6882 // type has already been converted.
6883 if (!this->is_converted_)
6885 go_assert(saw_errors());
6886 return gogo->backend()->error_type();
6889 go_assert(bt != NULL);
6891 // Complete the tree.
6892 Type* base = this->type_->base();
6894 switch (base->classification())
6897 return gogo->backend()->error_type();
6910 case TYPE_INTERFACE:
6914 // Don't build a circular data structure. GENERIC can't handle
6916 if (this->seen_in_get_backend_)
6918 this->is_circular_ = true;
6919 return gogo->backend()->circular_pointer_type(bt, true);
6921 this->seen_in_get_backend_ = true;
6922 bt1 = Type::get_named_base_btype(gogo, base);
6923 this->seen_in_get_backend_ = false;
6924 if (this->is_circular_)
6925 bt1 = gogo->backend()->circular_pointer_type(bt, true);
6926 if (!gogo->backend()->set_placeholder_function_type(bt, bt1))
6927 bt = gogo->backend()->error_type();
6931 // Don't build a circular data structure. GENERIC can't handle
6933 if (this->seen_in_get_backend_)
6935 this->is_circular_ = true;
6936 return gogo->backend()->circular_pointer_type(bt, false);
6938 this->seen_in_get_backend_ = true;
6939 bt1 = Type::get_named_base_btype(gogo, base);
6940 this->seen_in_get_backend_ = false;
6941 if (this->is_circular_)
6942 bt1 = gogo->backend()->circular_pointer_type(bt, false);
6943 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
6944 bt = gogo->backend()->error_type();
6949 case TYPE_CALL_MULTIPLE_RESULT:
6958 // Build a type descriptor for a named type.
6961 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6963 // If NAME is not NULL, then we don't really want the type
6964 // descriptor for this type; we want the descriptor for the
6965 // underlying type, giving it the name NAME.
6966 return this->named_type_descriptor(gogo, this->type_,
6967 name == NULL ? this : name);
6970 // Add to the reflection string. This is used mostly for the name of
6971 // the type used in a type descriptor, not for actual reflection
6975 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
6977 if (!Linemap::is_predeclared_location(this->location()))
6979 const Package* package = this->named_object_->package();
6980 if (package != NULL)
6981 ret->append(package->name());
6983 ret->append(gogo->package_name());
6984 ret->push_back('.');
6986 if (this->in_function_ != NULL)
6988 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
6989 ret->push_back('$');
6991 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
6994 // Get the mangled name.
6997 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6999 Named_object* no = this->named_object_;
7001 if (Linemap::is_predeclared_location(this->location()))
7002 go_assert(this->in_function_ == NULL);
7005 const std::string& unique_prefix(no->package() == NULL
7006 ? gogo->unique_prefix()
7007 : no->package()->unique_prefix());
7008 const std::string& package_name(no->package() == NULL
7009 ? gogo->package_name()
7010 : no->package()->name());
7011 name = unique_prefix;
7012 name.append(1, '.');
7013 name.append(package_name);
7014 name.append(1, '.');
7015 if (this->in_function_ != NULL)
7017 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
7018 name.append(1, '$');
7021 name.append(Gogo::unpack_hidden_name(no->name()));
7023 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
7028 // Export the type. This is called to export a global type.
7031 Named_type::export_named_type(Export* exp, const std::string&) const
7033 // We don't need to write the name of the type here, because it will
7034 // be written by Export::write_type anyhow.
7035 exp->write_c_string("type ");
7036 exp->write_type(this);
7037 exp->write_c_string(";\n");
7040 // Import a named type.
7043 Named_type::import_named_type(Import* imp, Named_type** ptype)
7045 imp->require_c_string("type ");
7046 Type *type = imp->read_type();
7047 *ptype = type->named_type();
7048 go_assert(*ptype != NULL);
7049 imp->require_c_string(";\n");
7052 // Export the type when it is referenced by another type. In this
7053 // case Export::export_type will already have issued the name.
7056 Named_type::do_export(Export* exp) const
7058 exp->write_type(this->type_);
7060 // To save space, we only export the methods directly attached to
7062 Bindings* methods = this->local_methods_;
7063 if (methods == NULL)
7066 exp->write_c_string("\n");
7067 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
7068 p != methods->end_definitions();
7071 exp->write_c_string(" ");
7072 (*p)->export_named_object(exp);
7075 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
7076 p != methods->end_declarations();
7079 if (p->second->is_function_declaration())
7081 exp->write_c_string(" ");
7082 p->second->export_named_object(exp);
7087 // Make a named type.
7090 Type::make_named_type(Named_object* named_object, Type* type,
7093 return new Named_type(named_object, type, location);
7096 // Finalize the methods for TYPE. It will be a named type or a struct
7097 // type. This sets *ALL_METHODS to the list of methods, and builds
7098 // all required stubs.
7101 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
7102 Methods** all_methods)
7104 *all_methods = NULL;
7105 Types_seen types_seen;
7106 Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen,
7108 Type::build_stub_methods(gogo, type, *all_methods, location);
7111 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
7112 // build up the struct field indexes as we go. DEPTH is the depth of
7113 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
7114 // adding these methods for an anonymous field with pointer type.
7115 // NEEDS_STUB_METHOD is true if we need to use a stub method which
7116 // calls the real method. TYPES_SEEN is used to avoid infinite
7120 Type::add_methods_for_type(const Type* type,
7121 const Method::Field_indexes* field_indexes,
7123 bool is_embedded_pointer,
7124 bool needs_stub_method,
7125 Types_seen* types_seen,
7128 // Pointer types may not have methods.
7129 if (type->points_to() != NULL)
7132 const Named_type* nt = type->named_type();
7135 std::pair<Types_seen::iterator, bool> ins = types_seen->insert(nt);
7141 Type::add_local_methods_for_type(nt, field_indexes, depth,
7142 is_embedded_pointer, needs_stub_method,
7145 Type::add_embedded_methods_for_type(type, field_indexes, depth,
7146 is_embedded_pointer, needs_stub_method,
7147 types_seen, methods);
7149 // If we are called with depth > 0, then we are looking at an
7150 // anonymous field of a struct. If such a field has interface type,
7151 // then we need to add the interface methods. We don't want to add
7152 // them when depth == 0, because we will already handle them
7153 // following the usual rules for an interface type.
7155 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
7158 // Add the local methods for the named type NT to *METHODS. The
7159 // parameters are as for add_methods_to_type.
7162 Type::add_local_methods_for_type(const Named_type* nt,
7163 const Method::Field_indexes* field_indexes,
7165 bool is_embedded_pointer,
7166 bool needs_stub_method,
7169 const Bindings* local_methods = nt->local_methods();
7170 if (local_methods == NULL)
7173 if (*methods == NULL)
7174 *methods = new Methods();
7176 for (Bindings::const_declarations_iterator p =
7177 local_methods->begin_declarations();
7178 p != local_methods->end_declarations();
7181 Named_object* no = p->second;
7182 bool is_value_method = (is_embedded_pointer
7183 || !Type::method_expects_pointer(no));
7184 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
7186 || (depth > 0 && is_value_method)));
7187 if (!(*methods)->insert(no->name(), m))
7192 // Add the embedded methods for TYPE to *METHODS. These are the
7193 // methods attached to anonymous fields. The parameters are as for
7194 // add_methods_to_type.
7197 Type::add_embedded_methods_for_type(const Type* type,
7198 const Method::Field_indexes* field_indexes,
7200 bool is_embedded_pointer,
7201 bool needs_stub_method,
7202 Types_seen* types_seen,
7205 // Look for anonymous fields in TYPE. TYPE has fields if it is a
7207 const Struct_type* st = type->struct_type();
7211 const Struct_field_list* fields = st->fields();
7216 for (Struct_field_list::const_iterator pf = fields->begin();
7217 pf != fields->end();
7220 if (!pf->is_anonymous())
7223 Type* ftype = pf->type();
7224 bool is_pointer = false;
7225 if (ftype->points_to() != NULL)
7227 ftype = ftype->points_to();
7230 Named_type* fnt = ftype->named_type();
7233 // This is an error, but it will be diagnosed elsewhere.
7237 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
7238 sub_field_indexes->next = field_indexes;
7239 sub_field_indexes->field_index = i;
7241 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
7242 (is_embedded_pointer || is_pointer),
7251 // If TYPE is an interface type, then add its method to *METHODS.
7252 // This is for interface methods attached to an anonymous field. The
7253 // parameters are as for add_methods_for_type.
7256 Type::add_interface_methods_for_type(const Type* type,
7257 const Method::Field_indexes* field_indexes,
7261 const Interface_type* it = type->interface_type();
7265 const Typed_identifier_list* imethods = it->methods();
7266 if (imethods == NULL)
7269 if (*methods == NULL)
7270 *methods = new Methods();
7272 for (Typed_identifier_list::const_iterator pm = imethods->begin();
7273 pm != imethods->end();
7276 Function_type* fntype = pm->type()->function_type();
7279 // This is an error, but it should be reported elsewhere
7280 // when we look at the methods for IT.
7283 go_assert(!fntype->is_method());
7284 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
7285 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
7286 field_indexes, depth);
7287 if (!(*methods)->insert(pm->name(), m))
7292 // Build stub methods for TYPE as needed. METHODS is the set of
7293 // methods for the type. A stub method may be needed when a type
7294 // inherits a method from an anonymous field. When we need the
7295 // address of the method, as in a type descriptor, we need to build a
7296 // little stub which does the required field dereferences and jumps to
7297 // the real method. LOCATION is the location of the type definition.
7300 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
7303 if (methods == NULL)
7305 for (Methods::const_iterator p = methods->begin();
7306 p != methods->end();
7309 Method* m = p->second;
7310 if (m->is_ambiguous() || !m->needs_stub_method())
7313 const std::string& name(p->first);
7315 // Build a stub method.
7317 const Function_type* fntype = m->type();
7319 static unsigned int counter;
7321 snprintf(buf, sizeof buf, "$this%u", counter);
7324 Type* receiver_type = const_cast<Type*>(type);
7325 if (!m->is_value_method())
7326 receiver_type = Type::make_pointer_type(receiver_type);
7327 Location receiver_location = m->receiver_location();
7328 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
7331 const Typed_identifier_list* fnparams = fntype->parameters();
7332 Typed_identifier_list* stub_params;
7333 if (fnparams == NULL || fnparams->empty())
7337 // We give each stub parameter a unique name.
7338 stub_params = new Typed_identifier_list();
7339 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
7340 pp != fnparams->end();
7344 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
7345 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
7351 const Typed_identifier_list* fnresults = fntype->results();
7352 Typed_identifier_list* stub_results;
7353 if (fnresults == NULL || fnresults->empty())
7354 stub_results = NULL;
7357 // We create the result parameters without any names, since
7358 // we won't refer to them.
7359 stub_results = new Typed_identifier_list();
7360 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
7361 pr != fnresults->end();
7363 stub_results->push_back(Typed_identifier("", pr->type(),
7367 Function_type* stub_type = Type::make_function_type(receiver,
7370 fntype->location());
7371 if (fntype->is_varargs())
7372 stub_type->set_is_varargs();
7374 // We only create the function in the package which creates the
7376 const Package* package;
7377 if (type->named_type() == NULL)
7380 package = type->named_type()->named_object()->package();
7382 if (package != NULL)
7383 stub = Named_object::make_function_declaration(name, package,
7384 stub_type, location);
7387 stub = gogo->start_function(name, stub_type, false,
7388 fntype->location());
7389 Type::build_one_stub_method(gogo, m, buf, stub_params,
7390 fntype->is_varargs(), location);
7391 gogo->finish_function(fntype->location());
7394 m->set_stub_object(stub);
7398 // Build a stub method which adjusts the receiver as required to call
7399 // METHOD. RECEIVER_NAME is the name we used for the receiver.
7400 // PARAMS is the list of function parameters.
7403 Type::build_one_stub_method(Gogo* gogo, Method* method,
7404 const char* receiver_name,
7405 const Typed_identifier_list* params,
7409 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
7410 go_assert(receiver_object != NULL);
7412 Expression* expr = Expression::make_var_reference(receiver_object, location);
7413 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
7414 if (expr->type()->points_to() == NULL)
7415 expr = Expression::make_unary(OPERATOR_AND, expr, location);
7417 Expression_list* arguments;
7418 if (params == NULL || params->empty())
7422 arguments = new Expression_list();
7423 for (Typed_identifier_list::const_iterator p = params->begin();
7427 Named_object* param = gogo->lookup(p->name(), NULL);
7428 go_assert(param != NULL);
7429 Expression* param_ref = Expression::make_var_reference(param,
7431 arguments->push_back(param_ref);
7435 Expression* func = method->bind_method(expr, location);
7436 go_assert(func != NULL);
7437 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
7439 call->set_hidden_fields_are_ok();
7440 size_t count = call->result_count();
7442 gogo->add_statement(Statement::make_statement(call, true));
7445 Expression_list* retvals = new Expression_list();
7447 retvals->push_back(call);
7450 for (size_t i = 0; i < count; ++i)
7451 retvals->push_back(Expression::make_call_result(call, i));
7453 Return_statement* retstat = Statement::make_return_statement(retvals,
7456 // We can return values with hidden fields from a stub. This is
7457 // necessary if the method is itself hidden.
7458 retstat->set_hidden_fields_are_ok();
7460 gogo->add_statement(retstat);
7464 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
7465 // in reverse order.
7468 Type::apply_field_indexes(Expression* expr,
7469 const Method::Field_indexes* field_indexes,
7472 if (field_indexes == NULL)
7474 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
7475 Struct_type* stype = expr->type()->deref()->struct_type();
7476 go_assert(stype != NULL
7477 && field_indexes->field_index < stype->field_count());
7478 if (expr->type()->struct_type() == NULL)
7480 go_assert(expr->type()->points_to() != NULL);
7481 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
7482 go_assert(expr->type()->struct_type() == stype);
7484 return Expression::make_field_reference(expr, field_indexes->field_index,
7488 // Return whether NO is a method for which the receiver is a pointer.
7491 Type::method_expects_pointer(const Named_object* no)
7493 const Function_type *fntype;
7494 if (no->is_function())
7495 fntype = no->func_value()->type();
7496 else if (no->is_function_declaration())
7497 fntype = no->func_declaration_value()->type();
7500 return fntype->receiver()->type()->points_to() != NULL;
7503 // Given a set of methods for a type, METHODS, return the method NAME,
7504 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
7505 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
7506 // but is ambiguous (and return NULL).
7509 Type::method_function(const Methods* methods, const std::string& name,
7512 if (is_ambiguous != NULL)
7513 *is_ambiguous = false;
7514 if (methods == NULL)
7516 Methods::const_iterator p = methods->find(name);
7517 if (p == methods->end())
7519 Method* m = p->second;
7520 if (m->is_ambiguous())
7522 if (is_ambiguous != NULL)
7523 *is_ambiguous = true;
7529 // Look for field or method NAME for TYPE. Return an Expression for
7530 // the field or method bound to EXPR. If there is no such field or
7531 // method, give an appropriate error and return an error expression.
7534 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
7535 const std::string& name,
7538 if (type->deref()->is_error_type())
7539 return Expression::make_error(location);
7541 const Named_type* nt = type->deref()->named_type();
7542 const Struct_type* st = type->deref()->struct_type();
7543 const Interface_type* it = type->interface_type();
7545 // If this is a pointer to a pointer, then it is possible that the
7546 // pointed-to type has methods.
7550 && type->points_to() != NULL
7551 && type->points_to()->points_to() != NULL)
7553 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
7554 type = type->points_to();
7555 if (type->deref()->is_error_type())
7556 return Expression::make_error(location);
7557 nt = type->points_to()->named_type();
7558 st = type->points_to()->struct_type();
7561 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
7562 || expr->is_addressable());
7563 std::vector<const Named_type*> seen;
7564 bool is_method = false;
7565 bool found_pointer_method = false;
7568 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
7569 &seen, NULL, &is_method,
7570 &found_pointer_method, &ambig1, &ambig2))
7575 go_assert(st != NULL);
7576 if (type->struct_type() == NULL)
7578 go_assert(type->points_to() != NULL);
7579 expr = Expression::make_unary(OPERATOR_MULT, expr,
7581 go_assert(expr->type()->struct_type() == st);
7583 ret = st->field_reference(expr, name, location);
7585 else if (it != NULL && it->find_method(name) != NULL)
7586 ret = Expression::make_interface_field_reference(expr, name,
7592 m = nt->method_function(name, NULL);
7593 else if (st != NULL)
7594 m = st->method_function(name, NULL);
7597 go_assert(m != NULL);
7598 if (!m->is_value_method() && expr->type()->points_to() == NULL)
7599 expr = Expression::make_unary(OPERATOR_AND, expr, location);
7600 ret = m->bind_method(expr, location);
7602 go_assert(ret != NULL);
7607 if (!ambig1.empty())
7608 error_at(location, "%qs is ambiguous via %qs and %qs",
7609 Gogo::message_name(name).c_str(), ambig1.c_str(),
7611 else if (found_pointer_method)
7612 error_at(location, "method requires a pointer");
7613 else if (nt == NULL && st == NULL && it == NULL)
7615 ("reference to field %qs in object which "
7616 "has no fields or methods"),
7617 Gogo::message_name(name).c_str());
7621 if (!Gogo::is_hidden_name(name))
7622 is_unexported = false;
7625 std::string unpacked = Gogo::unpack_hidden_name(name);
7627 is_unexported = Type::is_unexported_field_or_method(gogo, type,
7632 error_at(location, "reference to unexported field or method %qs",
7633 Gogo::message_name(name).c_str());
7635 error_at(location, "reference to undefined field or method %qs",
7636 Gogo::message_name(name).c_str());
7638 return Expression::make_error(location);
7642 // Look in TYPE for a field or method named NAME, return true if one
7643 // is found. This looks through embedded anonymous fields and handles
7644 // ambiguity. If a method is found, sets *IS_METHOD to true;
7645 // otherwise, if a field is found, set it to false. If
7646 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
7647 // whose address can not be taken. SEEN is used to avoid infinite
7648 // recursion on invalid types.
7650 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
7651 // method we couldn't use because it requires a pointer. LEVEL is
7652 // used for recursive calls, and can be NULL for a non-recursive call.
7653 // When this function returns false because it finds that the name is
7654 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
7655 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
7656 // will be unchanged.
7658 // This function just returns whether or not there is a field or
7659 // method, and whether it is a field or method. It doesn't build an
7660 // expression to refer to it. If it is a method, we then look in the
7661 // list of all methods for the type. If it is a field, the search has
7662 // to be done again, looking only for fields, and building up the
7663 // expression as we go.
7666 Type::find_field_or_method(const Type* type,
7667 const std::string& name,
7668 bool receiver_can_be_pointer,
7669 std::vector<const Named_type*>* seen,
7672 bool* found_pointer_method,
7673 std::string* ambig1,
7674 std::string* ambig2)
7676 // Named types can have locally defined methods.
7677 const Named_type* nt = type->named_type();
7678 if (nt == NULL && type->points_to() != NULL)
7679 nt = type->points_to()->named_type();
7682 Named_object* no = nt->find_local_method(name);
7685 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
7691 // Record that we have found a pointer method in order to
7692 // give a better error message if we don't find anything
7694 *found_pointer_method = true;
7697 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
7703 // We've already seen this type when searching for methods.
7709 // Interface types can have methods.
7710 const Interface_type* it = type->interface_type();
7711 if (it != NULL && it->find_method(name) != NULL)
7717 // Struct types can have fields. They can also inherit fields and
7718 // methods from anonymous fields.
7719 const Struct_type* st = type->deref()->struct_type();
7722 const Struct_field_list* fields = st->fields();
7727 seen->push_back(nt);
7729 int found_level = 0;
7730 bool found_is_method = false;
7731 std::string found_ambig1;
7732 std::string found_ambig2;
7733 const Struct_field* found_parent = NULL;
7734 for (Struct_field_list::const_iterator pf = fields->begin();
7735 pf != fields->end();
7738 if (pf->is_field_name(name))
7746 if (!pf->is_anonymous())
7749 if (pf->type()->deref()->is_error_type()
7750 || pf->type()->deref()->is_undefined())
7753 Named_type* fnt = pf->type()->named_type();
7755 fnt = pf->type()->deref()->named_type();
7756 go_assert(fnt != NULL);
7758 int sublevel = level == NULL ? 1 : *level + 1;
7760 std::string subambig1;
7761 std::string subambig2;
7762 bool subfound = Type::find_field_or_method(fnt,
7764 receiver_can_be_pointer,
7768 found_pointer_method,
7773 if (!subambig1.empty())
7775 // The name was found via this field, but is ambiguous.
7776 // if the ambiguity is lower or at the same level as
7777 // anything else we have already found, then we want to
7778 // pass the ambiguity back to the caller.
7779 if (found_level == 0 || sublevel <= found_level)
7781 found_ambig1 = (Gogo::message_name(pf->field_name())
7783 found_ambig2 = (Gogo::message_name(pf->field_name())
7785 found_level = sublevel;
7791 // The name was found via this field. Use the level to see
7792 // if we want to use this one, or whether it introduces an
7794 if (found_level == 0 || sublevel < found_level)
7796 found_level = sublevel;
7797 found_is_method = sub_is_method;
7798 found_ambig1.clear();
7799 found_ambig2.clear();
7800 found_parent = &*pf;
7802 else if (sublevel > found_level)
7804 else if (found_ambig1.empty())
7806 // We found an ambiguity.
7807 go_assert(found_parent != NULL);
7808 found_ambig1 = Gogo::message_name(found_parent->field_name());
7809 found_ambig2 = Gogo::message_name(pf->field_name());
7813 // We found an ambiguity, but we already know of one.
7814 // Just report the earlier one.
7819 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
7820 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
7821 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
7822 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
7827 if (found_level == 0)
7829 else if (!found_ambig1.empty())
7831 go_assert(!found_ambig1.empty());
7832 ambig1->assign(found_ambig1);
7833 ambig2->assign(found_ambig2);
7835 *level = found_level;
7841 *level = found_level;
7842 *is_method = found_is_method;
7847 // Return whether NAME is an unexported field or method for TYPE.
7850 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
7851 const std::string& name,
7852 std::vector<const Named_type*>* seen)
7854 const Named_type* nt = type->named_type();
7856 nt = type->deref()->named_type();
7859 if (nt->is_unexported_local_method(gogo, name))
7862 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
7868 // We've already seen this type.
7874 const Interface_type* it = type->interface_type();
7875 if (it != NULL && it->is_unexported_method(gogo, name))
7878 type = type->deref();
7880 const Struct_type* st = type->struct_type();
7881 if (st != NULL && st->is_unexported_local_field(gogo, name))
7887 const Struct_field_list* fields = st->fields();
7892 seen->push_back(nt);
7894 for (Struct_field_list::const_iterator pf = fields->begin();
7895 pf != fields->end();
7898 if (pf->is_anonymous()
7899 && !pf->type()->deref()->is_error_type()
7900 && !pf->type()->deref()->is_undefined())
7902 Named_type* subtype = pf->type()->named_type();
7903 if (subtype == NULL)
7904 subtype = pf->type()->deref()->named_type();
7905 if (subtype == NULL)
7907 // This is an error, but it will be diagnosed elsewhere.
7910 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
7925 // Class Forward_declaration.
7927 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
7928 : Type(TYPE_FORWARD),
7929 named_object_(named_object->resolve()), warned_(false)
7931 go_assert(this->named_object_->is_unknown()
7932 || this->named_object_->is_type_declaration());
7935 // Return the named object.
7938 Forward_declaration_type::named_object()
7940 return this->named_object_->resolve();
7944 Forward_declaration_type::named_object() const
7946 return this->named_object_->resolve();
7949 // Return the name of the forward declared type.
7952 Forward_declaration_type::name() const
7954 return this->named_object()->name();
7957 // Warn about a use of a type which has been declared but not defined.
7960 Forward_declaration_type::warn() const
7962 Named_object* no = this->named_object_->resolve();
7963 if (no->is_unknown())
7965 // The name was not defined anywhere.
7968 error_at(this->named_object_->location(),
7969 "use of undefined type %qs",
7970 no->message_name().c_str());
7971 this->warned_ = true;
7974 else if (no->is_type_declaration())
7976 // The name was seen as a type, but the type was never defined.
7977 if (no->type_declaration_value()->using_type())
7979 error_at(this->named_object_->location(),
7980 "use of undefined type %qs",
7981 no->message_name().c_str());
7982 this->warned_ = true;
7987 // The name was defined, but not as a type.
7990 error_at(this->named_object_->location(), "expected type");
7991 this->warned_ = true;
7996 // Get the base type of a declaration. This gives an error if the
7997 // type has not yet been defined.
8000 Forward_declaration_type::real_type()
8002 if (this->is_defined())
8003 return this->named_object()->type_value();
8007 return Type::make_error_type();
8012 Forward_declaration_type::real_type() const
8014 if (this->is_defined())
8015 return this->named_object()->type_value();
8019 return Type::make_error_type();
8023 // Return whether the base type is defined.
8026 Forward_declaration_type::is_defined() const
8028 return this->named_object()->is_type();
8031 // Add a method. This is used when methods are defined before the
8035 Forward_declaration_type::add_method(const std::string& name,
8038 Named_object* no = this->named_object();
8039 if (no->is_unknown())
8040 no->declare_as_type();
8041 return no->type_declaration_value()->add_method(name, function);
8044 // Add a method declaration. This is used when methods are declared
8048 Forward_declaration_type::add_method_declaration(const std::string& name,
8049 Function_type* type,
8052 Named_object* no = this->named_object();
8053 if (no->is_unknown())
8054 no->declare_as_type();
8055 Type_declaration* td = no->type_declaration_value();
8056 return td->add_method_declaration(name, type, location);
8062 Forward_declaration_type::do_traverse(Traverse* traverse)
8064 if (this->is_defined()
8065 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
8066 return TRAVERSE_EXIT;
8067 return TRAVERSE_CONTINUE;
8070 // Get the backend representation for the type.
8073 Forward_declaration_type::do_get_backend(Gogo* gogo)
8075 if (this->is_defined())
8076 return Type::get_named_base_btype(gogo, this->real_type());
8079 return gogo->backend()->error_type();
8081 // We represent an undefined type as a struct with no fields. That
8082 // should work fine for the backend, since the same case can arise
8084 std::vector<Backend::Btyped_identifier> fields;
8085 Btype* bt = gogo->backend()->struct_type(fields);
8086 return gogo->backend()->named_type(this->name(), bt,
8087 this->named_object()->location());
8090 // Build a type descriptor for a forwarded type.
8093 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8095 Location ploc = Linemap::predeclared_location();
8096 if (!this->is_defined())
8097 return Expression::make_nil(ploc);
8100 Type* t = this->real_type();
8102 return this->named_type_descriptor(gogo, t, name);
8104 return Expression::make_type_descriptor(t, ploc);
8108 // The reflection string.
8111 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
8113 this->append_reflection(this->real_type(), gogo, ret);
8116 // The mangled name.
8119 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8121 if (this->is_defined())
8122 this->append_mangled_name(this->real_type(), gogo, ret);
8125 const Named_object* no = this->named_object();
8127 if (no->package() == NULL)
8128 name = gogo->package_name();
8130 name = no->package()->name();
8132 name += Gogo::unpack_hidden_name(no->name());
8134 snprintf(buf, sizeof buf, "N%u_",
8135 static_cast<unsigned int>(name.length()));
8141 // Export a forward declaration. This can happen when a defined type
8142 // refers to a type which is only declared (and is presumably defined
8143 // in some other file in the same package).
8146 Forward_declaration_type::do_export(Export*) const
8148 // If there is a base type, that should be exported instead of this.
8149 go_assert(!this->is_defined());
8151 // We don't output anything.
8154 // Make a forward declaration.
8157 Type::make_forward_declaration(Named_object* named_object)
8159 return new Forward_declaration_type(named_object);
8162 // Class Typed_identifier_list.
8164 // Sort the entries by name.
8166 struct Typed_identifier_list_sort
8170 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
8171 { return t1.name() < t2.name(); }
8175 Typed_identifier_list::sort_by_name()
8177 std::sort(this->entries_.begin(), this->entries_.end(),
8178 Typed_identifier_list_sort());
8184 Typed_identifier_list::traverse(Traverse* traverse)
8186 for (Typed_identifier_list::const_iterator p = this->begin();
8190 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
8191 return TRAVERSE_EXIT;
8193 return TRAVERSE_CONTINUE;
8198 Typed_identifier_list*
8199 Typed_identifier_list::copy() const
8201 Typed_identifier_list* ret = new Typed_identifier_list();
8202 for (Typed_identifier_list::const_iterator p = this->begin();
8205 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));