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_open_array_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_open_array_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_open_array_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_open_array_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_open_array_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_open_array_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, source_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, 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 source_location loc = nt == NULL ? BUILTINS_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 source_location bloc = BUILTINS_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 source_location bloc = BUILTINS_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 source_location bloc = BUILTINS_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 source_location bloc = BUILTINS_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 source_location bloc = BUILTINS_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 source_location bloc = BUILTINS_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 source_location bloc = BUILTINS_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(BUILTINS_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 = Named_object::make_type("bool", NULL,
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 = Named_object::make_type(sname, NULL,
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 = Named_object::make_type(sname, NULL, float_type,
1970 Named_type* named_type = named_object->type_value();
1971 std::pair<Named_float_types::iterator, bool> ins =
1972 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
1973 go_assert(ins.second);
1977 // Look up an existing float type.
1980 Float_type::lookup_float_type(const char* name)
1982 Named_float_types::const_iterator p =
1983 Float_type::named_float_types.find(name);
1984 go_assert(p != Float_type::named_float_types.end());
1988 // Create a new abstract float type.
1991 Float_type::create_abstract_float_type()
1993 static Float_type* abstract_type;
1994 if (abstract_type == NULL)
1995 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
1996 return abstract_type;
1999 // Whether this type is identical with T.
2002 Float_type::is_identical(const Float_type* t) const
2004 if (this->bits_ != t->bits_)
2006 return this->is_abstract_ == t->is_abstract_;
2012 Float_type::do_hash_for_method(Gogo*) const
2014 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2017 // Convert to the backend representation.
2020 Float_type::do_get_backend(Gogo* gogo)
2022 return gogo->backend()->float_type(this->bits_);
2025 // The type descriptor for a float type. Float types are always named.
2028 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2030 go_assert(name != NULL);
2031 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2034 // We should not be asked for the reflection string of a basic type.
2037 Float_type::do_reflection(Gogo*, std::string*) const
2039 go_assert(saw_errors());
2045 Float_type::do_mangled_name(Gogo*, std::string* ret) const
2048 snprintf(buf, sizeof buf, "f%s%de",
2049 this->is_abstract_ ? "a" : "",
2054 // Make a floating point type.
2057 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
2059 return Float_type::create_float_type(name, bits, runtime_type_kind);
2062 // Make an abstract float type.
2065 Type::make_abstract_float_type()
2067 return Float_type::create_abstract_float_type();
2070 // Look up a float type.
2073 Type::lookup_float_type(const char* name)
2075 return Float_type::lookup_float_type(name);
2078 // Class Complex_type.
2080 Complex_type::Named_complex_types Complex_type::named_complex_types;
2082 // Create a new complex type. Non-abstract complex types always have
2086 Complex_type::create_complex_type(const char* name, int bits,
2087 int runtime_type_kind)
2089 Complex_type* complex_type = new Complex_type(false, bits,
2091 std::string sname(name);
2092 Named_object* named_object = Named_object::make_type(sname, NULL,
2095 Named_type* named_type = named_object->type_value();
2096 std::pair<Named_complex_types::iterator, bool> ins =
2097 Complex_type::named_complex_types.insert(std::make_pair(sname,
2099 go_assert(ins.second);
2103 // Look up an existing complex type.
2106 Complex_type::lookup_complex_type(const char* name)
2108 Named_complex_types::const_iterator p =
2109 Complex_type::named_complex_types.find(name);
2110 go_assert(p != Complex_type::named_complex_types.end());
2114 // Create a new abstract complex type.
2117 Complex_type::create_abstract_complex_type()
2119 static Complex_type* abstract_type;
2120 if (abstract_type == NULL)
2121 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
2122 return abstract_type;
2125 // Whether this type is identical with T.
2128 Complex_type::is_identical(const Complex_type *t) const
2130 if (this->bits_ != t->bits_)
2132 return this->is_abstract_ == t->is_abstract_;
2138 Complex_type::do_hash_for_method(Gogo*) const
2140 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2143 // Convert to the backend representation.
2146 Complex_type::do_get_backend(Gogo* gogo)
2148 return gogo->backend()->complex_type(this->bits_);
2151 // The type descriptor for a complex type. Complex types are always
2155 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2157 go_assert(name != NULL);
2158 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2161 // We should not be asked for the reflection string of a basic type.
2164 Complex_type::do_reflection(Gogo*, std::string*) const
2166 go_assert(saw_errors());
2172 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
2175 snprintf(buf, sizeof buf, "c%s%de",
2176 this->is_abstract_ ? "a" : "",
2181 // Make a complex type.
2184 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
2186 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
2189 // Make an abstract complex type.
2192 Type::make_abstract_complex_type()
2194 return Complex_type::create_abstract_complex_type();
2197 // Look up a complex type.
2200 Type::lookup_complex_type(const char* name)
2202 return Complex_type::lookup_complex_type(name);
2205 // Class String_type.
2207 // Convert String_type to the backend representation. A string is a
2208 // struct with two fields: a pointer to the characters and a length.
2211 String_type::do_get_backend(Gogo* gogo)
2213 static Btype* backend_string_type;
2214 if (backend_string_type == NULL)
2216 std::vector<Backend::Btyped_identifier> fields(2);
2218 Type* b = gogo->lookup_global("byte")->type_value();
2219 Type* pb = Type::make_pointer_type(b);
2220 fields[0].name = "__data";
2221 fields[0].btype = pb->get_backend(gogo);
2222 fields[0].location = UNKNOWN_LOCATION;
2224 Type* int_type = Type::lookup_integer_type("int");
2225 fields[1].name = "__length";
2226 fields[1].btype = int_type->get_backend(gogo);
2227 fields[1].location = UNKNOWN_LOCATION;
2229 backend_string_type = gogo->backend()->struct_type(fields);
2231 return backend_string_type;
2234 // Return a tree for the length of STRING.
2237 String_type::length_tree(Gogo*, tree string)
2239 tree string_type = TREE_TYPE(string);
2240 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2241 tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type));
2242 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)),
2244 return fold_build3(COMPONENT_REF, integer_type_node, string,
2245 length_field, NULL_TREE);
2248 // Return a tree for a pointer to the bytes of STRING.
2251 String_type::bytes_tree(Gogo*, tree string)
2253 tree string_type = TREE_TYPE(string);
2254 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2255 tree bytes_field = TYPE_FIELDS(string_type);
2256 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)),
2258 return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string,
2259 bytes_field, NULL_TREE);
2262 // The type descriptor for the string type.
2265 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2268 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
2271 Named_object* no = gogo->lookup_global("string");
2272 go_assert(no != NULL);
2273 return Type::type_descriptor(gogo, no->type_value());
2277 // We should not be asked for the reflection string of a basic type.
2280 String_type::do_reflection(Gogo*, std::string* ret) const
2282 ret->append("string");
2285 // Mangled name of a string type.
2288 String_type::do_mangled_name(Gogo*, std::string* ret) const
2290 ret->push_back('z');
2293 // Make a string type.
2296 Type::make_string_type()
2298 static String_type string_type;
2299 return &string_type;
2302 // The named type "string".
2304 static Named_type* named_string_type;
2306 // Get the named type "string".
2309 Type::lookup_string_type()
2311 return named_string_type;
2314 // Make the named type string.
2317 Type::make_named_string_type()
2319 Type* string_type = Type::make_string_type();
2320 Named_object* named_object = Named_object::make_type("string", NULL,
2323 Named_type* named_type = named_object->type_value();
2324 named_string_type = named_type;
2328 // The sink type. This is the type of the blank identifier _. Any
2329 // type may be assigned to it.
2331 class Sink_type : public Type
2340 do_get_backend(Gogo*)
2341 { go_unreachable(); }
2344 do_type_descriptor(Gogo*, Named_type*)
2345 { go_unreachable(); }
2348 do_reflection(Gogo*, std::string*) const
2349 { go_unreachable(); }
2352 do_mangled_name(Gogo*, std::string*) const
2353 { go_unreachable(); }
2356 // Make the sink type.
2359 Type::make_sink_type()
2361 static Sink_type sink_type;
2365 // Class Function_type.
2370 Function_type::do_traverse(Traverse* traverse)
2372 if (this->receiver_ != NULL
2373 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
2374 return TRAVERSE_EXIT;
2375 if (this->parameters_ != NULL
2376 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
2377 return TRAVERSE_EXIT;
2378 if (this->results_ != NULL
2379 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
2380 return TRAVERSE_EXIT;
2381 return TRAVERSE_CONTINUE;
2384 // Returns whether T is a valid redeclaration of this type. If this
2385 // returns false, and REASON is not NULL, *REASON may be set to a
2386 // brief explanation of why it returned false.
2389 Function_type::is_valid_redeclaration(const Function_type* t,
2390 std::string* reason) const
2392 if (!this->is_identical(t, false, true, reason))
2395 // A redeclaration of a function is required to use the same names
2396 // for the receiver and parameters.
2397 if (this->receiver() != NULL
2398 && this->receiver()->name() != t->receiver()->name()
2399 && this->receiver()->name() != Import::import_marker
2400 && t->receiver()->name() != Import::import_marker)
2403 *reason = "receiver name changed";
2407 const Typed_identifier_list* parms1 = this->parameters();
2408 const Typed_identifier_list* parms2 = t->parameters();
2411 Typed_identifier_list::const_iterator p1 = parms1->begin();
2412 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
2413 p2 != parms2->end();
2416 if (p1->name() != p2->name()
2417 && p1->name() != Import::import_marker
2418 && p2->name() != Import::import_marker)
2421 *reason = "parameter name changed";
2425 // This is called at parse time, so we may have unknown
2427 Type* t1 = p1->type()->forwarded();
2428 Type* t2 = p2->type()->forwarded();
2430 && t1->forward_declaration_type() != NULL
2431 && (t2->forward_declaration_type() == NULL
2432 || (t1->forward_declaration_type()->named_object()
2433 != t2->forward_declaration_type()->named_object())))
2438 const Typed_identifier_list* results1 = this->results();
2439 const Typed_identifier_list* results2 = t->results();
2440 if (results1 != NULL)
2442 Typed_identifier_list::const_iterator res1 = results1->begin();
2443 for (Typed_identifier_list::const_iterator res2 = results2->begin();
2444 res2 != results2->end();
2447 if (res1->name() != res2->name()
2448 && res1->name() != Import::import_marker
2449 && res2->name() != Import::import_marker)
2452 *reason = "result name changed";
2456 // This is called at parse time, so we may have unknown
2458 Type* t1 = res1->type()->forwarded();
2459 Type* t2 = res2->type()->forwarded();
2461 && t1->forward_declaration_type() != NULL
2462 && (t2->forward_declaration_type() == NULL
2463 || (t1->forward_declaration_type()->named_object()
2464 != t2->forward_declaration_type()->named_object())))
2472 // Check whether T is the same as this type.
2475 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
2476 bool errors_are_identical,
2477 std::string* reason) const
2479 if (!ignore_receiver)
2481 const Typed_identifier* r1 = this->receiver();
2482 const Typed_identifier* r2 = t->receiver();
2483 if ((r1 != NULL) != (r2 != NULL))
2486 *reason = _("different receiver types");
2491 if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
2494 if (reason != NULL && !reason->empty())
2495 *reason = "receiver: " + *reason;
2501 const Typed_identifier_list* parms1 = this->parameters();
2502 const Typed_identifier_list* parms2 = t->parameters();
2503 if ((parms1 != NULL) != (parms2 != NULL))
2506 *reason = _("different number of parameters");
2511 Typed_identifier_list::const_iterator p1 = parms1->begin();
2512 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
2513 p2 != parms2->end();
2516 if (p1 == parms1->end())
2519 *reason = _("different number of parameters");
2523 if (!Type::are_identical(p1->type(), p2->type(),
2524 errors_are_identical, NULL))
2527 *reason = _("different parameter types");
2531 if (p1 != parms1->end())
2534 *reason = _("different number of parameters");
2539 if (this->is_varargs() != t->is_varargs())
2542 *reason = _("different varargs");
2546 const Typed_identifier_list* results1 = this->results();
2547 const Typed_identifier_list* results2 = t->results();
2548 if ((results1 != NULL) != (results2 != NULL))
2551 *reason = _("different number of results");
2554 if (results1 != NULL)
2556 Typed_identifier_list::const_iterator res1 = results1->begin();
2557 for (Typed_identifier_list::const_iterator res2 = results2->begin();
2558 res2 != results2->end();
2561 if (res1 == results1->end())
2564 *reason = _("different number of results");
2568 if (!Type::are_identical(res1->type(), res2->type(),
2569 errors_are_identical, NULL))
2572 *reason = _("different result types");
2576 if (res1 != results1->end())
2579 *reason = _("different number of results");
2590 Function_type::do_hash_for_method(Gogo* gogo) const
2592 unsigned int ret = 0;
2593 // We ignore the receiver type for hash codes, because we need to
2594 // get the same hash code for a method in an interface and a method
2595 // declared for a type. The former will not have a receiver.
2596 if (this->parameters_ != NULL)
2599 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
2600 p != this->parameters_->end();
2602 ret += p->type()->hash_for_method(gogo) << shift;
2604 if (this->results_ != NULL)
2607 for (Typed_identifier_list::const_iterator p = this->results_->begin();
2608 p != this->results_->end();
2610 ret += p->type()->hash_for_method(gogo) << shift;
2612 if (this->is_varargs_)
2618 // Get the backend representation for a function type.
2621 Function_type::get_function_backend(Gogo* gogo)
2623 Backend::Btyped_identifier breceiver;
2624 if (this->receiver_ != NULL)
2626 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
2628 // We always pass the address of the receiver parameter, in
2629 // order to make interface calls work with unknown types.
2630 Type* rtype = this->receiver_->type();
2631 if (rtype->points_to() == NULL)
2632 rtype = Type::make_pointer_type(rtype);
2633 breceiver.btype = rtype->get_backend(gogo);
2634 breceiver.location = this->receiver_->location();
2637 std::vector<Backend::Btyped_identifier> bparameters;
2638 if (this->parameters_ != NULL)
2640 bparameters.resize(this->parameters_->size());
2642 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
2643 p != this->parameters_->end();
2646 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
2647 bparameters[i].btype = p->type()->get_backend(gogo);
2648 bparameters[i].location = p->location();
2650 go_assert(i == bparameters.size());
2653 std::vector<Backend::Btyped_identifier> bresults;
2654 if (this->results_ != NULL)
2656 bresults.resize(this->results_->size());
2658 for (Typed_identifier_list::const_iterator p = this->results_->begin();
2659 p != this->results_->end();
2662 bresults[i].name = Gogo::unpack_hidden_name(p->name());
2663 bresults[i].btype = p->type()->get_backend(gogo);
2664 bresults[i].location = p->location();
2666 go_assert(i == bresults.size());
2669 return gogo->backend()->function_type(breceiver, bparameters, bresults,
2673 // A hash table mapping function types to their backend placeholders.
2675 Function_type::Placeholders Function_type::placeholders;
2677 // Get the backend representation for a function type. If we are
2678 // still converting types, and this types has multiple results, return
2679 // a placeholder instead. We do this because for multiple results we
2680 // build a struct, and we need to make sure that all the types in the
2681 // struct are valid before we create the struct.
2684 Function_type::do_get_backend(Gogo* gogo)
2686 if (!gogo->named_types_are_converted()
2687 && this->results_ != NULL
2688 && this->results_->size() > 1)
2690 Btype* placeholder =
2691 gogo->backend()->placeholder_pointer_type("", this->location(), true);
2692 Function_type::placeholders.push_back(std::make_pair(this, placeholder));
2695 return this->get_function_backend(gogo);
2698 // Convert function types after all named types are converted.
2701 Function_type::convert_types(Gogo* gogo)
2703 for (Placeholders::const_iterator p = Function_type::placeholders.begin();
2704 p != Function_type::placeholders.end();
2707 Btype* bt = p->first->get_function_backend(gogo);
2708 if (!gogo->backend()->set_placeholder_function_type(p->second, bt))
2709 go_assert(saw_errors());
2713 // The type of a function type descriptor.
2716 Function_type::make_function_type_descriptor_type()
2721 Type* tdt = Type::make_type_descriptor_type();
2722 Type* ptdt = Type::make_type_descriptor_ptr_type();
2724 Type* bool_type = Type::lookup_bool_type();
2726 Type* slice_type = Type::make_array_type(ptdt, NULL);
2728 Struct_type* s = Type::make_builtin_struct_type(4,
2730 "dotdotdot", bool_type,
2734 ret = Type::make_builtin_named_type("FuncType", s);
2740 // The type descriptor for a function type.
2743 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2745 source_location bloc = BUILTINS_LOCATION;
2747 Type* ftdt = Function_type::make_function_type_descriptor_type();
2749 const Struct_field_list* fields = ftdt->struct_type()->fields();
2751 Expression_list* vals = new Expression_list();
2754 Struct_field_list::const_iterator p = fields->begin();
2755 go_assert(p->is_field_name("commonType"));
2756 vals->push_back(this->type_descriptor_constructor(gogo,
2757 RUNTIME_TYPE_KIND_FUNC,
2761 go_assert(p->is_field_name("dotdotdot"));
2762 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
2765 go_assert(p->is_field_name("in"));
2766 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
2767 this->parameters()));
2770 go_assert(p->is_field_name("out"));
2771 vals->push_back(this->type_descriptor_params(p->type(), NULL,
2775 go_assert(p == fields->end());
2777 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
2780 // Return a composite literal for the parameters or results of a type
2784 Function_type::type_descriptor_params(Type* params_type,
2785 const Typed_identifier* receiver,
2786 const Typed_identifier_list* params)
2788 source_location bloc = BUILTINS_LOCATION;
2790 if (receiver == NULL && params == NULL)
2791 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
2793 Expression_list* vals = new Expression_list();
2794 vals->reserve((params == NULL ? 0 : params->size())
2795 + (receiver != NULL ? 1 : 0));
2797 if (receiver != NULL)
2798 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
2802 for (Typed_identifier_list::const_iterator p = params->begin();
2805 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
2808 return Expression::make_slice_composite_literal(params_type, vals, bloc);
2811 // The reflection string.
2814 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
2816 // FIXME: Turn this off until we straighten out the type of the
2817 // struct field used in a go statement which calls a method.
2818 // go_assert(this->receiver_ == NULL);
2820 ret->append("func");
2822 if (this->receiver_ != NULL)
2824 ret->push_back('(');
2825 this->append_reflection(this->receiver_->type(), gogo, ret);
2826 ret->push_back(')');
2829 ret->push_back('(');
2830 const Typed_identifier_list* params = this->parameters();
2833 bool is_varargs = this->is_varargs_;
2834 for (Typed_identifier_list::const_iterator p = params->begin();
2838 if (p != params->begin())
2840 if (!is_varargs || p + 1 != params->end())
2841 this->append_reflection(p->type(), gogo, ret);
2845 this->append_reflection(p->type()->array_type()->element_type(),
2850 ret->push_back(')');
2852 const Typed_identifier_list* results = this->results();
2853 if (results != NULL && !results->empty())
2855 if (results->size() == 1)
2856 ret->push_back(' ');
2859 for (Typed_identifier_list::const_iterator p = results->begin();
2860 p != results->end();
2863 if (p != results->begin())
2865 this->append_reflection(p->type(), gogo, ret);
2867 if (results->size() > 1)
2868 ret->push_back(')');
2875 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
2877 ret->push_back('F');
2879 if (this->receiver_ != NULL)
2881 ret->push_back('m');
2882 this->append_mangled_name(this->receiver_->type(), gogo, ret);
2885 const Typed_identifier_list* params = this->parameters();
2888 ret->push_back('p');
2889 for (Typed_identifier_list::const_iterator p = params->begin();
2892 this->append_mangled_name(p->type(), gogo, ret);
2893 if (this->is_varargs_)
2894 ret->push_back('V');
2895 ret->push_back('e');
2898 const Typed_identifier_list* results = this->results();
2899 if (results != NULL)
2901 ret->push_back('r');
2902 for (Typed_identifier_list::const_iterator p = results->begin();
2903 p != results->end();
2905 this->append_mangled_name(p->type(), gogo, ret);
2906 ret->push_back('e');
2909 ret->push_back('e');
2912 // Export a function type.
2915 Function_type::do_export(Export* exp) const
2917 // We don't write out the receiver. The only function types which
2918 // should have a receiver are the ones associated with explicitly
2919 // defined methods. For those the receiver type is written out by
2920 // Function::export_func.
2922 exp->write_c_string("(");
2924 if (this->parameters_ != NULL)
2926 bool is_varargs = this->is_varargs_;
2927 for (Typed_identifier_list::const_iterator p =
2928 this->parameters_->begin();
2929 p != this->parameters_->end();
2935 exp->write_c_string(", ");
2936 if (!is_varargs || p + 1 != this->parameters_->end())
2937 exp->write_type(p->type());
2940 exp->write_c_string("...");
2941 exp->write_type(p->type()->array_type()->element_type());
2945 exp->write_c_string(")");
2947 const Typed_identifier_list* results = this->results_;
2948 if (results != NULL)
2950 exp->write_c_string(" ");
2951 if (results->size() == 1)
2952 exp->write_type(results->begin()->type());
2956 exp->write_c_string("(");
2957 for (Typed_identifier_list::const_iterator p = results->begin();
2958 p != results->end();
2964 exp->write_c_string(", ");
2965 exp->write_type(p->type());
2967 exp->write_c_string(")");
2972 // Import a function type.
2975 Function_type::do_import(Import* imp)
2977 imp->require_c_string("(");
2978 Typed_identifier_list* parameters;
2979 bool is_varargs = false;
2980 if (imp->peek_char() == ')')
2984 parameters = new Typed_identifier_list();
2987 if (imp->match_c_string("..."))
2993 Type* ptype = imp->read_type();
2995 ptype = Type::make_array_type(ptype, NULL);
2996 parameters->push_back(Typed_identifier(Import::import_marker,
2997 ptype, imp->location()));
2998 if (imp->peek_char() != ',')
3000 go_assert(!is_varargs);
3001 imp->require_c_string(", ");
3004 imp->require_c_string(")");
3006 Typed_identifier_list* results;
3007 if (imp->peek_char() != ' ')
3012 results = new Typed_identifier_list;
3013 if (imp->peek_char() != '(')
3015 Type* rtype = imp->read_type();
3016 results->push_back(Typed_identifier(Import::import_marker, rtype,
3024 Type* rtype = imp->read_type();
3025 results->push_back(Typed_identifier(Import::import_marker,
3026 rtype, imp->location()));
3027 if (imp->peek_char() != ',')
3029 imp->require_c_string(", ");
3031 imp->require_c_string(")");
3035 Function_type* ret = Type::make_function_type(NULL, parameters, results,
3038 ret->set_is_varargs();
3042 // Make a copy of a function type without a receiver.
3045 Function_type::copy_without_receiver() const
3047 go_assert(this->is_method());
3048 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
3051 if (this->is_varargs())
3052 ret->set_is_varargs();
3053 if (this->is_builtin())
3054 ret->set_is_builtin();
3058 // Make a copy of a function type with a receiver.
3061 Function_type::copy_with_receiver(Type* receiver_type) const
3063 go_assert(!this->is_method());
3064 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
3066 return Type::make_function_type(receiver, this->parameters_,
3067 this->results_, this->location_);
3070 // Make a function type.
3073 Type::make_function_type(Typed_identifier* receiver,
3074 Typed_identifier_list* parameters,
3075 Typed_identifier_list* results,
3076 source_location location)
3078 return new Function_type(receiver, parameters, results, location);
3081 // Class Pointer_type.
3086 Pointer_type::do_traverse(Traverse* traverse)
3088 return Type::traverse(this->to_type_, traverse);
3094 Pointer_type::do_hash_for_method(Gogo* gogo) const
3096 return this->to_type_->hash_for_method(gogo) << 4;
3099 // The tree for a pointer type.
3102 Pointer_type::do_get_backend(Gogo* gogo)
3104 Btype* to_btype = this->to_type_->get_backend(gogo);
3105 return gogo->backend()->pointer_type(to_btype);
3108 // The type of a pointer type descriptor.
3111 Pointer_type::make_pointer_type_descriptor_type()
3116 Type* tdt = Type::make_type_descriptor_type();
3117 Type* ptdt = Type::make_type_descriptor_ptr_type();
3119 Struct_type* s = Type::make_builtin_struct_type(2,
3123 ret = Type::make_builtin_named_type("PtrType", s);
3129 // The type descriptor for a pointer type.
3132 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3134 if (this->is_unsafe_pointer_type())
3136 go_assert(name != NULL);
3137 return this->plain_type_descriptor(gogo,
3138 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
3143 source_location bloc = BUILTINS_LOCATION;
3145 const Methods* methods;
3146 Type* deref = this->points_to();
3147 if (deref->named_type() != NULL)
3148 methods = deref->named_type()->methods();
3149 else if (deref->struct_type() != NULL)
3150 methods = deref->struct_type()->methods();
3154 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
3156 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
3158 Expression_list* vals = new Expression_list();
3161 Struct_field_list::const_iterator p = fields->begin();
3162 go_assert(p->is_field_name("commonType"));
3163 vals->push_back(this->type_descriptor_constructor(gogo,
3164 RUNTIME_TYPE_KIND_PTR,
3165 name, methods, false));
3168 go_assert(p->is_field_name("elem"));
3169 vals->push_back(Expression::make_type_descriptor(deref, bloc));
3171 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
3175 // Reflection string.
3178 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
3180 ret->push_back('*');
3181 this->append_reflection(this->to_type_, gogo, ret);
3187 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3189 ret->push_back('p');
3190 this->append_mangled_name(this->to_type_, gogo, ret);
3196 Pointer_type::do_export(Export* exp) const
3198 exp->write_c_string("*");
3199 if (this->is_unsafe_pointer_type())
3200 exp->write_c_string("any");
3202 exp->write_type(this->to_type_);
3208 Pointer_type::do_import(Import* imp)
3210 imp->require_c_string("*");
3211 if (imp->match_c_string("any"))
3214 return Type::make_pointer_type(Type::make_void_type());
3216 Type* to = imp->read_type();
3217 return Type::make_pointer_type(to);
3220 // Make a pointer type.
3223 Type::make_pointer_type(Type* to_type)
3225 typedef Unordered_map(Type*, Pointer_type*) Hashtable;
3226 static Hashtable pointer_types;
3227 Hashtable::const_iterator p = pointer_types.find(to_type);
3228 if (p != pointer_types.end())
3230 Pointer_type* ret = new Pointer_type(to_type);
3231 pointer_types[to_type] = ret;
3235 // The nil type. We use a special type for nil because it is not the
3236 // same as any other type. In C term nil has type void*, but there is
3237 // no such type in Go.
3239 class Nil_type : public Type
3248 do_get_backend(Gogo* gogo)
3249 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
3252 do_type_descriptor(Gogo*, Named_type*)
3253 { go_unreachable(); }
3256 do_reflection(Gogo*, std::string*) const
3257 { go_unreachable(); }
3260 do_mangled_name(Gogo*, std::string* ret) const
3261 { ret->push_back('n'); }
3264 // Make the nil type.
3267 Type::make_nil_type()
3269 static Nil_type singleton_nil_type;
3270 return &singleton_nil_type;
3273 // The type of a function call which returns multiple values. This is
3274 // really a struct, but we don't want to confuse a function call which
3275 // returns a struct with a function call which returns multiple
3278 class Call_multiple_result_type : public Type
3281 Call_multiple_result_type(Call_expression* call)
3282 : Type(TYPE_CALL_MULTIPLE_RESULT),
3288 do_has_pointer() const
3290 go_assert(saw_errors());
3295 do_get_backend(Gogo* gogo)
3297 go_assert(saw_errors());
3298 return gogo->backend()->error_type();
3302 do_type_descriptor(Gogo*, Named_type*)
3304 go_assert(saw_errors());
3305 return Expression::make_error(UNKNOWN_LOCATION);
3309 do_reflection(Gogo*, std::string*) const
3310 { go_assert(saw_errors()); }
3313 do_mangled_name(Gogo*, std::string*) const
3314 { go_assert(saw_errors()); }
3317 // The expression being called.
3318 Call_expression* call_;
3321 // Make a call result type.
3324 Type::make_call_multiple_result_type(Call_expression* call)
3326 return new Call_multiple_result_type(call);
3329 // Class Struct_field.
3331 // Get the name of a field.
3334 Struct_field::field_name() const
3336 const std::string& name(this->typed_identifier_.name());
3341 // This is called during parsing, before anything is lowered, so
3342 // we have to be pretty careful to avoid dereferencing an
3343 // unknown type name.
3344 Type* t = this->typed_identifier_.type();
3346 if (t->classification() == Type::TYPE_POINTER)
3349 Pointer_type* ptype = static_cast<Pointer_type*>(t);
3350 dt = ptype->points_to();
3352 if (dt->forward_declaration_type() != NULL)
3353 return dt->forward_declaration_type()->name();
3354 else if (dt->named_type() != NULL)
3355 return dt->named_type()->name();
3356 else if (t->is_error_type() || dt->is_error_type())
3358 static const std::string error_string = "*error*";
3359 return error_string;
3363 // Avoid crashing in the erroneous case where T is named but
3366 if (t->forward_declaration_type() != NULL)
3367 return t->forward_declaration_type()->name();
3368 else if (t->named_type() != NULL)
3369 return t->named_type()->name();
3376 // Return whether this field is named NAME.
3379 Struct_field::is_field_name(const std::string& name) const
3381 const std::string& me(this->typed_identifier_.name());
3386 Type* t = this->typed_identifier_.type();
3387 if (t->points_to() != NULL)
3389 Named_type* nt = t->named_type();
3390 if (nt != NULL && nt->name() == name)
3393 // This is a horrible hack caused by the fact that we don't pack
3394 // the names of builtin types. FIXME.
3397 && nt->name() == Gogo::unpack_hidden_name(name))
3404 // Class Struct_type.
3409 Struct_type::do_traverse(Traverse* traverse)
3411 Struct_field_list* fields = this->fields_;
3414 for (Struct_field_list::iterator p = fields->begin();
3418 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
3419 return TRAVERSE_EXIT;
3422 return TRAVERSE_CONTINUE;
3425 // Verify that the struct type is complete and valid.
3428 Struct_type::do_verify()
3430 Struct_field_list* fields = this->fields_;
3434 for (Struct_field_list::iterator p = fields->begin();
3438 Type* t = p->type();
3439 if (t->is_undefined())
3441 error_at(p->location(), "struct field type is incomplete");
3442 p->set_type(Type::make_error_type());
3445 else if (p->is_anonymous())
3447 if (t->named_type() != NULL && t->points_to() != NULL)
3449 error_at(p->location(), "embedded type may not be a pointer");
3450 p->set_type(Type::make_error_type());
3453 if (t->points_to() != NULL
3454 && t->points_to()->interface_type() != NULL)
3456 error_at(p->location(),
3457 "embedded type may not be pointer to interface");
3458 p->set_type(Type::make_error_type());
3466 // Whether this contains a pointer.
3469 Struct_type::do_has_pointer() const
3471 const Struct_field_list* fields = this->fields();
3474 for (Struct_field_list::const_iterator p = fields->begin();
3478 if (p->type()->has_pointer())
3484 // Whether this type is identical to T.
3487 Struct_type::is_identical(const Struct_type* t,
3488 bool errors_are_identical) const
3490 const Struct_field_list* fields1 = this->fields();
3491 const Struct_field_list* fields2 = t->fields();
3492 if (fields1 == NULL || fields2 == NULL)
3493 return fields1 == fields2;
3494 Struct_field_list::const_iterator pf2 = fields2->begin();
3495 for (Struct_field_list::const_iterator pf1 = fields1->begin();
3496 pf1 != fields1->end();
3499 if (pf2 == fields2->end())
3501 if (pf1->field_name() != pf2->field_name())
3503 if (pf1->is_anonymous() != pf2->is_anonymous()
3504 || !Type::are_identical(pf1->type(), pf2->type(),
3505 errors_are_identical, NULL))
3507 if (!pf1->has_tag())
3514 if (!pf2->has_tag())
3516 if (pf1->tag() != pf2->tag())
3520 if (pf2 != fields2->end())
3525 // Whether this struct type has any hidden fields.
3528 Struct_type::struct_has_hidden_fields(const Named_type* within,
3529 std::string* reason) const
3531 const Struct_field_list* fields = this->fields();
3534 const Package* within_package = (within == NULL
3536 : within->named_object()->package());
3537 for (Struct_field_list::const_iterator pf = fields->begin();
3538 pf != fields->end();
3541 if (within_package != NULL
3542 && !pf->is_anonymous()
3543 && Gogo::is_hidden_name(pf->field_name()))
3547 std::string within_name = within->named_object()->message_name();
3548 std::string name = Gogo::message_name(pf->field_name());
3549 size_t bufsize = 200 + within_name.length() + name.length();
3550 char* buf = new char[bufsize];
3551 snprintf(buf, bufsize,
3552 _("implicit assignment of %s%s%s hidden field %s%s%s"),
3553 open_quote, within_name.c_str(), close_quote,
3554 open_quote, name.c_str(), close_quote);
3555 reason->assign(buf);
3561 if (pf->type()->has_hidden_fields(within, reason))
3571 Struct_type::do_hash_for_method(Gogo* gogo) const
3573 unsigned int ret = 0;
3574 if (this->fields() != NULL)
3576 for (Struct_field_list::const_iterator pf = this->fields()->begin();
3577 pf != this->fields()->end();
3579 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
3584 // Find the local field NAME.
3587 Struct_type::find_local_field(const std::string& name,
3588 unsigned int *pindex) const
3590 const Struct_field_list* fields = this->fields_;
3594 for (Struct_field_list::const_iterator pf = fields->begin();
3595 pf != fields->end();
3598 if (pf->is_field_name(name))
3608 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
3610 Field_reference_expression*
3611 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
3612 source_location location) const
3615 return this->field_reference_depth(struct_expr, name, location, NULL,
3619 // Return an expression for a field, along with the depth at which it
3622 Field_reference_expression*
3623 Struct_type::field_reference_depth(Expression* struct_expr,
3624 const std::string& name,
3625 source_location location,
3626 Saw_named_type* saw,
3627 unsigned int* depth) const
3629 const Struct_field_list* fields = this->fields_;
3633 // Look for a field with this name.
3635 for (Struct_field_list::const_iterator pf = fields->begin();
3636 pf != fields->end();
3639 if (pf->is_field_name(name))
3642 return Expression::make_field_reference(struct_expr, i, location);
3646 // Look for an anonymous field which contains a field with this
3648 unsigned int found_depth = 0;
3649 Field_reference_expression* ret = NULL;
3651 for (Struct_field_list::const_iterator pf = fields->begin();
3652 pf != fields->end();
3655 if (!pf->is_anonymous())
3658 Struct_type* st = pf->type()->deref()->struct_type();
3662 Saw_named_type* hold_saw = saw;
3663 Saw_named_type saw_here;
3664 Named_type* nt = pf->type()->named_type();
3666 nt = pf->type()->deref()->named_type();
3670 for (q = saw; q != NULL; q = q->next)
3674 // If this is an error, it will be reported
3681 saw_here.next = saw;
3686 // Look for a reference using a NULL struct expression. If we
3687 // find one, fill in the struct expression with a reference to
3689 unsigned int subdepth;
3690 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
3700 if (ret == NULL || subdepth < found_depth)
3705 found_depth = subdepth;
3706 Expression* here = Expression::make_field_reference(struct_expr, i,
3708 if (pf->type()->points_to() != NULL)
3709 here = Expression::make_unary(OPERATOR_MULT, here, location);
3710 while (sub->expr() != NULL)
3712 sub = sub->expr()->deref()->field_reference_expression();
3713 go_assert(sub != NULL);
3715 sub->set_struct_expression(here);
3717 else if (subdepth > found_depth)
3721 // We do not handle ambiguity here--it should be handled by
3722 // Type::bind_field_or_method.
3730 *depth = found_depth + 1;
3735 // Return the total number of fields, including embedded fields.
3738 Struct_type::total_field_count() const
3740 if (this->fields_ == NULL)
3742 unsigned int ret = 0;
3743 for (Struct_field_list::const_iterator pf = this->fields_->begin();
3744 pf != this->fields_->end();
3747 if (!pf->is_anonymous() || pf->type()->deref()->struct_type() == NULL)
3750 ret += pf->type()->struct_type()->total_field_count();
3755 // Return whether NAME is an unexported field, for better error reporting.
3758 Struct_type::is_unexported_local_field(Gogo* gogo,
3759 const std::string& name) const
3761 const Struct_field_list* fields = this->fields_;
3764 for (Struct_field_list::const_iterator pf = fields->begin();
3765 pf != fields->end();
3768 const std::string& field_name(pf->field_name());
3769 if (Gogo::is_hidden_name(field_name)
3770 && name == Gogo::unpack_hidden_name(field_name)
3771 && gogo->pack_hidden_name(name, false) != field_name)
3778 // Finalize the methods of an unnamed struct.
3781 Struct_type::finalize_methods(Gogo* gogo)
3783 if (this->all_methods_ != NULL)
3785 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
3788 // Return the method NAME, or NULL if there isn't one or if it is
3789 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
3793 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
3795 return Type::method_function(this->all_methods_, name, is_ambiguous);
3798 // Convert struct fields to the backend representation. This is not
3799 // declared in types.h so that types.h doesn't have to #include
3803 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
3804 std::vector<Backend::Btyped_identifier>* bfields)
3806 bfields->resize(fields->size());
3808 for (Struct_field_list::const_iterator p = fields->begin();
3812 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
3813 (*bfields)[i].btype = p->type()->get_backend(gogo);
3814 (*bfields)[i].location = p->location();
3816 go_assert(i == fields->size());
3819 // Get the tree for a struct type.
3822 Struct_type::do_get_backend(Gogo* gogo)
3824 std::vector<Backend::Btyped_identifier> bfields;
3825 get_backend_struct_fields(gogo, this->fields_, &bfields);
3826 return gogo->backend()->struct_type(bfields);
3829 // The type of a struct type descriptor.
3832 Struct_type::make_struct_type_descriptor_type()
3837 Type* tdt = Type::make_type_descriptor_type();
3838 Type* ptdt = Type::make_type_descriptor_ptr_type();
3840 Type* uintptr_type = Type::lookup_integer_type("uintptr");
3841 Type* string_type = Type::lookup_string_type();
3842 Type* pointer_string_type = Type::make_pointer_type(string_type);
3845 Type::make_builtin_struct_type(5,
3846 "name", pointer_string_type,
3847 "pkgPath", pointer_string_type,
3849 "tag", pointer_string_type,
3850 "offset", uintptr_type);
3851 Type* nsf = Type::make_builtin_named_type("structField", sf);
3853 Type* slice_type = Type::make_array_type(nsf, NULL);
3855 Struct_type* s = Type::make_builtin_struct_type(2,
3857 "fields", slice_type);
3859 ret = Type::make_builtin_named_type("StructType", s);
3865 // Build a type descriptor for a struct type.
3868 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3870 source_location bloc = BUILTINS_LOCATION;
3872 Type* stdt = Struct_type::make_struct_type_descriptor_type();
3874 const Struct_field_list* fields = stdt->struct_type()->fields();
3876 Expression_list* vals = new Expression_list();
3879 const Methods* methods = this->methods();
3880 // A named struct should not have methods--the methods should attach
3881 // to the named type.
3882 go_assert(methods == NULL || name == NULL);
3884 Struct_field_list::const_iterator ps = fields->begin();
3885 go_assert(ps->is_field_name("commonType"));
3886 vals->push_back(this->type_descriptor_constructor(gogo,
3887 RUNTIME_TYPE_KIND_STRUCT,
3888 name, methods, true));
3891 go_assert(ps->is_field_name("fields"));
3893 Expression_list* elements = new Expression_list();
3894 elements->reserve(this->fields_->size());
3895 Type* element_type = ps->type()->array_type()->element_type();
3896 for (Struct_field_list::const_iterator pf = this->fields_->begin();
3897 pf != this->fields_->end();
3900 const Struct_field_list* f = element_type->struct_type()->fields();
3902 Expression_list* fvals = new Expression_list();
3905 Struct_field_list::const_iterator q = f->begin();
3906 go_assert(q->is_field_name("name"));
3907 if (pf->is_anonymous())
3908 fvals->push_back(Expression::make_nil(bloc));
3911 std::string n = Gogo::unpack_hidden_name(pf->field_name());
3912 Expression* s = Expression::make_string(n, bloc);
3913 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3917 go_assert(q->is_field_name("pkgPath"));
3918 if (!Gogo::is_hidden_name(pf->field_name()))
3919 fvals->push_back(Expression::make_nil(bloc));
3922 std::string n = Gogo::hidden_name_prefix(pf->field_name());
3923 Expression* s = Expression::make_string(n, bloc);
3924 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3928 go_assert(q->is_field_name("typ"));
3929 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
3932 go_assert(q->is_field_name("tag"));
3934 fvals->push_back(Expression::make_nil(bloc));
3937 Expression* s = Expression::make_string(pf->tag(), bloc);
3938 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3942 go_assert(q->is_field_name("offset"));
3943 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
3945 Expression* v = Expression::make_struct_composite_literal(element_type,
3947 elements->push_back(v);
3950 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
3953 return Expression::make_struct_composite_literal(stdt, vals, bloc);
3956 // Reflection string.
3959 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
3961 ret->append("struct { ");
3963 for (Struct_field_list::const_iterator p = this->fields_->begin();
3964 p != this->fields_->end();
3967 if (p != this->fields_->begin())
3969 if (p->is_anonymous())
3970 ret->push_back('?');
3972 ret->append(Gogo::unpack_hidden_name(p->field_name()));
3973 ret->push_back(' ');
3974 this->append_reflection(p->type(), gogo, ret);
3978 const std::string& tag(p->tag());
3980 for (std::string::const_iterator p = tag.begin();
3985 ret->append("\\x00");
3986 else if (*p == '\n')
3988 else if (*p == '\t')
3991 ret->append("\\\"");
3992 else if (*p == '\\')
3993 ret->append("\\\\");
3997 ret->push_back('"');
4007 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4009 ret->push_back('S');
4011 const Struct_field_list* fields = this->fields_;
4014 for (Struct_field_list::const_iterator p = fields->begin();
4018 if (p->is_anonymous())
4022 std::string n = Gogo::unpack_hidden_name(p->field_name());
4024 snprintf(buf, sizeof buf, "%u_",
4025 static_cast<unsigned int>(n.length()));
4029 this->append_mangled_name(p->type(), gogo, ret);
4032 const std::string& tag(p->tag());
4034 for (std::string::const_iterator p = tag.begin();
4038 if (ISALNUM(*p) || *p == '_')
4043 snprintf(buf, sizeof buf, ".%x.",
4044 static_cast<unsigned int>(*p));
4049 snprintf(buf, sizeof buf, "T%u_",
4050 static_cast<unsigned int>(out.length()));
4057 ret->push_back('e');
4063 Struct_type::do_export(Export* exp) const
4065 exp->write_c_string("struct { ");
4066 const Struct_field_list* fields = this->fields_;
4067 go_assert(fields != NULL);
4068 for (Struct_field_list::const_iterator p = fields->begin();
4072 if (p->is_anonymous())
4073 exp->write_string("? ");
4076 exp->write_string(p->field_name());
4077 exp->write_c_string(" ");
4079 exp->write_type(p->type());
4083 exp->write_c_string(" ");
4084 Expression* expr = Expression::make_string(p->tag(),
4086 expr->export_expression(exp);
4090 exp->write_c_string("; ");
4092 exp->write_c_string("}");
4098 Struct_type::do_import(Import* imp)
4100 imp->require_c_string("struct { ");
4101 Struct_field_list* fields = new Struct_field_list;
4102 if (imp->peek_char() != '}')
4107 if (imp->match_c_string("? "))
4111 name = imp->read_identifier();
4112 imp->require_c_string(" ");
4114 Type* ftype = imp->read_type();
4116 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
4118 if (imp->peek_char() == ' ')
4121 Expression* expr = Expression::import_expression(imp);
4122 String_expression* sexpr = expr->string_expression();
4123 go_assert(sexpr != NULL);
4124 sf.set_tag(sexpr->val());
4128 imp->require_c_string("; ");
4129 fields->push_back(sf);
4130 if (imp->peek_char() == '}')
4134 imp->require_c_string("}");
4136 return Type::make_struct_type(fields, imp->location());
4139 // Make a struct type.
4142 Type::make_struct_type(Struct_field_list* fields,
4143 source_location location)
4145 return new Struct_type(fields, location);
4148 // Class Array_type.
4150 // Whether two array types are identical.
4153 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
4155 if (!Type::are_identical(this->element_type(), t->element_type(),
4156 errors_are_identical, NULL))
4159 Expression* l1 = this->length();
4160 Expression* l2 = t->length();
4162 // Slices of the same element type are identical.
4163 if (l1 == NULL && l2 == NULL)
4166 // Arrays of the same element type are identical if they have the
4168 if (l1 != NULL && l2 != NULL)
4173 // Try to determine the lengths. If we can't, assume the arrays
4174 // are not identical.
4182 if (l1->integer_constant_value(true, v1, &type1)
4183 && l2->integer_constant_value(true, v2, &type2))
4184 ret = mpz_cmp(v1, v2) == 0;
4190 // Otherwise the arrays are not identical.
4197 Array_type::do_traverse(Traverse* traverse)
4199 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
4200 return TRAVERSE_EXIT;
4201 if (this->length_ != NULL
4202 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
4203 return TRAVERSE_EXIT;
4204 return TRAVERSE_CONTINUE;
4207 // Check that the length is valid.
4210 Array_type::verify_length()
4212 if (this->length_ == NULL)
4215 Type_context context(Type::lookup_integer_type("int"), false);
4216 this->length_->determine_type(&context);
4218 if (!this->length_->is_constant())
4220 error_at(this->length_->location(), "array bound is not constant");
4227 if (!this->length_->integer_constant_value(true, val, &vt))
4231 if (!this->length_->float_constant_value(fval, &vt))
4233 if (this->length_->type()->integer_type() != NULL
4234 || this->length_->type()->float_type() != NULL)
4235 error_at(this->length_->location(),
4236 "array bound is not constant");
4238 error_at(this->length_->location(),
4239 "array bound is not numeric");
4244 if (!mpfr_integer_p(fval))
4246 error_at(this->length_->location(),
4247 "array bound truncated to integer");
4253 mpfr_get_z(val, fval, GMP_RNDN);
4257 if (mpz_sgn(val) < 0)
4259 error_at(this->length_->location(), "negative array bound");
4264 Type* int_type = Type::lookup_integer_type("int");
4265 int tbits = int_type->integer_type()->bits();
4266 int vbits = mpz_sizeinbase(val, 2);
4267 if (vbits + 1 > tbits)
4269 error_at(this->length_->location(), "array bound overflows");
4282 Array_type::do_verify()
4284 if (!this->verify_length())
4286 this->length_ = Expression::make_error(this->length_->location());
4292 // Array type hash code.
4295 Array_type::do_hash_for_method(Gogo* gogo) const
4297 // There is no very convenient way to get a hash code for the
4299 return this->element_type_->hash_for_method(gogo) + 1;
4302 // Get a tree for the length of a fixed array. The length may be
4303 // computed using a function call, so we must only evaluate it once.
4306 Array_type::get_length_tree(Gogo* gogo)
4308 go_assert(this->length_ != NULL);
4309 if (this->length_tree_ == NULL_TREE)
4314 if (this->length_->integer_constant_value(true, val, &t))
4317 t = Type::lookup_integer_type("int");
4318 else if (t->is_abstract())
4319 t = t->make_non_abstract_type();
4320 tree tt = type_to_tree(t->get_backend(gogo));
4321 this->length_tree_ = Expression::integer_constant_tree(val, tt);
4328 // Make up a translation context for the array length
4329 // expression. FIXME: This won't work in general.
4330 Translate_context context(gogo, NULL, NULL, NULL);
4331 tree len = this->length_->get_tree(&context);
4332 if (len != error_mark_node)
4334 len = convert_to_integer(integer_type_node, len);
4335 len = save_expr(len);
4337 this->length_tree_ = len;
4340 return this->length_tree_;
4343 // Get the backend representation of the fields of a slice. This is
4344 // not declared in types.h so that types.h doesn't have to #include
4347 // We use int for the count and capacity fields. This matches 6g.
4348 // The language more or less assumes that we can't allocate space of a
4349 // size which does not fit in int.
4352 get_backend_slice_fields(Gogo* gogo, Array_type* type,
4353 std::vector<Backend::Btyped_identifier>* bfields)
4357 Type* pet = Type::make_pointer_type(type->element_type());
4358 Btype* pbet = pet->get_backend(gogo);
4360 Backend::Btyped_identifier* p = &(*bfields)[0];
4361 p->name = "__values";
4363 p->location = UNKNOWN_LOCATION;
4365 Type* int_type = Type::lookup_integer_type("int");
4368 p->name = "__count";
4369 p->btype = int_type->get_backend(gogo);
4370 p->location = UNKNOWN_LOCATION;
4373 p->name = "__capacity";
4374 p->btype = int_type->get_backend(gogo);
4375 p->location = UNKNOWN_LOCATION;
4378 // Get a tree for the type of this array. A fixed array is simply
4379 // represented as ARRAY_TYPE with the appropriate index--i.e., it is
4380 // just like an array in C. An open array is a struct with three
4381 // fields: a data pointer, the length, and the capacity.
4384 Array_type::do_get_backend(Gogo* gogo)
4386 if (this->length_ == NULL)
4388 std::vector<Backend::Btyped_identifier> bfields;
4389 get_backend_slice_fields(gogo, this, &bfields);
4390 return gogo->backend()->struct_type(bfields);
4394 Btype* element = this->get_backend_element(gogo);
4395 Bexpression* len = this->get_backend_length(gogo);
4396 return gogo->backend()->array_type(element, len);
4400 // Return the backend representation of the element type.
4402 Array_type::get_backend_element(Gogo* gogo)
4404 return this->element_type_->get_backend(gogo);
4407 // Return the backend representation of the length.
4410 Array_type::get_backend_length(Gogo* gogo)
4412 return tree_to_expr(this->get_length_tree(gogo));
4415 // Return a tree for a pointer to the values in ARRAY.
4418 Array_type::value_pointer_tree(Gogo*, tree array) const
4421 if (this->length() != NULL)
4424 ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))),
4425 build_fold_addr_expr(array));
4430 tree field = TYPE_FIELDS(TREE_TYPE(array));
4431 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
4433 ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field,
4436 if (TREE_CONSTANT(array))
4437 TREE_CONSTANT(ret) = 1;
4441 // Return a tree for the length of the array ARRAY which has this
4445 Array_type::length_tree(Gogo* gogo, tree array)
4447 if (this->length_ != NULL)
4449 if (TREE_CODE(array) == SAVE_EXPR)
4450 return fold_convert(integer_type_node, this->get_length_tree(gogo));
4452 return omit_one_operand(integer_type_node,
4453 this->get_length_tree(gogo), array);
4456 // This is an open array. We need to read the length field.
4458 tree type = TREE_TYPE(array);
4459 go_assert(TREE_CODE(type) == RECORD_TYPE);
4461 tree field = DECL_CHAIN(TYPE_FIELDS(type));
4462 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
4464 tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
4465 if (TREE_CONSTANT(array))
4466 TREE_CONSTANT(ret) = 1;
4470 // Return a tree for the capacity of the array ARRAY which has this
4474 Array_type::capacity_tree(Gogo* gogo, tree array)
4476 if (this->length_ != NULL)
4477 return omit_one_operand(sizetype, this->get_length_tree(gogo), array);
4479 // This is an open array. We need to read the capacity field.
4481 tree type = TREE_TYPE(array);
4482 go_assert(TREE_CODE(type) == RECORD_TYPE);
4484 tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type)));
4485 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
4487 return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
4493 Array_type::do_export(Export* exp) const
4495 exp->write_c_string("[");
4496 if (this->length_ != NULL)
4497 this->length_->export_expression(exp);
4498 exp->write_c_string("] ");
4499 exp->write_type(this->element_type_);
4505 Array_type::do_import(Import* imp)
4507 imp->require_c_string("[");
4509 if (imp->peek_char() == ']')
4512 length = Expression::import_expression(imp);
4513 imp->require_c_string("] ");
4514 Type* element_type = imp->read_type();
4515 return Type::make_array_type(element_type, length);
4518 // The type of an array type descriptor.
4521 Array_type::make_array_type_descriptor_type()
4526 Type* tdt = Type::make_type_descriptor_type();
4527 Type* ptdt = Type::make_type_descriptor_ptr_type();
4529 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4532 Type::make_builtin_struct_type(4,
4536 "len", uintptr_type);
4538 ret = Type::make_builtin_named_type("ArrayType", sf);
4544 // The type of an slice type descriptor.
4547 Array_type::make_slice_type_descriptor_type()
4552 Type* tdt = Type::make_type_descriptor_type();
4553 Type* ptdt = Type::make_type_descriptor_ptr_type();
4556 Type::make_builtin_struct_type(2,
4560 ret = Type::make_builtin_named_type("SliceType", sf);
4566 // Build a type descriptor for an array/slice type.
4569 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4571 if (this->length_ != NULL)
4572 return this->array_type_descriptor(gogo, name);
4574 return this->slice_type_descriptor(gogo, name);
4577 // Build a type descriptor for an array type.
4580 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
4582 source_location bloc = BUILTINS_LOCATION;
4584 Type* atdt = Array_type::make_array_type_descriptor_type();
4586 const Struct_field_list* fields = atdt->struct_type()->fields();
4588 Expression_list* vals = new Expression_list();
4591 Struct_field_list::const_iterator p = fields->begin();
4592 go_assert(p->is_field_name("commonType"));
4593 vals->push_back(this->type_descriptor_constructor(gogo,
4594 RUNTIME_TYPE_KIND_ARRAY,
4598 go_assert(p->is_field_name("elem"));
4599 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
4602 go_assert(p->is_field_name("slice"));
4603 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
4604 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
4607 go_assert(p->is_field_name("len"));
4608 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
4611 go_assert(p == fields->end());
4613 return Expression::make_struct_composite_literal(atdt, vals, bloc);
4616 // Build a type descriptor for a slice type.
4619 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
4621 source_location bloc = BUILTINS_LOCATION;
4623 Type* stdt = Array_type::make_slice_type_descriptor_type();
4625 const Struct_field_list* fields = stdt->struct_type()->fields();
4627 Expression_list* vals = new Expression_list();
4630 Struct_field_list::const_iterator p = fields->begin();
4631 go_assert(p->is_field_name("commonType"));
4632 vals->push_back(this->type_descriptor_constructor(gogo,
4633 RUNTIME_TYPE_KIND_SLICE,
4637 go_assert(p->is_field_name("elem"));
4638 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
4641 go_assert(p == fields->end());
4643 return Expression::make_struct_composite_literal(stdt, vals, bloc);
4646 // Reflection string.
4649 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
4651 ret->push_back('[');
4652 if (this->length_ != NULL)
4657 if (!this->length_->integer_constant_value(true, val, &type))
4658 error_at(this->length_->location(),
4659 "array length must be integer constant expression");
4660 else if (mpz_cmp_si(val, 0) < 0)
4661 error_at(this->length_->location(), "array length is negative");
4662 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
4663 error_at(this->length_->location(), "array length is too large");
4667 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
4672 ret->push_back(']');
4674 this->append_reflection(this->element_type_, gogo, ret);
4680 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4682 ret->push_back('A');
4683 this->append_mangled_name(this->element_type_, gogo, ret);
4684 if (this->length_ != NULL)
4689 if (!this->length_->integer_constant_value(true, val, &type))
4690 error_at(this->length_->location(),
4691 "array length must be integer constant expression");
4692 else if (mpz_cmp_si(val, 0) < 0)
4693 error_at(this->length_->location(), "array length is negative");
4694 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
4695 error_at(this->length_->location(), "array size is too large");
4699 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
4704 ret->push_back('e');
4707 // Make an array type.
4710 Type::make_array_type(Type* element_type, Expression* length)
4712 return new Array_type(element_type, length);
4720 Map_type::do_traverse(Traverse* traverse)
4722 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
4723 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
4724 return TRAVERSE_EXIT;
4725 return TRAVERSE_CONTINUE;
4728 // Check that the map type is OK.
4731 Map_type::do_verify()
4733 if (this->key_type_->struct_type() != NULL
4734 || this->key_type_->array_type() != NULL)
4736 error_at(this->location_, "invalid map key type");
4742 // Whether two map types are identical.
4745 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
4747 return (Type::are_identical(this->key_type(), t->key_type(),
4748 errors_are_identical, NULL)
4749 && Type::are_identical(this->val_type(), t->val_type(),
4750 errors_are_identical, NULL));
4756 Map_type::do_hash_for_method(Gogo* gogo) const
4758 return (this->key_type_->hash_for_method(gogo)
4759 + this->val_type_->hash_for_method(gogo)
4763 // Get the backend representation for a map type. A map type is
4764 // represented as a pointer to a struct. The struct is __go_map in
4768 Map_type::do_get_backend(Gogo* gogo)
4770 static Btype* backend_map_type;
4771 if (backend_map_type == NULL)
4773 std::vector<Backend::Btyped_identifier> bfields(4);
4775 Type* pdt = Type::make_type_descriptor_ptr_type();
4776 bfields[0].name = "__descriptor";
4777 bfields[0].btype = pdt->get_backend(gogo);
4778 bfields[0].location = BUILTINS_LOCATION;
4780 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4781 bfields[1].name = "__element_count";
4782 bfields[1].btype = uintptr_type->get_backend(gogo);
4783 bfields[1].location = BUILTINS_LOCATION;
4785 bfields[2].name = "__bucket_count";
4786 bfields[2].btype = bfields[1].btype;
4787 bfields[2].location = BUILTINS_LOCATION;
4789 Btype* bvt = gogo->backend()->void_type();
4790 Btype* bpvt = gogo->backend()->pointer_type(bvt);
4791 Btype* bppvt = gogo->backend()->pointer_type(bpvt);
4792 bfields[3].name = "__buckets";
4793 bfields[3].btype = bppvt;
4794 bfields[3].location = BUILTINS_LOCATION;
4796 Btype *bt = gogo->backend()->struct_type(bfields);
4797 bt = gogo->backend()->named_type("__go_map", bt, BUILTINS_LOCATION);
4798 backend_map_type = gogo->backend()->pointer_type(bt);
4800 return backend_map_type;
4803 // The type of a map type descriptor.
4806 Map_type::make_map_type_descriptor_type()
4811 Type* tdt = Type::make_type_descriptor_type();
4812 Type* ptdt = Type::make_type_descriptor_ptr_type();
4815 Type::make_builtin_struct_type(3,
4820 ret = Type::make_builtin_named_type("MapType", sf);
4826 // Build a type descriptor for a map type.
4829 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4831 source_location bloc = BUILTINS_LOCATION;
4833 Type* mtdt = Map_type::make_map_type_descriptor_type();
4835 const Struct_field_list* fields = mtdt->struct_type()->fields();
4837 Expression_list* vals = new Expression_list();
4840 Struct_field_list::const_iterator p = fields->begin();
4841 go_assert(p->is_field_name("commonType"));
4842 vals->push_back(this->type_descriptor_constructor(gogo,
4843 RUNTIME_TYPE_KIND_MAP,
4847 go_assert(p->is_field_name("key"));
4848 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
4851 go_assert(p->is_field_name("elem"));
4852 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
4855 go_assert(p == fields->end());
4857 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
4860 // A mapping from map types to map descriptors.
4862 Map_type::Map_descriptors Map_type::map_descriptors;
4864 // Build a map descriptor for this type. Return a pointer to it.
4867 Map_type::map_descriptor_pointer(Gogo* gogo, source_location location)
4869 Bvariable* bvar = this->map_descriptor(gogo);
4870 tree var_tree = var_to_tree(bvar);
4871 if (var_tree == error_mark_node)
4872 return error_mark_node;
4873 return build_fold_addr_expr_loc(location, var_tree);
4876 // Build a map descriptor for this type.
4879 Map_type::map_descriptor(Gogo* gogo)
4881 std::pair<Map_type*, Bvariable*> val(this, NULL);
4882 std::pair<Map_type::Map_descriptors::iterator, bool> ins =
4883 Map_type::map_descriptors.insert(val);
4885 return ins.first->second;
4887 Type* key_type = this->key_type_;
4888 Type* val_type = this->val_type_;
4890 // The map entry type is a struct with three fields. Build that
4891 // struct so that we can get the offsets of the key and value within
4892 // a map entry. The first field should technically be a pointer to
4893 // this type itself, but since we only care about field offsets we
4894 // just use pointer to bool.
4895 Type* pbool = Type::make_pointer_type(Type::make_boolean_type());
4896 Struct_type* map_entry_type =
4897 Type::make_builtin_struct_type(3,
4902 Type* map_descriptor_type = Map_type::make_map_descriptor_type();
4904 const Struct_field_list* fields =
4905 map_descriptor_type->struct_type()->fields();
4907 Expression_list* vals = new Expression_list();
4910 source_location bloc = BUILTINS_LOCATION;
4912 Struct_field_list::const_iterator p = fields->begin();
4914 go_assert(p->is_field_name("__map_descriptor"));
4915 vals->push_back(Expression::make_type_descriptor(this, bloc));
4918 go_assert(p->is_field_name("__entry_size"));
4919 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
4920 vals->push_back(Expression::make_type_info(map_entry_type, type_info));
4922 Struct_field_list::const_iterator pf = map_entry_type->fields()->begin();
4924 go_assert(pf->is_field_name("__key"));
4927 go_assert(p->is_field_name("__key_offset"));
4928 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
4931 go_assert(pf->is_field_name("__val"));
4934 go_assert(p->is_field_name("__val_offset"));
4935 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
4938 go_assert(p == fields->end());
4940 Expression* initializer =
4941 Expression::make_struct_composite_literal(map_descriptor_type, vals, bloc);
4943 std::string mangled_name = "__go_map_" + this->mangled_name(gogo);
4944 Btype* map_descriptor_btype = map_descriptor_type->get_backend(gogo);
4945 Bvariable* bvar = gogo->backend()->immutable_struct(mangled_name, true,
4946 map_descriptor_btype,
4949 Translate_context context(gogo, NULL, NULL, NULL);
4950 context.set_is_const();
4951 Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
4953 gogo->backend()->immutable_struct_set_init(bvar, mangled_name, true,
4954 map_descriptor_btype, bloc,
4957 ins.first->second = bvar;
4961 // Build the type of a map descriptor. This must match the struct
4962 // __go_map_descriptor in libgo/runtime/map.h.
4965 Map_type::make_map_descriptor_type()
4970 Type* ptdt = Type::make_type_descriptor_ptr_type();
4971 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4973 Type::make_builtin_struct_type(4,
4974 "__map_descriptor", ptdt,
4975 "__entry_size", uintptr_type,
4976 "__key_offset", uintptr_type,
4977 "__val_offset", uintptr_type);
4978 ret = Type::make_builtin_named_type("__go_map_descriptor", sf);
4983 // Reflection string for a map.
4986 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
4988 ret->append("map[");
4989 this->append_reflection(this->key_type_, gogo, ret);
4991 this->append_reflection(this->val_type_, gogo, ret);
4994 // Mangled name for a map.
4997 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4999 ret->push_back('M');
5000 this->append_mangled_name(this->key_type_, gogo, ret);
5002 this->append_mangled_name(this->val_type_, gogo, ret);
5005 // Export a map type.
5008 Map_type::do_export(Export* exp) const
5010 exp->write_c_string("map [");
5011 exp->write_type(this->key_type_);
5012 exp->write_c_string("] ");
5013 exp->write_type(this->val_type_);
5016 // Import a map type.
5019 Map_type::do_import(Import* imp)
5021 imp->require_c_string("map [");
5022 Type* key_type = imp->read_type();
5023 imp->require_c_string("] ");
5024 Type* val_type = imp->read_type();
5025 return Type::make_map_type(key_type, val_type, imp->location());
5031 Type::make_map_type(Type* key_type, Type* val_type, source_location location)
5033 return new Map_type(key_type, val_type, location);
5036 // Class Channel_type.
5041 Channel_type::do_hash_for_method(Gogo* gogo) const
5043 unsigned int ret = 0;
5044 if (this->may_send_)
5046 if (this->may_receive_)
5048 if (this->element_type_ != NULL)
5049 ret += this->element_type_->hash_for_method(gogo) << 2;
5053 // Whether this type is the same as T.
5056 Channel_type::is_identical(const Channel_type* t,
5057 bool errors_are_identical) const
5059 if (!Type::are_identical(this->element_type(), t->element_type(),
5060 errors_are_identical, NULL))
5062 return (this->may_send_ == t->may_send_
5063 && this->may_receive_ == t->may_receive_);
5066 // Return the tree for a channel type. A channel is a pointer to a
5067 // __go_channel struct. The __go_channel struct is defined in
5068 // libgo/runtime/channel.h.
5071 Channel_type::do_get_backend(Gogo* gogo)
5073 static Btype* backend_channel_type;
5074 if (backend_channel_type == NULL)
5076 std::vector<Backend::Btyped_identifier> bfields;
5077 Btype* bt = gogo->backend()->struct_type(bfields);
5078 bt = gogo->backend()->named_type("__go_channel", bt, BUILTINS_LOCATION);
5079 backend_channel_type = gogo->backend()->pointer_type(bt);
5081 return backend_channel_type;
5084 // Build a type descriptor for a channel type.
5087 Channel_type::make_chan_type_descriptor_type()
5092 Type* tdt = Type::make_type_descriptor_type();
5093 Type* ptdt = Type::make_type_descriptor_ptr_type();
5095 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5098 Type::make_builtin_struct_type(3,
5101 "dir", uintptr_type);
5103 ret = Type::make_builtin_named_type("ChanType", sf);
5109 // Build a type descriptor for a map type.
5112 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5114 source_location bloc = BUILTINS_LOCATION;
5116 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
5118 const Struct_field_list* fields = ctdt->struct_type()->fields();
5120 Expression_list* vals = new Expression_list();
5123 Struct_field_list::const_iterator p = fields->begin();
5124 go_assert(p->is_field_name("commonType"));
5125 vals->push_back(this->type_descriptor_constructor(gogo,
5126 RUNTIME_TYPE_KIND_CHAN,
5130 go_assert(p->is_field_name("elem"));
5131 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5134 go_assert(p->is_field_name("dir"));
5135 // These bits must match the ones in libgo/runtime/go-type.h.
5137 if (this->may_receive_)
5139 if (this->may_send_)
5142 mpz_init_set_ui(iv, val);
5143 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
5147 go_assert(p == fields->end());
5149 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
5152 // Reflection string.
5155 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
5157 if (!this->may_send_)
5159 ret->append("chan");
5160 if (!this->may_receive_)
5162 ret->push_back(' ');
5163 this->append_reflection(this->element_type_, gogo, ret);
5169 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5171 ret->push_back('C');
5172 this->append_mangled_name(this->element_type_, gogo, ret);
5173 if (this->may_send_)
5174 ret->push_back('s');
5175 if (this->may_receive_)
5176 ret->push_back('r');
5177 ret->push_back('e');
5183 Channel_type::do_export(Export* exp) const
5185 exp->write_c_string("chan ");
5186 if (this->may_send_ && !this->may_receive_)
5187 exp->write_c_string("-< ");
5188 else if (this->may_receive_ && !this->may_send_)
5189 exp->write_c_string("<- ");
5190 exp->write_type(this->element_type_);
5196 Channel_type::do_import(Import* imp)
5198 imp->require_c_string("chan ");
5202 if (imp->match_c_string("-< "))
5206 may_receive = false;
5208 else if (imp->match_c_string("<- "))
5220 Type* element_type = imp->read_type();
5222 return Type::make_channel_type(may_send, may_receive, element_type);
5225 // Make a new channel type.
5228 Type::make_channel_type(bool send, bool receive, Type* element_type)
5230 return new Channel_type(send, receive, element_type);
5233 // Class Interface_type.
5238 Interface_type::do_traverse(Traverse* traverse)
5240 if (this->methods_ == NULL)
5241 return TRAVERSE_CONTINUE;
5242 return this->methods_->traverse(traverse);
5245 // Finalize the methods. This handles interface inheritance.
5248 Interface_type::finalize_methods()
5250 if (this->methods_ == NULL)
5252 std::vector<Named_type*> seen;
5253 bool is_recursive = false;
5256 while (from < this->methods_->size())
5258 const Typed_identifier* p = &this->methods_->at(from);
5259 if (!p->name().empty())
5262 for (i = 0; i < to; ++i)
5264 if (this->methods_->at(i).name() == p->name())
5266 error_at(p->location(), "duplicate method %qs",
5267 Gogo::message_name(p->name()).c_str());
5274 this->methods_->set(to, *p);
5281 Interface_type* it = p->type()->interface_type();
5284 error_at(p->location(), "interface contains embedded non-interface");
5292 error_at(p->location(), "invalid recursive interface");
5293 is_recursive = true;
5299 Named_type* nt = p->type()->named_type();
5302 std::vector<Named_type*>::const_iterator q;
5303 for (q = seen.begin(); q != seen.end(); ++q)
5307 error_at(p->location(), "inherited interface loop");
5311 if (q != seen.end())
5319 const Typed_identifier_list* methods = it->methods();
5320 if (methods == NULL)
5325 for (Typed_identifier_list::const_iterator q = methods->begin();
5326 q != methods->end();
5329 if (q->name().empty())
5331 if (q->type()->forwarded() == p->type()->forwarded())
5332 error_at(p->location(), "interface inheritance loop");
5336 for (i = from + 1; i < this->methods_->size(); ++i)
5338 const Typed_identifier* r = &this->methods_->at(i);
5339 if (r->name().empty()
5340 && r->type()->forwarded() == q->type()->forwarded())
5342 error_at(p->location(),
5343 "inherited interface listed twice");
5347 if (i == this->methods_->size())
5348 this->methods_->push_back(Typed_identifier(q->name(),
5353 else if (this->find_method(q->name()) == NULL)
5354 this->methods_->push_back(Typed_identifier(q->name(), q->type(),
5359 error_at(p->location(), "inherited method %qs is ambiguous",
5360 Gogo::message_name(q->name()).c_str());
5367 delete this->methods_;
5368 this->methods_ = NULL;
5372 this->methods_->resize(to);
5373 this->methods_->sort_by_name();
5377 // Return the method NAME, or NULL.
5379 const Typed_identifier*
5380 Interface_type::find_method(const std::string& name) const
5382 if (this->methods_ == NULL)
5384 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5385 p != this->methods_->end();
5387 if (p->name() == name)
5392 // Return the method index.
5395 Interface_type::method_index(const std::string& name) const
5397 go_assert(this->methods_ != NULL);
5399 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5400 p != this->methods_->end();
5402 if (p->name() == name)
5407 // Return whether NAME is an unexported method, for better error
5411 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
5413 if (this->methods_ == NULL)
5415 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5416 p != this->methods_->end();
5419 const std::string& method_name(p->name());
5420 if (Gogo::is_hidden_name(method_name)
5421 && name == Gogo::unpack_hidden_name(method_name)
5422 && gogo->pack_hidden_name(name, false) != method_name)
5428 // Whether this type is identical with T.
5431 Interface_type::is_identical(const Interface_type* t,
5432 bool errors_are_identical) const
5434 // We require the same methods with the same types. The methods
5435 // have already been sorted.
5436 if (this->methods() == NULL || t->methods() == NULL)
5437 return this->methods() == t->methods();
5439 Typed_identifier_list::const_iterator p1 = this->methods()->begin();
5440 for (Typed_identifier_list::const_iterator p2 = t->methods()->begin();
5441 p2 != t->methods()->end();
5444 if (p1 == this->methods()->end())
5446 if (p1->name() != p2->name()
5447 || !Type::are_identical(p1->type(), p2->type(),
5448 errors_are_identical, NULL))
5451 if (p1 != this->methods()->end())
5456 // Whether we can assign the interface type T to this type. The types
5457 // are known to not be identical. An interface assignment is only
5458 // permitted if T is known to implement all methods in THIS.
5459 // Otherwise a type guard is required.
5462 Interface_type::is_compatible_for_assign(const Interface_type* t,
5463 std::string* reason) const
5465 if (this->methods() == NULL)
5467 for (Typed_identifier_list::const_iterator p = this->methods()->begin();
5468 p != this->methods()->end();
5471 const Typed_identifier* m = t->find_method(p->name());
5477 snprintf(buf, sizeof buf,
5478 _("need explicit conversion; missing method %s%s%s"),
5479 open_quote, Gogo::message_name(p->name()).c_str(),
5481 reason->assign(buf);
5486 std::string subreason;
5487 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
5491 std::string n = Gogo::message_name(p->name());
5492 size_t len = 100 + n.length() + subreason.length();
5493 char* buf = new char[len];
5494 if (subreason.empty())
5495 snprintf(buf, len, _("incompatible type for method %s%s%s"),
5496 open_quote, n.c_str(), close_quote);
5499 _("incompatible type for method %s%s%s (%s)"),
5500 open_quote, n.c_str(), close_quote,
5502 reason->assign(buf);
5515 Interface_type::do_hash_for_method(Gogo* gogo) const
5517 unsigned int ret = 0;
5518 if (this->methods_ != NULL)
5520 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5521 p != this->methods_->end();
5524 ret = Type::hash_string(p->name(), ret);
5525 ret += p->type()->hash_for_method(gogo);
5532 // Return true if T implements the interface. If it does not, and
5533 // REASON is not NULL, set *REASON to a useful error message.
5536 Interface_type::implements_interface(const Type* t, std::string* reason) const
5538 if (this->methods_ == NULL)
5541 bool is_pointer = false;
5542 const Named_type* nt = t->named_type();
5543 const Struct_type* st = t->struct_type();
5544 // If we start with a named type, we don't dereference it to find
5548 const Type* pt = t->points_to();
5551 // If T is a pointer to a named type, then we need to look at
5552 // the type to which it points.
5554 nt = pt->named_type();
5555 st = pt->struct_type();
5559 // If we have a named type, get the methods from it rather than from
5564 // Only named and struct types have methods.
5565 if (nt == NULL && st == NULL)
5569 if (t->points_to() != NULL
5570 && t->points_to()->interface_type() != NULL)
5571 reason->assign(_("pointer to interface type has no methods"));
5573 reason->assign(_("type has no methods"));
5578 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
5582 if (t->points_to() != NULL
5583 && t->points_to()->interface_type() != NULL)
5584 reason->assign(_("pointer to interface type has no methods"));
5586 reason->assign(_("type has no methods"));
5591 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5592 p != this->methods_->end();
5595 bool is_ambiguous = false;
5596 Method* m = (nt != NULL
5597 ? nt->method_function(p->name(), &is_ambiguous)
5598 : st->method_function(p->name(), &is_ambiguous));
5603 std::string n = Gogo::message_name(p->name());
5604 size_t len = n.length() + 100;
5605 char* buf = new char[len];
5607 snprintf(buf, len, _("ambiguous method %s%s%s"),
5608 open_quote, n.c_str(), close_quote);
5610 snprintf(buf, len, _("missing method %s%s%s"),
5611 open_quote, n.c_str(), close_quote);
5612 reason->assign(buf);
5618 Function_type *p_fn_type = p->type()->function_type();
5619 Function_type* m_fn_type = m->type()->function_type();
5620 go_assert(p_fn_type != NULL && m_fn_type != NULL);
5621 std::string subreason;
5622 if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
5626 std::string n = Gogo::message_name(p->name());
5627 size_t len = 100 + n.length() + subreason.length();
5628 char* buf = new char[len];
5629 if (subreason.empty())
5630 snprintf(buf, len, _("incompatible type for method %s%s%s"),
5631 open_quote, n.c_str(), close_quote);
5634 _("incompatible type for method %s%s%s (%s)"),
5635 open_quote, n.c_str(), close_quote,
5637 reason->assign(buf);
5643 if (!is_pointer && !m->is_value_method())
5647 std::string n = Gogo::message_name(p->name());
5648 size_t len = 100 + n.length();
5649 char* buf = new char[len];
5650 snprintf(buf, len, _("method %s%s%s requires a pointer"),
5651 open_quote, n.c_str(), close_quote);
5652 reason->assign(buf);
5662 // Return the backend representation of the empty interface type. We
5663 // use the same struct for all empty interfaces.
5666 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
5668 static Btype* empty_interface_type;
5669 if (empty_interface_type == NULL)
5671 std::vector<Backend::Btyped_identifier> bfields(2);
5673 Type* pdt = Type::make_type_descriptor_ptr_type();
5674 bfields[0].name = "__type_descriptor";
5675 bfields[0].btype = pdt->get_backend(gogo);
5676 bfields[0].location = UNKNOWN_LOCATION;
5678 Type* vt = Type::make_pointer_type(Type::make_void_type());
5679 bfields[1].name = "__object";
5680 bfields[1].btype = vt->get_backend(gogo);
5681 bfields[1].location = UNKNOWN_LOCATION;
5683 empty_interface_type = gogo->backend()->struct_type(bfields);
5685 return empty_interface_type;
5688 // Return the fields of a non-empty interface type. This is not
5689 // declared in types.h so that types.h doesn't have to #include
5693 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
5694 std::vector<Backend::Btyped_identifier>* bfields)
5696 source_location loc = type->location();
5698 std::vector<Backend::Btyped_identifier> mfields(type->methods()->size() + 1);
5700 Type* pdt = Type::make_type_descriptor_ptr_type();
5701 mfields[0].name = "__type_descriptor";
5702 mfields[0].btype = pdt->get_backend(gogo);
5703 mfields[0].location = loc;
5705 std::string last_name = "";
5707 for (Typed_identifier_list::const_iterator p = type->methods()->begin();
5708 p != type->methods()->end();
5711 mfields[i].name = Gogo::unpack_hidden_name(p->name());
5712 mfields[i].btype = p->type()->get_backend(gogo);
5713 mfields[i].location = loc;
5714 // Sanity check: the names should be sorted.
5715 go_assert(p->name() > last_name);
5716 last_name = p->name();
5719 Btype* methods = gogo->backend()->struct_type(mfields);
5723 (*bfields)[0].name = "__methods";
5724 (*bfields)[0].btype = gogo->backend()->pointer_type(methods);
5725 (*bfields)[0].location = loc;
5727 Type* vt = Type::make_pointer_type(Type::make_void_type());
5728 (*bfields)[1].name = "__object";
5729 (*bfields)[1].btype = vt->get_backend(gogo);
5730 (*bfields)[1].location = UNKNOWN_LOCATION;
5733 // Return a tree for an interface type. An interface is a pointer to
5734 // a struct. The struct has three fields. The first field is a
5735 // pointer to the type descriptor for the dynamic type of the object.
5736 // The second field is a pointer to a table of methods for the
5737 // interface to be used with the object. The third field is the value
5738 // of the object itself.
5741 Interface_type::do_get_backend(Gogo* gogo)
5743 if (this->methods_ == NULL)
5744 return Interface_type::get_backend_empty_interface_type(gogo);
5747 std::vector<Backend::Btyped_identifier> bfields;
5748 get_backend_interface_fields(gogo, this, &bfields);
5749 return gogo->backend()->struct_type(bfields);
5753 // The type of an interface type descriptor.
5756 Interface_type::make_interface_type_descriptor_type()
5761 Type* tdt = Type::make_type_descriptor_type();
5762 Type* ptdt = Type::make_type_descriptor_ptr_type();
5764 Type* string_type = Type::lookup_string_type();
5765 Type* pointer_string_type = Type::make_pointer_type(string_type);
5768 Type::make_builtin_struct_type(3,
5769 "name", pointer_string_type,
5770 "pkgPath", pointer_string_type,
5773 Type* nsm = Type::make_builtin_named_type("imethod", sm);
5775 Type* slice_nsm = Type::make_array_type(nsm, NULL);
5777 Struct_type* s = Type::make_builtin_struct_type(2,
5779 "methods", slice_nsm);
5781 ret = Type::make_builtin_named_type("InterfaceType", s);
5787 // Build a type descriptor for an interface type.
5790 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5792 source_location bloc = BUILTINS_LOCATION;
5794 Type* itdt = Interface_type::make_interface_type_descriptor_type();
5796 const Struct_field_list* ifields = itdt->struct_type()->fields();
5798 Expression_list* ivals = new Expression_list();
5801 Struct_field_list::const_iterator pif = ifields->begin();
5802 go_assert(pif->is_field_name("commonType"));
5803 ivals->push_back(this->type_descriptor_constructor(gogo,
5804 RUNTIME_TYPE_KIND_INTERFACE,
5808 go_assert(pif->is_field_name("methods"));
5810 Expression_list* methods = new Expression_list();
5811 if (this->methods_ != NULL && !this->methods_->empty())
5813 Type* elemtype = pif->type()->array_type()->element_type();
5815 methods->reserve(this->methods_->size());
5816 for (Typed_identifier_list::const_iterator pm = this->methods_->begin();
5817 pm != this->methods_->end();
5820 const Struct_field_list* mfields = elemtype->struct_type()->fields();
5822 Expression_list* mvals = new Expression_list();
5825 Struct_field_list::const_iterator pmf = mfields->begin();
5826 go_assert(pmf->is_field_name("name"));
5827 std::string s = Gogo::unpack_hidden_name(pm->name());
5828 Expression* e = Expression::make_string(s, bloc);
5829 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
5832 go_assert(pmf->is_field_name("pkgPath"));
5833 if (!Gogo::is_hidden_name(pm->name()))
5834 mvals->push_back(Expression::make_nil(bloc));
5837 s = Gogo::hidden_name_prefix(pm->name());
5838 e = Expression::make_string(s, bloc);
5839 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
5843 go_assert(pmf->is_field_name("typ"));
5844 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
5847 go_assert(pmf == mfields->end());
5849 e = Expression::make_struct_composite_literal(elemtype, mvals,
5851 methods->push_back(e);
5855 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
5859 go_assert(pif == ifields->end());
5861 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
5864 // Reflection string.
5867 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
5869 ret->append("interface {");
5870 if (this->methods_ != NULL)
5872 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5873 p != this->methods_->end();
5876 if (p != this->methods_->begin())
5878 ret->push_back(' ');
5879 if (!Gogo::is_hidden_name(p->name()))
5880 ret->append(p->name());
5883 // This matches what the gc compiler does.
5884 std::string prefix = Gogo::hidden_name_prefix(p->name());
5885 ret->append(prefix.substr(prefix.find('.') + 1));
5886 ret->push_back('.');
5887 ret->append(Gogo::unpack_hidden_name(p->name()));
5889 std::string sub = p->type()->reflection(gogo);
5890 go_assert(sub.compare(0, 4, "func") == 0);
5891 sub = sub.substr(4);
5901 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5903 ret->push_back('I');
5905 const Typed_identifier_list* methods = this->methods_;
5906 if (methods != NULL)
5908 for (Typed_identifier_list::const_iterator p = methods->begin();
5909 p != methods->end();
5912 std::string n = Gogo::unpack_hidden_name(p->name());
5914 snprintf(buf, sizeof buf, "%u_",
5915 static_cast<unsigned int>(n.length()));
5918 this->append_mangled_name(p->type(), gogo, ret);
5922 ret->push_back('e');
5928 Interface_type::do_export(Export* exp) const
5930 exp->write_c_string("interface { ");
5932 const Typed_identifier_list* methods = this->methods_;
5933 if (methods != NULL)
5935 for (Typed_identifier_list::const_iterator pm = methods->begin();
5936 pm != methods->end();
5939 exp->write_string(pm->name());
5940 exp->write_c_string(" (");
5942 const Function_type* fntype = pm->type()->function_type();
5945 const Typed_identifier_list* parameters = fntype->parameters();
5946 if (parameters != NULL)
5948 bool is_varargs = fntype->is_varargs();
5949 for (Typed_identifier_list::const_iterator pp =
5950 parameters->begin();
5951 pp != parameters->end();
5957 exp->write_c_string(", ");
5958 if (!is_varargs || pp + 1 != parameters->end())
5959 exp->write_type(pp->type());
5962 exp->write_c_string("...");
5963 Type *pptype = pp->type();
5964 exp->write_type(pptype->array_type()->element_type());
5969 exp->write_c_string(")");
5971 const Typed_identifier_list* results = fntype->results();
5972 if (results != NULL)
5974 exp->write_c_string(" ");
5975 if (results->size() == 1)
5976 exp->write_type(results->begin()->type());
5980 exp->write_c_string("(");
5981 for (Typed_identifier_list::const_iterator p =
5983 p != results->end();
5989 exp->write_c_string(", ");
5990 exp->write_type(p->type());
5992 exp->write_c_string(")");
5996 exp->write_c_string("; ");
6000 exp->write_c_string("}");
6003 // Import an interface type.
6006 Interface_type::do_import(Import* imp)
6008 imp->require_c_string("interface { ");
6010 Typed_identifier_list* methods = new Typed_identifier_list;
6011 while (imp->peek_char() != '}')
6013 std::string name = imp->read_identifier();
6014 imp->require_c_string(" (");
6016 Typed_identifier_list* parameters;
6017 bool is_varargs = false;
6018 if (imp->peek_char() == ')')
6022 parameters = new Typed_identifier_list;
6025 if (imp->match_c_string("..."))
6031 Type* ptype = imp->read_type();
6033 ptype = Type::make_array_type(ptype, NULL);
6034 parameters->push_back(Typed_identifier(Import::import_marker,
6035 ptype, imp->location()));
6036 if (imp->peek_char() != ',')
6038 go_assert(!is_varargs);
6039 imp->require_c_string(", ");
6042 imp->require_c_string(")");
6044 Typed_identifier_list* results;
6045 if (imp->peek_char() != ' ')
6049 results = new Typed_identifier_list;
6051 if (imp->peek_char() != '(')
6053 Type* rtype = imp->read_type();
6054 results->push_back(Typed_identifier(Import::import_marker,
6055 rtype, imp->location()));
6062 Type* rtype = imp->read_type();
6063 results->push_back(Typed_identifier(Import::import_marker,
6064 rtype, imp->location()));
6065 if (imp->peek_char() != ',')
6067 imp->require_c_string(", ");
6069 imp->require_c_string(")");
6073 Function_type* fntype = Type::make_function_type(NULL, parameters,
6077 fntype->set_is_varargs();
6078 methods->push_back(Typed_identifier(name, fntype, imp->location()));
6080 imp->require_c_string("; ");
6083 imp->require_c_string("}");
6085 if (methods->empty())
6091 return Type::make_interface_type(methods, imp->location());
6094 // Make an interface type.
6097 Type::make_interface_type(Typed_identifier_list* methods,
6098 source_location location)
6100 return new Interface_type(methods, location);
6105 // Bind a method to an object.
6108 Method::bind_method(Expression* expr, source_location location) const
6110 if (this->stub_ == NULL)
6112 // When there is no stub object, the binding is determined by
6114 return this->do_bind_method(expr, location);
6116 return Expression::make_bound_method(expr, this->stub_, location);
6119 // Return the named object associated with a method. This may only be
6120 // called after methods are finalized.
6123 Method::named_object() const
6125 if (this->stub_ != NULL)
6127 return this->do_named_object();
6130 // Class Named_method.
6132 // The type of the method.
6135 Named_method::do_type() const
6137 if (this->named_object_->is_function())
6138 return this->named_object_->func_value()->type();
6139 else if (this->named_object_->is_function_declaration())
6140 return this->named_object_->func_declaration_value()->type();
6145 // Return the location of the method receiver.
6148 Named_method::do_receiver_location() const
6150 return this->do_type()->receiver()->location();
6153 // Bind a method to an object.
6156 Named_method::do_bind_method(Expression* expr, source_location location) const
6158 Named_object* no = this->named_object_;
6159 Bound_method_expression* bme = Expression::make_bound_method(expr, no,
6161 // If this is not a local method, and it does not use a stub, then
6162 // the real method expects a different type. We need to cast the
6164 if (this->depth() > 0 && !this->needs_stub_method())
6166 Function_type* ftype = this->do_type();
6167 go_assert(ftype->is_method());
6168 Type* frtype = ftype->receiver()->type();
6169 bme->set_first_argument_type(frtype);
6174 // Class Interface_method.
6176 // Bind a method to an object.
6179 Interface_method::do_bind_method(Expression* expr,
6180 source_location location) const
6182 return Expression::make_interface_field_reference(expr, this->name_,
6188 // Insert a new method. Return true if it was inserted, false
6192 Methods::insert(const std::string& name, Method* m)
6194 std::pair<Method_map::iterator, bool> ins =
6195 this->methods_.insert(std::make_pair(name, m));
6200 Method* old_method = ins.first->second;
6201 if (m->depth() < old_method->depth())
6204 ins.first->second = m;
6209 if (m->depth() == old_method->depth())
6210 old_method->set_is_ambiguous();
6216 // Return the number of unambiguous methods.
6219 Methods::count() const
6222 for (Method_map::const_iterator p = this->methods_.begin();
6223 p != this->methods_.end();
6225 if (!p->second->is_ambiguous())
6230 // Class Named_type.
6232 // Return the name of the type.
6235 Named_type::name() const
6237 return this->named_object_->name();
6240 // Return the name of the type to use in an error message.
6243 Named_type::message_name() const
6245 return this->named_object_->message_name();
6248 // Return the base type for this type. We have to be careful about
6249 // circular type definitions, which are invalid but may be seen here.
6252 Named_type::named_base()
6257 Type* ret = this->type_->base();
6258 this->seen_ = false;
6263 Named_type::named_base() const
6268 const Type* ret = this->type_->base();
6269 this->seen_ = false;
6273 // Return whether this is an error type. We have to be careful about
6274 // circular type definitions, which are invalid but may be seen here.
6277 Named_type::is_named_error_type() const
6282 bool ret = this->type_->is_error_type();
6283 this->seen_ = false;
6287 // Add a method to this type.
6290 Named_type::add_method(const std::string& name, Function* function)
6292 if (this->local_methods_ == NULL)
6293 this->local_methods_ = new Bindings(NULL);
6294 return this->local_methods_->add_function(name, NULL, function);
6297 // Add a method declaration to this type.
6300 Named_type::add_method_declaration(const std::string& name, Package* package,
6301 Function_type* type,
6302 source_location location)
6304 if (this->local_methods_ == NULL)
6305 this->local_methods_ = new Bindings(NULL);
6306 return this->local_methods_->add_function_declaration(name, package, type,
6310 // Add an existing method to this type.
6313 Named_type::add_existing_method(Named_object* no)
6315 if (this->local_methods_ == NULL)
6316 this->local_methods_ = new Bindings(NULL);
6317 this->local_methods_->add_named_object(no);
6320 // Look for a local method NAME, and returns its named object, or NULL
6324 Named_type::find_local_method(const std::string& name) const
6326 if (this->local_methods_ == NULL)
6328 return this->local_methods_->lookup(name);
6331 // Return whether NAME is an unexported field or method, for better
6335 Named_type::is_unexported_local_method(Gogo* gogo,
6336 const std::string& name) const
6338 Bindings* methods = this->local_methods_;
6339 if (methods != NULL)
6341 for (Bindings::const_declarations_iterator p =
6342 methods->begin_declarations();
6343 p != methods->end_declarations();
6346 if (Gogo::is_hidden_name(p->first)
6347 && name == Gogo::unpack_hidden_name(p->first)
6348 && gogo->pack_hidden_name(name, false) != p->first)
6355 // Build the complete list of methods for this type, which means
6356 // recursively including all methods for anonymous fields. Create all
6360 Named_type::finalize_methods(Gogo* gogo)
6362 if (this->all_methods_ != NULL)
6365 if (this->local_methods_ != NULL
6366 && (this->points_to() != NULL || this->interface_type() != NULL))
6368 const Bindings* lm = this->local_methods_;
6369 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
6370 p != lm->end_declarations();
6372 error_at(p->second->location(),
6373 "invalid pointer or interface receiver type");
6374 delete this->local_methods_;
6375 this->local_methods_ = NULL;
6379 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6382 // Return the method NAME, or NULL if there isn't one or if it is
6383 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6387 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
6389 return Type::method_function(this->all_methods_, name, is_ambiguous);
6392 // Return a pointer to the interface method table for this type for
6393 // the interface INTERFACE. IS_POINTER is true if this is for a
6397 Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface,
6400 go_assert(!interface->is_empty());
6402 Interface_method_tables** pimt = (is_pointer
6403 ? &this->interface_method_tables_
6404 : &this->pointer_interface_method_tables_);
6407 *pimt = new Interface_method_tables(5);
6409 std::pair<const Interface_type*, tree> val(interface, NULL_TREE);
6410 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
6414 // This is a new entry in the hash table.
6415 go_assert(ins.first->second == NULL_TREE);
6416 ins.first->second = gogo->interface_method_table_for_type(interface,
6421 tree decl = ins.first->second;
6422 if (decl == error_mark_node)
6423 return error_mark_node;
6424 go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL);
6425 return build_fold_addr_expr(decl);
6428 // Return whether a named type has any hidden fields.
6431 Named_type::named_type_has_hidden_fields(std::string* reason) const
6436 bool ret = this->type_->has_hidden_fields(this, reason);
6437 this->seen_ = false;
6441 // Look for a use of a complete type within another type. This is
6442 // used to check that we don't try to use a type within itself.
6444 class Find_type_use : public Traverse
6447 Find_type_use(Named_type* find_type)
6448 : Traverse(traverse_types),
6449 find_type_(find_type), found_(false)
6452 // Whether we found the type.
6455 { return this->found_; }
6462 // The type we are looking for.
6463 Named_type* find_type_;
6464 // Whether we found the type.
6468 // Check for FIND_TYPE in TYPE.
6471 Find_type_use::type(Type* type)
6473 if (type->named_type() != NULL && this->find_type_ == type->named_type())
6475 this->found_ = true;
6476 return TRAVERSE_EXIT;
6479 // It's OK if we see a reference to the type in any type which is
6480 // essentially a pointer: a pointer, a slice, a function, a map, or
6482 if (type->points_to() != NULL
6483 || type->is_open_array_type()
6484 || type->function_type() != NULL
6485 || type->map_type() != NULL
6486 || type->channel_type() != NULL)
6487 return TRAVERSE_SKIP_COMPONENTS;
6489 // For an interface, a reference to the type in a method type should
6490 // be ignored, but we have to consider direct inheritance. When
6491 // this is called, there may be cases of direct inheritance
6492 // represented as a method with no name.
6493 if (type->interface_type() != NULL)
6495 const Typed_identifier_list* methods = type->interface_type()->methods();
6496 if (methods != NULL)
6498 for (Typed_identifier_list::const_iterator p = methods->begin();
6499 p != methods->end();
6502 if (p->name().empty())
6504 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
6505 return TRAVERSE_EXIT;
6509 return TRAVERSE_SKIP_COMPONENTS;
6512 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
6513 // to convert TYPE to the backend representation before we convert
6515 if (type->named_type() != NULL)
6517 switch (type->base()->classification())
6519 case Type::TYPE_ERROR:
6520 case Type::TYPE_BOOLEAN:
6521 case Type::TYPE_INTEGER:
6522 case Type::TYPE_FLOAT:
6523 case Type::TYPE_COMPLEX:
6524 case Type::TYPE_STRING:
6525 case Type::TYPE_NIL:
6528 case Type::TYPE_ARRAY:
6529 case Type::TYPE_STRUCT:
6530 this->find_type_->add_dependency(type->named_type());
6533 case Type::TYPE_VOID:
6534 case Type::TYPE_SINK:
6535 case Type::TYPE_FUNCTION:
6536 case Type::TYPE_POINTER:
6537 case Type::TYPE_CALL_MULTIPLE_RESULT:
6538 case Type::TYPE_MAP:
6539 case Type::TYPE_CHANNEL:
6540 case Type::TYPE_INTERFACE:
6541 case Type::TYPE_NAMED:
6542 case Type::TYPE_FORWARD:
6548 return TRAVERSE_CONTINUE;
6551 // Verify that a named type does not refer to itself.
6554 Named_type::do_verify()
6556 Find_type_use find(this);
6557 Type::traverse(this->type_, &find);
6560 error_at(this->location_, "invalid recursive type %qs",
6561 this->message_name().c_str());
6562 this->is_error_ = true;
6566 // Check whether any of the local methods overloads an existing
6567 // struct field or interface method. We don't need to check the
6568 // list of methods against itself: that is handled by the Bindings
6570 if (this->local_methods_ != NULL)
6572 Struct_type* st = this->type_->struct_type();
6573 bool found_dup = false;
6576 for (Bindings::const_declarations_iterator p =
6577 this->local_methods_->begin_declarations();
6578 p != this->local_methods_->end_declarations();
6581 const std::string& name(p->first);
6582 if (st != NULL && st->find_local_field(name, NULL) != NULL)
6584 error_at(p->second->location(),
6585 "method %qs redeclares struct field name",
6586 Gogo::message_name(name).c_str());
6598 // Return whether this type is or contains a pointer.
6601 Named_type::do_has_pointer() const
6606 bool ret = this->type_->has_pointer();
6607 this->seen_ = false;
6611 // Return a hash code. This is used for method lookup. We simply
6612 // hash on the name itself.
6615 Named_type::do_hash_for_method(Gogo* gogo) const
6617 const std::string& name(this->named_object()->name());
6618 unsigned int ret = Type::hash_string(name, 0);
6620 // GOGO will be NULL here when called from Type_hash_identical.
6621 // That is OK because that is only used for internal hash tables
6622 // where we are going to be comparing named types for equality. In
6623 // other cases, which are cases where the runtime is going to
6624 // compare hash codes to see if the types are the same, we need to
6625 // include the package prefix and name in the hash.
6626 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
6628 const Package* package = this->named_object()->package();
6629 if (package == NULL)
6631 ret = Type::hash_string(gogo->unique_prefix(), ret);
6632 ret = Type::hash_string(gogo->package_name(), ret);
6636 ret = Type::hash_string(package->unique_prefix(), ret);
6637 ret = Type::hash_string(package->name(), ret);
6644 // Convert a named type to the backend representation. In order to
6645 // get dependencies right, we fill in a dummy structure for this type,
6646 // then convert all the dependencies, then complete this type. When
6647 // this function is complete, the size of the type is known.
6650 Named_type::convert(Gogo* gogo)
6652 if (this->is_error_ || this->is_converted_)
6655 this->create_placeholder(gogo);
6657 // Convert all the dependencies. If they refer indirectly back to
6658 // this type, they will pick up the intermediate tree we just
6660 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
6661 p != this->dependencies_.end();
6663 (*p)->convert(gogo);
6665 // Complete this type.
6666 Btype* bt = this->named_btype_;
6667 Type* base = this->type_->base();
6668 switch (base->classification())
6685 // The size of these types is already correct. We don't worry
6686 // about filling them in until later, when we also track
6687 // circular references.
6692 std::vector<Backend::Btyped_identifier> bfields;
6693 get_backend_struct_fields(gogo, base->struct_type()->fields(),
6695 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6696 bt = gogo->backend()->error_type();
6701 // Slice types were completed in create_placeholder.
6702 if (!base->is_open_array_type())
6704 Btype* bet = base->array_type()->get_backend_element(gogo);
6705 Bexpression* blen = base->array_type()->get_backend_length(gogo);
6706 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
6707 bt = gogo->backend()->error_type();
6711 case TYPE_INTERFACE:
6712 // Interface types were completed in create_placeholder.
6720 case TYPE_CALL_MULTIPLE_RESULT:
6726 this->named_btype_ = bt;
6727 this->is_converted_ = true;
6730 // Create the placeholder for a named type. This is the first step in
6731 // converting to the backend representation.
6734 Named_type::create_placeholder(Gogo* gogo)
6736 if (this->is_error_)
6737 this->named_btype_ = gogo->backend()->error_type();
6739 if (this->named_btype_ != NULL)
6742 // Create the structure for this type. Note that because we call
6743 // base() here, we don't attempt to represent a named type defined
6744 // as another named type. Instead both named types will point to
6745 // different base representations.
6746 Type* base = this->type_->base();
6748 bool set_name = true;
6749 switch (base->classification())
6752 this->is_error_ = true;
6753 this->named_btype_ = gogo->backend()->error_type();
6763 // These are simple basic types, we can just create them
6765 bt = Type::get_named_base_btype(gogo, base);
6770 // All maps and channels have the same backend representation.
6771 bt = Type::get_named_base_btype(gogo, base);
6777 bool for_function = base->classification() == TYPE_FUNCTION;
6778 bt = gogo->backend()->placeholder_pointer_type(this->name(),
6786 bt = gogo->backend()->placeholder_struct_type(this->name(),
6792 if (base->is_open_array_type())
6793 bt = gogo->backend()->placeholder_struct_type(this->name(),
6796 bt = gogo->backend()->placeholder_array_type(this->name(),
6801 case TYPE_INTERFACE:
6802 if (base->interface_type()->is_empty())
6803 bt = Interface_type::get_backend_empty_interface_type(gogo);
6806 bt = gogo->backend()->placeholder_struct_type(this->name(),
6814 case TYPE_CALL_MULTIPLE_RESULT:
6821 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
6823 this->named_btype_ = bt;
6825 if (base->is_open_array_type())
6827 // We do not record slices as dependencies of other types,
6828 // because we can fill them in completely here with the final
6830 std::vector<Backend::Btyped_identifier> bfields;
6831 get_backend_slice_fields(gogo, base->array_type(), &bfields);
6832 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6833 this->named_btype_ = gogo->backend()->error_type();
6835 else if (base->interface_type() != NULL
6836 && !base->interface_type()->is_empty())
6838 // We do not record interfaces as dependencies of other types,
6839 // because we can fill them in completely here with the final
6841 std::vector<Backend::Btyped_identifier> bfields;
6842 get_backend_interface_fields(gogo, base->interface_type(), &bfields);
6843 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6844 this->named_btype_ = gogo->backend()->error_type();
6848 // Get a tree for a named type.
6851 Named_type::do_get_backend(Gogo* gogo)
6853 if (this->is_error_)
6854 return gogo->backend()->error_type();
6856 Btype* bt = this->named_btype_;
6858 if (!gogo->named_types_are_converted())
6860 // We have not completed converting named types. NAMED_BTYPE_
6861 // is a placeholder and we shouldn't do anything further.
6865 // We don't build dependencies for types whose sizes do not
6866 // change or are not relevant, so we may see them here while
6867 // converting types.
6868 this->create_placeholder(gogo);
6869 bt = this->named_btype_;
6870 go_assert(bt != NULL);
6874 // We are not converting types. This should only be called if the
6875 // type has already been converted.
6876 if (!this->is_converted_)
6878 go_assert(saw_errors());
6879 return gogo->backend()->error_type();
6882 go_assert(bt != NULL);
6884 // Complete the tree.
6885 Type* base = this->type_->base();
6887 switch (base->classification())
6890 return gogo->backend()->error_type();
6903 case TYPE_INTERFACE:
6907 // Don't build a circular data structure. GENERIC can't handle
6909 if (this->seen_in_get_backend_)
6911 this->is_circular_ = true;
6912 return gogo->backend()->circular_pointer_type(bt, true);
6914 this->seen_in_get_backend_ = true;
6915 bt1 = Type::get_named_base_btype(gogo, base);
6916 this->seen_in_get_backend_ = false;
6917 if (this->is_circular_)
6918 bt1 = gogo->backend()->circular_pointer_type(bt, true);
6919 if (!gogo->backend()->set_placeholder_function_type(bt, bt1))
6920 bt = gogo->backend()->error_type();
6924 // Don't build a circular data structure. GENERIC can't handle
6926 if (this->seen_in_get_backend_)
6928 this->is_circular_ = true;
6929 return gogo->backend()->circular_pointer_type(bt, false);
6931 this->seen_in_get_backend_ = true;
6932 bt1 = Type::get_named_base_btype(gogo, base);
6933 this->seen_in_get_backend_ = false;
6934 if (this->is_circular_)
6935 bt1 = gogo->backend()->circular_pointer_type(bt, false);
6936 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
6937 bt = gogo->backend()->error_type();
6942 case TYPE_CALL_MULTIPLE_RESULT:
6951 // Build a type descriptor for a named type.
6954 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6956 // If NAME is not NULL, then we don't really want the type
6957 // descriptor for this type; we want the descriptor for the
6958 // underlying type, giving it the name NAME.
6959 return this->named_type_descriptor(gogo, this->type_,
6960 name == NULL ? this : name);
6963 // Add to the reflection string. This is used mostly for the name of
6964 // the type used in a type descriptor, not for actual reflection
6968 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
6970 if (this->location() != BUILTINS_LOCATION)
6972 const Package* package = this->named_object_->package();
6973 if (package != NULL)
6974 ret->append(package->name());
6976 ret->append(gogo->package_name());
6977 ret->push_back('.');
6979 if (this->in_function_ != NULL)
6981 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
6982 ret->push_back('$');
6984 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
6987 // Get the mangled name.
6990 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6992 Named_object* no = this->named_object_;
6994 if (this->location() == BUILTINS_LOCATION)
6995 go_assert(this->in_function_ == NULL);
6998 const std::string& unique_prefix(no->package() == NULL
6999 ? gogo->unique_prefix()
7000 : no->package()->unique_prefix());
7001 const std::string& package_name(no->package() == NULL
7002 ? gogo->package_name()
7003 : no->package()->name());
7004 name = unique_prefix;
7005 name.append(1, '.');
7006 name.append(package_name);
7007 name.append(1, '.');
7008 if (this->in_function_ != NULL)
7010 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
7011 name.append(1, '$');
7014 name.append(Gogo::unpack_hidden_name(no->name()));
7016 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
7021 // Export the type. This is called to export a global type.
7024 Named_type::export_named_type(Export* exp, const std::string&) const
7026 // We don't need to write the name of the type here, because it will
7027 // be written by Export::write_type anyhow.
7028 exp->write_c_string("type ");
7029 exp->write_type(this);
7030 exp->write_c_string(";\n");
7033 // Import a named type.
7036 Named_type::import_named_type(Import* imp, Named_type** ptype)
7038 imp->require_c_string("type ");
7039 Type *type = imp->read_type();
7040 *ptype = type->named_type();
7041 go_assert(*ptype != NULL);
7042 imp->require_c_string(";\n");
7045 // Export the type when it is referenced by another type. In this
7046 // case Export::export_type will already have issued the name.
7049 Named_type::do_export(Export* exp) const
7051 exp->write_type(this->type_);
7053 // To save space, we only export the methods directly attached to
7055 Bindings* methods = this->local_methods_;
7056 if (methods == NULL)
7059 exp->write_c_string("\n");
7060 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
7061 p != methods->end_definitions();
7064 exp->write_c_string(" ");
7065 (*p)->export_named_object(exp);
7068 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
7069 p != methods->end_declarations();
7072 if (p->second->is_function_declaration())
7074 exp->write_c_string(" ");
7075 p->second->export_named_object(exp);
7080 // Make a named type.
7083 Type::make_named_type(Named_object* named_object, Type* type,
7084 source_location location)
7086 return new Named_type(named_object, type, location);
7089 // Finalize the methods for TYPE. It will be a named type or a struct
7090 // type. This sets *ALL_METHODS to the list of methods, and builds
7091 // all required stubs.
7094 Type::finalize_methods(Gogo* gogo, const Type* type, source_location location,
7095 Methods** all_methods)
7097 *all_methods = NULL;
7098 Types_seen types_seen;
7099 Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen,
7101 Type::build_stub_methods(gogo, type, *all_methods, location);
7104 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
7105 // build up the struct field indexes as we go. DEPTH is the depth of
7106 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
7107 // adding these methods for an anonymous field with pointer type.
7108 // NEEDS_STUB_METHOD is true if we need to use a stub method which
7109 // calls the real method. TYPES_SEEN is used to avoid infinite
7113 Type::add_methods_for_type(const Type* type,
7114 const Method::Field_indexes* field_indexes,
7116 bool is_embedded_pointer,
7117 bool needs_stub_method,
7118 Types_seen* types_seen,
7121 // Pointer types may not have methods.
7122 if (type->points_to() != NULL)
7125 const Named_type* nt = type->named_type();
7128 std::pair<Types_seen::iterator, bool> ins = types_seen->insert(nt);
7134 Type::add_local_methods_for_type(nt, field_indexes, depth,
7135 is_embedded_pointer, needs_stub_method,
7138 Type::add_embedded_methods_for_type(type, field_indexes, depth,
7139 is_embedded_pointer, needs_stub_method,
7140 types_seen, methods);
7142 // If we are called with depth > 0, then we are looking at an
7143 // anonymous field of a struct. If such a field has interface type,
7144 // then we need to add the interface methods. We don't want to add
7145 // them when depth == 0, because we will already handle them
7146 // following the usual rules for an interface type.
7148 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
7151 // Add the local methods for the named type NT to *METHODS. The
7152 // parameters are as for add_methods_to_type.
7155 Type::add_local_methods_for_type(const Named_type* nt,
7156 const Method::Field_indexes* field_indexes,
7158 bool is_embedded_pointer,
7159 bool needs_stub_method,
7162 const Bindings* local_methods = nt->local_methods();
7163 if (local_methods == NULL)
7166 if (*methods == NULL)
7167 *methods = new Methods();
7169 for (Bindings::const_declarations_iterator p =
7170 local_methods->begin_declarations();
7171 p != local_methods->end_declarations();
7174 Named_object* no = p->second;
7175 bool is_value_method = (is_embedded_pointer
7176 || !Type::method_expects_pointer(no));
7177 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
7179 || (depth > 0 && is_value_method)));
7180 if (!(*methods)->insert(no->name(), m))
7185 // Add the embedded methods for TYPE to *METHODS. These are the
7186 // methods attached to anonymous fields. The parameters are as for
7187 // add_methods_to_type.
7190 Type::add_embedded_methods_for_type(const Type* type,
7191 const Method::Field_indexes* field_indexes,
7193 bool is_embedded_pointer,
7194 bool needs_stub_method,
7195 Types_seen* types_seen,
7198 // Look for anonymous fields in TYPE. TYPE has fields if it is a
7200 const Struct_type* st = type->struct_type();
7204 const Struct_field_list* fields = st->fields();
7209 for (Struct_field_list::const_iterator pf = fields->begin();
7210 pf != fields->end();
7213 if (!pf->is_anonymous())
7216 Type* ftype = pf->type();
7217 bool is_pointer = false;
7218 if (ftype->points_to() != NULL)
7220 ftype = ftype->points_to();
7223 Named_type* fnt = ftype->named_type();
7226 // This is an error, but it will be diagnosed elsewhere.
7230 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
7231 sub_field_indexes->next = field_indexes;
7232 sub_field_indexes->field_index = i;
7234 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
7235 (is_embedded_pointer || is_pointer),
7244 // If TYPE is an interface type, then add its method to *METHODS.
7245 // This is for interface methods attached to an anonymous field. The
7246 // parameters are as for add_methods_for_type.
7249 Type::add_interface_methods_for_type(const Type* type,
7250 const Method::Field_indexes* field_indexes,
7254 const Interface_type* it = type->interface_type();
7258 const Typed_identifier_list* imethods = it->methods();
7259 if (imethods == NULL)
7262 if (*methods == NULL)
7263 *methods = new Methods();
7265 for (Typed_identifier_list::const_iterator pm = imethods->begin();
7266 pm != imethods->end();
7269 Function_type* fntype = pm->type()->function_type();
7272 // This is an error, but it should be reported elsewhere
7273 // when we look at the methods for IT.
7276 go_assert(!fntype->is_method());
7277 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
7278 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
7279 field_indexes, depth);
7280 if (!(*methods)->insert(pm->name(), m))
7285 // Build stub methods for TYPE as needed. METHODS is the set of
7286 // methods for the type. A stub method may be needed when a type
7287 // inherits a method from an anonymous field. When we need the
7288 // address of the method, as in a type descriptor, we need to build a
7289 // little stub which does the required field dereferences and jumps to
7290 // the real method. LOCATION is the location of the type definition.
7293 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
7294 source_location location)
7296 if (methods == NULL)
7298 for (Methods::const_iterator p = methods->begin();
7299 p != methods->end();
7302 Method* m = p->second;
7303 if (m->is_ambiguous() || !m->needs_stub_method())
7306 const std::string& name(p->first);
7308 // Build a stub method.
7310 const Function_type* fntype = m->type();
7312 static unsigned int counter;
7314 snprintf(buf, sizeof buf, "$this%u", counter);
7317 Type* receiver_type = const_cast<Type*>(type);
7318 if (!m->is_value_method())
7319 receiver_type = Type::make_pointer_type(receiver_type);
7320 source_location receiver_location = m->receiver_location();
7321 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
7324 const Typed_identifier_list* fnparams = fntype->parameters();
7325 Typed_identifier_list* stub_params;
7326 if (fnparams == NULL || fnparams->empty())
7330 // We give each stub parameter a unique name.
7331 stub_params = new Typed_identifier_list();
7332 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
7333 pp != fnparams->end();
7337 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
7338 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
7344 const Typed_identifier_list* fnresults = fntype->results();
7345 Typed_identifier_list* stub_results;
7346 if (fnresults == NULL || fnresults->empty())
7347 stub_results = NULL;
7350 // We create the result parameters without any names, since
7351 // we won't refer to them.
7352 stub_results = new Typed_identifier_list();
7353 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
7354 pr != fnresults->end();
7356 stub_results->push_back(Typed_identifier("", pr->type(),
7360 Function_type* stub_type = Type::make_function_type(receiver,
7363 fntype->location());
7364 if (fntype->is_varargs())
7365 stub_type->set_is_varargs();
7367 // We only create the function in the package which creates the
7369 const Package* package;
7370 if (type->named_type() == NULL)
7373 package = type->named_type()->named_object()->package();
7375 if (package != NULL)
7376 stub = Named_object::make_function_declaration(name, package,
7377 stub_type, location);
7380 stub = gogo->start_function(name, stub_type, false,
7381 fntype->location());
7382 Type::build_one_stub_method(gogo, m, buf, stub_params,
7383 fntype->is_varargs(), location);
7384 gogo->finish_function(fntype->location());
7387 m->set_stub_object(stub);
7391 // Build a stub method which adjusts the receiver as required to call
7392 // METHOD. RECEIVER_NAME is the name we used for the receiver.
7393 // PARAMS is the list of function parameters.
7396 Type::build_one_stub_method(Gogo* gogo, Method* method,
7397 const char* receiver_name,
7398 const Typed_identifier_list* params,
7400 source_location location)
7402 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
7403 go_assert(receiver_object != NULL);
7405 Expression* expr = Expression::make_var_reference(receiver_object, location);
7406 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
7407 if (expr->type()->points_to() == NULL)
7408 expr = Expression::make_unary(OPERATOR_AND, expr, location);
7410 Expression_list* arguments;
7411 if (params == NULL || params->empty())
7415 arguments = new Expression_list();
7416 for (Typed_identifier_list::const_iterator p = params->begin();
7420 Named_object* param = gogo->lookup(p->name(), NULL);
7421 go_assert(param != NULL);
7422 Expression* param_ref = Expression::make_var_reference(param,
7424 arguments->push_back(param_ref);
7428 Expression* func = method->bind_method(expr, location);
7429 go_assert(func != NULL);
7430 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
7432 call->set_hidden_fields_are_ok();
7433 size_t count = call->result_count();
7435 gogo->add_statement(Statement::make_statement(call, true));
7438 Expression_list* retvals = new Expression_list();
7440 retvals->push_back(call);
7443 for (size_t i = 0; i < count; ++i)
7444 retvals->push_back(Expression::make_call_result(call, i));
7446 Return_statement* retstat = Statement::make_return_statement(retvals,
7449 // We can return values with hidden fields from a stub. This is
7450 // necessary if the method is itself hidden.
7451 retstat->set_hidden_fields_are_ok();
7453 gogo->add_statement(retstat);
7457 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
7458 // in reverse order.
7461 Type::apply_field_indexes(Expression* expr,
7462 const Method::Field_indexes* field_indexes,
7463 source_location location)
7465 if (field_indexes == NULL)
7467 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
7468 Struct_type* stype = expr->type()->deref()->struct_type();
7469 go_assert(stype != NULL
7470 && field_indexes->field_index < stype->field_count());
7471 if (expr->type()->struct_type() == NULL)
7473 go_assert(expr->type()->points_to() != NULL);
7474 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
7475 go_assert(expr->type()->struct_type() == stype);
7477 return Expression::make_field_reference(expr, field_indexes->field_index,
7481 // Return whether NO is a method for which the receiver is a pointer.
7484 Type::method_expects_pointer(const Named_object* no)
7486 const Function_type *fntype;
7487 if (no->is_function())
7488 fntype = no->func_value()->type();
7489 else if (no->is_function_declaration())
7490 fntype = no->func_declaration_value()->type();
7493 return fntype->receiver()->type()->points_to() != NULL;
7496 // Given a set of methods for a type, METHODS, return the method NAME,
7497 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
7498 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
7499 // but is ambiguous (and return NULL).
7502 Type::method_function(const Methods* methods, const std::string& name,
7505 if (is_ambiguous != NULL)
7506 *is_ambiguous = false;
7507 if (methods == NULL)
7509 Methods::const_iterator p = methods->find(name);
7510 if (p == methods->end())
7512 Method* m = p->second;
7513 if (m->is_ambiguous())
7515 if (is_ambiguous != NULL)
7516 *is_ambiguous = true;
7522 // Look for field or method NAME for TYPE. Return an Expression for
7523 // the field or method bound to EXPR. If there is no such field or
7524 // method, give an appropriate error and return an error expression.
7527 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
7528 const std::string& name,
7529 source_location location)
7531 if (type->deref()->is_error_type())
7532 return Expression::make_error(location);
7534 const Named_type* nt = type->deref()->named_type();
7535 const Struct_type* st = type->deref()->struct_type();
7536 const Interface_type* it = type->interface_type();
7538 // If this is a pointer to a pointer, then it is possible that the
7539 // pointed-to type has methods.
7543 && type->points_to() != NULL
7544 && type->points_to()->points_to() != NULL)
7546 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
7547 type = type->points_to();
7548 if (type->deref()->is_error_type())
7549 return Expression::make_error(location);
7550 nt = type->points_to()->named_type();
7551 st = type->points_to()->struct_type();
7554 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
7555 || expr->is_addressable());
7556 std::vector<const Named_type*> seen;
7557 bool is_method = false;
7558 bool found_pointer_method = false;
7561 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
7562 &seen, NULL, &is_method,
7563 &found_pointer_method, &ambig1, &ambig2))
7568 go_assert(st != NULL);
7569 if (type->struct_type() == NULL)
7571 go_assert(type->points_to() != NULL);
7572 expr = Expression::make_unary(OPERATOR_MULT, expr,
7574 go_assert(expr->type()->struct_type() == st);
7576 ret = st->field_reference(expr, name, location);
7578 else if (it != NULL && it->find_method(name) != NULL)
7579 ret = Expression::make_interface_field_reference(expr, name,
7585 m = nt->method_function(name, NULL);
7586 else if (st != NULL)
7587 m = st->method_function(name, NULL);
7590 go_assert(m != NULL);
7591 if (!m->is_value_method() && expr->type()->points_to() == NULL)
7592 expr = Expression::make_unary(OPERATOR_AND, expr, location);
7593 ret = m->bind_method(expr, location);
7595 go_assert(ret != NULL);
7600 if (!ambig1.empty())
7601 error_at(location, "%qs is ambiguous via %qs and %qs",
7602 Gogo::message_name(name).c_str(), ambig1.c_str(),
7604 else if (found_pointer_method)
7605 error_at(location, "method requires a pointer");
7606 else if (nt == NULL && st == NULL && it == NULL)
7608 ("reference to field %qs in object which "
7609 "has no fields or methods"),
7610 Gogo::message_name(name).c_str());
7614 if (!Gogo::is_hidden_name(name))
7615 is_unexported = false;
7618 std::string unpacked = Gogo::unpack_hidden_name(name);
7620 is_unexported = Type::is_unexported_field_or_method(gogo, type,
7625 error_at(location, "reference to unexported field or method %qs",
7626 Gogo::message_name(name).c_str());
7628 error_at(location, "reference to undefined field or method %qs",
7629 Gogo::message_name(name).c_str());
7631 return Expression::make_error(location);
7635 // Look in TYPE for a field or method named NAME, return true if one
7636 // is found. This looks through embedded anonymous fields and handles
7637 // ambiguity. If a method is found, sets *IS_METHOD to true;
7638 // otherwise, if a field is found, set it to false. If
7639 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
7640 // whose address can not be taken. SEEN is used to avoid infinite
7641 // recursion on invalid types.
7643 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
7644 // method we couldn't use because it requires a pointer. LEVEL is
7645 // used for recursive calls, and can be NULL for a non-recursive call.
7646 // When this function returns false because it finds that the name is
7647 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
7648 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
7649 // will be unchanged.
7651 // This function just returns whether or not there is a field or
7652 // method, and whether it is a field or method. It doesn't build an
7653 // expression to refer to it. If it is a method, we then look in the
7654 // list of all methods for the type. If it is a field, the search has
7655 // to be done again, looking only for fields, and building up the
7656 // expression as we go.
7659 Type::find_field_or_method(const Type* type,
7660 const std::string& name,
7661 bool receiver_can_be_pointer,
7662 std::vector<const Named_type*>* seen,
7665 bool* found_pointer_method,
7666 std::string* ambig1,
7667 std::string* ambig2)
7669 // Named types can have locally defined methods.
7670 const Named_type* nt = type->named_type();
7671 if (nt == NULL && type->points_to() != NULL)
7672 nt = type->points_to()->named_type();
7675 Named_object* no = nt->find_local_method(name);
7678 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
7684 // Record that we have found a pointer method in order to
7685 // give a better error message if we don't find anything
7687 *found_pointer_method = true;
7690 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
7696 // We've already seen this type when searching for methods.
7702 // Interface types can have methods.
7703 const Interface_type* it = type->interface_type();
7704 if (it != NULL && it->find_method(name) != NULL)
7710 // Struct types can have fields. They can also inherit fields and
7711 // methods from anonymous fields.
7712 const Struct_type* st = type->deref()->struct_type();
7715 const Struct_field_list* fields = st->fields();
7720 seen->push_back(nt);
7722 int found_level = 0;
7723 bool found_is_method = false;
7724 std::string found_ambig1;
7725 std::string found_ambig2;
7726 const Struct_field* found_parent = NULL;
7727 for (Struct_field_list::const_iterator pf = fields->begin();
7728 pf != fields->end();
7731 if (pf->is_field_name(name))
7739 if (!pf->is_anonymous())
7742 if (pf->type()->deref()->is_error_type()
7743 || pf->type()->deref()->is_undefined())
7746 Named_type* fnt = pf->type()->named_type();
7748 fnt = pf->type()->deref()->named_type();
7749 go_assert(fnt != NULL);
7751 int sublevel = level == NULL ? 1 : *level + 1;
7753 std::string subambig1;
7754 std::string subambig2;
7755 bool subfound = Type::find_field_or_method(fnt,
7757 receiver_can_be_pointer,
7761 found_pointer_method,
7766 if (!subambig1.empty())
7768 // The name was found via this field, but is ambiguous.
7769 // if the ambiguity is lower or at the same level as
7770 // anything else we have already found, then we want to
7771 // pass the ambiguity back to the caller.
7772 if (found_level == 0 || sublevel <= found_level)
7774 found_ambig1 = (Gogo::message_name(pf->field_name())
7776 found_ambig2 = (Gogo::message_name(pf->field_name())
7778 found_level = sublevel;
7784 // The name was found via this field. Use the level to see
7785 // if we want to use this one, or whether it introduces an
7787 if (found_level == 0 || sublevel < found_level)
7789 found_level = sublevel;
7790 found_is_method = sub_is_method;
7791 found_ambig1.clear();
7792 found_ambig2.clear();
7793 found_parent = &*pf;
7795 else if (sublevel > found_level)
7797 else if (found_ambig1.empty())
7799 // We found an ambiguity.
7800 go_assert(found_parent != NULL);
7801 found_ambig1 = Gogo::message_name(found_parent->field_name());
7802 found_ambig2 = Gogo::message_name(pf->field_name());
7806 // We found an ambiguity, but we already know of one.
7807 // Just report the earlier one.
7812 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
7813 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
7814 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
7815 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
7820 if (found_level == 0)
7822 else if (!found_ambig1.empty())
7824 go_assert(!found_ambig1.empty());
7825 ambig1->assign(found_ambig1);
7826 ambig2->assign(found_ambig2);
7828 *level = found_level;
7834 *level = found_level;
7835 *is_method = found_is_method;
7840 // Return whether NAME is an unexported field or method for TYPE.
7843 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
7844 const std::string& name,
7845 std::vector<const Named_type*>* seen)
7847 const Named_type* nt = type->named_type();
7849 nt = type->deref()->named_type();
7852 if (nt->is_unexported_local_method(gogo, name))
7855 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
7861 // We've already seen this type.
7867 const Interface_type* it = type->interface_type();
7868 if (it != NULL && it->is_unexported_method(gogo, name))
7871 type = type->deref();
7873 const Struct_type* st = type->struct_type();
7874 if (st != NULL && st->is_unexported_local_field(gogo, name))
7880 const Struct_field_list* fields = st->fields();
7885 seen->push_back(nt);
7887 for (Struct_field_list::const_iterator pf = fields->begin();
7888 pf != fields->end();
7891 if (pf->is_anonymous()
7892 && !pf->type()->deref()->is_error_type()
7893 && !pf->type()->deref()->is_undefined())
7895 Named_type* subtype = pf->type()->named_type();
7896 if (subtype == NULL)
7897 subtype = pf->type()->deref()->named_type();
7898 if (subtype == NULL)
7900 // This is an error, but it will be diagnosed elsewhere.
7903 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
7918 // Class Forward_declaration.
7920 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
7921 : Type(TYPE_FORWARD),
7922 named_object_(named_object->resolve()), warned_(false)
7924 go_assert(this->named_object_->is_unknown()
7925 || this->named_object_->is_type_declaration());
7928 // Return the named object.
7931 Forward_declaration_type::named_object()
7933 return this->named_object_->resolve();
7937 Forward_declaration_type::named_object() const
7939 return this->named_object_->resolve();
7942 // Return the name of the forward declared type.
7945 Forward_declaration_type::name() const
7947 return this->named_object()->name();
7950 // Warn about a use of a type which has been declared but not defined.
7953 Forward_declaration_type::warn() const
7955 Named_object* no = this->named_object_->resolve();
7956 if (no->is_unknown())
7958 // The name was not defined anywhere.
7961 error_at(this->named_object_->location(),
7962 "use of undefined type %qs",
7963 no->message_name().c_str());
7964 this->warned_ = true;
7967 else if (no->is_type_declaration())
7969 // The name was seen as a type, but the type was never defined.
7970 if (no->type_declaration_value()->using_type())
7972 error_at(this->named_object_->location(),
7973 "use of undefined type %qs",
7974 no->message_name().c_str());
7975 this->warned_ = true;
7980 // The name was defined, but not as a type.
7983 error_at(this->named_object_->location(), "expected type");
7984 this->warned_ = true;
7989 // Get the base type of a declaration. This gives an error if the
7990 // type has not yet been defined.
7993 Forward_declaration_type::real_type()
7995 if (this->is_defined())
7996 return this->named_object()->type_value();
8000 return Type::make_error_type();
8005 Forward_declaration_type::real_type() const
8007 if (this->is_defined())
8008 return this->named_object()->type_value();
8012 return Type::make_error_type();
8016 // Return whether the base type is defined.
8019 Forward_declaration_type::is_defined() const
8021 return this->named_object()->is_type();
8024 // Add a method. This is used when methods are defined before the
8028 Forward_declaration_type::add_method(const std::string& name,
8031 Named_object* no = this->named_object();
8032 if (no->is_unknown())
8033 no->declare_as_type();
8034 return no->type_declaration_value()->add_method(name, function);
8037 // Add a method declaration. This is used when methods are declared
8041 Forward_declaration_type::add_method_declaration(const std::string& name,
8042 Function_type* type,
8043 source_location location)
8045 Named_object* no = this->named_object();
8046 if (no->is_unknown())
8047 no->declare_as_type();
8048 Type_declaration* td = no->type_declaration_value();
8049 return td->add_method_declaration(name, type, location);
8055 Forward_declaration_type::do_traverse(Traverse* traverse)
8057 if (this->is_defined()
8058 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
8059 return TRAVERSE_EXIT;
8060 return TRAVERSE_CONTINUE;
8063 // Get the backend representation for the type.
8066 Forward_declaration_type::do_get_backend(Gogo* gogo)
8068 if (this->is_defined())
8069 return Type::get_named_base_btype(gogo, this->real_type());
8072 return gogo->backend()->error_type();
8074 // We represent an undefined type as a struct with no fields. That
8075 // should work fine for the backend, since the same case can arise
8077 std::vector<Backend::Btyped_identifier> fields;
8078 Btype* bt = gogo->backend()->struct_type(fields);
8079 return gogo->backend()->named_type(this->name(), bt,
8080 this->named_object()->location());
8083 // Build a type descriptor for a forwarded type.
8086 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8088 if (!this->is_defined())
8089 return Expression::make_nil(BUILTINS_LOCATION);
8092 Type* t = this->real_type();
8094 return this->named_type_descriptor(gogo, t, name);
8096 return Expression::make_type_descriptor(t, BUILTINS_LOCATION);
8100 // The reflection string.
8103 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
8105 this->append_reflection(this->real_type(), gogo, ret);
8108 // The mangled name.
8111 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8113 if (this->is_defined())
8114 this->append_mangled_name(this->real_type(), gogo, ret);
8117 const Named_object* no = this->named_object();
8119 if (no->package() == NULL)
8120 name = gogo->package_name();
8122 name = no->package()->name();
8124 name += Gogo::unpack_hidden_name(no->name());
8126 snprintf(buf, sizeof buf, "N%u_",
8127 static_cast<unsigned int>(name.length()));
8133 // Export a forward declaration. This can happen when a defined type
8134 // refers to a type which is only declared (and is presumably defined
8135 // in some other file in the same package).
8138 Forward_declaration_type::do_export(Export*) const
8140 // If there is a base type, that should be exported instead of this.
8141 go_assert(!this->is_defined());
8143 // We don't output anything.
8146 // Make a forward declaration.
8149 Type::make_forward_declaration(Named_object* named_object)
8151 return new Forward_declaration_type(named_object);
8154 // Class Typed_identifier_list.
8156 // Sort the entries by name.
8158 struct Typed_identifier_list_sort
8162 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
8163 { return t1.name() < t2.name(); }
8167 Typed_identifier_list::sort_by_name()
8169 std::sort(this->entries_.begin(), this->entries_.end(),
8170 Typed_identifier_list_sort());
8176 Typed_identifier_list::traverse(Traverse* traverse)
8178 for (Typed_identifier_list::const_iterator p = this->begin();
8182 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
8183 return TRAVERSE_EXIT;
8185 return TRAVERSE_CONTINUE;
8190 Typed_identifier_list*
8191 Typed_identifier_list::copy() const
8193 Typed_identifier_list* ret = new Typed_identifier_list();
8194 for (Typed_identifier_list::const_iterator p = this->begin();
8197 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));