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->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->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->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->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->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->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->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->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->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->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->field_name() == "name");
1408 go_assert(p->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->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->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->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->field_name() == "mtyp");
1564 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
1567 go_assert(p->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->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->field_name() == "commonType");
2756 vals->push_back(this->type_descriptor_constructor(gogo,
2757 RUNTIME_TYPE_KIND_FUNC,
2761 go_assert(p->field_name() == "dotdotdot");
2762 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
2765 go_assert(p->field_name() == "in");
2766 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
2767 this->parameters()));
2770 go_assert(p->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->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->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 // Class Struct_type.
3381 Struct_type::do_traverse(Traverse* traverse)
3383 Struct_field_list* fields = this->fields_;
3386 for (Struct_field_list::iterator p = fields->begin();
3390 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
3391 return TRAVERSE_EXIT;
3394 return TRAVERSE_CONTINUE;
3397 // Verify that the struct type is complete and valid.
3400 Struct_type::do_verify()
3402 Struct_field_list* fields = this->fields_;
3406 for (Struct_field_list::iterator p = fields->begin();
3410 Type* t = p->type();
3411 if (t->is_undefined())
3413 error_at(p->location(), "struct field type is incomplete");
3414 p->set_type(Type::make_error_type());
3417 else if (p->is_anonymous())
3419 if (t->named_type() != NULL && t->points_to() != NULL)
3421 error_at(p->location(), "embedded type may not be a pointer");
3422 p->set_type(Type::make_error_type());
3425 if (t->points_to() != NULL
3426 && t->points_to()->interface_type() != NULL)
3428 error_at(p->location(),
3429 "embedded type may not be pointer to interface");
3430 p->set_type(Type::make_error_type());
3438 // Whether this contains a pointer.
3441 Struct_type::do_has_pointer() const
3443 const Struct_field_list* fields = this->fields();
3446 for (Struct_field_list::const_iterator p = fields->begin();
3450 if (p->type()->has_pointer())
3456 // Whether this type is identical to T.
3459 Struct_type::is_identical(const Struct_type* t,
3460 bool errors_are_identical) const
3462 const Struct_field_list* fields1 = this->fields();
3463 const Struct_field_list* fields2 = t->fields();
3464 if (fields1 == NULL || fields2 == NULL)
3465 return fields1 == fields2;
3466 Struct_field_list::const_iterator pf2 = fields2->begin();
3467 for (Struct_field_list::const_iterator pf1 = fields1->begin();
3468 pf1 != fields1->end();
3471 if (pf2 == fields2->end())
3473 if (pf1->field_name() != pf2->field_name())
3475 if (pf1->is_anonymous() != pf2->is_anonymous()
3476 || !Type::are_identical(pf1->type(), pf2->type(),
3477 errors_are_identical, NULL))
3479 if (!pf1->has_tag())
3486 if (!pf2->has_tag())
3488 if (pf1->tag() != pf2->tag())
3492 if (pf2 != fields2->end())
3497 // Whether this struct type has any hidden fields.
3500 Struct_type::struct_has_hidden_fields(const Named_type* within,
3501 std::string* reason) const
3503 const Struct_field_list* fields = this->fields();
3506 const Package* within_package = (within == NULL
3508 : within->named_object()->package());
3509 for (Struct_field_list::const_iterator pf = fields->begin();
3510 pf != fields->end();
3513 if (within_package != NULL
3514 && !pf->is_anonymous()
3515 && Gogo::is_hidden_name(pf->field_name()))
3519 std::string within_name = within->named_object()->message_name();
3520 std::string name = Gogo::message_name(pf->field_name());
3521 size_t bufsize = 200 + within_name.length() + name.length();
3522 char* buf = new char[bufsize];
3523 snprintf(buf, bufsize,
3524 _("implicit assignment of %s%s%s hidden field %s%s%s"),
3525 open_quote, within_name.c_str(), close_quote,
3526 open_quote, name.c_str(), close_quote);
3527 reason->assign(buf);
3533 if (pf->type()->has_hidden_fields(within, reason))
3543 Struct_type::do_hash_for_method(Gogo* gogo) const
3545 unsigned int ret = 0;
3546 if (this->fields() != NULL)
3548 for (Struct_field_list::const_iterator pf = this->fields()->begin();
3549 pf != this->fields()->end();
3551 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
3556 // Find the local field NAME.
3559 Struct_type::find_local_field(const std::string& name,
3560 unsigned int *pindex) const
3562 const Struct_field_list* fields = this->fields_;
3566 for (Struct_field_list::const_iterator pf = fields->begin();
3567 pf != fields->end();
3570 if (pf->field_name() == name)
3580 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
3582 Field_reference_expression*
3583 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
3584 source_location location) const
3587 return this->field_reference_depth(struct_expr, name, location, NULL,
3591 // Return an expression for a field, along with the depth at which it
3594 Field_reference_expression*
3595 Struct_type::field_reference_depth(Expression* struct_expr,
3596 const std::string& name,
3597 source_location location,
3598 Saw_named_type* saw,
3599 unsigned int* depth) const
3601 const Struct_field_list* fields = this->fields_;
3605 // Look for a field with this name.
3607 for (Struct_field_list::const_iterator pf = fields->begin();
3608 pf != fields->end();
3611 if (pf->field_name() == name)
3614 return Expression::make_field_reference(struct_expr, i, location);
3618 // Look for an anonymous field which contains a field with this
3620 unsigned int found_depth = 0;
3621 Field_reference_expression* ret = NULL;
3623 for (Struct_field_list::const_iterator pf = fields->begin();
3624 pf != fields->end();
3627 if (!pf->is_anonymous())
3630 Struct_type* st = pf->type()->deref()->struct_type();
3634 Saw_named_type* hold_saw = saw;
3635 Saw_named_type saw_here;
3636 Named_type* nt = pf->type()->named_type();
3638 nt = pf->type()->deref()->named_type();
3642 for (q = saw; q != NULL; q = q->next)
3646 // If this is an error, it will be reported
3653 saw_here.next = saw;
3658 // Look for a reference using a NULL struct expression. If we
3659 // find one, fill in the struct expression with a reference to
3661 unsigned int subdepth;
3662 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
3672 if (ret == NULL || subdepth < found_depth)
3677 found_depth = subdepth;
3678 Expression* here = Expression::make_field_reference(struct_expr, i,
3680 if (pf->type()->points_to() != NULL)
3681 here = Expression::make_unary(OPERATOR_MULT, here, location);
3682 while (sub->expr() != NULL)
3684 sub = sub->expr()->deref()->field_reference_expression();
3685 go_assert(sub != NULL);
3687 sub->set_struct_expression(here);
3689 else if (subdepth > found_depth)
3693 // We do not handle ambiguity here--it should be handled by
3694 // Type::bind_field_or_method.
3702 *depth = found_depth + 1;
3707 // Return the total number of fields, including embedded fields.
3710 Struct_type::total_field_count() const
3712 if (this->fields_ == NULL)
3714 unsigned int ret = 0;
3715 for (Struct_field_list::const_iterator pf = this->fields_->begin();
3716 pf != this->fields_->end();
3719 if (!pf->is_anonymous() || pf->type()->deref()->struct_type() == NULL)
3722 ret += pf->type()->struct_type()->total_field_count();
3727 // Return whether NAME is an unexported field, for better error reporting.
3730 Struct_type::is_unexported_local_field(Gogo* gogo,
3731 const std::string& name) const
3733 const Struct_field_list* fields = this->fields_;
3736 for (Struct_field_list::const_iterator pf = fields->begin();
3737 pf != fields->end();
3740 const std::string& field_name(pf->field_name());
3741 if (Gogo::is_hidden_name(field_name)
3742 && name == Gogo::unpack_hidden_name(field_name)
3743 && gogo->pack_hidden_name(name, false) != field_name)
3750 // Finalize the methods of an unnamed struct.
3753 Struct_type::finalize_methods(Gogo* gogo)
3755 if (this->all_methods_ != NULL)
3757 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
3760 // Return the method NAME, or NULL if there isn't one or if it is
3761 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
3765 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
3767 return Type::method_function(this->all_methods_, name, is_ambiguous);
3770 // Convert struct fields to the backend representation. This is not
3771 // declared in types.h so that types.h doesn't have to #include
3775 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
3776 std::vector<Backend::Btyped_identifier>* bfields)
3778 bfields->resize(fields->size());
3780 for (Struct_field_list::const_iterator p = fields->begin();
3784 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
3785 (*bfields)[i].btype = p->type()->get_backend(gogo);
3786 (*bfields)[i].location = p->location();
3788 go_assert(i == fields->size());
3791 // Get the tree for a struct type.
3794 Struct_type::do_get_backend(Gogo* gogo)
3796 std::vector<Backend::Btyped_identifier> bfields;
3797 get_backend_struct_fields(gogo, this->fields_, &bfields);
3798 return gogo->backend()->struct_type(bfields);
3801 // The type of a struct type descriptor.
3804 Struct_type::make_struct_type_descriptor_type()
3809 Type* tdt = Type::make_type_descriptor_type();
3810 Type* ptdt = Type::make_type_descriptor_ptr_type();
3812 Type* uintptr_type = Type::lookup_integer_type("uintptr");
3813 Type* string_type = Type::lookup_string_type();
3814 Type* pointer_string_type = Type::make_pointer_type(string_type);
3817 Type::make_builtin_struct_type(5,
3818 "name", pointer_string_type,
3819 "pkgPath", pointer_string_type,
3821 "tag", pointer_string_type,
3822 "offset", uintptr_type);
3823 Type* nsf = Type::make_builtin_named_type("structField", sf);
3825 Type* slice_type = Type::make_array_type(nsf, NULL);
3827 Struct_type* s = Type::make_builtin_struct_type(2,
3829 "fields", slice_type);
3831 ret = Type::make_builtin_named_type("StructType", s);
3837 // Build a type descriptor for a struct type.
3840 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3842 source_location bloc = BUILTINS_LOCATION;
3844 Type* stdt = Struct_type::make_struct_type_descriptor_type();
3846 const Struct_field_list* fields = stdt->struct_type()->fields();
3848 Expression_list* vals = new Expression_list();
3851 const Methods* methods = this->methods();
3852 // A named struct should not have methods--the methods should attach
3853 // to the named type.
3854 go_assert(methods == NULL || name == NULL);
3856 Struct_field_list::const_iterator ps = fields->begin();
3857 go_assert(ps->field_name() == "commonType");
3858 vals->push_back(this->type_descriptor_constructor(gogo,
3859 RUNTIME_TYPE_KIND_STRUCT,
3860 name, methods, true));
3863 go_assert(ps->field_name() == "fields");
3865 Expression_list* elements = new Expression_list();
3866 elements->reserve(this->fields_->size());
3867 Type* element_type = ps->type()->array_type()->element_type();
3868 for (Struct_field_list::const_iterator pf = this->fields_->begin();
3869 pf != this->fields_->end();
3872 const Struct_field_list* f = element_type->struct_type()->fields();
3874 Expression_list* fvals = new Expression_list();
3877 Struct_field_list::const_iterator q = f->begin();
3878 go_assert(q->field_name() == "name");
3879 if (pf->is_anonymous())
3880 fvals->push_back(Expression::make_nil(bloc));
3883 std::string n = Gogo::unpack_hidden_name(pf->field_name());
3884 Expression* s = Expression::make_string(n, bloc);
3885 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3889 go_assert(q->field_name() == "pkgPath");
3890 if (!Gogo::is_hidden_name(pf->field_name()))
3891 fvals->push_back(Expression::make_nil(bloc));
3894 std::string n = Gogo::hidden_name_prefix(pf->field_name());
3895 Expression* s = Expression::make_string(n, bloc);
3896 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3900 go_assert(q->field_name() == "typ");
3901 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
3904 go_assert(q->field_name() == "tag");
3906 fvals->push_back(Expression::make_nil(bloc));
3909 Expression* s = Expression::make_string(pf->tag(), bloc);
3910 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3914 go_assert(q->field_name() == "offset");
3915 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
3917 Expression* v = Expression::make_struct_composite_literal(element_type,
3919 elements->push_back(v);
3922 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
3925 return Expression::make_struct_composite_literal(stdt, vals, bloc);
3928 // Reflection string.
3931 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
3933 ret->append("struct { ");
3935 for (Struct_field_list::const_iterator p = this->fields_->begin();
3936 p != this->fields_->end();
3939 if (p != this->fields_->begin())
3941 if (p->is_anonymous())
3942 ret->push_back('?');
3944 ret->append(Gogo::unpack_hidden_name(p->field_name()));
3945 ret->push_back(' ');
3946 this->append_reflection(p->type(), gogo, ret);
3950 const std::string& tag(p->tag());
3952 for (std::string::const_iterator p = tag.begin();
3957 ret->append("\\x00");
3958 else if (*p == '\n')
3960 else if (*p == '\t')
3963 ret->append("\\\"");
3964 else if (*p == '\\')
3965 ret->append("\\\\");
3969 ret->push_back('"');
3979 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3981 ret->push_back('S');
3983 const Struct_field_list* fields = this->fields_;
3986 for (Struct_field_list::const_iterator p = fields->begin();
3990 if (p->is_anonymous())
3994 std::string n = Gogo::unpack_hidden_name(p->field_name());
3996 snprintf(buf, sizeof buf, "%u_",
3997 static_cast<unsigned int>(n.length()));
4001 this->append_mangled_name(p->type(), gogo, ret);
4004 const std::string& tag(p->tag());
4006 for (std::string::const_iterator p = tag.begin();
4010 if (ISALNUM(*p) || *p == '_')
4015 snprintf(buf, sizeof buf, ".%x.",
4016 static_cast<unsigned int>(*p));
4021 snprintf(buf, sizeof buf, "T%u_",
4022 static_cast<unsigned int>(out.length()));
4029 ret->push_back('e');
4035 Struct_type::do_export(Export* exp) const
4037 exp->write_c_string("struct { ");
4038 const Struct_field_list* fields = this->fields_;
4039 go_assert(fields != NULL);
4040 for (Struct_field_list::const_iterator p = fields->begin();
4044 if (p->is_anonymous())
4045 exp->write_string("? ");
4048 exp->write_string(p->field_name());
4049 exp->write_c_string(" ");
4051 exp->write_type(p->type());
4055 exp->write_c_string(" ");
4056 Expression* expr = Expression::make_string(p->tag(),
4058 expr->export_expression(exp);
4062 exp->write_c_string("; ");
4064 exp->write_c_string("}");
4070 Struct_type::do_import(Import* imp)
4072 imp->require_c_string("struct { ");
4073 Struct_field_list* fields = new Struct_field_list;
4074 if (imp->peek_char() != '}')
4079 if (imp->match_c_string("? "))
4083 name = imp->read_identifier();
4084 imp->require_c_string(" ");
4086 Type* ftype = imp->read_type();
4088 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
4090 if (imp->peek_char() == ' ')
4093 Expression* expr = Expression::import_expression(imp);
4094 String_expression* sexpr = expr->string_expression();
4095 go_assert(sexpr != NULL);
4096 sf.set_tag(sexpr->val());
4100 imp->require_c_string("; ");
4101 fields->push_back(sf);
4102 if (imp->peek_char() == '}')
4106 imp->require_c_string("}");
4108 return Type::make_struct_type(fields, imp->location());
4111 // Make a struct type.
4114 Type::make_struct_type(Struct_field_list* fields,
4115 source_location location)
4117 return new Struct_type(fields, location);
4120 // Class Array_type.
4122 // Whether two array types are identical.
4125 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
4127 if (!Type::are_identical(this->element_type(), t->element_type(),
4128 errors_are_identical, NULL))
4131 Expression* l1 = this->length();
4132 Expression* l2 = t->length();
4134 // Slices of the same element type are identical.
4135 if (l1 == NULL && l2 == NULL)
4138 // Arrays of the same element type are identical if they have the
4140 if (l1 != NULL && l2 != NULL)
4145 // Try to determine the lengths. If we can't, assume the arrays
4146 // are not identical.
4154 if (l1->integer_constant_value(true, v1, &type1)
4155 && l2->integer_constant_value(true, v2, &type2))
4156 ret = mpz_cmp(v1, v2) == 0;
4162 // Otherwise the arrays are not identical.
4169 Array_type::do_traverse(Traverse* traverse)
4171 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
4172 return TRAVERSE_EXIT;
4173 if (this->length_ != NULL
4174 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
4175 return TRAVERSE_EXIT;
4176 return TRAVERSE_CONTINUE;
4179 // Check that the length is valid.
4182 Array_type::verify_length()
4184 if (this->length_ == NULL)
4187 Type_context context(Type::lookup_integer_type("int"), false);
4188 this->length_->determine_type(&context);
4190 if (!this->length_->is_constant())
4192 error_at(this->length_->location(), "array bound is not constant");
4199 if (!this->length_->integer_constant_value(true, val, &vt))
4203 if (!this->length_->float_constant_value(fval, &vt))
4205 if (this->length_->type()->integer_type() != NULL
4206 || this->length_->type()->float_type() != NULL)
4207 error_at(this->length_->location(),
4208 "array bound is not constant");
4210 error_at(this->length_->location(),
4211 "array bound is not numeric");
4216 if (!mpfr_integer_p(fval))
4218 error_at(this->length_->location(),
4219 "array bound truncated to integer");
4225 mpfr_get_z(val, fval, GMP_RNDN);
4229 if (mpz_sgn(val) < 0)
4231 error_at(this->length_->location(), "negative array bound");
4236 Type* int_type = Type::lookup_integer_type("int");
4237 int tbits = int_type->integer_type()->bits();
4238 int vbits = mpz_sizeinbase(val, 2);
4239 if (vbits + 1 > tbits)
4241 error_at(this->length_->location(), "array bound overflows");
4254 Array_type::do_verify()
4256 if (!this->verify_length())
4258 this->length_ = Expression::make_error(this->length_->location());
4264 // Array type hash code.
4267 Array_type::do_hash_for_method(Gogo* gogo) const
4269 // There is no very convenient way to get a hash code for the
4271 return this->element_type_->hash_for_method(gogo) + 1;
4274 // Get a tree for the length of a fixed array. The length may be
4275 // computed using a function call, so we must only evaluate it once.
4278 Array_type::get_length_tree(Gogo* gogo)
4280 go_assert(this->length_ != NULL);
4281 if (this->length_tree_ == NULL_TREE)
4286 if (this->length_->integer_constant_value(true, val, &t))
4289 t = Type::lookup_integer_type("int");
4290 else if (t->is_abstract())
4291 t = t->make_non_abstract_type();
4292 tree tt = type_to_tree(t->get_backend(gogo));
4293 this->length_tree_ = Expression::integer_constant_tree(val, tt);
4300 // Make up a translation context for the array length
4301 // expression. FIXME: This won't work in general.
4302 Translate_context context(gogo, NULL, NULL, NULL);
4303 tree len = this->length_->get_tree(&context);
4304 if (len != error_mark_node)
4306 len = convert_to_integer(integer_type_node, len);
4307 len = save_expr(len);
4309 this->length_tree_ = len;
4312 return this->length_tree_;
4315 // Get the backend representation of the fields of a slice. This is
4316 // not declared in types.h so that types.h doesn't have to #include
4319 // We use int for the count and capacity fields. This matches 6g.
4320 // The language more or less assumes that we can't allocate space of a
4321 // size which does not fit in int.
4324 get_backend_slice_fields(Gogo* gogo, Array_type* type,
4325 std::vector<Backend::Btyped_identifier>* bfields)
4329 Type* pet = Type::make_pointer_type(type->element_type());
4330 Btype* pbet = pet->get_backend(gogo);
4332 Backend::Btyped_identifier* p = &(*bfields)[0];
4333 p->name = "__values";
4335 p->location = UNKNOWN_LOCATION;
4337 Type* int_type = Type::lookup_integer_type("int");
4340 p->name = "__count";
4341 p->btype = int_type->get_backend(gogo);
4342 p->location = UNKNOWN_LOCATION;
4345 p->name = "__capacity";
4346 p->btype = int_type->get_backend(gogo);
4347 p->location = UNKNOWN_LOCATION;
4350 // Get a tree for the type of this array. A fixed array is simply
4351 // represented as ARRAY_TYPE with the appropriate index--i.e., it is
4352 // just like an array in C. An open array is a struct with three
4353 // fields: a data pointer, the length, and the capacity.
4356 Array_type::do_get_backend(Gogo* gogo)
4358 if (this->length_ == NULL)
4360 std::vector<Backend::Btyped_identifier> bfields;
4361 get_backend_slice_fields(gogo, this, &bfields);
4362 return gogo->backend()->struct_type(bfields);
4366 Btype* element = this->get_backend_element(gogo);
4367 Bexpression* len = this->get_backend_length(gogo);
4368 return gogo->backend()->array_type(element, len);
4372 // Return the backend representation of the element type.
4374 Array_type::get_backend_element(Gogo* gogo)
4376 return this->element_type_->get_backend(gogo);
4379 // Return the backend representation of the length.
4382 Array_type::get_backend_length(Gogo* gogo)
4384 return tree_to_expr(this->get_length_tree(gogo));
4387 // Return a tree for a pointer to the values in ARRAY.
4390 Array_type::value_pointer_tree(Gogo*, tree array) const
4393 if (this->length() != NULL)
4396 ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))),
4397 build_fold_addr_expr(array));
4402 tree field = TYPE_FIELDS(TREE_TYPE(array));
4403 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
4405 ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field,
4408 if (TREE_CONSTANT(array))
4409 TREE_CONSTANT(ret) = 1;
4413 // Return a tree for the length of the array ARRAY which has this
4417 Array_type::length_tree(Gogo* gogo, tree array)
4419 if (this->length_ != NULL)
4421 if (TREE_CODE(array) == SAVE_EXPR)
4422 return fold_convert(integer_type_node, this->get_length_tree(gogo));
4424 return omit_one_operand(integer_type_node,
4425 this->get_length_tree(gogo), array);
4428 // This is an open array. We need to read the length field.
4430 tree type = TREE_TYPE(array);
4431 go_assert(TREE_CODE(type) == RECORD_TYPE);
4433 tree field = DECL_CHAIN(TYPE_FIELDS(type));
4434 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
4436 tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
4437 if (TREE_CONSTANT(array))
4438 TREE_CONSTANT(ret) = 1;
4442 // Return a tree for the capacity of the array ARRAY which has this
4446 Array_type::capacity_tree(Gogo* gogo, tree array)
4448 if (this->length_ != NULL)
4449 return omit_one_operand(sizetype, this->get_length_tree(gogo), array);
4451 // This is an open array. We need to read the capacity field.
4453 tree type = TREE_TYPE(array);
4454 go_assert(TREE_CODE(type) == RECORD_TYPE);
4456 tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type)));
4457 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
4459 return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
4465 Array_type::do_export(Export* exp) const
4467 exp->write_c_string("[");
4468 if (this->length_ != NULL)
4469 this->length_->export_expression(exp);
4470 exp->write_c_string("] ");
4471 exp->write_type(this->element_type_);
4477 Array_type::do_import(Import* imp)
4479 imp->require_c_string("[");
4481 if (imp->peek_char() == ']')
4484 length = Expression::import_expression(imp);
4485 imp->require_c_string("] ");
4486 Type* element_type = imp->read_type();
4487 return Type::make_array_type(element_type, length);
4490 // The type of an array type descriptor.
4493 Array_type::make_array_type_descriptor_type()
4498 Type* tdt = Type::make_type_descriptor_type();
4499 Type* ptdt = Type::make_type_descriptor_ptr_type();
4501 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4504 Type::make_builtin_struct_type(4,
4508 "len", uintptr_type);
4510 ret = Type::make_builtin_named_type("ArrayType", sf);
4516 // The type of an slice type descriptor.
4519 Array_type::make_slice_type_descriptor_type()
4524 Type* tdt = Type::make_type_descriptor_type();
4525 Type* ptdt = Type::make_type_descriptor_ptr_type();
4528 Type::make_builtin_struct_type(2,
4532 ret = Type::make_builtin_named_type("SliceType", sf);
4538 // Build a type descriptor for an array/slice type.
4541 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4543 if (this->length_ != NULL)
4544 return this->array_type_descriptor(gogo, name);
4546 return this->slice_type_descriptor(gogo, name);
4549 // Build a type descriptor for an array type.
4552 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
4554 source_location bloc = BUILTINS_LOCATION;
4556 Type* atdt = Array_type::make_array_type_descriptor_type();
4558 const Struct_field_list* fields = atdt->struct_type()->fields();
4560 Expression_list* vals = new Expression_list();
4563 Struct_field_list::const_iterator p = fields->begin();
4564 go_assert(p->field_name() == "commonType");
4565 vals->push_back(this->type_descriptor_constructor(gogo,
4566 RUNTIME_TYPE_KIND_ARRAY,
4570 go_assert(p->field_name() == "elem");
4571 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
4574 go_assert(p->field_name() == "slice");
4575 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
4576 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
4579 go_assert(p->field_name() == "len");
4580 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
4583 go_assert(p == fields->end());
4585 return Expression::make_struct_composite_literal(atdt, vals, bloc);
4588 // Build a type descriptor for a slice type.
4591 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
4593 source_location bloc = BUILTINS_LOCATION;
4595 Type* stdt = Array_type::make_slice_type_descriptor_type();
4597 const Struct_field_list* fields = stdt->struct_type()->fields();
4599 Expression_list* vals = new Expression_list();
4602 Struct_field_list::const_iterator p = fields->begin();
4603 go_assert(p->field_name() == "commonType");
4604 vals->push_back(this->type_descriptor_constructor(gogo,
4605 RUNTIME_TYPE_KIND_SLICE,
4609 go_assert(p->field_name() == "elem");
4610 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
4613 go_assert(p == fields->end());
4615 return Expression::make_struct_composite_literal(stdt, vals, bloc);
4618 // Reflection string.
4621 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
4623 ret->push_back('[');
4624 if (this->length_ != NULL)
4629 if (!this->length_->integer_constant_value(true, val, &type))
4630 error_at(this->length_->location(),
4631 "array length must be integer constant expression");
4632 else if (mpz_cmp_si(val, 0) < 0)
4633 error_at(this->length_->location(), "array length is negative");
4634 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
4635 error_at(this->length_->location(), "array length is too large");
4639 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
4644 ret->push_back(']');
4646 this->append_reflection(this->element_type_, gogo, ret);
4652 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4654 ret->push_back('A');
4655 this->append_mangled_name(this->element_type_, gogo, ret);
4656 if (this->length_ != NULL)
4661 if (!this->length_->integer_constant_value(true, val, &type))
4662 error_at(this->length_->location(),
4663 "array length must be integer constant expression");
4664 else if (mpz_cmp_si(val, 0) < 0)
4665 error_at(this->length_->location(), "array length is negative");
4666 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
4667 error_at(this->length_->location(), "array size is too large");
4671 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
4676 ret->push_back('e');
4679 // Make an array type.
4682 Type::make_array_type(Type* element_type, Expression* length)
4684 return new Array_type(element_type, length);
4692 Map_type::do_traverse(Traverse* traverse)
4694 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
4695 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
4696 return TRAVERSE_EXIT;
4697 return TRAVERSE_CONTINUE;
4700 // Check that the map type is OK.
4703 Map_type::do_verify()
4705 if (this->key_type_->struct_type() != NULL
4706 || this->key_type_->array_type() != NULL)
4708 error_at(this->location_, "invalid map key type");
4714 // Whether two map types are identical.
4717 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
4719 return (Type::are_identical(this->key_type(), t->key_type(),
4720 errors_are_identical, NULL)
4721 && Type::are_identical(this->val_type(), t->val_type(),
4722 errors_are_identical, NULL));
4728 Map_type::do_hash_for_method(Gogo* gogo) const
4730 return (this->key_type_->hash_for_method(gogo)
4731 + this->val_type_->hash_for_method(gogo)
4735 // Get the backend representation for a map type. A map type is
4736 // represented as a pointer to a struct. The struct is __go_map in
4740 Map_type::do_get_backend(Gogo* gogo)
4742 static Btype* backend_map_type;
4743 if (backend_map_type == NULL)
4745 std::vector<Backend::Btyped_identifier> bfields(4);
4747 Type* pdt = Type::make_type_descriptor_ptr_type();
4748 bfields[0].name = "__descriptor";
4749 bfields[0].btype = pdt->get_backend(gogo);
4750 bfields[0].location = BUILTINS_LOCATION;
4752 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4753 bfields[1].name = "__element_count";
4754 bfields[1].btype = uintptr_type->get_backend(gogo);
4755 bfields[1].location = BUILTINS_LOCATION;
4757 bfields[2].name = "__bucket_count";
4758 bfields[2].btype = bfields[1].btype;
4759 bfields[2].location = BUILTINS_LOCATION;
4761 Btype* bvt = gogo->backend()->void_type();
4762 Btype* bpvt = gogo->backend()->pointer_type(bvt);
4763 Btype* bppvt = gogo->backend()->pointer_type(bpvt);
4764 bfields[3].name = "__buckets";
4765 bfields[3].btype = bppvt;
4766 bfields[3].location = BUILTINS_LOCATION;
4768 Btype *bt = gogo->backend()->struct_type(bfields);
4769 bt = gogo->backend()->named_type("__go_map", bt, BUILTINS_LOCATION);
4770 backend_map_type = gogo->backend()->pointer_type(bt);
4772 return backend_map_type;
4775 // The type of a map type descriptor.
4778 Map_type::make_map_type_descriptor_type()
4783 Type* tdt = Type::make_type_descriptor_type();
4784 Type* ptdt = Type::make_type_descriptor_ptr_type();
4787 Type::make_builtin_struct_type(3,
4792 ret = Type::make_builtin_named_type("MapType", sf);
4798 // Build a type descriptor for a map type.
4801 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4803 source_location bloc = BUILTINS_LOCATION;
4805 Type* mtdt = Map_type::make_map_type_descriptor_type();
4807 const Struct_field_list* fields = mtdt->struct_type()->fields();
4809 Expression_list* vals = new Expression_list();
4812 Struct_field_list::const_iterator p = fields->begin();
4813 go_assert(p->field_name() == "commonType");
4814 vals->push_back(this->type_descriptor_constructor(gogo,
4815 RUNTIME_TYPE_KIND_MAP,
4819 go_assert(p->field_name() == "key");
4820 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
4823 go_assert(p->field_name() == "elem");
4824 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
4827 go_assert(p == fields->end());
4829 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
4832 // A mapping from map types to map descriptors.
4834 Map_type::Map_descriptors Map_type::map_descriptors;
4836 // Build a map descriptor for this type. Return a pointer to it.
4839 Map_type::map_descriptor_pointer(Gogo* gogo, source_location location)
4841 Bvariable* bvar = this->map_descriptor(gogo);
4842 tree var_tree = var_to_tree(bvar);
4843 if (var_tree == error_mark_node)
4844 return error_mark_node;
4845 return build_fold_addr_expr_loc(location, var_tree);
4848 // Build a map descriptor for this type.
4851 Map_type::map_descriptor(Gogo* gogo)
4853 std::pair<Map_type*, Bvariable*> val(this, NULL);
4854 std::pair<Map_type::Map_descriptors::iterator, bool> ins =
4855 Map_type::map_descriptors.insert(val);
4857 return ins.first->second;
4859 Type* key_type = this->key_type_;
4860 Type* val_type = this->val_type_;
4862 // The map entry type is a struct with three fields. Build that
4863 // struct so that we can get the offsets of the key and value within
4864 // a map entry. The first field should technically be a pointer to
4865 // this type itself, but since we only care about field offsets we
4866 // just use pointer to bool.
4867 Type* pbool = Type::make_pointer_type(Type::make_boolean_type());
4868 Struct_type* map_entry_type =
4869 Type::make_builtin_struct_type(3,
4874 Type* map_descriptor_type = Map_type::make_map_descriptor_type();
4876 const Struct_field_list* fields =
4877 map_descriptor_type->struct_type()->fields();
4879 Expression_list* vals = new Expression_list();
4882 source_location bloc = BUILTINS_LOCATION;
4884 Struct_field_list::const_iterator p = fields->begin();
4886 go_assert(p->field_name() == "__map_descriptor");
4887 vals->push_back(Expression::make_type_descriptor(this, bloc));
4890 go_assert(p->field_name() == "__entry_size");
4891 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
4892 vals->push_back(Expression::make_type_info(map_entry_type, type_info));
4894 Struct_field_list::const_iterator pf = map_entry_type->fields()->begin();
4896 go_assert(pf->field_name() == "__key");
4899 go_assert(p->field_name() == "__key_offset");
4900 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
4903 go_assert(pf->field_name() == "__val");
4906 go_assert(p->field_name() == "__val_offset");
4907 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
4910 go_assert(p == fields->end());
4912 Expression* initializer =
4913 Expression::make_struct_composite_literal(map_descriptor_type, vals, bloc);
4915 std::string mangled_name = "__go_map_" + this->mangled_name(gogo);
4916 Btype* map_descriptor_btype = map_descriptor_type->get_backend(gogo);
4917 Bvariable* bvar = gogo->backend()->immutable_struct(mangled_name, true,
4918 map_descriptor_btype,
4921 Translate_context context(gogo, NULL, NULL, NULL);
4922 context.set_is_const();
4923 Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
4925 gogo->backend()->immutable_struct_set_init(bvar, mangled_name, true,
4926 map_descriptor_btype, bloc,
4929 ins.first->second = bvar;
4933 // Build the type of a map descriptor. This must match the struct
4934 // __go_map_descriptor in libgo/runtime/map.h.
4937 Map_type::make_map_descriptor_type()
4942 Type* ptdt = Type::make_type_descriptor_ptr_type();
4943 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4945 Type::make_builtin_struct_type(4,
4946 "__map_descriptor", ptdt,
4947 "__entry_size", uintptr_type,
4948 "__key_offset", uintptr_type,
4949 "__val_offset", uintptr_type);
4950 ret = Type::make_builtin_named_type("__go_map_descriptor", sf);
4955 // Reflection string for a map.
4958 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
4960 ret->append("map[");
4961 this->append_reflection(this->key_type_, gogo, ret);
4963 this->append_reflection(this->val_type_, gogo, ret);
4966 // Mangled name for a map.
4969 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4971 ret->push_back('M');
4972 this->append_mangled_name(this->key_type_, gogo, ret);
4974 this->append_mangled_name(this->val_type_, gogo, ret);
4977 // Export a map type.
4980 Map_type::do_export(Export* exp) const
4982 exp->write_c_string("map [");
4983 exp->write_type(this->key_type_);
4984 exp->write_c_string("] ");
4985 exp->write_type(this->val_type_);
4988 // Import a map type.
4991 Map_type::do_import(Import* imp)
4993 imp->require_c_string("map [");
4994 Type* key_type = imp->read_type();
4995 imp->require_c_string("] ");
4996 Type* val_type = imp->read_type();
4997 return Type::make_map_type(key_type, val_type, imp->location());
5003 Type::make_map_type(Type* key_type, Type* val_type, source_location location)
5005 return new Map_type(key_type, val_type, location);
5008 // Class Channel_type.
5013 Channel_type::do_hash_for_method(Gogo* gogo) const
5015 unsigned int ret = 0;
5016 if (this->may_send_)
5018 if (this->may_receive_)
5020 if (this->element_type_ != NULL)
5021 ret += this->element_type_->hash_for_method(gogo) << 2;
5025 // Whether this type is the same as T.
5028 Channel_type::is_identical(const Channel_type* t,
5029 bool errors_are_identical) const
5031 if (!Type::are_identical(this->element_type(), t->element_type(),
5032 errors_are_identical, NULL))
5034 return (this->may_send_ == t->may_send_
5035 && this->may_receive_ == t->may_receive_);
5038 // Return the tree for a channel type. A channel is a pointer to a
5039 // __go_channel struct. The __go_channel struct is defined in
5040 // libgo/runtime/channel.h.
5043 Channel_type::do_get_backend(Gogo* gogo)
5045 static Btype* backend_channel_type;
5046 if (backend_channel_type == NULL)
5048 std::vector<Backend::Btyped_identifier> bfields;
5049 Btype* bt = gogo->backend()->struct_type(bfields);
5050 bt = gogo->backend()->named_type("__go_channel", bt, BUILTINS_LOCATION);
5051 backend_channel_type = gogo->backend()->pointer_type(bt);
5053 return backend_channel_type;
5056 // Build a type descriptor for a channel type.
5059 Channel_type::make_chan_type_descriptor_type()
5064 Type* tdt = Type::make_type_descriptor_type();
5065 Type* ptdt = Type::make_type_descriptor_ptr_type();
5067 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5070 Type::make_builtin_struct_type(3,
5073 "dir", uintptr_type);
5075 ret = Type::make_builtin_named_type("ChanType", sf);
5081 // Build a type descriptor for a map type.
5084 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5086 source_location bloc = BUILTINS_LOCATION;
5088 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
5090 const Struct_field_list* fields = ctdt->struct_type()->fields();
5092 Expression_list* vals = new Expression_list();
5095 Struct_field_list::const_iterator p = fields->begin();
5096 go_assert(p->field_name() == "commonType");
5097 vals->push_back(this->type_descriptor_constructor(gogo,
5098 RUNTIME_TYPE_KIND_CHAN,
5102 go_assert(p->field_name() == "elem");
5103 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5106 go_assert(p->field_name() == "dir");
5107 // These bits must match the ones in libgo/runtime/go-type.h.
5109 if (this->may_receive_)
5111 if (this->may_send_)
5114 mpz_init_set_ui(iv, val);
5115 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
5119 go_assert(p == fields->end());
5121 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
5124 // Reflection string.
5127 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
5129 if (!this->may_send_)
5131 ret->append("chan");
5132 if (!this->may_receive_)
5134 ret->push_back(' ');
5135 this->append_reflection(this->element_type_, gogo, ret);
5141 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5143 ret->push_back('C');
5144 this->append_mangled_name(this->element_type_, gogo, ret);
5145 if (this->may_send_)
5146 ret->push_back('s');
5147 if (this->may_receive_)
5148 ret->push_back('r');
5149 ret->push_back('e');
5155 Channel_type::do_export(Export* exp) const
5157 exp->write_c_string("chan ");
5158 if (this->may_send_ && !this->may_receive_)
5159 exp->write_c_string("-< ");
5160 else if (this->may_receive_ && !this->may_send_)
5161 exp->write_c_string("<- ");
5162 exp->write_type(this->element_type_);
5168 Channel_type::do_import(Import* imp)
5170 imp->require_c_string("chan ");
5174 if (imp->match_c_string("-< "))
5178 may_receive = false;
5180 else if (imp->match_c_string("<- "))
5192 Type* element_type = imp->read_type();
5194 return Type::make_channel_type(may_send, may_receive, element_type);
5197 // Make a new channel type.
5200 Type::make_channel_type(bool send, bool receive, Type* element_type)
5202 return new Channel_type(send, receive, element_type);
5205 // Class Interface_type.
5210 Interface_type::do_traverse(Traverse* traverse)
5212 if (this->methods_ == NULL)
5213 return TRAVERSE_CONTINUE;
5214 return this->methods_->traverse(traverse);
5217 // Finalize the methods. This handles interface inheritance.
5220 Interface_type::finalize_methods()
5222 if (this->methods_ == NULL)
5224 std::vector<Named_type*> seen;
5225 bool is_recursive = false;
5228 while (from < this->methods_->size())
5230 const Typed_identifier* p = &this->methods_->at(from);
5231 if (!p->name().empty())
5234 for (i = 0; i < to; ++i)
5236 if (this->methods_->at(i).name() == p->name())
5238 error_at(p->location(), "duplicate method %qs",
5239 Gogo::message_name(p->name()).c_str());
5246 this->methods_->set(to, *p);
5253 Interface_type* it = p->type()->interface_type();
5256 error_at(p->location(), "interface contains embedded non-interface");
5264 error_at(p->location(), "invalid recursive interface");
5265 is_recursive = true;
5271 Named_type* nt = p->type()->named_type();
5274 std::vector<Named_type*>::const_iterator q;
5275 for (q = seen.begin(); q != seen.end(); ++q)
5279 error_at(p->location(), "inherited interface loop");
5283 if (q != seen.end())
5291 const Typed_identifier_list* methods = it->methods();
5292 if (methods == NULL)
5297 for (Typed_identifier_list::const_iterator q = methods->begin();
5298 q != methods->end();
5301 if (q->name().empty())
5303 if (q->type()->forwarded() == p->type()->forwarded())
5304 error_at(p->location(), "interface inheritance loop");
5308 for (i = from + 1; i < this->methods_->size(); ++i)
5310 const Typed_identifier* r = &this->methods_->at(i);
5311 if (r->name().empty()
5312 && r->type()->forwarded() == q->type()->forwarded())
5314 error_at(p->location(),
5315 "inherited interface listed twice");
5319 if (i == this->methods_->size())
5320 this->methods_->push_back(Typed_identifier(q->name(),
5325 else if (this->find_method(q->name()) == NULL)
5326 this->methods_->push_back(Typed_identifier(q->name(), q->type(),
5331 error_at(p->location(), "inherited method %qs is ambiguous",
5332 Gogo::message_name(q->name()).c_str());
5339 delete this->methods_;
5340 this->methods_ = NULL;
5344 this->methods_->resize(to);
5345 this->methods_->sort_by_name();
5349 // Return the method NAME, or NULL.
5351 const Typed_identifier*
5352 Interface_type::find_method(const std::string& name) const
5354 if (this->methods_ == NULL)
5356 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5357 p != this->methods_->end();
5359 if (p->name() == name)
5364 // Return the method index.
5367 Interface_type::method_index(const std::string& name) const
5369 go_assert(this->methods_ != NULL);
5371 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5372 p != this->methods_->end();
5374 if (p->name() == name)
5379 // Return whether NAME is an unexported method, for better error
5383 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
5385 if (this->methods_ == NULL)
5387 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5388 p != this->methods_->end();
5391 const std::string& method_name(p->name());
5392 if (Gogo::is_hidden_name(method_name)
5393 && name == Gogo::unpack_hidden_name(method_name)
5394 && gogo->pack_hidden_name(name, false) != method_name)
5400 // Whether this type is identical with T.
5403 Interface_type::is_identical(const Interface_type* t,
5404 bool errors_are_identical) const
5406 // We require the same methods with the same types. The methods
5407 // have already been sorted.
5408 if (this->methods() == NULL || t->methods() == NULL)
5409 return this->methods() == t->methods();
5411 Typed_identifier_list::const_iterator p1 = this->methods()->begin();
5412 for (Typed_identifier_list::const_iterator p2 = t->methods()->begin();
5413 p2 != t->methods()->end();
5416 if (p1 == this->methods()->end())
5418 if (p1->name() != p2->name()
5419 || !Type::are_identical(p1->type(), p2->type(),
5420 errors_are_identical, NULL))
5423 if (p1 != this->methods()->end())
5428 // Whether we can assign the interface type T to this type. The types
5429 // are known to not be identical. An interface assignment is only
5430 // permitted if T is known to implement all methods in THIS.
5431 // Otherwise a type guard is required.
5434 Interface_type::is_compatible_for_assign(const Interface_type* t,
5435 std::string* reason) const
5437 if (this->methods() == NULL)
5439 for (Typed_identifier_list::const_iterator p = this->methods()->begin();
5440 p != this->methods()->end();
5443 const Typed_identifier* m = t->find_method(p->name());
5449 snprintf(buf, sizeof buf,
5450 _("need explicit conversion; missing method %s%s%s"),
5451 open_quote, Gogo::message_name(p->name()).c_str(),
5453 reason->assign(buf);
5458 std::string subreason;
5459 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
5463 std::string n = Gogo::message_name(p->name());
5464 size_t len = 100 + n.length() + subreason.length();
5465 char* buf = new char[len];
5466 if (subreason.empty())
5467 snprintf(buf, len, _("incompatible type for method %s%s%s"),
5468 open_quote, n.c_str(), close_quote);
5471 _("incompatible type for method %s%s%s (%s)"),
5472 open_quote, n.c_str(), close_quote,
5474 reason->assign(buf);
5487 Interface_type::do_hash_for_method(Gogo* gogo) const
5489 unsigned int ret = 0;
5490 if (this->methods_ != NULL)
5492 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5493 p != this->methods_->end();
5496 ret = Type::hash_string(p->name(), ret);
5497 ret += p->type()->hash_for_method(gogo);
5504 // Return true if T implements the interface. If it does not, and
5505 // REASON is not NULL, set *REASON to a useful error message.
5508 Interface_type::implements_interface(const Type* t, std::string* reason) const
5510 if (this->methods_ == NULL)
5513 bool is_pointer = false;
5514 const Named_type* nt = t->named_type();
5515 const Struct_type* st = t->struct_type();
5516 // If we start with a named type, we don't dereference it to find
5520 const Type* pt = t->points_to();
5523 // If T is a pointer to a named type, then we need to look at
5524 // the type to which it points.
5526 nt = pt->named_type();
5527 st = pt->struct_type();
5531 // If we have a named type, get the methods from it rather than from
5536 // Only named and struct types have methods.
5537 if (nt == NULL && st == NULL)
5541 if (t->points_to() != NULL
5542 && t->points_to()->interface_type() != NULL)
5543 reason->assign(_("pointer to interface type has no methods"));
5545 reason->assign(_("type has no methods"));
5550 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
5554 if (t->points_to() != NULL
5555 && t->points_to()->interface_type() != NULL)
5556 reason->assign(_("pointer to interface type has no methods"));
5558 reason->assign(_("type has no methods"));
5563 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5564 p != this->methods_->end();
5567 bool is_ambiguous = false;
5568 Method* m = (nt != NULL
5569 ? nt->method_function(p->name(), &is_ambiguous)
5570 : st->method_function(p->name(), &is_ambiguous));
5575 std::string n = Gogo::message_name(p->name());
5576 size_t len = n.length() + 100;
5577 char* buf = new char[len];
5579 snprintf(buf, len, _("ambiguous method %s%s%s"),
5580 open_quote, n.c_str(), close_quote);
5582 snprintf(buf, len, _("missing method %s%s%s"),
5583 open_quote, n.c_str(), close_quote);
5584 reason->assign(buf);
5590 Function_type *p_fn_type = p->type()->function_type();
5591 Function_type* m_fn_type = m->type()->function_type();
5592 go_assert(p_fn_type != NULL && m_fn_type != NULL);
5593 std::string subreason;
5594 if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
5598 std::string n = Gogo::message_name(p->name());
5599 size_t len = 100 + n.length() + subreason.length();
5600 char* buf = new char[len];
5601 if (subreason.empty())
5602 snprintf(buf, len, _("incompatible type for method %s%s%s"),
5603 open_quote, n.c_str(), close_quote);
5606 _("incompatible type for method %s%s%s (%s)"),
5607 open_quote, n.c_str(), close_quote,
5609 reason->assign(buf);
5615 if (!is_pointer && !m->is_value_method())
5619 std::string n = Gogo::message_name(p->name());
5620 size_t len = 100 + n.length();
5621 char* buf = new char[len];
5622 snprintf(buf, len, _("method %s%s%s requires a pointer"),
5623 open_quote, n.c_str(), close_quote);
5624 reason->assign(buf);
5634 // Return the backend representation of the empty interface type. We
5635 // use the same struct for all empty interfaces.
5638 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
5640 static Btype* empty_interface_type;
5641 if (empty_interface_type == NULL)
5643 std::vector<Backend::Btyped_identifier> bfields(2);
5645 Type* pdt = Type::make_type_descriptor_ptr_type();
5646 bfields[0].name = "__type_descriptor";
5647 bfields[0].btype = pdt->get_backend(gogo);
5648 bfields[0].location = UNKNOWN_LOCATION;
5650 Type* vt = Type::make_pointer_type(Type::make_void_type());
5651 bfields[1].name = "__object";
5652 bfields[1].btype = vt->get_backend(gogo);
5653 bfields[1].location = UNKNOWN_LOCATION;
5655 empty_interface_type = gogo->backend()->struct_type(bfields);
5657 return empty_interface_type;
5660 // Return the fields of a non-empty interface type. This is not
5661 // declared in types.h so that types.h doesn't have to #include
5665 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
5666 std::vector<Backend::Btyped_identifier>* bfields)
5668 source_location loc = type->location();
5670 std::vector<Backend::Btyped_identifier> mfields(type->methods()->size() + 1);
5672 Type* pdt = Type::make_type_descriptor_ptr_type();
5673 mfields[0].name = "__type_descriptor";
5674 mfields[0].btype = pdt->get_backend(gogo);
5675 mfields[0].location = loc;
5677 std::string last_name = "";
5679 for (Typed_identifier_list::const_iterator p = type->methods()->begin();
5680 p != type->methods()->end();
5683 mfields[i].name = Gogo::unpack_hidden_name(p->name());
5684 mfields[i].btype = p->type()->get_backend(gogo);
5685 mfields[i].location = loc;
5686 // Sanity check: the names should be sorted.
5687 go_assert(p->name() > last_name);
5688 last_name = p->name();
5691 Btype* methods = gogo->backend()->struct_type(mfields);
5695 (*bfields)[0].name = "__methods";
5696 (*bfields)[0].btype = gogo->backend()->pointer_type(methods);
5697 (*bfields)[0].location = loc;
5699 Type* vt = Type::make_pointer_type(Type::make_void_type());
5700 (*bfields)[1].name = "__object";
5701 (*bfields)[1].btype = vt->get_backend(gogo);
5702 (*bfields)[1].location = UNKNOWN_LOCATION;
5705 // Return a tree for an interface type. An interface is a pointer to
5706 // a struct. The struct has three fields. The first field is a
5707 // pointer to the type descriptor for the dynamic type of the object.
5708 // The second field is a pointer to a table of methods for the
5709 // interface to be used with the object. The third field is the value
5710 // of the object itself.
5713 Interface_type::do_get_backend(Gogo* gogo)
5715 if (this->methods_ == NULL)
5716 return Interface_type::get_backend_empty_interface_type(gogo);
5719 std::vector<Backend::Btyped_identifier> bfields;
5720 get_backend_interface_fields(gogo, this, &bfields);
5721 return gogo->backend()->struct_type(bfields);
5725 // The type of an interface type descriptor.
5728 Interface_type::make_interface_type_descriptor_type()
5733 Type* tdt = Type::make_type_descriptor_type();
5734 Type* ptdt = Type::make_type_descriptor_ptr_type();
5736 Type* string_type = Type::lookup_string_type();
5737 Type* pointer_string_type = Type::make_pointer_type(string_type);
5740 Type::make_builtin_struct_type(3,
5741 "name", pointer_string_type,
5742 "pkgPath", pointer_string_type,
5745 Type* nsm = Type::make_builtin_named_type("imethod", sm);
5747 Type* slice_nsm = Type::make_array_type(nsm, NULL);
5749 Struct_type* s = Type::make_builtin_struct_type(2,
5751 "methods", slice_nsm);
5753 ret = Type::make_builtin_named_type("InterfaceType", s);
5759 // Build a type descriptor for an interface type.
5762 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5764 source_location bloc = BUILTINS_LOCATION;
5766 Type* itdt = Interface_type::make_interface_type_descriptor_type();
5768 const Struct_field_list* ifields = itdt->struct_type()->fields();
5770 Expression_list* ivals = new Expression_list();
5773 Struct_field_list::const_iterator pif = ifields->begin();
5774 go_assert(pif->field_name() == "commonType");
5775 ivals->push_back(this->type_descriptor_constructor(gogo,
5776 RUNTIME_TYPE_KIND_INTERFACE,
5780 go_assert(pif->field_name() == "methods");
5782 Expression_list* methods = new Expression_list();
5783 if (this->methods_ != NULL && !this->methods_->empty())
5785 Type* elemtype = pif->type()->array_type()->element_type();
5787 methods->reserve(this->methods_->size());
5788 for (Typed_identifier_list::const_iterator pm = this->methods_->begin();
5789 pm != this->methods_->end();
5792 const Struct_field_list* mfields = elemtype->struct_type()->fields();
5794 Expression_list* mvals = new Expression_list();
5797 Struct_field_list::const_iterator pmf = mfields->begin();
5798 go_assert(pmf->field_name() == "name");
5799 std::string s = Gogo::unpack_hidden_name(pm->name());
5800 Expression* e = Expression::make_string(s, bloc);
5801 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
5804 go_assert(pmf->field_name() == "pkgPath");
5805 if (!Gogo::is_hidden_name(pm->name()))
5806 mvals->push_back(Expression::make_nil(bloc));
5809 s = Gogo::hidden_name_prefix(pm->name());
5810 e = Expression::make_string(s, bloc);
5811 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
5815 go_assert(pmf->field_name() == "typ");
5816 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
5819 go_assert(pmf == mfields->end());
5821 e = Expression::make_struct_composite_literal(elemtype, mvals,
5823 methods->push_back(e);
5827 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
5831 go_assert(pif == ifields->end());
5833 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
5836 // Reflection string.
5839 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
5841 ret->append("interface {");
5842 if (this->methods_ != NULL)
5844 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5845 p != this->methods_->end();
5848 if (p != this->methods_->begin())
5850 ret->push_back(' ');
5851 if (!Gogo::is_hidden_name(p->name()))
5852 ret->append(p->name());
5855 // This matches what the gc compiler does.
5856 std::string prefix = Gogo::hidden_name_prefix(p->name());
5857 ret->append(prefix.substr(prefix.find('.') + 1));
5858 ret->push_back('.');
5859 ret->append(Gogo::unpack_hidden_name(p->name()));
5861 std::string sub = p->type()->reflection(gogo);
5862 go_assert(sub.compare(0, 4, "func") == 0);
5863 sub = sub.substr(4);
5873 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5875 ret->push_back('I');
5877 const Typed_identifier_list* methods = this->methods_;
5878 if (methods != NULL)
5880 for (Typed_identifier_list::const_iterator p = methods->begin();
5881 p != methods->end();
5884 std::string n = Gogo::unpack_hidden_name(p->name());
5886 snprintf(buf, sizeof buf, "%u_",
5887 static_cast<unsigned int>(n.length()));
5890 this->append_mangled_name(p->type(), gogo, ret);
5894 ret->push_back('e');
5900 Interface_type::do_export(Export* exp) const
5902 exp->write_c_string("interface { ");
5904 const Typed_identifier_list* methods = this->methods_;
5905 if (methods != NULL)
5907 for (Typed_identifier_list::const_iterator pm = methods->begin();
5908 pm != methods->end();
5911 exp->write_string(pm->name());
5912 exp->write_c_string(" (");
5914 const Function_type* fntype = pm->type()->function_type();
5917 const Typed_identifier_list* parameters = fntype->parameters();
5918 if (parameters != NULL)
5920 bool is_varargs = fntype->is_varargs();
5921 for (Typed_identifier_list::const_iterator pp =
5922 parameters->begin();
5923 pp != parameters->end();
5929 exp->write_c_string(", ");
5930 if (!is_varargs || pp + 1 != parameters->end())
5931 exp->write_type(pp->type());
5934 exp->write_c_string("...");
5935 Type *pptype = pp->type();
5936 exp->write_type(pptype->array_type()->element_type());
5941 exp->write_c_string(")");
5943 const Typed_identifier_list* results = fntype->results();
5944 if (results != NULL)
5946 exp->write_c_string(" ");
5947 if (results->size() == 1)
5948 exp->write_type(results->begin()->type());
5952 exp->write_c_string("(");
5953 for (Typed_identifier_list::const_iterator p =
5955 p != results->end();
5961 exp->write_c_string(", ");
5962 exp->write_type(p->type());
5964 exp->write_c_string(")");
5968 exp->write_c_string("; ");
5972 exp->write_c_string("}");
5975 // Import an interface type.
5978 Interface_type::do_import(Import* imp)
5980 imp->require_c_string("interface { ");
5982 Typed_identifier_list* methods = new Typed_identifier_list;
5983 while (imp->peek_char() != '}')
5985 std::string name = imp->read_identifier();
5986 imp->require_c_string(" (");
5988 Typed_identifier_list* parameters;
5989 bool is_varargs = false;
5990 if (imp->peek_char() == ')')
5994 parameters = new Typed_identifier_list;
5997 if (imp->match_c_string("..."))
6003 Type* ptype = imp->read_type();
6005 ptype = Type::make_array_type(ptype, NULL);
6006 parameters->push_back(Typed_identifier(Import::import_marker,
6007 ptype, imp->location()));
6008 if (imp->peek_char() != ',')
6010 go_assert(!is_varargs);
6011 imp->require_c_string(", ");
6014 imp->require_c_string(")");
6016 Typed_identifier_list* results;
6017 if (imp->peek_char() != ' ')
6021 results = new Typed_identifier_list;
6023 if (imp->peek_char() != '(')
6025 Type* rtype = imp->read_type();
6026 results->push_back(Typed_identifier(Import::import_marker,
6027 rtype, imp->location()));
6034 Type* rtype = imp->read_type();
6035 results->push_back(Typed_identifier(Import::import_marker,
6036 rtype, imp->location()));
6037 if (imp->peek_char() != ',')
6039 imp->require_c_string(", ");
6041 imp->require_c_string(")");
6045 Function_type* fntype = Type::make_function_type(NULL, parameters,
6049 fntype->set_is_varargs();
6050 methods->push_back(Typed_identifier(name, fntype, imp->location()));
6052 imp->require_c_string("; ");
6055 imp->require_c_string("}");
6057 if (methods->empty())
6063 return Type::make_interface_type(methods, imp->location());
6066 // Make an interface type.
6069 Type::make_interface_type(Typed_identifier_list* methods,
6070 source_location location)
6072 return new Interface_type(methods, location);
6077 // Bind a method to an object.
6080 Method::bind_method(Expression* expr, source_location location) const
6082 if (this->stub_ == NULL)
6084 // When there is no stub object, the binding is determined by
6086 return this->do_bind_method(expr, location);
6088 return Expression::make_bound_method(expr, this->stub_, location);
6091 // Return the named object associated with a method. This may only be
6092 // called after methods are finalized.
6095 Method::named_object() const
6097 if (this->stub_ != NULL)
6099 return this->do_named_object();
6102 // Class Named_method.
6104 // The type of the method.
6107 Named_method::do_type() const
6109 if (this->named_object_->is_function())
6110 return this->named_object_->func_value()->type();
6111 else if (this->named_object_->is_function_declaration())
6112 return this->named_object_->func_declaration_value()->type();
6117 // Return the location of the method receiver.
6120 Named_method::do_receiver_location() const
6122 return this->do_type()->receiver()->location();
6125 // Bind a method to an object.
6128 Named_method::do_bind_method(Expression* expr, source_location location) const
6130 Named_object* no = this->named_object_;
6131 Bound_method_expression* bme = Expression::make_bound_method(expr, no,
6133 // If this is not a local method, and it does not use a stub, then
6134 // the real method expects a different type. We need to cast the
6136 if (this->depth() > 0 && !this->needs_stub_method())
6138 Function_type* ftype = this->do_type();
6139 go_assert(ftype->is_method());
6140 Type* frtype = ftype->receiver()->type();
6141 bme->set_first_argument_type(frtype);
6146 // Class Interface_method.
6148 // Bind a method to an object.
6151 Interface_method::do_bind_method(Expression* expr,
6152 source_location location) const
6154 return Expression::make_interface_field_reference(expr, this->name_,
6160 // Insert a new method. Return true if it was inserted, false
6164 Methods::insert(const std::string& name, Method* m)
6166 std::pair<Method_map::iterator, bool> ins =
6167 this->methods_.insert(std::make_pair(name, m));
6172 Method* old_method = ins.first->second;
6173 if (m->depth() < old_method->depth())
6176 ins.first->second = m;
6181 if (m->depth() == old_method->depth())
6182 old_method->set_is_ambiguous();
6188 // Return the number of unambiguous methods.
6191 Methods::count() const
6194 for (Method_map::const_iterator p = this->methods_.begin();
6195 p != this->methods_.end();
6197 if (!p->second->is_ambiguous())
6202 // Class Named_type.
6204 // Return the name of the type.
6207 Named_type::name() const
6209 return this->named_object_->name();
6212 // Return the name of the type to use in an error message.
6215 Named_type::message_name() const
6217 return this->named_object_->message_name();
6220 // Return the base type for this type. We have to be careful about
6221 // circular type definitions, which are invalid but may be seen here.
6224 Named_type::named_base()
6226 if (this->seen_ > 0)
6229 Type* ret = this->type_->base();
6235 Named_type::named_base() const
6237 if (this->seen_ > 0)
6240 const Type* ret = this->type_->base();
6245 // Return whether this is an error type. We have to be careful about
6246 // circular type definitions, which are invalid but may be seen here.
6249 Named_type::is_named_error_type() const
6251 if (this->seen_ > 0)
6254 bool ret = this->type_->is_error_type();
6259 // Add a method to this type.
6262 Named_type::add_method(const std::string& name, Function* function)
6264 if (this->local_methods_ == NULL)
6265 this->local_methods_ = new Bindings(NULL);
6266 return this->local_methods_->add_function(name, NULL, function);
6269 // Add a method declaration to this type.
6272 Named_type::add_method_declaration(const std::string& name, Package* package,
6273 Function_type* type,
6274 source_location location)
6276 if (this->local_methods_ == NULL)
6277 this->local_methods_ = new Bindings(NULL);
6278 return this->local_methods_->add_function_declaration(name, package, type,
6282 // Add an existing method to this type.
6285 Named_type::add_existing_method(Named_object* no)
6287 if (this->local_methods_ == NULL)
6288 this->local_methods_ = new Bindings(NULL);
6289 this->local_methods_->add_named_object(no);
6292 // Look for a local method NAME, and returns its named object, or NULL
6296 Named_type::find_local_method(const std::string& name) const
6298 if (this->local_methods_ == NULL)
6300 return this->local_methods_->lookup(name);
6303 // Return whether NAME is an unexported field or method, for better
6307 Named_type::is_unexported_local_method(Gogo* gogo,
6308 const std::string& name) const
6310 Bindings* methods = this->local_methods_;
6311 if (methods != NULL)
6313 for (Bindings::const_declarations_iterator p =
6314 methods->begin_declarations();
6315 p != methods->end_declarations();
6318 if (Gogo::is_hidden_name(p->first)
6319 && name == Gogo::unpack_hidden_name(p->first)
6320 && gogo->pack_hidden_name(name, false) != p->first)
6327 // Build the complete list of methods for this type, which means
6328 // recursively including all methods for anonymous fields. Create all
6332 Named_type::finalize_methods(Gogo* gogo)
6334 if (this->all_methods_ != NULL)
6337 if (this->local_methods_ != NULL
6338 && (this->points_to() != NULL || this->interface_type() != NULL))
6340 const Bindings* lm = this->local_methods_;
6341 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
6342 p != lm->end_declarations();
6344 error_at(p->second->location(),
6345 "invalid pointer or interface receiver type");
6346 delete this->local_methods_;
6347 this->local_methods_ = NULL;
6351 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6354 // Return the method NAME, or NULL if there isn't one or if it is
6355 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6359 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
6361 return Type::method_function(this->all_methods_, name, is_ambiguous);
6364 // Return a pointer to the interface method table for this type for
6365 // the interface INTERFACE. IS_POINTER is true if this is for a
6369 Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface,
6372 go_assert(!interface->is_empty());
6374 Interface_method_tables** pimt = (is_pointer
6375 ? &this->interface_method_tables_
6376 : &this->pointer_interface_method_tables_);
6379 *pimt = new Interface_method_tables(5);
6381 std::pair<const Interface_type*, tree> val(interface, NULL_TREE);
6382 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
6386 // This is a new entry in the hash table.
6387 go_assert(ins.first->second == NULL_TREE);
6388 ins.first->second = gogo->interface_method_table_for_type(interface,
6393 tree decl = ins.first->second;
6394 if (decl == error_mark_node)
6395 return error_mark_node;
6396 go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL);
6397 return build_fold_addr_expr(decl);
6400 // Return whether a named type has any hidden fields.
6403 Named_type::named_type_has_hidden_fields(std::string* reason) const
6405 if (this->seen_ > 0)
6408 bool ret = this->type_->has_hidden_fields(this, reason);
6413 // Look for a use of a complete type within another type. This is
6414 // used to check that we don't try to use a type within itself.
6416 class Find_type_use : public Traverse
6419 Find_type_use(Named_type* find_type)
6420 : Traverse(traverse_types),
6421 find_type_(find_type), found_(false)
6424 // Whether we found the type.
6427 { return this->found_; }
6434 // The type we are looking for.
6435 Named_type* find_type_;
6436 // Whether we found the type.
6440 // Check for FIND_TYPE in TYPE.
6443 Find_type_use::type(Type* type)
6445 if (type->named_type() != NULL && this->find_type_ == type->named_type())
6447 this->found_ = true;
6448 return TRAVERSE_EXIT;
6451 // It's OK if we see a reference to the type in any type which is
6452 // essentially a pointer: a pointer, a slice, a function, a map, or
6454 if (type->points_to() != NULL
6455 || type->is_open_array_type()
6456 || type->function_type() != NULL
6457 || type->map_type() != NULL
6458 || type->channel_type() != NULL)
6459 return TRAVERSE_SKIP_COMPONENTS;
6461 // For an interface, a reference to the type in a method type should
6462 // be ignored, but we have to consider direct inheritance. When
6463 // this is called, there may be cases of direct inheritance
6464 // represented as a method with no name.
6465 if (type->interface_type() != NULL)
6467 const Typed_identifier_list* methods = type->interface_type()->methods();
6468 if (methods != NULL)
6470 for (Typed_identifier_list::const_iterator p = methods->begin();
6471 p != methods->end();
6474 if (p->name().empty())
6476 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
6477 return TRAVERSE_EXIT;
6481 return TRAVERSE_SKIP_COMPONENTS;
6484 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
6485 // to convert TYPE to the backend representation before we convert
6487 if (type->named_type() != NULL)
6489 switch (type->base()->classification())
6491 case Type::TYPE_ERROR:
6492 case Type::TYPE_BOOLEAN:
6493 case Type::TYPE_INTEGER:
6494 case Type::TYPE_FLOAT:
6495 case Type::TYPE_COMPLEX:
6496 case Type::TYPE_STRING:
6497 case Type::TYPE_NIL:
6500 case Type::TYPE_ARRAY:
6501 case Type::TYPE_STRUCT:
6502 this->find_type_->add_dependency(type->named_type());
6505 case Type::TYPE_VOID:
6506 case Type::TYPE_SINK:
6507 case Type::TYPE_FUNCTION:
6508 case Type::TYPE_POINTER:
6509 case Type::TYPE_CALL_MULTIPLE_RESULT:
6510 case Type::TYPE_MAP:
6511 case Type::TYPE_CHANNEL:
6512 case Type::TYPE_INTERFACE:
6513 case Type::TYPE_NAMED:
6514 case Type::TYPE_FORWARD:
6520 return TRAVERSE_CONTINUE;
6523 // Verify that a named type does not refer to itself.
6526 Named_type::do_verify()
6528 Find_type_use find(this);
6529 Type::traverse(this->type_, &find);
6532 error_at(this->location_, "invalid recursive type %qs",
6533 this->message_name().c_str());
6534 this->is_error_ = true;
6538 // Check whether any of the local methods overloads an existing
6539 // struct field or interface method. We don't need to check the
6540 // list of methods against itself: that is handled by the Bindings
6542 if (this->local_methods_ != NULL)
6544 Struct_type* st = this->type_->struct_type();
6545 bool found_dup = false;
6548 for (Bindings::const_declarations_iterator p =
6549 this->local_methods_->begin_declarations();
6550 p != this->local_methods_->end_declarations();
6553 const std::string& name(p->first);
6554 if (st != NULL && st->find_local_field(name, NULL) != NULL)
6556 error_at(p->second->location(),
6557 "method %qs redeclares struct field name",
6558 Gogo::message_name(name).c_str());
6570 // Return whether this type is or contains a pointer.
6573 Named_type::do_has_pointer() const
6575 if (this->seen_ > 0)
6578 bool ret = this->type_->has_pointer();
6583 // Return a hash code. This is used for method lookup. We simply
6584 // hash on the name itself.
6587 Named_type::do_hash_for_method(Gogo* gogo) const
6589 const std::string& name(this->named_object()->name());
6590 unsigned int ret = Type::hash_string(name, 0);
6592 // GOGO will be NULL here when called from Type_hash_identical.
6593 // That is OK because that is only used for internal hash tables
6594 // where we are going to be comparing named types for equality. In
6595 // other cases, which are cases where the runtime is going to
6596 // compare hash codes to see if the types are the same, we need to
6597 // include the package prefix and name in the hash.
6598 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
6600 const Package* package = this->named_object()->package();
6601 if (package == NULL)
6603 ret = Type::hash_string(gogo->unique_prefix(), ret);
6604 ret = Type::hash_string(gogo->package_name(), ret);
6608 ret = Type::hash_string(package->unique_prefix(), ret);
6609 ret = Type::hash_string(package->name(), ret);
6616 // Convert a named type to the backend representation. In order to
6617 // get dependencies right, we fill in a dummy structure for this type,
6618 // then convert all the dependencies, then complete this type. When
6619 // this function is complete, the size of the type is known.
6622 Named_type::convert(Gogo* gogo)
6624 if (this->is_error_ || this->is_converted_)
6627 this->create_placeholder(gogo);
6629 // Convert all the dependencies. If they refer indirectly back to
6630 // this type, they will pick up the intermediate tree we just
6632 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
6633 p != this->dependencies_.end();
6635 (*p)->convert(gogo);
6637 // Complete this type.
6638 Btype* bt = this->named_btype_;
6639 Type* base = this->type_->base();
6640 switch (base->classification())
6657 // The size of these types is already correct. We don't worry
6658 // about filling them in until later, when we also track
6659 // circular references.
6664 std::vector<Backend::Btyped_identifier> bfields;
6665 get_backend_struct_fields(gogo, base->struct_type()->fields(),
6667 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6668 bt = gogo->backend()->error_type();
6673 // Slice types were completed in create_placeholder.
6674 if (!base->is_open_array_type())
6676 Btype* bet = base->array_type()->get_backend_element(gogo);
6677 Bexpression* blen = base->array_type()->get_backend_length(gogo);
6678 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
6679 bt = gogo->backend()->error_type();
6683 case TYPE_INTERFACE:
6684 // Interface types were completed in create_placeholder.
6692 case TYPE_CALL_MULTIPLE_RESULT:
6698 this->named_btype_ = bt;
6699 this->is_converted_ = true;
6702 // Create the placeholder for a named type. This is the first step in
6703 // converting to the backend representation.
6706 Named_type::create_placeholder(Gogo* gogo)
6708 if (this->is_error_)
6709 this->named_btype_ = gogo->backend()->error_type();
6711 if (this->named_btype_ != NULL)
6714 // Create the structure for this type. Note that because we call
6715 // base() here, we don't attempt to represent a named type defined
6716 // as another named type. Instead both named types will point to
6717 // different base representations.
6718 Type* base = this->type_->base();
6720 bool set_name = true;
6721 switch (base->classification())
6724 this->is_error_ = true;
6725 this->named_btype_ = gogo->backend()->error_type();
6735 // These are simple basic types, we can just create them
6737 bt = Type::get_named_base_btype(gogo, base);
6742 // All maps and channels have the same backend representation.
6743 bt = Type::get_named_base_btype(gogo, base);
6749 bool for_function = base->classification() == TYPE_FUNCTION;
6750 bt = gogo->backend()->placeholder_pointer_type(this->name(),
6758 bt = gogo->backend()->placeholder_struct_type(this->name(),
6764 if (base->is_open_array_type())
6765 bt = gogo->backend()->placeholder_struct_type(this->name(),
6768 bt = gogo->backend()->placeholder_array_type(this->name(),
6773 case TYPE_INTERFACE:
6774 if (base->interface_type()->is_empty())
6775 bt = Interface_type::get_backend_empty_interface_type(gogo);
6778 bt = gogo->backend()->placeholder_struct_type(this->name(),
6786 case TYPE_CALL_MULTIPLE_RESULT:
6793 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
6795 this->named_btype_ = bt;
6797 if (base->is_open_array_type())
6799 // We do not record slices as dependencies of other types,
6800 // because we can fill them in completely here with the final
6802 std::vector<Backend::Btyped_identifier> bfields;
6803 get_backend_slice_fields(gogo, base->array_type(), &bfields);
6804 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6805 this->named_btype_ = gogo->backend()->error_type();
6807 else if (base->interface_type() != NULL
6808 && !base->interface_type()->is_empty())
6810 // We do not record interfaces as dependencies of other types,
6811 // because we can fill them in completely here with the final
6813 std::vector<Backend::Btyped_identifier> bfields;
6814 get_backend_interface_fields(gogo, base->interface_type(), &bfields);
6815 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6816 this->named_btype_ = gogo->backend()->error_type();
6820 // Get a tree for a named type.
6823 Named_type::do_get_backend(Gogo* gogo)
6825 if (this->is_error_)
6826 return gogo->backend()->error_type();
6828 Btype* bt = this->named_btype_;
6830 if (!gogo->named_types_are_converted())
6832 // We have not completed converting named types. NAMED_BTYPE_
6833 // is a placeholder and we shouldn't do anything further.
6837 // We don't build dependencies for types whose sizes do not
6838 // change or are not relevant, so we may see them here while
6839 // converting types.
6840 this->create_placeholder(gogo);
6841 bt = this->named_btype_;
6842 go_assert(bt != NULL);
6846 // We are not converting types. This should only be called if the
6847 // type has already been converted.
6848 if (!this->is_converted_)
6850 go_assert(saw_errors());
6851 return gogo->backend()->error_type();
6854 go_assert(bt != NULL);
6856 // Complete the tree.
6857 Type* base = this->type_->base();
6859 switch (base->classification())
6862 return gogo->backend()->error_type();
6875 case TYPE_INTERFACE:
6879 // Don't build a circular data structure. GENERIC can't handle
6881 if (this->seen_ > 0)
6883 this->is_circular_ = true;
6884 return gogo->backend()->circular_pointer_type(bt, true);
6887 bt1 = Type::get_named_base_btype(gogo, base);
6889 if (this->is_circular_)
6890 bt1 = gogo->backend()->circular_pointer_type(bt, true);
6891 if (!gogo->backend()->set_placeholder_function_type(bt, bt1))
6892 bt = gogo->backend()->error_type();
6896 // Don't build a circular data structure. GENERIC can't handle
6898 if (this->seen_ > 0)
6900 this->is_circular_ = true;
6901 return gogo->backend()->circular_pointer_type(bt, false);
6904 bt1 = Type::get_named_base_btype(gogo, base);
6906 if (this->is_circular_)
6907 bt1 = gogo->backend()->circular_pointer_type(bt, false);
6908 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
6909 bt = gogo->backend()->error_type();
6914 case TYPE_CALL_MULTIPLE_RESULT:
6923 // Build a type descriptor for a named type.
6926 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6928 // If NAME is not NULL, then we don't really want the type
6929 // descriptor for this type; we want the descriptor for the
6930 // underlying type, giving it the name NAME.
6931 return this->named_type_descriptor(gogo, this->type_,
6932 name == NULL ? this : name);
6935 // Add to the reflection string. This is used mostly for the name of
6936 // the type used in a type descriptor, not for actual reflection
6940 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
6942 if (this->location() != BUILTINS_LOCATION)
6944 const Package* package = this->named_object_->package();
6945 if (package != NULL)
6946 ret->append(package->name());
6948 ret->append(gogo->package_name());
6949 ret->push_back('.');
6951 if (this->in_function_ != NULL)
6953 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
6954 ret->push_back('$');
6956 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
6959 // Get the mangled name.
6962 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6964 Named_object* no = this->named_object_;
6966 if (this->location() == BUILTINS_LOCATION)
6967 go_assert(this->in_function_ == NULL);
6970 const std::string& unique_prefix(no->package() == NULL
6971 ? gogo->unique_prefix()
6972 : no->package()->unique_prefix());
6973 const std::string& package_name(no->package() == NULL
6974 ? gogo->package_name()
6975 : no->package()->name());
6976 name = unique_prefix;
6977 name.append(1, '.');
6978 name.append(package_name);
6979 name.append(1, '.');
6980 if (this->in_function_ != NULL)
6982 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
6983 name.append(1, '$');
6986 name.append(Gogo::unpack_hidden_name(no->name()));
6988 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
6993 // Export the type. This is called to export a global type.
6996 Named_type::export_named_type(Export* exp, const std::string&) const
6998 // We don't need to write the name of the type here, because it will
6999 // be written by Export::write_type anyhow.
7000 exp->write_c_string("type ");
7001 exp->write_type(this);
7002 exp->write_c_string(";\n");
7005 // Import a named type.
7008 Named_type::import_named_type(Import* imp, Named_type** ptype)
7010 imp->require_c_string("type ");
7011 Type *type = imp->read_type();
7012 *ptype = type->named_type();
7013 go_assert(*ptype != NULL);
7014 imp->require_c_string(";\n");
7017 // Export the type when it is referenced by another type. In this
7018 // case Export::export_type will already have issued the name.
7021 Named_type::do_export(Export* exp) const
7023 exp->write_type(this->type_);
7025 // To save space, we only export the methods directly attached to
7027 Bindings* methods = this->local_methods_;
7028 if (methods == NULL)
7031 exp->write_c_string("\n");
7032 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
7033 p != methods->end_definitions();
7036 exp->write_c_string(" ");
7037 (*p)->export_named_object(exp);
7040 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
7041 p != methods->end_declarations();
7044 if (p->second->is_function_declaration())
7046 exp->write_c_string(" ");
7047 p->second->export_named_object(exp);
7052 // Make a named type.
7055 Type::make_named_type(Named_object* named_object, Type* type,
7056 source_location location)
7058 return new Named_type(named_object, type, location);
7061 // Finalize the methods for TYPE. It will be a named type or a struct
7062 // type. This sets *ALL_METHODS to the list of methods, and builds
7063 // all required stubs.
7066 Type::finalize_methods(Gogo* gogo, const Type* type, source_location location,
7067 Methods** all_methods)
7069 *all_methods = NULL;
7070 Types_seen types_seen;
7071 Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen,
7073 Type::build_stub_methods(gogo, type, *all_methods, location);
7076 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
7077 // build up the struct field indexes as we go. DEPTH is the depth of
7078 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
7079 // adding these methods for an anonymous field with pointer type.
7080 // NEEDS_STUB_METHOD is true if we need to use a stub method which
7081 // calls the real method. TYPES_SEEN is used to avoid infinite
7085 Type::add_methods_for_type(const Type* type,
7086 const Method::Field_indexes* field_indexes,
7088 bool is_embedded_pointer,
7089 bool needs_stub_method,
7090 Types_seen* types_seen,
7093 // Pointer types may not have methods.
7094 if (type->points_to() != NULL)
7097 const Named_type* nt = type->named_type();
7100 std::pair<Types_seen::iterator, bool> ins = types_seen->insert(nt);
7106 Type::add_local_methods_for_type(nt, field_indexes, depth,
7107 is_embedded_pointer, needs_stub_method,
7110 Type::add_embedded_methods_for_type(type, field_indexes, depth,
7111 is_embedded_pointer, needs_stub_method,
7112 types_seen, methods);
7114 // If we are called with depth > 0, then we are looking at an
7115 // anonymous field of a struct. If such a field has interface type,
7116 // then we need to add the interface methods. We don't want to add
7117 // them when depth == 0, because we will already handle them
7118 // following the usual rules for an interface type.
7120 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
7123 // Add the local methods for the named type NT to *METHODS. The
7124 // parameters are as for add_methods_to_type.
7127 Type::add_local_methods_for_type(const Named_type* nt,
7128 const Method::Field_indexes* field_indexes,
7130 bool is_embedded_pointer,
7131 bool needs_stub_method,
7134 const Bindings* local_methods = nt->local_methods();
7135 if (local_methods == NULL)
7138 if (*methods == NULL)
7139 *methods = new Methods();
7141 for (Bindings::const_declarations_iterator p =
7142 local_methods->begin_declarations();
7143 p != local_methods->end_declarations();
7146 Named_object* no = p->second;
7147 bool is_value_method = (is_embedded_pointer
7148 || !Type::method_expects_pointer(no));
7149 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
7151 || (depth > 0 && is_value_method)));
7152 if (!(*methods)->insert(no->name(), m))
7157 // Add the embedded methods for TYPE to *METHODS. These are the
7158 // methods attached to anonymous fields. The parameters are as for
7159 // add_methods_to_type.
7162 Type::add_embedded_methods_for_type(const Type* type,
7163 const Method::Field_indexes* field_indexes,
7165 bool is_embedded_pointer,
7166 bool needs_stub_method,
7167 Types_seen* types_seen,
7170 // Look for anonymous fields in TYPE. TYPE has fields if it is a
7172 const Struct_type* st = type->struct_type();
7176 const Struct_field_list* fields = st->fields();
7181 for (Struct_field_list::const_iterator pf = fields->begin();
7182 pf != fields->end();
7185 if (!pf->is_anonymous())
7188 Type* ftype = pf->type();
7189 bool is_pointer = false;
7190 if (ftype->points_to() != NULL)
7192 ftype = ftype->points_to();
7195 Named_type* fnt = ftype->named_type();
7198 // This is an error, but it will be diagnosed elsewhere.
7202 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
7203 sub_field_indexes->next = field_indexes;
7204 sub_field_indexes->field_index = i;
7206 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
7207 (is_embedded_pointer || is_pointer),
7216 // If TYPE is an interface type, then add its method to *METHODS.
7217 // This is for interface methods attached to an anonymous field. The
7218 // parameters are as for add_methods_for_type.
7221 Type::add_interface_methods_for_type(const Type* type,
7222 const Method::Field_indexes* field_indexes,
7226 const Interface_type* it = type->interface_type();
7230 const Typed_identifier_list* imethods = it->methods();
7231 if (imethods == NULL)
7234 if (*methods == NULL)
7235 *methods = new Methods();
7237 for (Typed_identifier_list::const_iterator pm = imethods->begin();
7238 pm != imethods->end();
7241 Function_type* fntype = pm->type()->function_type();
7244 // This is an error, but it should be reported elsewhere
7245 // when we look at the methods for IT.
7248 go_assert(!fntype->is_method());
7249 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
7250 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
7251 field_indexes, depth);
7252 if (!(*methods)->insert(pm->name(), m))
7257 // Build stub methods for TYPE as needed. METHODS is the set of
7258 // methods for the type. A stub method may be needed when a type
7259 // inherits a method from an anonymous field. When we need the
7260 // address of the method, as in a type descriptor, we need to build a
7261 // little stub which does the required field dereferences and jumps to
7262 // the real method. LOCATION is the location of the type definition.
7265 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
7266 source_location location)
7268 if (methods == NULL)
7270 for (Methods::const_iterator p = methods->begin();
7271 p != methods->end();
7274 Method* m = p->second;
7275 if (m->is_ambiguous() || !m->needs_stub_method())
7278 const std::string& name(p->first);
7280 // Build a stub method.
7282 const Function_type* fntype = m->type();
7284 static unsigned int counter;
7286 snprintf(buf, sizeof buf, "$this%u", counter);
7289 Type* receiver_type = const_cast<Type*>(type);
7290 if (!m->is_value_method())
7291 receiver_type = Type::make_pointer_type(receiver_type);
7292 source_location receiver_location = m->receiver_location();
7293 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
7296 const Typed_identifier_list* fnparams = fntype->parameters();
7297 Typed_identifier_list* stub_params;
7298 if (fnparams == NULL || fnparams->empty())
7302 // We give each stub parameter a unique name.
7303 stub_params = new Typed_identifier_list();
7304 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
7305 pp != fnparams->end();
7309 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
7310 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
7316 const Typed_identifier_list* fnresults = fntype->results();
7317 Typed_identifier_list* stub_results;
7318 if (fnresults == NULL || fnresults->empty())
7319 stub_results = NULL;
7322 // We create the result parameters without any names, since
7323 // we won't refer to them.
7324 stub_results = new Typed_identifier_list();
7325 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
7326 pr != fnresults->end();
7328 stub_results->push_back(Typed_identifier("", pr->type(),
7332 Function_type* stub_type = Type::make_function_type(receiver,
7335 fntype->location());
7336 if (fntype->is_varargs())
7337 stub_type->set_is_varargs();
7339 // We only create the function in the package which creates the
7341 const Package* package;
7342 if (type->named_type() == NULL)
7345 package = type->named_type()->named_object()->package();
7347 if (package != NULL)
7348 stub = Named_object::make_function_declaration(name, package,
7349 stub_type, location);
7352 stub = gogo->start_function(name, stub_type, false,
7353 fntype->location());
7354 Type::build_one_stub_method(gogo, m, buf, stub_params,
7355 fntype->is_varargs(), location);
7356 gogo->finish_function(fntype->location());
7359 m->set_stub_object(stub);
7363 // Build a stub method which adjusts the receiver as required to call
7364 // METHOD. RECEIVER_NAME is the name we used for the receiver.
7365 // PARAMS is the list of function parameters.
7368 Type::build_one_stub_method(Gogo* gogo, Method* method,
7369 const char* receiver_name,
7370 const Typed_identifier_list* params,
7372 source_location location)
7374 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
7375 go_assert(receiver_object != NULL);
7377 Expression* expr = Expression::make_var_reference(receiver_object, location);
7378 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
7379 if (expr->type()->points_to() == NULL)
7380 expr = Expression::make_unary(OPERATOR_AND, expr, location);
7382 Expression_list* arguments;
7383 if (params == NULL || params->empty())
7387 arguments = new Expression_list();
7388 for (Typed_identifier_list::const_iterator p = params->begin();
7392 Named_object* param = gogo->lookup(p->name(), NULL);
7393 go_assert(param != NULL);
7394 Expression* param_ref = Expression::make_var_reference(param,
7396 arguments->push_back(param_ref);
7400 Expression* func = method->bind_method(expr, location);
7401 go_assert(func != NULL);
7402 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
7404 size_t count = call->result_count();
7406 gogo->add_statement(Statement::make_statement(call));
7409 Expression_list* retvals = new Expression_list();
7411 retvals->push_back(call);
7414 for (size_t i = 0; i < count; ++i)
7415 retvals->push_back(Expression::make_call_result(call, i));
7417 Return_statement* retstat = Statement::make_return_statement(retvals,
7420 // We can return values with hidden fields from a stub. This is
7421 // necessary if the method is itself hidden.
7422 retstat->set_hidden_fields_are_ok();
7424 gogo->add_statement(retstat);
7428 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
7429 // in reverse order.
7432 Type::apply_field_indexes(Expression* expr,
7433 const Method::Field_indexes* field_indexes,
7434 source_location location)
7436 if (field_indexes == NULL)
7438 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
7439 Struct_type* stype = expr->type()->deref()->struct_type();
7440 go_assert(stype != NULL
7441 && field_indexes->field_index < stype->field_count());
7442 if (expr->type()->struct_type() == NULL)
7444 go_assert(expr->type()->points_to() != NULL);
7445 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
7446 go_assert(expr->type()->struct_type() == stype);
7448 return Expression::make_field_reference(expr, field_indexes->field_index,
7452 // Return whether NO is a method for which the receiver is a pointer.
7455 Type::method_expects_pointer(const Named_object* no)
7457 const Function_type *fntype;
7458 if (no->is_function())
7459 fntype = no->func_value()->type();
7460 else if (no->is_function_declaration())
7461 fntype = no->func_declaration_value()->type();
7464 return fntype->receiver()->type()->points_to() != NULL;
7467 // Given a set of methods for a type, METHODS, return the method NAME,
7468 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
7469 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
7470 // but is ambiguous (and return NULL).
7473 Type::method_function(const Methods* methods, const std::string& name,
7476 if (is_ambiguous != NULL)
7477 *is_ambiguous = false;
7478 if (methods == NULL)
7480 Methods::const_iterator p = methods->find(name);
7481 if (p == methods->end())
7483 Method* m = p->second;
7484 if (m->is_ambiguous())
7486 if (is_ambiguous != NULL)
7487 *is_ambiguous = true;
7493 // Look for field or method NAME for TYPE. Return an Expression for
7494 // the field or method bound to EXPR. If there is no such field or
7495 // method, give an appropriate error and return an error expression.
7498 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
7499 const std::string& name,
7500 source_location location)
7502 if (type->deref()->is_error_type())
7503 return Expression::make_error(location);
7505 const Named_type* nt = type->deref()->named_type();
7506 const Struct_type* st = type->deref()->struct_type();
7507 const Interface_type* it = type->interface_type();
7509 // If this is a pointer to a pointer, then it is possible that the
7510 // pointed-to type has methods.
7514 && type->points_to() != NULL
7515 && type->points_to()->points_to() != NULL)
7517 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
7518 type = type->points_to();
7519 if (type->deref()->is_error_type())
7520 return Expression::make_error(location);
7521 nt = type->points_to()->named_type();
7522 st = type->points_to()->struct_type();
7525 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
7526 || expr->is_addressable());
7527 std::vector<const Named_type*> seen;
7528 bool is_method = false;
7529 bool found_pointer_method = false;
7532 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
7533 &seen, NULL, &is_method,
7534 &found_pointer_method, &ambig1, &ambig2))
7539 go_assert(st != NULL);
7540 if (type->struct_type() == NULL)
7542 go_assert(type->points_to() != NULL);
7543 expr = Expression::make_unary(OPERATOR_MULT, expr,
7545 go_assert(expr->type()->struct_type() == st);
7547 ret = st->field_reference(expr, name, location);
7549 else if (it != NULL && it->find_method(name) != NULL)
7550 ret = Expression::make_interface_field_reference(expr, name,
7556 m = nt->method_function(name, NULL);
7557 else if (st != NULL)
7558 m = st->method_function(name, NULL);
7561 go_assert(m != NULL);
7562 if (!m->is_value_method() && expr->type()->points_to() == NULL)
7563 expr = Expression::make_unary(OPERATOR_AND, expr, location);
7564 ret = m->bind_method(expr, location);
7566 go_assert(ret != NULL);
7571 if (!ambig1.empty())
7572 error_at(location, "%qs is ambiguous via %qs and %qs",
7573 Gogo::message_name(name).c_str(),
7574 Gogo::message_name(ambig1).c_str(),
7575 Gogo::message_name(ambig2).c_str());
7576 else if (found_pointer_method)
7577 error_at(location, "method requires a pointer");
7578 else if (nt == NULL && st == NULL && it == NULL)
7580 ("reference to field %qs in object which "
7581 "has no fields or methods"),
7582 Gogo::message_name(name).c_str());
7586 if (!Gogo::is_hidden_name(name))
7587 is_unexported = false;
7590 std::string unpacked = Gogo::unpack_hidden_name(name);
7592 is_unexported = Type::is_unexported_field_or_method(gogo, type,
7597 error_at(location, "reference to unexported field or method %qs",
7598 Gogo::message_name(name).c_str());
7600 error_at(location, "reference to undefined field or method %qs",
7601 Gogo::message_name(name).c_str());
7603 return Expression::make_error(location);
7607 // Look in TYPE for a field or method named NAME, return true if one
7608 // is found. This looks through embedded anonymous fields and handles
7609 // ambiguity. If a method is found, sets *IS_METHOD to true;
7610 // otherwise, if a field is found, set it to false. If
7611 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
7612 // whose address can not be taken. SEEN is used to avoid infinite
7613 // recursion on invalid types.
7615 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
7616 // method we couldn't use because it requires a pointer. LEVEL is
7617 // used for recursive calls, and can be NULL for a non-recursive call.
7618 // When this function returns false because it finds that the name is
7619 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
7620 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
7621 // will be unchanged.
7623 // This function just returns whether or not there is a field or
7624 // method, and whether it is a field or method. It doesn't build an
7625 // expression to refer to it. If it is a method, we then look in the
7626 // list of all methods for the type. If it is a field, the search has
7627 // to be done again, looking only for fields, and building up the
7628 // expression as we go.
7631 Type::find_field_or_method(const Type* type,
7632 const std::string& name,
7633 bool receiver_can_be_pointer,
7634 std::vector<const Named_type*>* seen,
7637 bool* found_pointer_method,
7638 std::string* ambig1,
7639 std::string* ambig2)
7641 // Named types can have locally defined methods.
7642 const Named_type* nt = type->named_type();
7643 if (nt == NULL && type->points_to() != NULL)
7644 nt = type->points_to()->named_type();
7647 Named_object* no = nt->find_local_method(name);
7650 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
7656 // Record that we have found a pointer method in order to
7657 // give a better error message if we don't find anything
7659 *found_pointer_method = true;
7662 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
7668 // We've already seen this type when searching for methods.
7674 // Interface types can have methods.
7675 const Interface_type* it = type->interface_type();
7676 if (it != NULL && it->find_method(name) != NULL)
7682 // Struct types can have fields. They can also inherit fields and
7683 // methods from anonymous fields.
7684 const Struct_type* st = type->deref()->struct_type();
7687 const Struct_field_list* fields = st->fields();
7692 seen->push_back(nt);
7694 int found_level = 0;
7695 bool found_is_method = false;
7696 std::string found_ambig1;
7697 std::string found_ambig2;
7698 const Struct_field* found_parent = NULL;
7699 for (Struct_field_list::const_iterator pf = fields->begin();
7700 pf != fields->end();
7703 if (pf->field_name() == name)
7711 if (!pf->is_anonymous())
7714 if (pf->type()->deref()->is_error_type()
7715 || pf->type()->deref()->is_undefined())
7718 Named_type* fnt = pf->type()->named_type();
7720 fnt = pf->type()->deref()->named_type();
7721 go_assert(fnt != NULL);
7723 int sublevel = level == NULL ? 1 : *level + 1;
7725 std::string subambig1;
7726 std::string subambig2;
7727 bool subfound = Type::find_field_or_method(fnt,
7729 receiver_can_be_pointer,
7733 found_pointer_method,
7738 if (!subambig1.empty())
7740 // The name was found via this field, but is ambiguous.
7741 // if the ambiguity is lower or at the same level as
7742 // anything else we have already found, then we want to
7743 // pass the ambiguity back to the caller.
7744 if (found_level == 0 || sublevel <= found_level)
7746 found_ambig1 = pf->field_name() + '.' + subambig1;
7747 found_ambig2 = pf->field_name() + '.' + subambig2;
7748 found_level = sublevel;
7754 // The name was found via this field. Use the level to see
7755 // if we want to use this one, or whether it introduces an
7757 if (found_level == 0 || sublevel < found_level)
7759 found_level = sublevel;
7760 found_is_method = sub_is_method;
7761 found_ambig1.clear();
7762 found_ambig2.clear();
7763 found_parent = &*pf;
7765 else if (sublevel > found_level)
7767 else if (found_ambig1.empty())
7769 // We found an ambiguity.
7770 go_assert(found_parent != NULL);
7771 found_ambig1 = found_parent->field_name();
7772 found_ambig2 = pf->field_name();
7776 // We found an ambiguity, but we already know of one.
7777 // Just report the earlier one.
7782 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
7783 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
7784 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
7785 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
7790 if (found_level == 0)
7792 else if (!found_ambig1.empty())
7794 go_assert(!found_ambig1.empty());
7795 ambig1->assign(found_ambig1);
7796 ambig2->assign(found_ambig2);
7798 *level = found_level;
7804 *level = found_level;
7805 *is_method = found_is_method;
7810 // Return whether NAME is an unexported field or method for TYPE.
7813 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
7814 const std::string& name,
7815 std::vector<const Named_type*>* seen)
7817 const Named_type* nt = type->named_type();
7819 nt = type->deref()->named_type();
7822 if (nt->is_unexported_local_method(gogo, name))
7825 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
7831 // We've already seen this type.
7837 const Interface_type* it = type->interface_type();
7838 if (it != NULL && it->is_unexported_method(gogo, name))
7841 type = type->deref();
7843 const Struct_type* st = type->struct_type();
7844 if (st != NULL && st->is_unexported_local_field(gogo, name))
7850 const Struct_field_list* fields = st->fields();
7855 seen->push_back(nt);
7857 for (Struct_field_list::const_iterator pf = fields->begin();
7858 pf != fields->end();
7861 if (pf->is_anonymous()
7862 && !pf->type()->deref()->is_error_type()
7863 && !pf->type()->deref()->is_undefined())
7865 Named_type* subtype = pf->type()->named_type();
7866 if (subtype == NULL)
7867 subtype = pf->type()->deref()->named_type();
7868 if (subtype == NULL)
7870 // This is an error, but it will be diagnosed elsewhere.
7873 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
7888 // Class Forward_declaration.
7890 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
7891 : Type(TYPE_FORWARD),
7892 named_object_(named_object->resolve()), warned_(false)
7894 go_assert(this->named_object_->is_unknown()
7895 || this->named_object_->is_type_declaration());
7898 // Return the named object.
7901 Forward_declaration_type::named_object()
7903 return this->named_object_->resolve();
7907 Forward_declaration_type::named_object() const
7909 return this->named_object_->resolve();
7912 // Return the name of the forward declared type.
7915 Forward_declaration_type::name() const
7917 return this->named_object()->name();
7920 // Warn about a use of a type which has been declared but not defined.
7923 Forward_declaration_type::warn() const
7925 Named_object* no = this->named_object_->resolve();
7926 if (no->is_unknown())
7928 // The name was not defined anywhere.
7931 error_at(this->named_object_->location(),
7932 "use of undefined type %qs",
7933 no->message_name().c_str());
7934 this->warned_ = true;
7937 else if (no->is_type_declaration())
7939 // The name was seen as a type, but the type was never defined.
7940 if (no->type_declaration_value()->using_type())
7942 error_at(this->named_object_->location(),
7943 "use of undefined type %qs",
7944 no->message_name().c_str());
7945 this->warned_ = true;
7950 // The name was defined, but not as a type.
7953 error_at(this->named_object_->location(), "expected type");
7954 this->warned_ = true;
7959 // Get the base type of a declaration. This gives an error if the
7960 // type has not yet been defined.
7963 Forward_declaration_type::real_type()
7965 if (this->is_defined())
7966 return this->named_object()->type_value();
7970 return Type::make_error_type();
7975 Forward_declaration_type::real_type() const
7977 if (this->is_defined())
7978 return this->named_object()->type_value();
7982 return Type::make_error_type();
7986 // Return whether the base type is defined.
7989 Forward_declaration_type::is_defined() const
7991 return this->named_object()->is_type();
7994 // Add a method. This is used when methods are defined before the
7998 Forward_declaration_type::add_method(const std::string& name,
8001 Named_object* no = this->named_object();
8002 if (no->is_unknown())
8003 no->declare_as_type();
8004 return no->type_declaration_value()->add_method(name, function);
8007 // Add a method declaration. This is used when methods are declared
8011 Forward_declaration_type::add_method_declaration(const std::string& name,
8012 Function_type* type,
8013 source_location location)
8015 Named_object* no = this->named_object();
8016 if (no->is_unknown())
8017 no->declare_as_type();
8018 Type_declaration* td = no->type_declaration_value();
8019 return td->add_method_declaration(name, type, location);
8025 Forward_declaration_type::do_traverse(Traverse* traverse)
8027 if (this->is_defined()
8028 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
8029 return TRAVERSE_EXIT;
8030 return TRAVERSE_CONTINUE;
8033 // Get the backend representation for the type.
8036 Forward_declaration_type::do_get_backend(Gogo* gogo)
8038 if (this->is_defined())
8039 return Type::get_named_base_btype(gogo, this->real_type());
8042 return gogo->backend()->error_type();
8044 // We represent an undefined type as a struct with no fields. That
8045 // should work fine for the backend, since the same case can arise
8047 std::vector<Backend::Btyped_identifier> fields;
8048 Btype* bt = gogo->backend()->struct_type(fields);
8049 return gogo->backend()->named_type(this->name(), bt,
8050 this->named_object()->location());
8053 // Build a type descriptor for a forwarded type.
8056 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8058 if (!this->is_defined())
8059 return Expression::make_nil(BUILTINS_LOCATION);
8062 Type* t = this->real_type();
8064 return this->named_type_descriptor(gogo, t, name);
8066 return Expression::make_type_descriptor(t, BUILTINS_LOCATION);
8070 // The reflection string.
8073 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
8075 this->append_reflection(this->real_type(), gogo, ret);
8078 // The mangled name.
8081 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8083 if (this->is_defined())
8084 this->append_mangled_name(this->real_type(), gogo, ret);
8087 const Named_object* no = this->named_object();
8089 if (no->package() == NULL)
8090 name = gogo->package_name();
8092 name = no->package()->name();
8094 name += Gogo::unpack_hidden_name(no->name());
8096 snprintf(buf, sizeof buf, "N%u_",
8097 static_cast<unsigned int>(name.length()));
8103 // Export a forward declaration. This can happen when a defined type
8104 // refers to a type which is only declared (and is presumably defined
8105 // in some other file in the same package).
8108 Forward_declaration_type::do_export(Export*) const
8110 // If there is a base type, that should be exported instead of this.
8111 go_assert(!this->is_defined());
8113 // We don't output anything.
8116 // Make a forward declaration.
8119 Type::make_forward_declaration(Named_object* named_object)
8121 return new Forward_declaration_type(named_object);
8124 // Class Typed_identifier_list.
8126 // Sort the entries by name.
8128 struct Typed_identifier_list_sort
8132 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
8133 { return t1.name() < t2.name(); }
8137 Typed_identifier_list::sort_by_name()
8139 std::sort(this->entries_.begin(), this->entries_.end(),
8140 Typed_identifier_list_sort());
8146 Typed_identifier_list::traverse(Traverse* traverse)
8148 for (Typed_identifier_list::const_iterator p = this->begin();
8152 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
8153 return TRAVERSE_EXIT;
8155 return TRAVERSE_CONTINUE;
8160 Typed_identifier_list*
8161 Typed_identifier_list::copy() const
8163 Typed_identifier_list* ret = new Typed_identifier_list();
8164 for (Typed_identifier_list::const_iterator p = this->begin();
8167 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));