1 // types.cc -- Go frontend types.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
11 #ifndef ENABLE_BUILD_WITH_CXX
23 #ifndef ENABLE_BUILD_WITH_CXX
30 #include "expressions.h"
31 #include "statements.h"
39 Type::Type(Type_classification classification)
40 : classification_(classification), btype_(NULL), type_descriptor_var_(NULL)
48 // Get the base type for a type--skip names and forward declarations.
53 switch (this->classification_)
56 return this->named_type()->named_base();
58 return this->forward_declaration_type()->real_type()->base();
67 switch (this->classification_)
70 return this->named_type()->named_base();
72 return this->forward_declaration_type()->real_type()->base();
78 // Skip defined forward declarations.
84 Forward_declaration_type* ftype = t->forward_declaration_type();
85 while (ftype != NULL && ftype->is_defined())
87 t = ftype->real_type();
88 ftype = t->forward_declaration_type();
94 Type::forwarded() const
97 const Forward_declaration_type* ftype = t->forward_declaration_type();
98 while (ftype != NULL && ftype->is_defined())
100 t = ftype->real_type();
101 ftype = t->forward_declaration_type();
106 // If this is a named type, return it. Otherwise, return NULL.
111 return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
115 Type::named_type() const
117 return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
120 // Return true if this type is not defined.
123 Type::is_undefined() const
125 return this->forwarded()->forward_declaration_type() != NULL;
128 // Return true if this is a basic type: a type which is not composed
129 // of other types, and is not void.
132 Type::is_basic_type() const
134 switch (this->classification_)
157 return this->base()->is_basic_type();
164 // Return true if this is an abstract type.
167 Type::is_abstract() const
169 switch (this->classification())
172 return this->integer_type()->is_abstract();
174 return this->float_type()->is_abstract();
176 return this->complex_type()->is_abstract();
178 return this->is_abstract_string_type();
180 return this->is_abstract_boolean_type();
186 // Return a non-abstract version of an abstract type.
189 Type::make_non_abstract_type()
191 go_assert(this->is_abstract());
192 switch (this->classification())
195 return Type::lookup_integer_type("int");
197 return Type::lookup_float_type("float64");
199 return Type::lookup_complex_type("complex128");
201 return Type::lookup_string_type();
203 return Type::lookup_bool_type();
209 // Return true if this is an error type. Don't give an error if we
210 // try to dereference an undefined forwarding type, as this is called
211 // in the parser when the type may legitimately be undefined.
214 Type::is_error_type() const
216 const Type* t = this->forwarded();
217 // Note that we return false for an undefined forward type.
218 switch (t->classification_)
223 return t->named_type()->is_named_error_type();
229 // If this is a pointer type, return the type to which it points.
230 // Otherwise, return NULL.
233 Type::points_to() const
235 const Pointer_type* ptype = this->convert<const Pointer_type,
237 return ptype == NULL ? NULL : ptype->points_to();
240 // Return whether this is an open array type.
243 Type::is_slice_type() const
245 return this->array_type() != NULL && this->array_type()->length() == NULL;
248 // Return whether this is the predeclared constant nil being used as a
252 Type::is_nil_constant_as_type() const
254 const Type* t = this->forwarded();
255 if (t->forward_declaration_type() != NULL)
257 const Named_object* no = t->forward_declaration_type()->named_object();
258 if (no->is_unknown())
259 no = no->unknown_value()->real_named_object();
262 && no->const_value()->expr()->is_nil_expression())
271 Type::traverse(Type* type, Traverse* traverse)
273 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
274 || (traverse->traverse_mask()
275 & Traverse::traverse_expressions) != 0);
276 if (traverse->remember_type(type))
278 // We have already traversed this type.
279 return TRAVERSE_CONTINUE;
281 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
283 int t = traverse->type(type);
284 if (t == TRAVERSE_EXIT)
285 return TRAVERSE_EXIT;
286 else if (t == TRAVERSE_SKIP_COMPONENTS)
287 return TRAVERSE_CONTINUE;
289 // An array type has an expression which we need to traverse if
290 // traverse_expressions is set.
291 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
292 return TRAVERSE_EXIT;
293 return TRAVERSE_CONTINUE;
296 // Default implementation for do_traverse for child class.
299 Type::do_traverse(Traverse*)
301 return TRAVERSE_CONTINUE;
304 // Return whether two types are identical. If ERRORS_ARE_IDENTICAL,
305 // then return true for all erroneous types; this is used to avoid
306 // cascading errors. If REASON is not NULL, optionally set *REASON to
307 // the reason the types are not identical.
310 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
313 if (t1 == NULL || t2 == NULL)
315 // Something is wrong.
316 return errors_are_identical ? true : t1 == t2;
319 // Skip defined forward declarations.
320 t1 = t1->forwarded();
321 t2 = t2->forwarded();
326 // An undefined forward declaration is an error.
327 if (t1->forward_declaration_type() != NULL
328 || t2->forward_declaration_type() != NULL)
329 return errors_are_identical;
331 // Avoid cascading errors with error types.
332 if (t1->is_error_type() || t2->is_error_type())
334 if (errors_are_identical)
336 return t1->is_error_type() && t2->is_error_type();
339 // Get a good reason for the sink type. Note that the sink type on
340 // the left hand side of an assignment is handled in are_assignable.
341 if (t1->is_sink_type() || t2->is_sink_type())
344 *reason = "invalid use of _";
348 // A named type is only identical to itself.
349 if (t1->named_type() != NULL || t2->named_type() != NULL)
352 // Check type shapes.
353 if (t1->classification() != t2->classification())
356 switch (t1->classification())
362 // These types are always identical.
366 return t1->integer_type()->is_identical(t2->integer_type());
369 return t1->float_type()->is_identical(t2->float_type());
372 return t1->complex_type()->is_identical(t2->complex_type());
375 return t1->function_type()->is_identical(t2->function_type(),
377 errors_are_identical,
381 return Type::are_identical(t1->points_to(), t2->points_to(),
382 errors_are_identical, reason);
385 return t1->struct_type()->is_identical(t2->struct_type(),
386 errors_are_identical);
389 return t1->array_type()->is_identical(t2->array_type(),
390 errors_are_identical);
393 return t1->map_type()->is_identical(t2->map_type(),
394 errors_are_identical);
397 return t1->channel_type()->is_identical(t2->channel_type(),
398 errors_are_identical);
401 return t1->interface_type()->is_identical(t2->interface_type(),
402 errors_are_identical);
404 case TYPE_CALL_MULTIPLE_RESULT:
406 *reason = "invalid use of multiple value function call";
414 // Return true if it's OK to have a binary operation with types LHS
415 // and RHS. This is not used for shifts or comparisons.
418 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
420 if (Type::are_identical(lhs, rhs, true, NULL))
423 // A constant of abstract bool type may be mixed with any bool type.
424 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
425 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
428 // A constant of abstract string type may be mixed with any string
430 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
431 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
437 // A constant of abstract integer, float, or complex type may be
438 // mixed with an integer, float, or complex type.
439 if ((rhs->is_abstract()
440 && (rhs->integer_type() != NULL
441 || rhs->float_type() != NULL
442 || rhs->complex_type() != NULL)
443 && (lhs->integer_type() != NULL
444 || lhs->float_type() != NULL
445 || lhs->complex_type() != NULL))
446 || (lhs->is_abstract()
447 && (lhs->integer_type() != NULL
448 || lhs->float_type() != NULL
449 || lhs->complex_type() != NULL)
450 && (rhs->integer_type() != NULL
451 || rhs->float_type() != NULL
452 || rhs->complex_type() != NULL)))
455 // The nil type may be compared to a pointer, an interface type, a
456 // slice type, a channel type, a map type, or a function type.
457 if (lhs->is_nil_type()
458 && (rhs->points_to() != NULL
459 || rhs->interface_type() != NULL
460 || rhs->is_slice_type()
461 || rhs->map_type() != NULL
462 || rhs->channel_type() != NULL
463 || rhs->function_type() != NULL))
465 if (rhs->is_nil_type()
466 && (lhs->points_to() != NULL
467 || lhs->interface_type() != NULL
468 || lhs->is_slice_type()
469 || lhs->map_type() != NULL
470 || lhs->channel_type() != NULL
471 || lhs->function_type() != NULL))
477 // Return true if a value with type RHS may be assigned to a variable
478 // with type LHS. If CHECK_HIDDEN_FIELDS is true, check whether any
479 // hidden fields are modified. If REASON is not NULL, set *REASON to
480 // the reason the types are not assignable.
483 Type::are_assignable_check_hidden(const Type* lhs, const Type* rhs,
484 bool check_hidden_fields,
487 // Do some checks first. Make sure the types are defined.
489 && rhs->forwarded()->forward_declaration_type() == NULL
490 && rhs->is_void_type())
493 *reason = "non-value used as value";
497 if (lhs != NULL && lhs->forwarded()->forward_declaration_type() == NULL)
499 // Any value may be assigned to the blank identifier.
500 if (lhs->is_sink_type())
503 // All fields of a struct must be exported, or the assignment
504 // must be in the same package.
505 if (check_hidden_fields
507 && rhs->forwarded()->forward_declaration_type() == NULL)
509 if (lhs->has_hidden_fields(NULL, reason)
510 || rhs->has_hidden_fields(NULL, reason))
515 // Identical types are assignable.
516 if (Type::are_identical(lhs, rhs, true, reason))
519 // The types are assignable if they have identical underlying types
520 // and either LHS or RHS is not a named type.
521 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
522 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
523 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
526 // The types are assignable if LHS is an interface type and RHS
527 // implements the required methods.
528 const Interface_type* lhs_interface_type = lhs->interface_type();
529 if (lhs_interface_type != NULL)
531 if (lhs_interface_type->implements_interface(rhs, reason))
533 const Interface_type* rhs_interface_type = rhs->interface_type();
534 if (rhs_interface_type != NULL
535 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
540 // The type are assignable if RHS is a bidirectional channel type,
541 // LHS is a channel type, they have identical element types, and
542 // either LHS or RHS is not a named type.
543 if (lhs->channel_type() != NULL
544 && rhs->channel_type() != NULL
545 && rhs->channel_type()->may_send()
546 && rhs->channel_type()->may_receive()
547 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
548 && Type::are_identical(lhs->channel_type()->element_type(),
549 rhs->channel_type()->element_type(),
554 // The nil type may be assigned to a pointer, function, slice, map,
555 // channel, or interface type.
556 if (rhs->is_nil_type()
557 && (lhs->points_to() != NULL
558 || lhs->function_type() != NULL
559 || lhs->is_slice_type()
560 || lhs->map_type() != NULL
561 || lhs->channel_type() != NULL
562 || lhs->interface_type() != NULL))
565 // An untyped numeric constant may be assigned to a numeric type if
566 // it is representable in that type.
567 if ((rhs->is_abstract()
568 && (rhs->integer_type() != NULL
569 || rhs->float_type() != NULL
570 || rhs->complex_type() != NULL))
571 && (lhs->integer_type() != NULL
572 || lhs->float_type() != NULL
573 || lhs->complex_type() != NULL))
576 // Give some better error messages.
577 if (reason != NULL && reason->empty())
579 if (rhs->interface_type() != NULL)
580 reason->assign(_("need explicit conversion"));
581 else if (rhs->is_call_multiple_result_type())
582 reason->assign(_("multiple value function call in "
583 "single value context"));
584 else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
586 size_t len = (lhs->named_type()->name().length()
587 + rhs->named_type()->name().length()
589 char* buf = new char[len];
590 snprintf(buf, len, _("cannot use type %s as type %s"),
591 rhs->named_type()->message_name().c_str(),
592 lhs->named_type()->message_name().c_str());
601 // Return true if a value with type RHS may be assigned to a variable
602 // with type LHS. If REASON is not NULL, set *REASON to the reason
603 // the types are not assignable.
606 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
608 return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
611 // Like are_assignable but don't check for hidden fields.
614 Type::are_assignable_hidden_ok(const Type* lhs, const Type* rhs,
617 return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
620 // Return true if a value with type RHS may be converted to type LHS.
621 // If REASON is not NULL, set *REASON to the reason the types are not
625 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
627 // The types are convertible if they are assignable.
628 if (Type::are_assignable(lhs, rhs, reason))
631 // The types are convertible if they have identical underlying
633 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
634 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
637 // The types are convertible if they are both unnamed pointer types
638 // and their pointer base types have identical underlying types.
639 if (lhs->named_type() == NULL
640 && rhs->named_type() == NULL
641 && lhs->points_to() != NULL
642 && rhs->points_to() != NULL
643 && (lhs->points_to()->named_type() != NULL
644 || rhs->points_to()->named_type() != NULL)
645 && Type::are_identical(lhs->points_to()->base(),
646 rhs->points_to()->base(),
651 // Integer and floating point types are convertible to each other.
652 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
653 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
656 // Complex types are convertible to each other.
657 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
660 // An integer, or []byte, or []int, may be converted to a string.
661 if (lhs->is_string_type())
663 if (rhs->integer_type() != NULL)
665 if (rhs->is_slice_type())
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() && lhs->is_slice_type())
678 const Type* e = lhs->array_type()->element_type()->forwarded();
679 if (e->integer_type() != NULL
680 && (e == Type::lookup_integer_type("uint8")
681 || e == Type::lookup_integer_type("int")))
685 // An unsafe.Pointer type may be converted to any pointer type or to
686 // uintptr, and vice-versa.
687 if (lhs->is_unsafe_pointer_type()
688 && (rhs->points_to() != NULL
689 || (rhs->integer_type() != NULL
690 && rhs->forwarded() == Type::lookup_integer_type("uintptr"))))
692 if (rhs->is_unsafe_pointer_type()
693 && (lhs->points_to() != NULL
694 || (lhs->integer_type() != NULL
695 && lhs->forwarded() == Type::lookup_integer_type("uintptr"))))
698 // Give a better error message.
702 *reason = "invalid type conversion";
705 std::string s = "invalid type conversion (";
715 // Return whether this type has any hidden fields. This is only a
716 // possibility for a few types.
719 Type::has_hidden_fields(const Named_type* within, std::string* reason) const
721 switch (this->forwarded()->classification_)
724 return this->named_type()->named_type_has_hidden_fields(reason);
726 return this->struct_type()->struct_has_hidden_fields(within, reason);
728 return this->array_type()->array_has_hidden_fields(within, reason);
734 // Return a hash code for the type to be used for method lookup.
737 Type::hash_for_method(Gogo* gogo) const
739 unsigned int ret = 0;
740 if (this->classification_ != TYPE_FORWARD)
741 ret += this->classification_;
742 return ret + this->do_hash_for_method(gogo);
745 // Default implementation of do_hash_for_method. This is appropriate
746 // for types with no subfields.
749 Type::do_hash_for_method(Gogo*) const
754 // Return a hash code for a string, given a starting hash.
757 Type::hash_string(const std::string& s, unsigned int h)
759 const char* p = s.data();
760 size_t len = s.length();
761 for (; len > 0; --len)
769 // A hash table mapping unnamed types to the backend representation of
772 Type::Type_btypes Type::type_btypes;
774 // Return a tree representing this type.
777 Type::get_backend(Gogo* gogo)
779 if (this->btype_ != NULL)
782 if (this->forward_declaration_type() != NULL
783 || this->named_type() != NULL)
784 return this->get_btype_without_hash(gogo);
786 if (this->is_error_type())
787 return gogo->backend()->error_type();
789 // To avoid confusing the backend, translate all identical Go types
790 // to the same backend representation. We use a hash table to do
791 // that. There is no need to use the hash table for named types, as
792 // named types are only identical to themselves.
794 std::pair<Type*, Btype*> val(this, NULL);
795 std::pair<Type_btypes::iterator, bool> ins =
796 Type::type_btypes.insert(val);
797 if (!ins.second && ins.first->second != NULL)
799 if (gogo != NULL && gogo->named_types_are_converted())
800 this->btype_ = ins.first->second;
801 return ins.first->second;
804 Btype* bt = this->get_btype_without_hash(gogo);
806 if (ins.first->second == NULL)
807 ins.first->second = bt;
810 // We have already created a backend representation for this
811 // type. This can happen when an unnamed type is defined using
812 // a named type which in turns uses an identical unnamed type.
813 // Use the tree we created earlier and ignore the one we just
815 bt = ins.first->second;
816 if (gogo == NULL || !gogo->named_types_are_converted())
824 // Return the backend representation for a type without looking in the
825 // hash table for identical types. This is used for named types,
826 // since a named type is never identical to any other type.
829 Type::get_btype_without_hash(Gogo* gogo)
831 if (this->btype_ == NULL)
833 Btype* bt = this->do_get_backend(gogo);
835 // For a recursive function or pointer type, we will temporarily
836 // return a circular pointer type during the recursion. We
837 // don't want to record that for a forwarding type, as it may
839 if (this->forward_declaration_type() != NULL
840 && gogo->backend()->is_circular_pointer_type(bt))
843 if (gogo == NULL || !gogo->named_types_are_converted())
851 // Return a pointer to the type descriptor for this type.
854 Type::type_descriptor_pointer(Gogo* gogo, Location location)
856 Type* t = this->forwarded();
857 if (t->type_descriptor_var_ == NULL)
859 t->make_type_descriptor_var(gogo);
860 go_assert(t->type_descriptor_var_ != NULL);
862 tree var_tree = var_to_tree(t->type_descriptor_var_);
863 if (var_tree == error_mark_node)
864 return error_mark_node;
865 return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
868 // A mapping from unnamed types to type descriptor variables.
870 Type::Type_descriptor_vars Type::type_descriptor_vars;
872 // Build the type descriptor for this type.
875 Type::make_type_descriptor_var(Gogo* gogo)
877 go_assert(this->type_descriptor_var_ == NULL);
879 Named_type* nt = this->named_type();
881 // We can have multiple instances of unnamed types, but we only want
882 // to emit the type descriptor once. We use a hash table. This is
883 // not necessary for named types, as they are unique, and we store
884 // the type descriptor in the type itself.
885 Bvariable** phash = NULL;
888 Bvariable* bvnull = NULL;
889 std::pair<Type_descriptor_vars::iterator, bool> ins =
890 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
893 // We've already build a type descriptor for this type.
894 this->type_descriptor_var_ = ins.first->second;
897 phash = &ins.first->second;
900 std::string var_name;
902 var_name = this->unnamed_type_descriptor_var_name(gogo);
904 var_name = this->type_descriptor_var_name(gogo);
906 // Build the contents of the type descriptor.
907 Expression* initializer = this->do_type_descriptor(gogo, NULL);
909 Btype* initializer_btype = initializer->type()->get_backend(gogo);
911 // See if this type descriptor is defined in a different package.
912 bool is_defined_elsewhere = false;
915 if (nt->named_object()->package() != NULL)
917 // This is a named type defined in a different package. The
918 // type descriptor should be defined in that package.
919 is_defined_elsewhere = true;
924 if (this->points_to() != NULL
925 && this->points_to()->named_type() != NULL
926 && this->points_to()->named_type()->named_object()->package() != NULL)
928 // This is an unnamed pointer to a named type defined in a
929 // different package. The descriptor should be defined in
931 is_defined_elsewhere = true;
935 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
937 if (is_defined_elsewhere)
939 this->type_descriptor_var_ =
940 gogo->backend()->immutable_struct_reference(var_name,
944 *phash = this->type_descriptor_var_;
948 // See if this type descriptor can appear in multiple packages.
949 bool is_common = false;
952 // We create the descriptor for a builtin type whenever we need
954 is_common = nt->is_builtin();
958 // This is an unnamed type. The descriptor could be defined in
959 // any package where it is needed, and the linker will pick one
960 // descriptor to keep.
964 // We are going to build the type descriptor in this package. We
965 // must create the variable before we convert the initializer to the
966 // backend representation, because the initializer may refer to the
967 // type descriptor of this type. By setting type_descriptor_var_ we
968 // ensure that type_descriptor_pointer will work if called while
969 // converting INITIALIZER.
971 this->type_descriptor_var_ =
972 gogo->backend()->immutable_struct(var_name, is_common, initializer_btype,
975 *phash = this->type_descriptor_var_;
977 Translate_context context(gogo, NULL, NULL, NULL);
978 context.set_is_const();
979 Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
981 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
983 initializer_btype, loc,
987 // Return the name of the type descriptor variable for an unnamed
991 Type::unnamed_type_descriptor_var_name(Gogo* gogo)
993 return "__go_td_" + this->mangled_name(gogo);
996 // Return the name of the type descriptor variable for a named type.
999 Type::type_descriptor_var_name(Gogo* gogo)
1001 Named_type* nt = this->named_type();
1002 Named_object* no = nt->named_object();
1003 const Named_object* in_function = nt->in_function();
1004 std::string ret = "__go_tdn_";
1005 if (nt->is_builtin())
1006 go_assert(in_function == NULL);
1009 const std::string& unique_prefix(no->package() == NULL
1010 ? gogo->unique_prefix()
1011 : no->package()->unique_prefix());
1012 const std::string& package_name(no->package() == NULL
1013 ? gogo->package_name()
1014 : no->package()->name());
1015 ret.append(unique_prefix);
1017 ret.append(package_name);
1019 if (in_function != NULL)
1021 ret.append(Gogo::unpack_hidden_name(in_function->name()));
1025 ret.append(no->name());
1029 // Return a composite literal for a type descriptor.
1032 Type::type_descriptor(Gogo* gogo, Type* type)
1034 return type->do_type_descriptor(gogo, NULL);
1037 // Return a composite literal for a type descriptor with a name.
1040 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1042 go_assert(name != NULL && type->named_type() != name);
1043 return type->do_type_descriptor(gogo, name);
1046 // Make a builtin struct type from a list of fields. The fields are
1047 // pairs of a name and a type.
1050 Type::make_builtin_struct_type(int nfields, ...)
1053 va_start(ap, nfields);
1055 Location bloc = Linemap::predeclared_location();
1056 Struct_field_list* sfl = new Struct_field_list();
1057 for (int i = 0; i < nfields; i++)
1059 const char* field_name = va_arg(ap, const char *);
1060 Type* type = va_arg(ap, Type*);
1061 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1066 return Type::make_struct_type(sfl, bloc);
1069 // A list of builtin named types.
1071 std::vector<Named_type*> Type::named_builtin_types;
1073 // Make a builtin named type.
1076 Type::make_builtin_named_type(const char* name, Type* type)
1078 Location bloc = Linemap::predeclared_location();
1079 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1080 Named_type* ret = no->type_value();
1081 Type::named_builtin_types.push_back(ret);
1085 // Convert the named builtin types.
1088 Type::convert_builtin_named_types(Gogo* gogo)
1090 for (std::vector<Named_type*>::const_iterator p =
1091 Type::named_builtin_types.begin();
1092 p != Type::named_builtin_types.end();
1095 bool r = (*p)->verify();
1097 (*p)->convert(gogo);
1101 // Return the type of a type descriptor. We should really tie this to
1102 // runtime.Type rather than copying it. This must match commonType in
1103 // libgo/go/runtime/type.go.
1106 Type::make_type_descriptor_type()
1111 Location bloc = Linemap::predeclared_location();
1113 Type* uint8_type = Type::lookup_integer_type("uint8");
1114 Type* uint32_type = Type::lookup_integer_type("uint32");
1115 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1116 Type* string_type = Type::lookup_string_type();
1117 Type* pointer_string_type = Type::make_pointer_type(string_type);
1119 // This is an unnamed version of unsafe.Pointer. Perhaps we
1120 // should use the named version instead, although that would
1121 // require us to create the unsafe package if it has not been
1122 // imported. It probably doesn't matter.
1123 Type* void_type = Type::make_void_type();
1124 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1126 // Forward declaration for the type descriptor type.
1127 Named_object* named_type_descriptor_type =
1128 Named_object::make_type_declaration("commonType", NULL, bloc);
1129 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1130 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1132 // The type of a method on a concrete type.
1133 Struct_type* method_type =
1134 Type::make_builtin_struct_type(5,
1135 "name", pointer_string_type,
1136 "pkgPath", pointer_string_type,
1137 "mtyp", pointer_type_descriptor_type,
1138 "typ", pointer_type_descriptor_type,
1139 "tfn", unsafe_pointer_type);
1140 Named_type* named_method_type =
1141 Type::make_builtin_named_type("method", method_type);
1143 // Information for types with a name or methods.
1144 Type* slice_named_method_type =
1145 Type::make_array_type(named_method_type, NULL);
1146 Struct_type* uncommon_type =
1147 Type::make_builtin_struct_type(3,
1148 "name", pointer_string_type,
1149 "pkgPath", pointer_string_type,
1150 "methods", slice_named_method_type);
1151 Named_type* named_uncommon_type =
1152 Type::make_builtin_named_type("uncommonType", uncommon_type);
1154 Type* pointer_uncommon_type =
1155 Type::make_pointer_type(named_uncommon_type);
1157 // The type descriptor type.
1159 Typed_identifier_list* params = new Typed_identifier_list();
1160 params->push_back(Typed_identifier("", unsafe_pointer_type, bloc));
1161 params->push_back(Typed_identifier("", uintptr_type, bloc));
1163 Typed_identifier_list* results = new Typed_identifier_list();
1164 results->push_back(Typed_identifier("", uintptr_type, bloc));
1166 Type* hashfn_type = Type::make_function_type(NULL, params, results, bloc);
1168 params = new Typed_identifier_list();
1169 params->push_back(Typed_identifier("", unsafe_pointer_type, bloc));
1170 params->push_back(Typed_identifier("", unsafe_pointer_type, bloc));
1171 params->push_back(Typed_identifier("", uintptr_type, bloc));
1173 results = new Typed_identifier_list();
1174 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1176 Type* equalfn_type = Type::make_function_type(NULL, params, results,
1179 Struct_type* type_descriptor_type =
1180 Type::make_builtin_struct_type(10,
1182 "align", uint8_type,
1183 "fieldAlign", uint8_type,
1184 "size", uintptr_type,
1185 "hash", uint32_type,
1186 "hashfn", hashfn_type,
1187 "equalfn", equalfn_type,
1188 "string", pointer_string_type,
1189 "", pointer_uncommon_type,
1191 pointer_type_descriptor_type);
1193 Named_type* named = Type::make_builtin_named_type("commonType",
1194 type_descriptor_type);
1196 named_type_descriptor_type->set_type_value(named);
1204 // Make the type of a pointer to a type descriptor as represented in
1208 Type::make_type_descriptor_ptr_type()
1212 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1216 // Return the names of runtime functions which compute a hash code for
1217 // this type and which compare whether two values of this type are
1221 Type::type_functions(const char** hash_fn, const char** equal_fn) const
1223 switch (this->base()->classification())
1225 case Type::TYPE_ERROR:
1226 case Type::TYPE_VOID:
1227 case Type::TYPE_NIL:
1228 // These types can not be hashed or compared.
1229 *hash_fn = "__go_type_hash_error";
1230 *equal_fn = "__go_type_equal_error";
1233 case Type::TYPE_BOOLEAN:
1234 case Type::TYPE_INTEGER:
1235 case Type::TYPE_FLOAT:
1236 case Type::TYPE_COMPLEX:
1237 case Type::TYPE_POINTER:
1238 case Type::TYPE_FUNCTION:
1239 case Type::TYPE_MAP:
1240 case Type::TYPE_CHANNEL:
1241 *hash_fn = "__go_type_hash_identity";
1242 *equal_fn = "__go_type_equal_identity";
1245 case Type::TYPE_STRING:
1246 *hash_fn = "__go_type_hash_string";
1247 *equal_fn = "__go_type_equal_string";
1250 case Type::TYPE_STRUCT:
1251 case Type::TYPE_ARRAY:
1252 // These types can not be hashed or compared.
1253 *hash_fn = "__go_type_hash_error";
1254 *equal_fn = "__go_type_equal_error";
1257 case Type::TYPE_INTERFACE:
1258 if (this->interface_type()->is_empty())
1260 *hash_fn = "__go_type_hash_empty_interface";
1261 *equal_fn = "__go_type_equal_empty_interface";
1265 *hash_fn = "__go_type_hash_interface";
1266 *equal_fn = "__go_type_equal_interface";
1270 case Type::TYPE_NAMED:
1271 case Type::TYPE_FORWARD:
1279 // Return a composite literal for the type descriptor for a plain type
1280 // of kind RUNTIME_TYPE_KIND named NAME.
1283 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
1284 Named_type* name, const Methods* methods,
1285 bool only_value_methods)
1287 Location bloc = Linemap::predeclared_location();
1289 Type* td_type = Type::make_type_descriptor_type();
1290 const Struct_field_list* fields = td_type->struct_type()->fields();
1292 Expression_list* vals = new Expression_list();
1295 if (!this->has_pointer())
1296 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
1297 Struct_field_list::const_iterator p = fields->begin();
1298 go_assert(p->is_field_name("Kind"));
1300 mpz_init_set_ui(iv, runtime_type_kind);
1301 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1304 go_assert(p->is_field_name("align"));
1305 Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT;
1306 vals->push_back(Expression::make_type_info(this, type_info));
1309 go_assert(p->is_field_name("fieldAlign"));
1310 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
1311 vals->push_back(Expression::make_type_info(this, type_info));
1314 go_assert(p->is_field_name("size"));
1315 type_info = Expression::TYPE_INFO_SIZE;
1316 vals->push_back(Expression::make_type_info(this, type_info));
1319 go_assert(p->is_field_name("hash"));
1320 mpz_set_ui(iv, this->hash_for_method(gogo));
1321 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1323 const char* hash_fn;
1324 const char* equal_fn;
1325 this->type_functions(&hash_fn, &equal_fn);
1328 go_assert(p->is_field_name("hashfn"));
1329 Function_type* fntype = p->type()->function_type();
1330 Named_object* no = Named_object::make_function_declaration(hash_fn, NULL,
1333 no->func_declaration_value()->set_asm_name(hash_fn);
1334 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
1337 go_assert(p->is_field_name("equalfn"));
1338 fntype = p->type()->function_type();
1339 no = Named_object::make_function_declaration(equal_fn, NULL, fntype, bloc);
1340 no->func_declaration_value()->set_asm_name(equal_fn);
1341 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
1344 go_assert(p->is_field_name("string"));
1345 Expression* s = Expression::make_string((name != NULL
1346 ? name->reflection(gogo)
1347 : this->reflection(gogo)),
1349 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1352 go_assert(p->is_field_name("uncommonType"));
1353 if (name == NULL && methods == NULL)
1354 vals->push_back(Expression::make_nil(bloc));
1357 if (methods == NULL)
1358 methods = name->methods();
1359 vals->push_back(this->uncommon_type_constructor(gogo,
1362 only_value_methods));
1366 go_assert(p->is_field_name("ptrToThis"));
1368 vals->push_back(Expression::make_nil(bloc));
1371 Type* pt = Type::make_pointer_type(name);
1372 vals->push_back(Expression::make_type_descriptor(pt, bloc));
1376 go_assert(p == fields->end());
1380 return Expression::make_struct_composite_literal(td_type, vals, bloc);
1383 // Return a composite literal for the uncommon type information for
1384 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
1385 // struct. If name is not NULL, it is the name of the type. If
1386 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
1387 // is true if only value methods should be included. At least one of
1388 // NAME and METHODS must not be NULL.
1391 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
1392 Named_type* name, const Methods* methods,
1393 bool only_value_methods) const
1395 Location bloc = Linemap::predeclared_location();
1397 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
1399 Expression_list* vals = new Expression_list();
1402 Struct_field_list::const_iterator p = fields->begin();
1403 go_assert(p->is_field_name("name"));
1406 go_assert(p->is_field_name("pkgPath"));
1410 vals->push_back(Expression::make_nil(bloc));
1411 vals->push_back(Expression::make_nil(bloc));
1415 Named_object* no = name->named_object();
1416 std::string n = Gogo::unpack_hidden_name(no->name());
1417 Expression* s = Expression::make_string(n, bloc);
1418 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1420 if (name->is_builtin())
1421 vals->push_back(Expression::make_nil(bloc));
1424 const Package* package = no->package();
1425 const std::string& unique_prefix(package == NULL
1426 ? gogo->unique_prefix()
1427 : package->unique_prefix());
1428 const std::string& package_name(package == NULL
1429 ? gogo->package_name()
1431 n.assign(unique_prefix);
1433 n.append(package_name);
1434 if (name->in_function() != NULL)
1437 n.append(Gogo::unpack_hidden_name(name->in_function()->name()));
1439 s = Expression::make_string(n, bloc);
1440 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1445 go_assert(p->is_field_name("methods"));
1446 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
1447 only_value_methods));
1450 go_assert(p == fields->end());
1452 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
1454 return Expression::make_unary(OPERATOR_AND, r, bloc);
1457 // Sort methods by name.
1463 operator()(const std::pair<std::string, const Method*>& m1,
1464 const std::pair<std::string, const Method*>& m2) const
1465 { return m1.first < m2.first; }
1468 // Return a composite literal for the type method table for this type.
1469 // METHODS_TYPE is the type of the table, and is a slice type.
1470 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
1471 // then only value methods are used.
1474 Type::methods_constructor(Gogo* gogo, Type* methods_type,
1475 const Methods* methods,
1476 bool only_value_methods) const
1478 Location bloc = Linemap::predeclared_location();
1480 std::vector<std::pair<std::string, const Method*> > smethods;
1481 if (methods != NULL)
1483 smethods.reserve(methods->count());
1484 for (Methods::const_iterator p = methods->begin();
1485 p != methods->end();
1488 if (p->second->is_ambiguous())
1490 if (only_value_methods && !p->second->is_value_method())
1492 smethods.push_back(std::make_pair(p->first, p->second));
1496 if (smethods.empty())
1497 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
1499 std::sort(smethods.begin(), smethods.end(), Sort_methods());
1501 Type* method_type = methods_type->array_type()->element_type();
1503 Expression_list* vals = new Expression_list();
1504 vals->reserve(smethods.size());
1505 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
1507 p != smethods.end();
1509 vals->push_back(this->method_constructor(gogo, method_type, p->first,
1510 p->second, only_value_methods));
1512 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
1515 // Return a composite literal for a single method. METHOD_TYPE is the
1516 // type of the entry. METHOD_NAME is the name of the method and M is
1517 // the method information.
1520 Type::method_constructor(Gogo*, Type* method_type,
1521 const std::string& method_name,
1523 bool only_value_methods) const
1525 Location bloc = Linemap::predeclared_location();
1527 const Struct_field_list* fields = method_type->struct_type()->fields();
1529 Expression_list* vals = new Expression_list();
1532 Struct_field_list::const_iterator p = fields->begin();
1533 go_assert(p->is_field_name("name"));
1534 const std::string n = Gogo::unpack_hidden_name(method_name);
1535 Expression* s = Expression::make_string(n, bloc);
1536 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1539 go_assert(p->is_field_name("pkgPath"));
1540 if (!Gogo::is_hidden_name(method_name))
1541 vals->push_back(Expression::make_nil(bloc));
1544 s = Expression::make_string(Gogo::hidden_name_prefix(method_name), bloc);
1545 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1548 Named_object* no = (m->needs_stub_method()
1550 : m->named_object());
1552 Function_type* mtype;
1553 if (no->is_function())
1554 mtype = no->func_value()->type();
1556 mtype = no->func_declaration_value()->type();
1557 go_assert(mtype->is_method());
1558 Type* nonmethod_type = mtype->copy_without_receiver();
1561 go_assert(p->is_field_name("mtyp"));
1562 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
1565 go_assert(p->is_field_name("typ"));
1566 if (!only_value_methods && m->is_value_method())
1568 // This is a value method on a pointer type. Change the type of
1569 // the method to use a pointer receiver. The implementation
1570 // always uses a pointer receiver anyhow.
1571 Type* rtype = mtype->receiver()->type();
1572 Type* prtype = Type::make_pointer_type(rtype);
1573 Typed_identifier* receiver =
1574 new Typed_identifier(mtype->receiver()->name(), prtype,
1575 mtype->receiver()->location());
1576 mtype = Type::make_function_type(receiver,
1577 (mtype->parameters() == NULL
1579 : mtype->parameters()->copy()),
1580 (mtype->results() == NULL
1582 : mtype->results()->copy()),
1585 vals->push_back(Expression::make_type_descriptor(mtype, bloc));
1588 go_assert(p->is_field_name("tfn"));
1589 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
1592 go_assert(p == fields->end());
1594 return Expression::make_struct_composite_literal(method_type, vals, bloc);
1597 // Return a composite literal for the type descriptor of a plain type.
1598 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
1599 // NULL, it is the name to use as well as the list of methods.
1602 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
1605 return this->type_descriptor_constructor(gogo, runtime_type_kind,
1609 // Return the type reflection string for this type.
1612 Type::reflection(Gogo* gogo) const
1616 // The do_reflection virtual function should set RET to the
1617 // reflection string.
1618 this->do_reflection(gogo, &ret);
1623 // Return a mangled name for the type.
1626 Type::mangled_name(Gogo* gogo) const
1630 // The do_mangled_name virtual function should set RET to the
1631 // mangled name. For a composite type it should append a code for
1632 // the composition and then call do_mangled_name on the components.
1633 this->do_mangled_name(gogo, &ret);
1638 // Default function to export a type.
1641 Type::do_export(Export*) const
1649 Type::import_type(Import* imp)
1651 if (imp->match_c_string("("))
1652 return Function_type::do_import(imp);
1653 else if (imp->match_c_string("*"))
1654 return Pointer_type::do_import(imp);
1655 else if (imp->match_c_string("struct "))
1656 return Struct_type::do_import(imp);
1657 else if (imp->match_c_string("["))
1658 return Array_type::do_import(imp);
1659 else if (imp->match_c_string("map "))
1660 return Map_type::do_import(imp);
1661 else if (imp->match_c_string("chan "))
1662 return Channel_type::do_import(imp);
1663 else if (imp->match_c_string("interface"))
1664 return Interface_type::do_import(imp);
1667 error_at(imp->location(), "import error: expected type");
1668 return Type::make_error_type();
1672 // A type used to indicate a parsing error. This exists to simplify
1673 // later error detection.
1675 class Error_type : public Type
1684 do_get_backend(Gogo* gogo)
1685 { return gogo->backend()->error_type(); }
1688 do_type_descriptor(Gogo*, Named_type*)
1689 { return Expression::make_error(Linemap::predeclared_location()); }
1692 do_reflection(Gogo*, std::string*) const
1693 { go_assert(saw_errors()); }
1696 do_mangled_name(Gogo*, std::string* ret) const
1697 { ret->push_back('E'); }
1701 Type::make_error_type()
1703 static Error_type singleton_error_type;
1704 return &singleton_error_type;
1709 class Void_type : public Type
1718 do_get_backend(Gogo* gogo)
1719 { return gogo->backend()->void_type(); }
1722 do_type_descriptor(Gogo*, Named_type*)
1723 { go_unreachable(); }
1726 do_reflection(Gogo*, std::string*) const
1730 do_mangled_name(Gogo*, std::string* ret) const
1731 { ret->push_back('v'); }
1735 Type::make_void_type()
1737 static Void_type singleton_void_type;
1738 return &singleton_void_type;
1741 // The boolean type.
1743 class Boolean_type : public Type
1747 : Type(TYPE_BOOLEAN)
1752 do_get_backend(Gogo* gogo)
1753 { return gogo->backend()->bool_type(); }
1756 do_type_descriptor(Gogo*, Named_type* name);
1758 // We should not be asked for the reflection string of a basic type.
1760 do_reflection(Gogo*, std::string* ret) const
1761 { ret->append("bool"); }
1764 do_mangled_name(Gogo*, std::string* ret) const
1765 { ret->push_back('b'); }
1768 // Make the type descriptor.
1771 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
1774 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
1777 Named_object* no = gogo->lookup_global("bool");
1778 go_assert(no != NULL);
1779 return Type::type_descriptor(gogo, no->type_value());
1784 Type::make_boolean_type()
1786 static Boolean_type boolean_type;
1787 return &boolean_type;
1790 // The named type "bool".
1792 static Named_type* named_bool_type;
1794 // Get the named type "bool".
1797 Type::lookup_bool_type()
1799 return named_bool_type;
1802 // Make the named type "bool".
1805 Type::make_named_bool_type()
1807 Type* bool_type = Type::make_boolean_type();
1808 Named_object* named_object =
1809 Named_object::make_type("bool", NULL, bool_type,
1810 Linemap::predeclared_location());
1811 Named_type* named_type = named_object->type_value();
1812 named_bool_type = named_type;
1816 // Class Integer_type.
1818 Integer_type::Named_integer_types Integer_type::named_integer_types;
1820 // Create a new integer type. Non-abstract integer types always have
1824 Integer_type::create_integer_type(const char* name, bool is_unsigned,
1825 int bits, int runtime_type_kind)
1827 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
1829 std::string sname(name);
1830 Named_object* named_object =
1831 Named_object::make_type(sname, NULL, integer_type,
1832 Linemap::predeclared_location());
1833 Named_type* named_type = named_object->type_value();
1834 std::pair<Named_integer_types::iterator, bool> ins =
1835 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
1836 go_assert(ins.second);
1840 // Look up an existing integer type.
1843 Integer_type::lookup_integer_type(const char* name)
1845 Named_integer_types::const_iterator p =
1846 Integer_type::named_integer_types.find(name);
1847 go_assert(p != Integer_type::named_integer_types.end());
1851 // Create a new abstract integer type.
1854 Integer_type::create_abstract_integer_type()
1856 static Integer_type* abstract_type;
1857 if (abstract_type == NULL)
1858 abstract_type = new Integer_type(true, false, INT_TYPE_SIZE,
1859 RUNTIME_TYPE_KIND_INT);
1860 return abstract_type;
1863 // Integer type compatibility.
1866 Integer_type::is_identical(const Integer_type* t) const
1868 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
1870 return this->is_abstract_ == t->is_abstract_;
1876 Integer_type::do_hash_for_method(Gogo*) const
1878 return ((this->bits_ << 4)
1879 + ((this->is_unsigned_ ? 1 : 0) << 8)
1880 + ((this->is_abstract_ ? 1 : 0) << 9));
1883 // Convert an Integer_type to the backend representation.
1886 Integer_type::do_get_backend(Gogo* gogo)
1888 if (this->is_abstract_)
1890 go_assert(saw_errors());
1891 return gogo->backend()->error_type();
1893 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
1896 // The type descriptor for an integer type. Integer types are always
1900 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
1902 go_assert(name != NULL);
1903 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
1906 // We should not be asked for the reflection string of a basic type.
1909 Integer_type::do_reflection(Gogo*, std::string*) const
1911 go_assert(saw_errors());
1917 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
1920 snprintf(buf, sizeof buf, "i%s%s%de",
1921 this->is_abstract_ ? "a" : "",
1922 this->is_unsigned_ ? "u" : "",
1927 // Make an integer type.
1930 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
1931 int runtime_type_kind)
1933 return Integer_type::create_integer_type(name, is_unsigned, bits,
1937 // Make an abstract integer type.
1940 Type::make_abstract_integer_type()
1942 return Integer_type::create_abstract_integer_type();
1945 // Look up an integer type.
1948 Type::lookup_integer_type(const char* name)
1950 return Integer_type::lookup_integer_type(name);
1953 // Class Float_type.
1955 Float_type::Named_float_types Float_type::named_float_types;
1957 // Create a new float type. Non-abstract float types always have
1961 Float_type::create_float_type(const char* name, int bits,
1962 int runtime_type_kind)
1964 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
1965 std::string sname(name);
1966 Named_object* named_object =
1967 Named_object::make_type(sname, NULL, float_type,
1968 Linemap::predeclared_location());
1969 Named_type* named_type = named_object->type_value();
1970 std::pair<Named_float_types::iterator, bool> ins =
1971 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
1972 go_assert(ins.second);
1976 // Look up an existing float type.
1979 Float_type::lookup_float_type(const char* name)
1981 Named_float_types::const_iterator p =
1982 Float_type::named_float_types.find(name);
1983 go_assert(p != Float_type::named_float_types.end());
1987 // Create a new abstract float type.
1990 Float_type::create_abstract_float_type()
1992 static Float_type* abstract_type;
1993 if (abstract_type == NULL)
1994 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
1995 return abstract_type;
1998 // Whether this type is identical with T.
2001 Float_type::is_identical(const Float_type* t) const
2003 if (this->bits_ != t->bits_)
2005 return this->is_abstract_ == t->is_abstract_;
2011 Float_type::do_hash_for_method(Gogo*) const
2013 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2016 // Convert to the backend representation.
2019 Float_type::do_get_backend(Gogo* gogo)
2021 return gogo->backend()->float_type(this->bits_);
2024 // The type descriptor for a float type. Float types are always named.
2027 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2029 go_assert(name != NULL);
2030 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2033 // We should not be asked for the reflection string of a basic type.
2036 Float_type::do_reflection(Gogo*, std::string*) const
2038 go_assert(saw_errors());
2044 Float_type::do_mangled_name(Gogo*, std::string* ret) const
2047 snprintf(buf, sizeof buf, "f%s%de",
2048 this->is_abstract_ ? "a" : "",
2053 // Make a floating point type.
2056 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
2058 return Float_type::create_float_type(name, bits, runtime_type_kind);
2061 // Make an abstract float type.
2064 Type::make_abstract_float_type()
2066 return Float_type::create_abstract_float_type();
2069 // Look up a float type.
2072 Type::lookup_float_type(const char* name)
2074 return Float_type::lookup_float_type(name);
2077 // Class Complex_type.
2079 Complex_type::Named_complex_types Complex_type::named_complex_types;
2081 // Create a new complex type. Non-abstract complex types always have
2085 Complex_type::create_complex_type(const char* name, int bits,
2086 int runtime_type_kind)
2088 Complex_type* complex_type = new Complex_type(false, bits,
2090 std::string sname(name);
2091 Named_object* named_object =
2092 Named_object::make_type(sname, NULL, complex_type,
2093 Linemap::predeclared_location());
2094 Named_type* named_type = named_object->type_value();
2095 std::pair<Named_complex_types::iterator, bool> ins =
2096 Complex_type::named_complex_types.insert(std::make_pair(sname,
2098 go_assert(ins.second);
2102 // Look up an existing complex type.
2105 Complex_type::lookup_complex_type(const char* name)
2107 Named_complex_types::const_iterator p =
2108 Complex_type::named_complex_types.find(name);
2109 go_assert(p != Complex_type::named_complex_types.end());
2113 // Create a new abstract complex type.
2116 Complex_type::create_abstract_complex_type()
2118 static Complex_type* abstract_type;
2119 if (abstract_type == NULL)
2120 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
2121 return abstract_type;
2124 // Whether this type is identical with T.
2127 Complex_type::is_identical(const Complex_type *t) const
2129 if (this->bits_ != t->bits_)
2131 return this->is_abstract_ == t->is_abstract_;
2137 Complex_type::do_hash_for_method(Gogo*) const
2139 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2142 // Convert to the backend representation.
2145 Complex_type::do_get_backend(Gogo* gogo)
2147 return gogo->backend()->complex_type(this->bits_);
2150 // The type descriptor for a complex type. Complex types are always
2154 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2156 go_assert(name != NULL);
2157 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2160 // We should not be asked for the reflection string of a basic type.
2163 Complex_type::do_reflection(Gogo*, std::string*) const
2165 go_assert(saw_errors());
2171 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
2174 snprintf(buf, sizeof buf, "c%s%de",
2175 this->is_abstract_ ? "a" : "",
2180 // Make a complex type.
2183 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
2185 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
2188 // Make an abstract complex type.
2191 Type::make_abstract_complex_type()
2193 return Complex_type::create_abstract_complex_type();
2196 // Look up a complex type.
2199 Type::lookup_complex_type(const char* name)
2201 return Complex_type::lookup_complex_type(name);
2204 // Class String_type.
2206 // Convert String_type to the backend representation. A string is a
2207 // struct with two fields: a pointer to the characters and a length.
2210 String_type::do_get_backend(Gogo* gogo)
2212 static Btype* backend_string_type;
2213 if (backend_string_type == NULL)
2215 std::vector<Backend::Btyped_identifier> fields(2);
2217 Type* b = gogo->lookup_global("byte")->type_value();
2218 Type* pb = Type::make_pointer_type(b);
2219 fields[0].name = "__data";
2220 fields[0].btype = pb->get_backend(gogo);
2221 fields[0].location = Linemap::predeclared_location();
2223 Type* int_type = Type::lookup_integer_type("int");
2224 fields[1].name = "__length";
2225 fields[1].btype = int_type->get_backend(gogo);
2226 fields[1].location = fields[0].location;
2228 backend_string_type = gogo->backend()->struct_type(fields);
2230 return backend_string_type;
2233 // Return a tree for the length of STRING.
2236 String_type::length_tree(Gogo*, tree string)
2238 tree string_type = TREE_TYPE(string);
2239 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2240 tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type));
2241 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)),
2243 return fold_build3(COMPONENT_REF, integer_type_node, string,
2244 length_field, NULL_TREE);
2247 // Return a tree for a pointer to the bytes of STRING.
2250 String_type::bytes_tree(Gogo*, tree string)
2252 tree string_type = TREE_TYPE(string);
2253 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2254 tree bytes_field = TYPE_FIELDS(string_type);
2255 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)),
2257 return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string,
2258 bytes_field, NULL_TREE);
2261 // The type descriptor for the string type.
2264 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2267 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
2270 Named_object* no = gogo->lookup_global("string");
2271 go_assert(no != NULL);
2272 return Type::type_descriptor(gogo, no->type_value());
2276 // We should not be asked for the reflection string of a basic type.
2279 String_type::do_reflection(Gogo*, std::string* ret) const
2281 ret->append("string");
2284 // Mangled name of a string type.
2287 String_type::do_mangled_name(Gogo*, std::string* ret) const
2289 ret->push_back('z');
2292 // Make a string type.
2295 Type::make_string_type()
2297 static String_type string_type;
2298 return &string_type;
2301 // The named type "string".
2303 static Named_type* named_string_type;
2305 // Get the named type "string".
2308 Type::lookup_string_type()
2310 return named_string_type;
2313 // Make the named type string.
2316 Type::make_named_string_type()
2318 Type* string_type = Type::make_string_type();
2319 Named_object* named_object =
2320 Named_object::make_type("string", NULL, string_type,
2321 Linemap::predeclared_location());
2322 Named_type* named_type = named_object->type_value();
2323 named_string_type = named_type;
2327 // The sink type. This is the type of the blank identifier _. Any
2328 // type may be assigned to it.
2330 class Sink_type : public Type
2339 do_get_backend(Gogo*)
2340 { go_unreachable(); }
2343 do_type_descriptor(Gogo*, Named_type*)
2344 { go_unreachable(); }
2347 do_reflection(Gogo*, std::string*) const
2348 { go_unreachable(); }
2351 do_mangled_name(Gogo*, std::string*) const
2352 { go_unreachable(); }
2355 // Make the sink type.
2358 Type::make_sink_type()
2360 static Sink_type sink_type;
2364 // Class Function_type.
2369 Function_type::do_traverse(Traverse* traverse)
2371 if (this->receiver_ != NULL
2372 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
2373 return TRAVERSE_EXIT;
2374 if (this->parameters_ != NULL
2375 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
2376 return TRAVERSE_EXIT;
2377 if (this->results_ != NULL
2378 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
2379 return TRAVERSE_EXIT;
2380 return TRAVERSE_CONTINUE;
2383 // Returns whether T is a valid redeclaration of this type. If this
2384 // returns false, and REASON is not NULL, *REASON may be set to a
2385 // brief explanation of why it returned false.
2388 Function_type::is_valid_redeclaration(const Function_type* t,
2389 std::string* reason) const
2391 if (!this->is_identical(t, false, true, reason))
2394 // A redeclaration of a function is required to use the same names
2395 // for the receiver and parameters.
2396 if (this->receiver() != NULL
2397 && this->receiver()->name() != t->receiver()->name()
2398 && this->receiver()->name() != Import::import_marker
2399 && t->receiver()->name() != Import::import_marker)
2402 *reason = "receiver name changed";
2406 const Typed_identifier_list* parms1 = this->parameters();
2407 const Typed_identifier_list* parms2 = t->parameters();
2410 Typed_identifier_list::const_iterator p1 = parms1->begin();
2411 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
2412 p2 != parms2->end();
2415 if (p1->name() != p2->name()
2416 && p1->name() != Import::import_marker
2417 && p2->name() != Import::import_marker)
2420 *reason = "parameter name changed";
2424 // This is called at parse time, so we may have unknown
2426 Type* t1 = p1->type()->forwarded();
2427 Type* t2 = p2->type()->forwarded();
2429 && t1->forward_declaration_type() != NULL
2430 && (t2->forward_declaration_type() == NULL
2431 || (t1->forward_declaration_type()->named_object()
2432 != t2->forward_declaration_type()->named_object())))
2437 const Typed_identifier_list* results1 = this->results();
2438 const Typed_identifier_list* results2 = t->results();
2439 if (results1 != NULL)
2441 Typed_identifier_list::const_iterator res1 = results1->begin();
2442 for (Typed_identifier_list::const_iterator res2 = results2->begin();
2443 res2 != results2->end();
2446 if (res1->name() != res2->name()
2447 && res1->name() != Import::import_marker
2448 && res2->name() != Import::import_marker)
2451 *reason = "result name changed";
2455 // This is called at parse time, so we may have unknown
2457 Type* t1 = res1->type()->forwarded();
2458 Type* t2 = res2->type()->forwarded();
2460 && t1->forward_declaration_type() != NULL
2461 && (t2->forward_declaration_type() == NULL
2462 || (t1->forward_declaration_type()->named_object()
2463 != t2->forward_declaration_type()->named_object())))
2471 // Check whether T is the same as this type.
2474 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
2475 bool errors_are_identical,
2476 std::string* reason) const
2478 if (!ignore_receiver)
2480 const Typed_identifier* r1 = this->receiver();
2481 const Typed_identifier* r2 = t->receiver();
2482 if ((r1 != NULL) != (r2 != NULL))
2485 *reason = _("different receiver types");
2490 if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
2493 if (reason != NULL && !reason->empty())
2494 *reason = "receiver: " + *reason;
2500 const Typed_identifier_list* parms1 = this->parameters();
2501 const Typed_identifier_list* parms2 = t->parameters();
2502 if ((parms1 != NULL) != (parms2 != NULL))
2505 *reason = _("different number of parameters");
2510 Typed_identifier_list::const_iterator p1 = parms1->begin();
2511 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
2512 p2 != parms2->end();
2515 if (p1 == parms1->end())
2518 *reason = _("different number of parameters");
2522 if (!Type::are_identical(p1->type(), p2->type(),
2523 errors_are_identical, NULL))
2526 *reason = _("different parameter types");
2530 if (p1 != parms1->end())
2533 *reason = _("different number of parameters");
2538 if (this->is_varargs() != t->is_varargs())
2541 *reason = _("different varargs");
2545 const Typed_identifier_list* results1 = this->results();
2546 const Typed_identifier_list* results2 = t->results();
2547 if ((results1 != NULL) != (results2 != NULL))
2550 *reason = _("different number of results");
2553 if (results1 != NULL)
2555 Typed_identifier_list::const_iterator res1 = results1->begin();
2556 for (Typed_identifier_list::const_iterator res2 = results2->begin();
2557 res2 != results2->end();
2560 if (res1 == results1->end())
2563 *reason = _("different number of results");
2567 if (!Type::are_identical(res1->type(), res2->type(),
2568 errors_are_identical, NULL))
2571 *reason = _("different result types");
2575 if (res1 != results1->end())
2578 *reason = _("different number of results");
2589 Function_type::do_hash_for_method(Gogo* gogo) const
2591 unsigned int ret = 0;
2592 // We ignore the receiver type for hash codes, because we need to
2593 // get the same hash code for a method in an interface and a method
2594 // declared for a type. The former will not have a receiver.
2595 if (this->parameters_ != NULL)
2598 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
2599 p != this->parameters_->end();
2601 ret += p->type()->hash_for_method(gogo) << shift;
2603 if (this->results_ != NULL)
2606 for (Typed_identifier_list::const_iterator p = this->results_->begin();
2607 p != this->results_->end();
2609 ret += p->type()->hash_for_method(gogo) << shift;
2611 if (this->is_varargs_)
2617 // Get the backend representation for a function type.
2620 Function_type::get_function_backend(Gogo* gogo)
2622 Backend::Btyped_identifier breceiver;
2623 if (this->receiver_ != NULL)
2625 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
2627 // We always pass the address of the receiver parameter, in
2628 // order to make interface calls work with unknown types.
2629 Type* rtype = this->receiver_->type();
2630 if (rtype->points_to() == NULL)
2631 rtype = Type::make_pointer_type(rtype);
2632 breceiver.btype = rtype->get_backend(gogo);
2633 breceiver.location = this->receiver_->location();
2636 std::vector<Backend::Btyped_identifier> bparameters;
2637 if (this->parameters_ != NULL)
2639 bparameters.resize(this->parameters_->size());
2641 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
2642 p != this->parameters_->end();
2645 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
2646 bparameters[i].btype = p->type()->get_backend(gogo);
2647 bparameters[i].location = p->location();
2649 go_assert(i == bparameters.size());
2652 std::vector<Backend::Btyped_identifier> bresults;
2653 if (this->results_ != NULL)
2655 bresults.resize(this->results_->size());
2657 for (Typed_identifier_list::const_iterator p = this->results_->begin();
2658 p != this->results_->end();
2661 bresults[i].name = Gogo::unpack_hidden_name(p->name());
2662 bresults[i].btype = p->type()->get_backend(gogo);
2663 bresults[i].location = p->location();
2665 go_assert(i == bresults.size());
2668 return gogo->backend()->function_type(breceiver, bparameters, bresults,
2672 // A hash table mapping function types to their backend placeholders.
2674 Function_type::Placeholders Function_type::placeholders;
2676 // Get the backend representation for a function type. If we are
2677 // still converting types, and this types has multiple results, return
2678 // a placeholder instead. We do this because for multiple results we
2679 // build a struct, and we need to make sure that all the types in the
2680 // struct are valid before we create the struct.
2683 Function_type::do_get_backend(Gogo* gogo)
2685 if (!gogo->named_types_are_converted()
2686 && this->results_ != NULL
2687 && this->results_->size() > 1)
2689 Btype* placeholder =
2690 gogo->backend()->placeholder_pointer_type("", this->location(), true);
2691 Function_type::placeholders.push_back(std::make_pair(this, placeholder));
2694 return this->get_function_backend(gogo);
2697 // Convert function types after all named types are converted.
2700 Function_type::convert_types(Gogo* gogo)
2702 for (Placeholders::const_iterator p = Function_type::placeholders.begin();
2703 p != Function_type::placeholders.end();
2706 Btype* bt = p->first->get_function_backend(gogo);
2707 if (!gogo->backend()->set_placeholder_function_type(p->second, bt))
2708 go_assert(saw_errors());
2712 // The type of a function type descriptor.
2715 Function_type::make_function_type_descriptor_type()
2720 Type* tdt = Type::make_type_descriptor_type();
2721 Type* ptdt = Type::make_type_descriptor_ptr_type();
2723 Type* bool_type = Type::lookup_bool_type();
2725 Type* slice_type = Type::make_array_type(ptdt, NULL);
2727 Struct_type* s = Type::make_builtin_struct_type(4,
2729 "dotdotdot", bool_type,
2733 ret = Type::make_builtin_named_type("FuncType", s);
2739 // The type descriptor for a function type.
2742 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2744 Location bloc = Linemap::predeclared_location();
2746 Type* ftdt = Function_type::make_function_type_descriptor_type();
2748 const Struct_field_list* fields = ftdt->struct_type()->fields();
2750 Expression_list* vals = new Expression_list();
2753 Struct_field_list::const_iterator p = fields->begin();
2754 go_assert(p->is_field_name("commonType"));
2755 vals->push_back(this->type_descriptor_constructor(gogo,
2756 RUNTIME_TYPE_KIND_FUNC,
2760 go_assert(p->is_field_name("dotdotdot"));
2761 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
2764 go_assert(p->is_field_name("in"));
2765 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
2766 this->parameters()));
2769 go_assert(p->is_field_name("out"));
2770 vals->push_back(this->type_descriptor_params(p->type(), NULL,
2774 go_assert(p == fields->end());
2776 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
2779 // Return a composite literal for the parameters or results of a type
2783 Function_type::type_descriptor_params(Type* params_type,
2784 const Typed_identifier* receiver,
2785 const Typed_identifier_list* params)
2787 Location bloc = Linemap::predeclared_location();
2789 if (receiver == NULL && params == NULL)
2790 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
2792 Expression_list* vals = new Expression_list();
2793 vals->reserve((params == NULL ? 0 : params->size())
2794 + (receiver != NULL ? 1 : 0));
2796 if (receiver != NULL)
2797 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
2801 for (Typed_identifier_list::const_iterator p = params->begin();
2804 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
2807 return Expression::make_slice_composite_literal(params_type, vals, bloc);
2810 // The reflection string.
2813 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
2815 // FIXME: Turn this off until we straighten out the type of the
2816 // struct field used in a go statement which calls a method.
2817 // go_assert(this->receiver_ == NULL);
2819 ret->append("func");
2821 if (this->receiver_ != NULL)
2823 ret->push_back('(');
2824 this->append_reflection(this->receiver_->type(), gogo, ret);
2825 ret->push_back(')');
2828 ret->push_back('(');
2829 const Typed_identifier_list* params = this->parameters();
2832 bool is_varargs = this->is_varargs_;
2833 for (Typed_identifier_list::const_iterator p = params->begin();
2837 if (p != params->begin())
2839 if (!is_varargs || p + 1 != params->end())
2840 this->append_reflection(p->type(), gogo, ret);
2844 this->append_reflection(p->type()->array_type()->element_type(),
2849 ret->push_back(')');
2851 const Typed_identifier_list* results = this->results();
2852 if (results != NULL && !results->empty())
2854 if (results->size() == 1)
2855 ret->push_back(' ');
2858 for (Typed_identifier_list::const_iterator p = results->begin();
2859 p != results->end();
2862 if (p != results->begin())
2864 this->append_reflection(p->type(), gogo, ret);
2866 if (results->size() > 1)
2867 ret->push_back(')');
2874 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
2876 ret->push_back('F');
2878 if (this->receiver_ != NULL)
2880 ret->push_back('m');
2881 this->append_mangled_name(this->receiver_->type(), gogo, ret);
2884 const Typed_identifier_list* params = this->parameters();
2887 ret->push_back('p');
2888 for (Typed_identifier_list::const_iterator p = params->begin();
2891 this->append_mangled_name(p->type(), gogo, ret);
2892 if (this->is_varargs_)
2893 ret->push_back('V');
2894 ret->push_back('e');
2897 const Typed_identifier_list* results = this->results();
2898 if (results != NULL)
2900 ret->push_back('r');
2901 for (Typed_identifier_list::const_iterator p = results->begin();
2902 p != results->end();
2904 this->append_mangled_name(p->type(), gogo, ret);
2905 ret->push_back('e');
2908 ret->push_back('e');
2911 // Export a function type.
2914 Function_type::do_export(Export* exp) const
2916 // We don't write out the receiver. The only function types which
2917 // should have a receiver are the ones associated with explicitly
2918 // defined methods. For those the receiver type is written out by
2919 // Function::export_func.
2921 exp->write_c_string("(");
2923 if (this->parameters_ != NULL)
2925 bool is_varargs = this->is_varargs_;
2926 for (Typed_identifier_list::const_iterator p =
2927 this->parameters_->begin();
2928 p != this->parameters_->end();
2934 exp->write_c_string(", ");
2935 if (!is_varargs || p + 1 != this->parameters_->end())
2936 exp->write_type(p->type());
2939 exp->write_c_string("...");
2940 exp->write_type(p->type()->array_type()->element_type());
2944 exp->write_c_string(")");
2946 const Typed_identifier_list* results = this->results_;
2947 if (results != NULL)
2949 exp->write_c_string(" ");
2950 if (results->size() == 1)
2951 exp->write_type(results->begin()->type());
2955 exp->write_c_string("(");
2956 for (Typed_identifier_list::const_iterator p = results->begin();
2957 p != results->end();
2963 exp->write_c_string(", ");
2964 exp->write_type(p->type());
2966 exp->write_c_string(")");
2971 // Import a function type.
2974 Function_type::do_import(Import* imp)
2976 imp->require_c_string("(");
2977 Typed_identifier_list* parameters;
2978 bool is_varargs = false;
2979 if (imp->peek_char() == ')')
2983 parameters = new Typed_identifier_list();
2986 if (imp->match_c_string("..."))
2992 Type* ptype = imp->read_type();
2994 ptype = Type::make_array_type(ptype, NULL);
2995 parameters->push_back(Typed_identifier(Import::import_marker,
2996 ptype, imp->location()));
2997 if (imp->peek_char() != ',')
2999 go_assert(!is_varargs);
3000 imp->require_c_string(", ");
3003 imp->require_c_string(")");
3005 Typed_identifier_list* results;
3006 if (imp->peek_char() != ' ')
3011 results = new Typed_identifier_list;
3012 if (imp->peek_char() != '(')
3014 Type* rtype = imp->read_type();
3015 results->push_back(Typed_identifier(Import::import_marker, rtype,
3023 Type* rtype = imp->read_type();
3024 results->push_back(Typed_identifier(Import::import_marker,
3025 rtype, imp->location()));
3026 if (imp->peek_char() != ',')
3028 imp->require_c_string(", ");
3030 imp->require_c_string(")");
3034 Function_type* ret = Type::make_function_type(NULL, parameters, results,
3037 ret->set_is_varargs();
3041 // Make a copy of a function type without a receiver.
3044 Function_type::copy_without_receiver() const
3046 go_assert(this->is_method());
3047 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
3050 if (this->is_varargs())
3051 ret->set_is_varargs();
3052 if (this->is_builtin())
3053 ret->set_is_builtin();
3057 // Make a copy of a function type with a receiver.
3060 Function_type::copy_with_receiver(Type* receiver_type) const
3062 go_assert(!this->is_method());
3063 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
3065 return Type::make_function_type(receiver, this->parameters_,
3066 this->results_, this->location_);
3069 // Make a function type.
3072 Type::make_function_type(Typed_identifier* receiver,
3073 Typed_identifier_list* parameters,
3074 Typed_identifier_list* results,
3077 return new Function_type(receiver, parameters, results, location);
3080 // Class Pointer_type.
3085 Pointer_type::do_traverse(Traverse* traverse)
3087 return Type::traverse(this->to_type_, traverse);
3093 Pointer_type::do_hash_for_method(Gogo* gogo) const
3095 return this->to_type_->hash_for_method(gogo) << 4;
3098 // The tree for a pointer type.
3101 Pointer_type::do_get_backend(Gogo* gogo)
3103 Btype* to_btype = this->to_type_->get_backend(gogo);
3104 return gogo->backend()->pointer_type(to_btype);
3107 // The type of a pointer type descriptor.
3110 Pointer_type::make_pointer_type_descriptor_type()
3115 Type* tdt = Type::make_type_descriptor_type();
3116 Type* ptdt = Type::make_type_descriptor_ptr_type();
3118 Struct_type* s = Type::make_builtin_struct_type(2,
3122 ret = Type::make_builtin_named_type("PtrType", s);
3128 // The type descriptor for a pointer type.
3131 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3133 if (this->is_unsafe_pointer_type())
3135 go_assert(name != NULL);
3136 return this->plain_type_descriptor(gogo,
3137 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
3142 Location bloc = Linemap::predeclared_location();
3144 const Methods* methods;
3145 Type* deref = this->points_to();
3146 if (deref->named_type() != NULL)
3147 methods = deref->named_type()->methods();
3148 else if (deref->struct_type() != NULL)
3149 methods = deref->struct_type()->methods();
3153 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
3155 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
3157 Expression_list* vals = new Expression_list();
3160 Struct_field_list::const_iterator p = fields->begin();
3161 go_assert(p->is_field_name("commonType"));
3162 vals->push_back(this->type_descriptor_constructor(gogo,
3163 RUNTIME_TYPE_KIND_PTR,
3164 name, methods, false));
3167 go_assert(p->is_field_name("elem"));
3168 vals->push_back(Expression::make_type_descriptor(deref, bloc));
3170 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
3174 // Reflection string.
3177 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
3179 ret->push_back('*');
3180 this->append_reflection(this->to_type_, gogo, ret);
3186 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3188 ret->push_back('p');
3189 this->append_mangled_name(this->to_type_, gogo, ret);
3195 Pointer_type::do_export(Export* exp) const
3197 exp->write_c_string("*");
3198 if (this->is_unsafe_pointer_type())
3199 exp->write_c_string("any");
3201 exp->write_type(this->to_type_);
3207 Pointer_type::do_import(Import* imp)
3209 imp->require_c_string("*");
3210 if (imp->match_c_string("any"))
3213 return Type::make_pointer_type(Type::make_void_type());
3215 Type* to = imp->read_type();
3216 return Type::make_pointer_type(to);
3219 // Make a pointer type.
3222 Type::make_pointer_type(Type* to_type)
3224 typedef Unordered_map(Type*, Pointer_type*) Hashtable;
3225 static Hashtable pointer_types;
3226 Hashtable::const_iterator p = pointer_types.find(to_type);
3227 if (p != pointer_types.end())
3229 Pointer_type* ret = new Pointer_type(to_type);
3230 pointer_types[to_type] = ret;
3234 // The nil type. We use a special type for nil because it is not the
3235 // same as any other type. In C term nil has type void*, but there is
3236 // no such type in Go.
3238 class Nil_type : public Type
3247 do_get_backend(Gogo* gogo)
3248 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
3251 do_type_descriptor(Gogo*, Named_type*)
3252 { go_unreachable(); }
3255 do_reflection(Gogo*, std::string*) const
3256 { go_unreachable(); }
3259 do_mangled_name(Gogo*, std::string* ret) const
3260 { ret->push_back('n'); }
3263 // Make the nil type.
3266 Type::make_nil_type()
3268 static Nil_type singleton_nil_type;
3269 return &singleton_nil_type;
3272 // The type of a function call which returns multiple values. This is
3273 // really a struct, but we don't want to confuse a function call which
3274 // returns a struct with a function call which returns multiple
3277 class Call_multiple_result_type : public Type
3280 Call_multiple_result_type(Call_expression* call)
3281 : Type(TYPE_CALL_MULTIPLE_RESULT),
3287 do_has_pointer() const
3289 go_assert(saw_errors());
3294 do_get_backend(Gogo* gogo)
3296 go_assert(saw_errors());
3297 return gogo->backend()->error_type();
3301 do_type_descriptor(Gogo*, Named_type*)
3303 go_assert(saw_errors());
3304 return Expression::make_error(Linemap::unknown_location());
3308 do_reflection(Gogo*, std::string*) const
3309 { go_assert(saw_errors()); }
3312 do_mangled_name(Gogo*, std::string*) const
3313 { go_assert(saw_errors()); }
3316 // The expression being called.
3317 Call_expression* call_;
3320 // Make a call result type.
3323 Type::make_call_multiple_result_type(Call_expression* call)
3325 return new Call_multiple_result_type(call);
3328 // Class Struct_field.
3330 // Get the name of a field.
3333 Struct_field::field_name() const
3335 const std::string& name(this->typed_identifier_.name());
3340 // This is called during parsing, before anything is lowered, so
3341 // we have to be pretty careful to avoid dereferencing an
3342 // unknown type name.
3343 Type* t = this->typed_identifier_.type();
3345 if (t->classification() == Type::TYPE_POINTER)
3348 Pointer_type* ptype = static_cast<Pointer_type*>(t);
3349 dt = ptype->points_to();
3351 if (dt->forward_declaration_type() != NULL)
3352 return dt->forward_declaration_type()->name();
3353 else if (dt->named_type() != NULL)
3354 return dt->named_type()->name();
3355 else if (t->is_error_type() || dt->is_error_type())
3357 static const std::string error_string = "*error*";
3358 return error_string;
3362 // Avoid crashing in the erroneous case where T is named but
3365 if (t->forward_declaration_type() != NULL)
3366 return t->forward_declaration_type()->name();
3367 else if (t->named_type() != NULL)
3368 return t->named_type()->name();
3375 // Return whether this field is named NAME.
3378 Struct_field::is_field_name(const std::string& name) const
3380 const std::string& me(this->typed_identifier_.name());
3385 Type* t = this->typed_identifier_.type();
3386 if (t->points_to() != NULL)
3388 Named_type* nt = t->named_type();
3389 if (nt != NULL && nt->name() == name)
3392 // This is a horrible hack caused by the fact that we don't pack
3393 // the names of builtin types. FIXME.
3396 && nt->name() == Gogo::unpack_hidden_name(name))
3403 // Class Struct_type.
3408 Struct_type::do_traverse(Traverse* traverse)
3410 Struct_field_list* fields = this->fields_;
3413 for (Struct_field_list::iterator p = fields->begin();
3417 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
3418 return TRAVERSE_EXIT;
3421 return TRAVERSE_CONTINUE;
3424 // Verify that the struct type is complete and valid.
3427 Struct_type::do_verify()
3429 Struct_field_list* fields = this->fields_;
3433 for (Struct_field_list::iterator p = fields->begin();
3437 Type* t = p->type();
3438 if (t->is_undefined())
3440 error_at(p->location(), "struct field type is incomplete");
3441 p->set_type(Type::make_error_type());
3444 else if (p->is_anonymous())
3446 if (t->named_type() != NULL && t->points_to() != NULL)
3448 error_at(p->location(), "embedded type may not be a pointer");
3449 p->set_type(Type::make_error_type());
3452 if (t->points_to() != NULL
3453 && t->points_to()->interface_type() != NULL)
3455 error_at(p->location(),
3456 "embedded type may not be pointer to interface");
3457 p->set_type(Type::make_error_type());
3465 // Whether this contains a pointer.
3468 Struct_type::do_has_pointer() const
3470 const Struct_field_list* fields = this->fields();
3473 for (Struct_field_list::const_iterator p = fields->begin();
3477 if (p->type()->has_pointer())
3483 // Whether this type is identical to T.
3486 Struct_type::is_identical(const Struct_type* t,
3487 bool errors_are_identical) const
3489 const Struct_field_list* fields1 = this->fields();
3490 const Struct_field_list* fields2 = t->fields();
3491 if (fields1 == NULL || fields2 == NULL)
3492 return fields1 == fields2;
3493 Struct_field_list::const_iterator pf2 = fields2->begin();
3494 for (Struct_field_list::const_iterator pf1 = fields1->begin();
3495 pf1 != fields1->end();
3498 if (pf2 == fields2->end())
3500 if (pf1->field_name() != pf2->field_name())
3502 if (pf1->is_anonymous() != pf2->is_anonymous()
3503 || !Type::are_identical(pf1->type(), pf2->type(),
3504 errors_are_identical, NULL))
3506 if (!pf1->has_tag())
3513 if (!pf2->has_tag())
3515 if (pf1->tag() != pf2->tag())
3519 if (pf2 != fields2->end())
3524 // Whether this struct type has any hidden fields.
3527 Struct_type::struct_has_hidden_fields(const Named_type* within,
3528 std::string* reason) const
3530 const Struct_field_list* fields = this->fields();
3533 const Package* within_package = (within == NULL
3535 : within->named_object()->package());
3536 for (Struct_field_list::const_iterator pf = fields->begin();
3537 pf != fields->end();
3540 if (within_package != NULL
3541 && !pf->is_anonymous()
3542 && Gogo::is_hidden_name(pf->field_name()))
3546 std::string within_name = within->named_object()->message_name();
3547 std::string name = Gogo::message_name(pf->field_name());
3548 size_t bufsize = 200 + within_name.length() + name.length();
3549 char* buf = new char[bufsize];
3550 snprintf(buf, bufsize,
3551 _("implicit assignment of %s%s%s hidden field %s%s%s"),
3552 open_quote, within_name.c_str(), close_quote,
3553 open_quote, name.c_str(), close_quote);
3554 reason->assign(buf);
3560 if (pf->type()->has_hidden_fields(within, reason))
3570 Struct_type::do_hash_for_method(Gogo* gogo) const
3572 unsigned int ret = 0;
3573 if (this->fields() != NULL)
3575 for (Struct_field_list::const_iterator pf = this->fields()->begin();
3576 pf != this->fields()->end();
3578 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
3583 // Find the local field NAME.
3586 Struct_type::find_local_field(const std::string& name,
3587 unsigned int *pindex) const
3589 const Struct_field_list* fields = this->fields_;
3593 for (Struct_field_list::const_iterator pf = fields->begin();
3594 pf != fields->end();
3597 if (pf->is_field_name(name))
3607 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
3609 Field_reference_expression*
3610 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
3611 Location location) const
3614 return this->field_reference_depth(struct_expr, name, location, NULL,
3618 // Return an expression for a field, along with the depth at which it
3621 Field_reference_expression*
3622 Struct_type::field_reference_depth(Expression* struct_expr,
3623 const std::string& name,
3625 Saw_named_type* saw,
3626 unsigned int* depth) const
3628 const Struct_field_list* fields = this->fields_;
3632 // Look for a field with this name.
3634 for (Struct_field_list::const_iterator pf = fields->begin();
3635 pf != fields->end();
3638 if (pf->is_field_name(name))
3641 return Expression::make_field_reference(struct_expr, i, location);
3645 // Look for an anonymous field which contains a field with this
3647 unsigned int found_depth = 0;
3648 Field_reference_expression* ret = NULL;
3650 for (Struct_field_list::const_iterator pf = fields->begin();
3651 pf != fields->end();
3654 if (!pf->is_anonymous())
3657 Struct_type* st = pf->type()->deref()->struct_type();
3661 Saw_named_type* hold_saw = saw;
3662 Saw_named_type saw_here;
3663 Named_type* nt = pf->type()->named_type();
3665 nt = pf->type()->deref()->named_type();
3669 for (q = saw; q != NULL; q = q->next)
3673 // If this is an error, it will be reported
3680 saw_here.next = saw;
3685 // Look for a reference using a NULL struct expression. If we
3686 // find one, fill in the struct expression with a reference to
3688 unsigned int subdepth;
3689 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
3699 if (ret == NULL || subdepth < found_depth)
3704 found_depth = subdepth;
3705 Expression* here = Expression::make_field_reference(struct_expr, i,
3707 if (pf->type()->points_to() != NULL)
3708 here = Expression::make_unary(OPERATOR_MULT, here, location);
3709 while (sub->expr() != NULL)
3711 sub = sub->expr()->deref()->field_reference_expression();
3712 go_assert(sub != NULL);
3714 sub->set_struct_expression(here);
3716 else if (subdepth > found_depth)
3720 // We do not handle ambiguity here--it should be handled by
3721 // Type::bind_field_or_method.
3729 *depth = found_depth + 1;
3734 // Return the total number of fields, including embedded fields.
3737 Struct_type::total_field_count() const
3739 if (this->fields_ == NULL)
3741 unsigned int ret = 0;
3742 for (Struct_field_list::const_iterator pf = this->fields_->begin();
3743 pf != this->fields_->end();
3746 if (!pf->is_anonymous() || pf->type()->deref()->struct_type() == NULL)
3749 ret += pf->type()->struct_type()->total_field_count();
3754 // Return whether NAME is an unexported field, for better error reporting.
3757 Struct_type::is_unexported_local_field(Gogo* gogo,
3758 const std::string& name) const
3760 const Struct_field_list* fields = this->fields_;
3763 for (Struct_field_list::const_iterator pf = fields->begin();
3764 pf != fields->end();
3767 const std::string& field_name(pf->field_name());
3768 if (Gogo::is_hidden_name(field_name)
3769 && name == Gogo::unpack_hidden_name(field_name)
3770 && gogo->pack_hidden_name(name, false) != field_name)
3777 // Finalize the methods of an unnamed struct.
3780 Struct_type::finalize_methods(Gogo* gogo)
3782 if (this->all_methods_ != NULL)
3784 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
3787 // Return the method NAME, or NULL if there isn't one or if it is
3788 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
3792 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
3794 return Type::method_function(this->all_methods_, name, is_ambiguous);
3797 // Convert struct fields to the backend representation. This is not
3798 // declared in types.h so that types.h doesn't have to #include
3802 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
3803 std::vector<Backend::Btyped_identifier>* bfields)
3805 bfields->resize(fields->size());
3807 for (Struct_field_list::const_iterator p = fields->begin();
3811 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
3812 (*bfields)[i].btype = p->type()->get_backend(gogo);
3813 (*bfields)[i].location = p->location();
3815 go_assert(i == fields->size());
3818 // Get the tree for a struct type.
3821 Struct_type::do_get_backend(Gogo* gogo)
3823 std::vector<Backend::Btyped_identifier> bfields;
3824 get_backend_struct_fields(gogo, this->fields_, &bfields);
3825 return gogo->backend()->struct_type(bfields);
3828 // The type of a struct type descriptor.
3831 Struct_type::make_struct_type_descriptor_type()
3836 Type* tdt = Type::make_type_descriptor_type();
3837 Type* ptdt = Type::make_type_descriptor_ptr_type();
3839 Type* uintptr_type = Type::lookup_integer_type("uintptr");
3840 Type* string_type = Type::lookup_string_type();
3841 Type* pointer_string_type = Type::make_pointer_type(string_type);
3844 Type::make_builtin_struct_type(5,
3845 "name", pointer_string_type,
3846 "pkgPath", pointer_string_type,
3848 "tag", pointer_string_type,
3849 "offset", uintptr_type);
3850 Type* nsf = Type::make_builtin_named_type("structField", sf);
3852 Type* slice_type = Type::make_array_type(nsf, NULL);
3854 Struct_type* s = Type::make_builtin_struct_type(2,
3856 "fields", slice_type);
3858 ret = Type::make_builtin_named_type("StructType", s);
3864 // Build a type descriptor for a struct type.
3867 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3869 Location bloc = Linemap::predeclared_location();
3871 Type* stdt = Struct_type::make_struct_type_descriptor_type();
3873 const Struct_field_list* fields = stdt->struct_type()->fields();
3875 Expression_list* vals = new Expression_list();
3878 const Methods* methods = this->methods();
3879 // A named struct should not have methods--the methods should attach
3880 // to the named type.
3881 go_assert(methods == NULL || name == NULL);
3883 Struct_field_list::const_iterator ps = fields->begin();
3884 go_assert(ps->is_field_name("commonType"));
3885 vals->push_back(this->type_descriptor_constructor(gogo,
3886 RUNTIME_TYPE_KIND_STRUCT,
3887 name, methods, true));
3890 go_assert(ps->is_field_name("fields"));
3892 Expression_list* elements = new Expression_list();
3893 elements->reserve(this->fields_->size());
3894 Type* element_type = ps->type()->array_type()->element_type();
3895 for (Struct_field_list::const_iterator pf = this->fields_->begin();
3896 pf != this->fields_->end();
3899 const Struct_field_list* f = element_type->struct_type()->fields();
3901 Expression_list* fvals = new Expression_list();
3904 Struct_field_list::const_iterator q = f->begin();
3905 go_assert(q->is_field_name("name"));
3906 if (pf->is_anonymous())
3907 fvals->push_back(Expression::make_nil(bloc));
3910 std::string n = Gogo::unpack_hidden_name(pf->field_name());
3911 Expression* s = Expression::make_string(n, bloc);
3912 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3916 go_assert(q->is_field_name("pkgPath"));
3917 if (!Gogo::is_hidden_name(pf->field_name()))
3918 fvals->push_back(Expression::make_nil(bloc));
3921 std::string n = Gogo::hidden_name_prefix(pf->field_name());
3922 Expression* s = Expression::make_string(n, bloc);
3923 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3927 go_assert(q->is_field_name("typ"));
3928 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
3931 go_assert(q->is_field_name("tag"));
3933 fvals->push_back(Expression::make_nil(bloc));
3936 Expression* s = Expression::make_string(pf->tag(), bloc);
3937 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3941 go_assert(q->is_field_name("offset"));
3942 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
3944 Expression* v = Expression::make_struct_composite_literal(element_type,
3946 elements->push_back(v);
3949 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
3952 return Expression::make_struct_composite_literal(stdt, vals, bloc);
3955 // Reflection string.
3958 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
3960 ret->append("struct { ");
3962 for (Struct_field_list::const_iterator p = this->fields_->begin();
3963 p != this->fields_->end();
3966 if (p != this->fields_->begin())
3968 if (p->is_anonymous())
3969 ret->push_back('?');
3971 ret->append(Gogo::unpack_hidden_name(p->field_name()));
3972 ret->push_back(' ');
3973 this->append_reflection(p->type(), gogo, ret);
3977 const std::string& tag(p->tag());
3979 for (std::string::const_iterator p = tag.begin();
3984 ret->append("\\x00");
3985 else if (*p == '\n')
3987 else if (*p == '\t')
3990 ret->append("\\\"");
3991 else if (*p == '\\')
3992 ret->append("\\\\");
3996 ret->push_back('"');
4006 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4008 ret->push_back('S');
4010 const Struct_field_list* fields = this->fields_;
4013 for (Struct_field_list::const_iterator p = fields->begin();
4017 if (p->is_anonymous())
4021 std::string n = Gogo::unpack_hidden_name(p->field_name());
4023 snprintf(buf, sizeof buf, "%u_",
4024 static_cast<unsigned int>(n.length()));
4028 this->append_mangled_name(p->type(), gogo, ret);
4031 const std::string& tag(p->tag());
4033 for (std::string::const_iterator p = tag.begin();
4037 if (ISALNUM(*p) || *p == '_')
4042 snprintf(buf, sizeof buf, ".%x.",
4043 static_cast<unsigned int>(*p));
4048 snprintf(buf, sizeof buf, "T%u_",
4049 static_cast<unsigned int>(out.length()));
4056 ret->push_back('e');
4062 Struct_type::do_export(Export* exp) const
4064 exp->write_c_string("struct { ");
4065 const Struct_field_list* fields = this->fields_;
4066 go_assert(fields != NULL);
4067 for (Struct_field_list::const_iterator p = fields->begin();
4071 if (p->is_anonymous())
4072 exp->write_string("? ");
4075 exp->write_string(p->field_name());
4076 exp->write_c_string(" ");
4078 exp->write_type(p->type());
4082 exp->write_c_string(" ");
4084 Expression::make_string(p->tag(), Linemap::predeclared_location());
4085 expr->export_expression(exp);
4089 exp->write_c_string("; ");
4091 exp->write_c_string("}");
4097 Struct_type::do_import(Import* imp)
4099 imp->require_c_string("struct { ");
4100 Struct_field_list* fields = new Struct_field_list;
4101 if (imp->peek_char() != '}')
4106 if (imp->match_c_string("? "))
4110 name = imp->read_identifier();
4111 imp->require_c_string(" ");
4113 Type* ftype = imp->read_type();
4115 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
4117 if (imp->peek_char() == ' ')
4120 Expression* expr = Expression::import_expression(imp);
4121 String_expression* sexpr = expr->string_expression();
4122 go_assert(sexpr != NULL);
4123 sf.set_tag(sexpr->val());
4127 imp->require_c_string("; ");
4128 fields->push_back(sf);
4129 if (imp->peek_char() == '}')
4133 imp->require_c_string("}");
4135 return Type::make_struct_type(fields, imp->location());
4138 // Make a struct type.
4141 Type::make_struct_type(Struct_field_list* fields,
4144 return new Struct_type(fields, location);
4147 // Class Array_type.
4149 // Whether two array types are identical.
4152 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
4154 if (!Type::are_identical(this->element_type(), t->element_type(),
4155 errors_are_identical, NULL))
4158 Expression* l1 = this->length();
4159 Expression* l2 = t->length();
4161 // Slices of the same element type are identical.
4162 if (l1 == NULL && l2 == NULL)
4165 // Arrays of the same element type are identical if they have the
4167 if (l1 != NULL && l2 != NULL)
4172 // Try to determine the lengths. If we can't, assume the arrays
4173 // are not identical.
4181 if (l1->integer_constant_value(true, v1, &type1)
4182 && l2->integer_constant_value(true, v2, &type2))
4183 ret = mpz_cmp(v1, v2) == 0;
4189 // Otherwise the arrays are not identical.
4196 Array_type::do_traverse(Traverse* traverse)
4198 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
4199 return TRAVERSE_EXIT;
4200 if (this->length_ != NULL
4201 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
4202 return TRAVERSE_EXIT;
4203 return TRAVERSE_CONTINUE;
4206 // Check that the length is valid.
4209 Array_type::verify_length()
4211 if (this->length_ == NULL)
4214 Type_context context(Type::lookup_integer_type("int"), false);
4215 this->length_->determine_type(&context);
4217 if (!this->length_->is_constant())
4219 error_at(this->length_->location(), "array bound is not constant");
4226 if (!this->length_->integer_constant_value(true, val, &vt))
4230 if (!this->length_->float_constant_value(fval, &vt))
4232 if (this->length_->type()->integer_type() != NULL
4233 || this->length_->type()->float_type() != NULL)
4234 error_at(this->length_->location(),
4235 "array bound is not constant");
4237 error_at(this->length_->location(),
4238 "array bound is not numeric");
4243 if (!mpfr_integer_p(fval))
4245 error_at(this->length_->location(),
4246 "array bound truncated to integer");
4252 mpfr_get_z(val, fval, GMP_RNDN);
4256 if (mpz_sgn(val) < 0)
4258 error_at(this->length_->location(), "negative array bound");
4263 Type* int_type = Type::lookup_integer_type("int");
4264 int tbits = int_type->integer_type()->bits();
4265 int vbits = mpz_sizeinbase(val, 2);
4266 if (vbits + 1 > tbits)
4268 error_at(this->length_->location(), "array bound overflows");
4281 Array_type::do_verify()
4283 if (!this->verify_length())
4285 this->length_ = Expression::make_error(this->length_->location());
4291 // Array type hash code.
4294 Array_type::do_hash_for_method(Gogo* gogo) const
4296 // There is no very convenient way to get a hash code for the
4298 return this->element_type_->hash_for_method(gogo) + 1;
4301 // Get a tree for the length of a fixed array. The length may be
4302 // computed using a function call, so we must only evaluate it once.
4305 Array_type::get_length_tree(Gogo* gogo)
4307 go_assert(this->length_ != NULL);
4308 if (this->length_tree_ == NULL_TREE)
4313 if (this->length_->integer_constant_value(true, val, &t))
4316 t = Type::lookup_integer_type("int");
4317 else if (t->is_abstract())
4318 t = t->make_non_abstract_type();
4319 tree tt = type_to_tree(t->get_backend(gogo));
4320 this->length_tree_ = Expression::integer_constant_tree(val, tt);
4327 // Make up a translation context for the array length
4328 // expression. FIXME: This won't work in general.
4329 Translate_context context(gogo, NULL, NULL, NULL);
4330 tree len = this->length_->get_tree(&context);
4331 if (len != error_mark_node)
4333 len = convert_to_integer(integer_type_node, len);
4334 len = save_expr(len);
4336 this->length_tree_ = len;
4339 return this->length_tree_;
4342 // Get the backend representation of the fields of a slice. This is
4343 // not declared in types.h so that types.h doesn't have to #include
4346 // We use int for the count and capacity fields. This matches 6g.
4347 // The language more or less assumes that we can't allocate space of a
4348 // size which does not fit in int.
4351 get_backend_slice_fields(Gogo* gogo, Array_type* type,
4352 std::vector<Backend::Btyped_identifier>* bfields)
4356 Type* pet = Type::make_pointer_type(type->element_type());
4357 Btype* pbet = pet->get_backend(gogo);
4358 Location ploc = Linemap::predeclared_location();
4360 Backend::Btyped_identifier* p = &(*bfields)[0];
4361 p->name = "__values";
4365 Type* int_type = Type::lookup_integer_type("int");
4368 p->name = "__count";
4369 p->btype = int_type->get_backend(gogo);
4373 p->name = "__capacity";
4374 p->btype = int_type->get_backend(gogo);
4378 // Get a tree for the type of this array. A fixed array is simply
4379 // represented as ARRAY_TYPE with the appropriate index--i.e., it is
4380 // just like an array in C. An open array is a struct with three
4381 // fields: a data pointer, the length, and the capacity.
4384 Array_type::do_get_backend(Gogo* gogo)
4386 if (this->length_ == NULL)
4388 std::vector<Backend::Btyped_identifier> bfields;
4389 get_backend_slice_fields(gogo, this, &bfields);
4390 return gogo->backend()->struct_type(bfields);
4394 Btype* element = this->get_backend_element(gogo);
4395 Bexpression* len = this->get_backend_length(gogo);
4396 return gogo->backend()->array_type(element, len);
4400 // Return the backend representation of the element type.
4402 Array_type::get_backend_element(Gogo* gogo)
4404 return this->element_type_->get_backend(gogo);
4407 // Return the backend representation of the length.
4410 Array_type::get_backend_length(Gogo* gogo)
4412 return tree_to_expr(this->get_length_tree(gogo));
4415 // Return a tree for a pointer to the values in ARRAY.
4418 Array_type::value_pointer_tree(Gogo*, tree array) const
4421 if (this->length() != NULL)
4424 ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))),
4425 build_fold_addr_expr(array));
4430 tree field = TYPE_FIELDS(TREE_TYPE(array));
4431 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
4433 ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field,
4436 if (TREE_CONSTANT(array))
4437 TREE_CONSTANT(ret) = 1;
4441 // Return a tree for the length of the array ARRAY which has this
4445 Array_type::length_tree(Gogo* gogo, tree array)
4447 if (this->length_ != NULL)
4449 if (TREE_CODE(array) == SAVE_EXPR)
4450 return fold_convert(integer_type_node, this->get_length_tree(gogo));
4452 return omit_one_operand(integer_type_node,
4453 this->get_length_tree(gogo), array);
4456 // This is an open array. We need to read the length field.
4458 tree type = TREE_TYPE(array);
4459 go_assert(TREE_CODE(type) == RECORD_TYPE);
4461 tree field = DECL_CHAIN(TYPE_FIELDS(type));
4462 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
4464 tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
4465 if (TREE_CONSTANT(array))
4466 TREE_CONSTANT(ret) = 1;
4470 // Return a tree for the capacity of the array ARRAY which has this
4474 Array_type::capacity_tree(Gogo* gogo, tree array)
4476 if (this->length_ != NULL)
4477 return omit_one_operand(sizetype, this->get_length_tree(gogo), array);
4479 // This is an open array. We need to read the capacity field.
4481 tree type = TREE_TYPE(array);
4482 go_assert(TREE_CODE(type) == RECORD_TYPE);
4484 tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type)));
4485 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
4487 return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
4493 Array_type::do_export(Export* exp) const
4495 exp->write_c_string("[");
4496 if (this->length_ != NULL)
4497 this->length_->export_expression(exp);
4498 exp->write_c_string("] ");
4499 exp->write_type(this->element_type_);
4505 Array_type::do_import(Import* imp)
4507 imp->require_c_string("[");
4509 if (imp->peek_char() == ']')
4512 length = Expression::import_expression(imp);
4513 imp->require_c_string("] ");
4514 Type* element_type = imp->read_type();
4515 return Type::make_array_type(element_type, length);
4518 // The type of an array type descriptor.
4521 Array_type::make_array_type_descriptor_type()
4526 Type* tdt = Type::make_type_descriptor_type();
4527 Type* ptdt = Type::make_type_descriptor_ptr_type();
4529 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4532 Type::make_builtin_struct_type(4,
4536 "len", uintptr_type);
4538 ret = Type::make_builtin_named_type("ArrayType", sf);
4544 // The type of an slice type descriptor.
4547 Array_type::make_slice_type_descriptor_type()
4552 Type* tdt = Type::make_type_descriptor_type();
4553 Type* ptdt = Type::make_type_descriptor_ptr_type();
4556 Type::make_builtin_struct_type(2,
4560 ret = Type::make_builtin_named_type("SliceType", sf);
4566 // Build a type descriptor for an array/slice type.
4569 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4571 if (this->length_ != NULL)
4572 return this->array_type_descriptor(gogo, name);
4574 return this->slice_type_descriptor(gogo, name);
4577 // Build a type descriptor for an array type.
4580 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
4582 Location bloc = Linemap::predeclared_location();
4584 Type* atdt = Array_type::make_array_type_descriptor_type();
4586 const Struct_field_list* fields = atdt->struct_type()->fields();
4588 Expression_list* vals = new Expression_list();
4591 Struct_field_list::const_iterator p = fields->begin();
4592 go_assert(p->is_field_name("commonType"));
4593 vals->push_back(this->type_descriptor_constructor(gogo,
4594 RUNTIME_TYPE_KIND_ARRAY,
4598 go_assert(p->is_field_name("elem"));
4599 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
4602 go_assert(p->is_field_name("slice"));
4603 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
4604 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
4607 go_assert(p->is_field_name("len"));
4608 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
4611 go_assert(p == fields->end());
4613 return Expression::make_struct_composite_literal(atdt, vals, bloc);
4616 // Build a type descriptor for a slice type.
4619 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
4621 Location bloc = Linemap::predeclared_location();
4623 Type* stdt = Array_type::make_slice_type_descriptor_type();
4625 const Struct_field_list* fields = stdt->struct_type()->fields();
4627 Expression_list* vals = new Expression_list();
4630 Struct_field_list::const_iterator p = fields->begin();
4631 go_assert(p->is_field_name("commonType"));
4632 vals->push_back(this->type_descriptor_constructor(gogo,
4633 RUNTIME_TYPE_KIND_SLICE,
4637 go_assert(p->is_field_name("elem"));
4638 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
4641 go_assert(p == fields->end());
4643 return Expression::make_struct_composite_literal(stdt, vals, bloc);
4646 // Reflection string.
4649 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
4651 ret->push_back('[');
4652 if (this->length_ != NULL)
4657 if (!this->length_->integer_constant_value(true, val, &type))
4658 error_at(this->length_->location(),
4659 "array length must be integer constant expression");
4660 else if (mpz_cmp_si(val, 0) < 0)
4661 error_at(this->length_->location(), "array length is negative");
4662 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
4663 error_at(this->length_->location(), "array length is too large");
4667 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
4672 ret->push_back(']');
4674 this->append_reflection(this->element_type_, gogo, ret);
4680 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4682 ret->push_back('A');
4683 this->append_mangled_name(this->element_type_, gogo, ret);
4684 if (this->length_ != NULL)
4689 if (!this->length_->integer_constant_value(true, val, &type))
4690 error_at(this->length_->location(),
4691 "array length must be integer constant expression");
4692 else if (mpz_cmp_si(val, 0) < 0)
4693 error_at(this->length_->location(), "array length is negative");
4694 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
4695 error_at(this->length_->location(), "array size is too large");
4699 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
4704 ret->push_back('e');
4707 // Make an array type.
4710 Type::make_array_type(Type* element_type, Expression* length)
4712 return new Array_type(element_type, length);
4720 Map_type::do_traverse(Traverse* traverse)
4722 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
4723 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
4724 return TRAVERSE_EXIT;
4725 return TRAVERSE_CONTINUE;
4728 // Check that the map type is OK.
4731 Map_type::do_verify()
4733 if (this->key_type_->struct_type() != NULL
4734 || this->key_type_->array_type() != NULL)
4736 error_at(this->location_, "invalid map key type");
4742 // Whether two map types are identical.
4745 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
4747 return (Type::are_identical(this->key_type(), t->key_type(),
4748 errors_are_identical, NULL)
4749 && Type::are_identical(this->val_type(), t->val_type(),
4750 errors_are_identical, NULL));
4756 Map_type::do_hash_for_method(Gogo* gogo) const
4758 return (this->key_type_->hash_for_method(gogo)
4759 + this->val_type_->hash_for_method(gogo)
4763 // Get the backend representation for a map type. A map type is
4764 // represented as a pointer to a struct. The struct is __go_map in
4768 Map_type::do_get_backend(Gogo* gogo)
4770 static Btype* backend_map_type;
4771 if (backend_map_type == NULL)
4773 std::vector<Backend::Btyped_identifier> bfields(4);
4775 Location bloc = Linemap::predeclared_location();
4777 Type* pdt = Type::make_type_descriptor_ptr_type();
4778 bfields[0].name = "__descriptor";
4779 bfields[0].btype = pdt->get_backend(gogo);
4780 bfields[0].location = bloc;
4782 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4783 bfields[1].name = "__element_count";
4784 bfields[1].btype = uintptr_type->get_backend(gogo);
4785 bfields[1].location = bloc;
4787 bfields[2].name = "__bucket_count";
4788 bfields[2].btype = bfields[1].btype;
4789 bfields[2].location = bloc;
4791 Btype* bvt = gogo->backend()->void_type();
4792 Btype* bpvt = gogo->backend()->pointer_type(bvt);
4793 Btype* bppvt = gogo->backend()->pointer_type(bpvt);
4794 bfields[3].name = "__buckets";
4795 bfields[3].btype = bppvt;
4796 bfields[3].location = bloc;
4798 Btype *bt = gogo->backend()->struct_type(bfields);
4799 bt = gogo->backend()->named_type("__go_map", bt, bloc);
4800 backend_map_type = gogo->backend()->pointer_type(bt);
4802 return backend_map_type;
4805 // The type of a map type descriptor.
4808 Map_type::make_map_type_descriptor_type()
4813 Type* tdt = Type::make_type_descriptor_type();
4814 Type* ptdt = Type::make_type_descriptor_ptr_type();
4817 Type::make_builtin_struct_type(3,
4822 ret = Type::make_builtin_named_type("MapType", sf);
4828 // Build a type descriptor for a map type.
4831 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4833 Location bloc = Linemap::predeclared_location();
4835 Type* mtdt = Map_type::make_map_type_descriptor_type();
4837 const Struct_field_list* fields = mtdt->struct_type()->fields();
4839 Expression_list* vals = new Expression_list();
4842 Struct_field_list::const_iterator p = fields->begin();
4843 go_assert(p->is_field_name("commonType"));
4844 vals->push_back(this->type_descriptor_constructor(gogo,
4845 RUNTIME_TYPE_KIND_MAP,
4849 go_assert(p->is_field_name("key"));
4850 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
4853 go_assert(p->is_field_name("elem"));
4854 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
4857 go_assert(p == fields->end());
4859 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
4862 // A mapping from map types to map descriptors.
4864 Map_type::Map_descriptors Map_type::map_descriptors;
4866 // Build a map descriptor for this type. Return a pointer to it.
4869 Map_type::map_descriptor_pointer(Gogo* gogo, Location location)
4871 Bvariable* bvar = this->map_descriptor(gogo);
4872 tree var_tree = var_to_tree(bvar);
4873 if (var_tree == error_mark_node)
4874 return error_mark_node;
4875 return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
4878 // Build a map descriptor for this type.
4881 Map_type::map_descriptor(Gogo* gogo)
4883 std::pair<Map_type*, Bvariable*> val(this, NULL);
4884 std::pair<Map_type::Map_descriptors::iterator, bool> ins =
4885 Map_type::map_descriptors.insert(val);
4887 return ins.first->second;
4889 Type* key_type = this->key_type_;
4890 Type* val_type = this->val_type_;
4892 // The map entry type is a struct with three fields. Build that
4893 // struct so that we can get the offsets of the key and value within
4894 // a map entry. The first field should technically be a pointer to
4895 // this type itself, but since we only care about field offsets we
4896 // just use pointer to bool.
4897 Type* pbool = Type::make_pointer_type(Type::make_boolean_type());
4898 Struct_type* map_entry_type =
4899 Type::make_builtin_struct_type(3,
4904 Type* map_descriptor_type = Map_type::make_map_descriptor_type();
4906 const Struct_field_list* fields =
4907 map_descriptor_type->struct_type()->fields();
4909 Expression_list* vals = new Expression_list();
4912 Location bloc = Linemap::predeclared_location();
4914 Struct_field_list::const_iterator p = fields->begin();
4916 go_assert(p->is_field_name("__map_descriptor"));
4917 vals->push_back(Expression::make_type_descriptor(this, bloc));
4920 go_assert(p->is_field_name("__entry_size"));
4921 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
4922 vals->push_back(Expression::make_type_info(map_entry_type, type_info));
4924 Struct_field_list::const_iterator pf = map_entry_type->fields()->begin();
4926 go_assert(pf->is_field_name("__key"));
4929 go_assert(p->is_field_name("__key_offset"));
4930 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
4933 go_assert(pf->is_field_name("__val"));
4936 go_assert(p->is_field_name("__val_offset"));
4937 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
4940 go_assert(p == fields->end());
4942 Expression* initializer =
4943 Expression::make_struct_composite_literal(map_descriptor_type, vals, bloc);
4945 std::string mangled_name = "__go_map_" + this->mangled_name(gogo);
4946 Btype* map_descriptor_btype = map_descriptor_type->get_backend(gogo);
4947 Bvariable* bvar = gogo->backend()->immutable_struct(mangled_name, true,
4948 map_descriptor_btype,
4951 Translate_context context(gogo, NULL, NULL, NULL);
4952 context.set_is_const();
4953 Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
4955 gogo->backend()->immutable_struct_set_init(bvar, mangled_name, true,
4956 map_descriptor_btype, bloc,
4959 ins.first->second = bvar;
4963 // Build the type of a map descriptor. This must match the struct
4964 // __go_map_descriptor in libgo/runtime/map.h.
4967 Map_type::make_map_descriptor_type()
4972 Type* ptdt = Type::make_type_descriptor_ptr_type();
4973 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4975 Type::make_builtin_struct_type(4,
4976 "__map_descriptor", ptdt,
4977 "__entry_size", uintptr_type,
4978 "__key_offset", uintptr_type,
4979 "__val_offset", uintptr_type);
4980 ret = Type::make_builtin_named_type("__go_map_descriptor", sf);
4985 // Reflection string for a map.
4988 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
4990 ret->append("map[");
4991 this->append_reflection(this->key_type_, gogo, ret);
4993 this->append_reflection(this->val_type_, gogo, ret);
4996 // Mangled name for a map.
4999 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5001 ret->push_back('M');
5002 this->append_mangled_name(this->key_type_, gogo, ret);
5004 this->append_mangled_name(this->val_type_, gogo, ret);
5007 // Export a map type.
5010 Map_type::do_export(Export* exp) const
5012 exp->write_c_string("map [");
5013 exp->write_type(this->key_type_);
5014 exp->write_c_string("] ");
5015 exp->write_type(this->val_type_);
5018 // Import a map type.
5021 Map_type::do_import(Import* imp)
5023 imp->require_c_string("map [");
5024 Type* key_type = imp->read_type();
5025 imp->require_c_string("] ");
5026 Type* val_type = imp->read_type();
5027 return Type::make_map_type(key_type, val_type, imp->location());
5033 Type::make_map_type(Type* key_type, Type* val_type, Location location)
5035 return new Map_type(key_type, val_type, location);
5038 // Class Channel_type.
5043 Channel_type::do_hash_for_method(Gogo* gogo) const
5045 unsigned int ret = 0;
5046 if (this->may_send_)
5048 if (this->may_receive_)
5050 if (this->element_type_ != NULL)
5051 ret += this->element_type_->hash_for_method(gogo) << 2;
5055 // Whether this type is the same as T.
5058 Channel_type::is_identical(const Channel_type* t,
5059 bool errors_are_identical) const
5061 if (!Type::are_identical(this->element_type(), t->element_type(),
5062 errors_are_identical, NULL))
5064 return (this->may_send_ == t->may_send_
5065 && this->may_receive_ == t->may_receive_);
5068 // Return the tree for a channel type. A channel is a pointer to a
5069 // __go_channel struct. The __go_channel struct is defined in
5070 // libgo/runtime/channel.h.
5073 Channel_type::do_get_backend(Gogo* gogo)
5075 static Btype* backend_channel_type;
5076 if (backend_channel_type == NULL)
5078 std::vector<Backend::Btyped_identifier> bfields;
5079 Btype* bt = gogo->backend()->struct_type(bfields);
5080 bt = gogo->backend()->named_type("__go_channel", bt,
5081 Linemap::predeclared_location());
5082 backend_channel_type = gogo->backend()->pointer_type(bt);
5084 return backend_channel_type;
5087 // Build a type descriptor for a channel type.
5090 Channel_type::make_chan_type_descriptor_type()
5095 Type* tdt = Type::make_type_descriptor_type();
5096 Type* ptdt = Type::make_type_descriptor_ptr_type();
5098 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5101 Type::make_builtin_struct_type(3,
5104 "dir", uintptr_type);
5106 ret = Type::make_builtin_named_type("ChanType", sf);
5112 // Build a type descriptor for a map type.
5115 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5117 Location bloc = Linemap::predeclared_location();
5119 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
5121 const Struct_field_list* fields = ctdt->struct_type()->fields();
5123 Expression_list* vals = new Expression_list();
5126 Struct_field_list::const_iterator p = fields->begin();
5127 go_assert(p->is_field_name("commonType"));
5128 vals->push_back(this->type_descriptor_constructor(gogo,
5129 RUNTIME_TYPE_KIND_CHAN,
5133 go_assert(p->is_field_name("elem"));
5134 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5137 go_assert(p->is_field_name("dir"));
5138 // These bits must match the ones in libgo/runtime/go-type.h.
5140 if (this->may_receive_)
5142 if (this->may_send_)
5145 mpz_init_set_ui(iv, val);
5146 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
5150 go_assert(p == fields->end());
5152 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
5155 // Reflection string.
5158 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
5160 if (!this->may_send_)
5162 ret->append("chan");
5163 if (!this->may_receive_)
5165 ret->push_back(' ');
5166 this->append_reflection(this->element_type_, gogo, ret);
5172 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5174 ret->push_back('C');
5175 this->append_mangled_name(this->element_type_, gogo, ret);
5176 if (this->may_send_)
5177 ret->push_back('s');
5178 if (this->may_receive_)
5179 ret->push_back('r');
5180 ret->push_back('e');
5186 Channel_type::do_export(Export* exp) const
5188 exp->write_c_string("chan ");
5189 if (this->may_send_ && !this->may_receive_)
5190 exp->write_c_string("-< ");
5191 else if (this->may_receive_ && !this->may_send_)
5192 exp->write_c_string("<- ");
5193 exp->write_type(this->element_type_);
5199 Channel_type::do_import(Import* imp)
5201 imp->require_c_string("chan ");
5205 if (imp->match_c_string("-< "))
5209 may_receive = false;
5211 else if (imp->match_c_string("<- "))
5223 Type* element_type = imp->read_type();
5225 return Type::make_channel_type(may_send, may_receive, element_type);
5228 // Make a new channel type.
5231 Type::make_channel_type(bool send, bool receive, Type* element_type)
5233 return new Channel_type(send, receive, element_type);
5236 // Class Interface_type.
5241 Interface_type::do_traverse(Traverse* traverse)
5243 if (this->methods_ == NULL)
5244 return TRAVERSE_CONTINUE;
5245 return this->methods_->traverse(traverse);
5248 // Finalize the methods. This handles interface inheritance.
5251 Interface_type::finalize_methods()
5253 if (this->methods_ == NULL)
5255 std::vector<Named_type*> seen;
5256 bool is_recursive = false;
5259 while (from < this->methods_->size())
5261 const Typed_identifier* p = &this->methods_->at(from);
5262 if (!p->name().empty())
5265 for (i = 0; i < to; ++i)
5267 if (this->methods_->at(i).name() == p->name())
5269 error_at(p->location(), "duplicate method %qs",
5270 Gogo::message_name(p->name()).c_str());
5277 this->methods_->set(to, *p);
5284 Interface_type* it = p->type()->interface_type();
5287 error_at(p->location(), "interface contains embedded non-interface");
5295 error_at(p->location(), "invalid recursive interface");
5296 is_recursive = true;
5302 Named_type* nt = p->type()->named_type();
5305 std::vector<Named_type*>::const_iterator q;
5306 for (q = seen.begin(); q != seen.end(); ++q)
5310 error_at(p->location(), "inherited interface loop");
5314 if (q != seen.end())
5322 const Typed_identifier_list* methods = it->methods();
5323 if (methods == NULL)
5328 for (Typed_identifier_list::const_iterator q = methods->begin();
5329 q != methods->end();
5332 if (q->name().empty())
5334 if (q->type()->forwarded() == p->type()->forwarded())
5335 error_at(p->location(), "interface inheritance loop");
5339 for (i = from + 1; i < this->methods_->size(); ++i)
5341 const Typed_identifier* r = &this->methods_->at(i);
5342 if (r->name().empty()
5343 && r->type()->forwarded() == q->type()->forwarded())
5345 error_at(p->location(),
5346 "inherited interface listed twice");
5350 if (i == this->methods_->size())
5351 this->methods_->push_back(Typed_identifier(q->name(),
5356 else if (this->find_method(q->name()) == NULL)
5357 this->methods_->push_back(Typed_identifier(q->name(), q->type(),
5362 error_at(p->location(), "inherited method %qs is ambiguous",
5363 Gogo::message_name(q->name()).c_str());
5370 delete this->methods_;
5371 this->methods_ = NULL;
5375 this->methods_->resize(to);
5376 this->methods_->sort_by_name();
5380 // Return the method NAME, or NULL.
5382 const Typed_identifier*
5383 Interface_type::find_method(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();
5390 if (p->name() == name)
5395 // Return the method index.
5398 Interface_type::method_index(const std::string& name) const
5400 go_assert(this->methods_ != NULL);
5402 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5403 p != this->methods_->end();
5405 if (p->name() == name)
5410 // Return whether NAME is an unexported method, for better error
5414 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
5416 if (this->methods_ == NULL)
5418 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5419 p != this->methods_->end();
5422 const std::string& method_name(p->name());
5423 if (Gogo::is_hidden_name(method_name)
5424 && name == Gogo::unpack_hidden_name(method_name)
5425 && gogo->pack_hidden_name(name, false) != method_name)
5431 // Whether this type is identical with T.
5434 Interface_type::is_identical(const Interface_type* t,
5435 bool errors_are_identical) const
5437 // We require the same methods with the same types. The methods
5438 // have already been sorted.
5439 if (this->methods() == NULL || t->methods() == NULL)
5440 return this->methods() == t->methods();
5442 Typed_identifier_list::const_iterator p1 = this->methods()->begin();
5443 for (Typed_identifier_list::const_iterator p2 = t->methods()->begin();
5444 p2 != t->methods()->end();
5447 if (p1 == this->methods()->end())
5449 if (p1->name() != p2->name()
5450 || !Type::are_identical(p1->type(), p2->type(),
5451 errors_are_identical, NULL))
5454 if (p1 != this->methods()->end())
5459 // Whether we can assign the interface type T to this type. The types
5460 // are known to not be identical. An interface assignment is only
5461 // permitted if T is known to implement all methods in THIS.
5462 // Otherwise a type guard is required.
5465 Interface_type::is_compatible_for_assign(const Interface_type* t,
5466 std::string* reason) const
5468 if (this->methods() == NULL)
5470 for (Typed_identifier_list::const_iterator p = this->methods()->begin();
5471 p != this->methods()->end();
5474 const Typed_identifier* m = t->find_method(p->name());
5480 snprintf(buf, sizeof buf,
5481 _("need explicit conversion; missing method %s%s%s"),
5482 open_quote, Gogo::message_name(p->name()).c_str(),
5484 reason->assign(buf);
5489 std::string subreason;
5490 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
5494 std::string n = Gogo::message_name(p->name());
5495 size_t len = 100 + n.length() + subreason.length();
5496 char* buf = new char[len];
5497 if (subreason.empty())
5498 snprintf(buf, len, _("incompatible type for method %s%s%s"),
5499 open_quote, n.c_str(), close_quote);
5502 _("incompatible type for method %s%s%s (%s)"),
5503 open_quote, n.c_str(), close_quote,
5505 reason->assign(buf);
5518 Interface_type::do_hash_for_method(Gogo* gogo) const
5520 unsigned int ret = 0;
5521 if (this->methods_ != NULL)
5523 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5524 p != this->methods_->end();
5527 ret = Type::hash_string(p->name(), ret);
5528 ret += p->type()->hash_for_method(gogo);
5535 // Return true if T implements the interface. If it does not, and
5536 // REASON is not NULL, set *REASON to a useful error message.
5539 Interface_type::implements_interface(const Type* t, std::string* reason) const
5541 if (this->methods_ == NULL)
5544 bool is_pointer = false;
5545 const Named_type* nt = t->named_type();
5546 const Struct_type* st = t->struct_type();
5547 // If we start with a named type, we don't dereference it to find
5551 const Type* pt = t->points_to();
5554 // If T is a pointer to a named type, then we need to look at
5555 // the type to which it points.
5557 nt = pt->named_type();
5558 st = pt->struct_type();
5562 // If we have a named type, get the methods from it rather than from
5567 // Only named and struct types have methods.
5568 if (nt == NULL && st == NULL)
5572 if (t->points_to() != NULL
5573 && t->points_to()->interface_type() != NULL)
5574 reason->assign(_("pointer to interface type has no methods"));
5576 reason->assign(_("type has no methods"));
5581 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
5585 if (t->points_to() != NULL
5586 && t->points_to()->interface_type() != NULL)
5587 reason->assign(_("pointer to interface type has no methods"));
5589 reason->assign(_("type has no methods"));
5594 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5595 p != this->methods_->end();
5598 bool is_ambiguous = false;
5599 Method* m = (nt != NULL
5600 ? nt->method_function(p->name(), &is_ambiguous)
5601 : st->method_function(p->name(), &is_ambiguous));
5606 std::string n = Gogo::message_name(p->name());
5607 size_t len = n.length() + 100;
5608 char* buf = new char[len];
5610 snprintf(buf, len, _("ambiguous method %s%s%s"),
5611 open_quote, n.c_str(), close_quote);
5613 snprintf(buf, len, _("missing method %s%s%s"),
5614 open_quote, n.c_str(), close_quote);
5615 reason->assign(buf);
5621 Function_type *p_fn_type = p->type()->function_type();
5622 Function_type* m_fn_type = m->type()->function_type();
5623 go_assert(p_fn_type != NULL && m_fn_type != NULL);
5624 std::string subreason;
5625 if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
5629 std::string n = Gogo::message_name(p->name());
5630 size_t len = 100 + n.length() + subreason.length();
5631 char* buf = new char[len];
5632 if (subreason.empty())
5633 snprintf(buf, len, _("incompatible type for method %s%s%s"),
5634 open_quote, n.c_str(), close_quote);
5637 _("incompatible type for method %s%s%s (%s)"),
5638 open_quote, n.c_str(), close_quote,
5640 reason->assign(buf);
5646 if (!is_pointer && !m->is_value_method())
5650 std::string n = Gogo::message_name(p->name());
5651 size_t len = 100 + n.length();
5652 char* buf = new char[len];
5653 snprintf(buf, len, _("method %s%s%s requires a pointer"),
5654 open_quote, n.c_str(), close_quote);
5655 reason->assign(buf);
5665 // Return the backend representation of the empty interface type. We
5666 // use the same struct for all empty interfaces.
5669 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
5671 static Btype* empty_interface_type;
5672 if (empty_interface_type == NULL)
5674 std::vector<Backend::Btyped_identifier> bfields(2);
5676 Location bloc = Linemap::predeclared_location();
5678 Type* pdt = Type::make_type_descriptor_ptr_type();
5679 bfields[0].name = "__type_descriptor";
5680 bfields[0].btype = pdt->get_backend(gogo);
5681 bfields[0].location = bloc;
5683 Type* vt = Type::make_pointer_type(Type::make_void_type());
5684 bfields[1].name = "__object";
5685 bfields[1].btype = vt->get_backend(gogo);
5686 bfields[1].location = bloc;
5688 empty_interface_type = gogo->backend()->struct_type(bfields);
5690 return empty_interface_type;
5693 // Return the fields of a non-empty interface type. This is not
5694 // declared in types.h so that types.h doesn't have to #include
5698 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
5699 std::vector<Backend::Btyped_identifier>* bfields)
5701 Location loc = type->location();
5703 std::vector<Backend::Btyped_identifier> mfields(type->methods()->size() + 1);
5705 Type* pdt = Type::make_type_descriptor_ptr_type();
5706 mfields[0].name = "__type_descriptor";
5707 mfields[0].btype = pdt->get_backend(gogo);
5708 mfields[0].location = loc;
5710 std::string last_name = "";
5712 for (Typed_identifier_list::const_iterator p = type->methods()->begin();
5713 p != type->methods()->end();
5716 mfields[i].name = Gogo::unpack_hidden_name(p->name());
5717 mfields[i].btype = p->type()->get_backend(gogo);
5718 mfields[i].location = loc;
5719 // Sanity check: the names should be sorted.
5720 go_assert(p->name() > last_name);
5721 last_name = p->name();
5724 Btype* methods = gogo->backend()->struct_type(mfields);
5728 (*bfields)[0].name = "__methods";
5729 (*bfields)[0].btype = gogo->backend()->pointer_type(methods);
5730 (*bfields)[0].location = loc;
5732 Type* vt = Type::make_pointer_type(Type::make_void_type());
5733 (*bfields)[1].name = "__object";
5734 (*bfields)[1].btype = vt->get_backend(gogo);
5735 (*bfields)[1].location = Linemap::predeclared_location();
5738 // Return a tree for an interface type. An interface is a pointer to
5739 // a struct. The struct has three fields. The first field is a
5740 // pointer to the type descriptor for the dynamic type of the object.
5741 // The second field is a pointer to a table of methods for the
5742 // interface to be used with the object. The third field is the value
5743 // of the object itself.
5746 Interface_type::do_get_backend(Gogo* gogo)
5748 if (this->methods_ == NULL)
5749 return Interface_type::get_backend_empty_interface_type(gogo);
5752 std::vector<Backend::Btyped_identifier> bfields;
5753 get_backend_interface_fields(gogo, this, &bfields);
5754 return gogo->backend()->struct_type(bfields);
5758 // The type of an interface type descriptor.
5761 Interface_type::make_interface_type_descriptor_type()
5766 Type* tdt = Type::make_type_descriptor_type();
5767 Type* ptdt = Type::make_type_descriptor_ptr_type();
5769 Type* string_type = Type::lookup_string_type();
5770 Type* pointer_string_type = Type::make_pointer_type(string_type);
5773 Type::make_builtin_struct_type(3,
5774 "name", pointer_string_type,
5775 "pkgPath", pointer_string_type,
5778 Type* nsm = Type::make_builtin_named_type("imethod", sm);
5780 Type* slice_nsm = Type::make_array_type(nsm, NULL);
5782 Struct_type* s = Type::make_builtin_struct_type(2,
5784 "methods", slice_nsm);
5786 ret = Type::make_builtin_named_type("InterfaceType", s);
5792 // Build a type descriptor for an interface type.
5795 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5797 Location bloc = Linemap::predeclared_location();
5799 Type* itdt = Interface_type::make_interface_type_descriptor_type();
5801 const Struct_field_list* ifields = itdt->struct_type()->fields();
5803 Expression_list* ivals = new Expression_list();
5806 Struct_field_list::const_iterator pif = ifields->begin();
5807 go_assert(pif->is_field_name("commonType"));
5808 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
5809 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
5813 go_assert(pif->is_field_name("methods"));
5815 Expression_list* methods = new Expression_list();
5816 if (this->methods_ != NULL && !this->methods_->empty())
5818 Type* elemtype = pif->type()->array_type()->element_type();
5820 methods->reserve(this->methods_->size());
5821 for (Typed_identifier_list::const_iterator pm = this->methods_->begin();
5822 pm != this->methods_->end();
5825 const Struct_field_list* mfields = elemtype->struct_type()->fields();
5827 Expression_list* mvals = new Expression_list();
5830 Struct_field_list::const_iterator pmf = mfields->begin();
5831 go_assert(pmf->is_field_name("name"));
5832 std::string s = Gogo::unpack_hidden_name(pm->name());
5833 Expression* e = Expression::make_string(s, bloc);
5834 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
5837 go_assert(pmf->is_field_name("pkgPath"));
5838 if (!Gogo::is_hidden_name(pm->name()))
5839 mvals->push_back(Expression::make_nil(bloc));
5842 s = Gogo::hidden_name_prefix(pm->name());
5843 e = Expression::make_string(s, bloc);
5844 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
5848 go_assert(pmf->is_field_name("typ"));
5849 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
5852 go_assert(pmf == mfields->end());
5854 e = Expression::make_struct_composite_literal(elemtype, mvals,
5856 methods->push_back(e);
5860 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
5864 go_assert(pif == ifields->end());
5866 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
5869 // Reflection string.
5872 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
5874 ret->append("interface {");
5875 if (this->methods_ != NULL)
5877 ret->push_back(' ');
5878 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5879 p != this->methods_->end();
5882 if (p != this->methods_->begin())
5884 if (!Gogo::is_hidden_name(p->name()))
5885 ret->append(p->name());
5888 // This matches what the gc compiler does.
5889 std::string prefix = Gogo::hidden_name_prefix(p->name());
5890 ret->append(prefix.substr(prefix.find('.') + 1));
5891 ret->push_back('.');
5892 ret->append(Gogo::unpack_hidden_name(p->name()));
5894 std::string sub = p->type()->reflection(gogo);
5895 go_assert(sub.compare(0, 4, "func") == 0);
5896 sub = sub.substr(4);
5899 ret->push_back(' ');
5907 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5909 ret->push_back('I');
5911 const Typed_identifier_list* methods = this->methods_;
5912 if (methods != NULL)
5914 for (Typed_identifier_list::const_iterator p = methods->begin();
5915 p != methods->end();
5918 std::string n = Gogo::unpack_hidden_name(p->name());
5920 snprintf(buf, sizeof buf, "%u_",
5921 static_cast<unsigned int>(n.length()));
5924 this->append_mangled_name(p->type(), gogo, ret);
5928 ret->push_back('e');
5934 Interface_type::do_export(Export* exp) const
5936 exp->write_c_string("interface { ");
5938 const Typed_identifier_list* methods = this->methods_;
5939 if (methods != NULL)
5941 for (Typed_identifier_list::const_iterator pm = methods->begin();
5942 pm != methods->end();
5945 exp->write_string(pm->name());
5946 exp->write_c_string(" (");
5948 const Function_type* fntype = pm->type()->function_type();
5951 const Typed_identifier_list* parameters = fntype->parameters();
5952 if (parameters != NULL)
5954 bool is_varargs = fntype->is_varargs();
5955 for (Typed_identifier_list::const_iterator pp =
5956 parameters->begin();
5957 pp != parameters->end();
5963 exp->write_c_string(", ");
5964 if (!is_varargs || pp + 1 != parameters->end())
5965 exp->write_type(pp->type());
5968 exp->write_c_string("...");
5969 Type *pptype = pp->type();
5970 exp->write_type(pptype->array_type()->element_type());
5975 exp->write_c_string(")");
5977 const Typed_identifier_list* results = fntype->results();
5978 if (results != NULL)
5980 exp->write_c_string(" ");
5981 if (results->size() == 1)
5982 exp->write_type(results->begin()->type());
5986 exp->write_c_string("(");
5987 for (Typed_identifier_list::const_iterator p =
5989 p != results->end();
5995 exp->write_c_string(", ");
5996 exp->write_type(p->type());
5998 exp->write_c_string(")");
6002 exp->write_c_string("; ");
6006 exp->write_c_string("}");
6009 // Import an interface type.
6012 Interface_type::do_import(Import* imp)
6014 imp->require_c_string("interface { ");
6016 Typed_identifier_list* methods = new Typed_identifier_list;
6017 while (imp->peek_char() != '}')
6019 std::string name = imp->read_identifier();
6020 imp->require_c_string(" (");
6022 Typed_identifier_list* parameters;
6023 bool is_varargs = false;
6024 if (imp->peek_char() == ')')
6028 parameters = new Typed_identifier_list;
6031 if (imp->match_c_string("..."))
6037 Type* ptype = imp->read_type();
6039 ptype = Type::make_array_type(ptype, NULL);
6040 parameters->push_back(Typed_identifier(Import::import_marker,
6041 ptype, imp->location()));
6042 if (imp->peek_char() != ',')
6044 go_assert(!is_varargs);
6045 imp->require_c_string(", ");
6048 imp->require_c_string(")");
6050 Typed_identifier_list* results;
6051 if (imp->peek_char() != ' ')
6055 results = new Typed_identifier_list;
6057 if (imp->peek_char() != '(')
6059 Type* rtype = imp->read_type();
6060 results->push_back(Typed_identifier(Import::import_marker,
6061 rtype, imp->location()));
6068 Type* rtype = imp->read_type();
6069 results->push_back(Typed_identifier(Import::import_marker,
6070 rtype, imp->location()));
6071 if (imp->peek_char() != ',')
6073 imp->require_c_string(", ");
6075 imp->require_c_string(")");
6079 Function_type* fntype = Type::make_function_type(NULL, parameters,
6083 fntype->set_is_varargs();
6084 methods->push_back(Typed_identifier(name, fntype, imp->location()));
6086 imp->require_c_string("; ");
6089 imp->require_c_string("}");
6091 if (methods->empty())
6097 return Type::make_interface_type(methods, imp->location());
6100 // Make an interface type.
6103 Type::make_interface_type(Typed_identifier_list* methods,
6106 return new Interface_type(methods, location);
6111 // Bind a method to an object.
6114 Method::bind_method(Expression* expr, Location location) const
6116 if (this->stub_ == NULL)
6118 // When there is no stub object, the binding is determined by
6120 return this->do_bind_method(expr, location);
6122 return Expression::make_bound_method(expr, this->stub_, location);
6125 // Return the named object associated with a method. This may only be
6126 // called after methods are finalized.
6129 Method::named_object() const
6131 if (this->stub_ != NULL)
6133 return this->do_named_object();
6136 // Class Named_method.
6138 // The type of the method.
6141 Named_method::do_type() const
6143 if (this->named_object_->is_function())
6144 return this->named_object_->func_value()->type();
6145 else if (this->named_object_->is_function_declaration())
6146 return this->named_object_->func_declaration_value()->type();
6151 // Return the location of the method receiver.
6154 Named_method::do_receiver_location() const
6156 return this->do_type()->receiver()->location();
6159 // Bind a method to an object.
6162 Named_method::do_bind_method(Expression* expr, Location location) const
6164 Named_object* no = this->named_object_;
6165 Bound_method_expression* bme = Expression::make_bound_method(expr, no,
6167 // If this is not a local method, and it does not use a stub, then
6168 // the real method expects a different type. We need to cast the
6170 if (this->depth() > 0 && !this->needs_stub_method())
6172 Function_type* ftype = this->do_type();
6173 go_assert(ftype->is_method());
6174 Type* frtype = ftype->receiver()->type();
6175 bme->set_first_argument_type(frtype);
6180 // Class Interface_method.
6182 // Bind a method to an object.
6185 Interface_method::do_bind_method(Expression* expr,
6186 Location location) const
6188 return Expression::make_interface_field_reference(expr, this->name_,
6194 // Insert a new method. Return true if it was inserted, false
6198 Methods::insert(const std::string& name, Method* m)
6200 std::pair<Method_map::iterator, bool> ins =
6201 this->methods_.insert(std::make_pair(name, m));
6206 Method* old_method = ins.first->second;
6207 if (m->depth() < old_method->depth())
6210 ins.first->second = m;
6215 if (m->depth() == old_method->depth())
6216 old_method->set_is_ambiguous();
6222 // Return the number of unambiguous methods.
6225 Methods::count() const
6228 for (Method_map::const_iterator p = this->methods_.begin();
6229 p != this->methods_.end();
6231 if (!p->second->is_ambiguous())
6236 // Class Named_type.
6238 // Return the name of the type.
6241 Named_type::name() const
6243 return this->named_object_->name();
6246 // Return the name of the type to use in an error message.
6249 Named_type::message_name() const
6251 return this->named_object_->message_name();
6254 // Return the base type for this type. We have to be careful about
6255 // circular type definitions, which are invalid but may be seen here.
6258 Named_type::named_base()
6263 Type* ret = this->type_->base();
6264 this->seen_ = false;
6269 Named_type::named_base() const
6274 const Type* ret = this->type_->base();
6275 this->seen_ = false;
6279 // Return whether this is an error type. We have to be careful about
6280 // circular type definitions, which are invalid but may be seen here.
6283 Named_type::is_named_error_type() const
6288 bool ret = this->type_->is_error_type();
6289 this->seen_ = false;
6293 // Add a method to this type.
6296 Named_type::add_method(const std::string& name, Function* function)
6298 if (this->local_methods_ == NULL)
6299 this->local_methods_ = new Bindings(NULL);
6300 return this->local_methods_->add_function(name, NULL, function);
6303 // Add a method declaration to this type.
6306 Named_type::add_method_declaration(const std::string& name, Package* package,
6307 Function_type* type,
6310 if (this->local_methods_ == NULL)
6311 this->local_methods_ = new Bindings(NULL);
6312 return this->local_methods_->add_function_declaration(name, package, type,
6316 // Add an existing method to this type.
6319 Named_type::add_existing_method(Named_object* no)
6321 if (this->local_methods_ == NULL)
6322 this->local_methods_ = new Bindings(NULL);
6323 this->local_methods_->add_named_object(no);
6326 // Look for a local method NAME, and returns its named object, or NULL
6330 Named_type::find_local_method(const std::string& name) const
6332 if (this->local_methods_ == NULL)
6334 return this->local_methods_->lookup(name);
6337 // Return whether NAME is an unexported field or method, for better
6341 Named_type::is_unexported_local_method(Gogo* gogo,
6342 const std::string& name) const
6344 Bindings* methods = this->local_methods_;
6345 if (methods != NULL)
6347 for (Bindings::const_declarations_iterator p =
6348 methods->begin_declarations();
6349 p != methods->end_declarations();
6352 if (Gogo::is_hidden_name(p->first)
6353 && name == Gogo::unpack_hidden_name(p->first)
6354 && gogo->pack_hidden_name(name, false) != p->first)
6361 // Build the complete list of methods for this type, which means
6362 // recursively including all methods for anonymous fields. Create all
6366 Named_type::finalize_methods(Gogo* gogo)
6368 if (this->all_methods_ != NULL)
6371 if (this->local_methods_ != NULL
6372 && (this->points_to() != NULL || this->interface_type() != NULL))
6374 const Bindings* lm = this->local_methods_;
6375 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
6376 p != lm->end_declarations();
6378 error_at(p->second->location(),
6379 "invalid pointer or interface receiver type");
6380 delete this->local_methods_;
6381 this->local_methods_ = NULL;
6385 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6388 // Return the method NAME, or NULL if there isn't one or if it is
6389 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6393 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
6395 return Type::method_function(this->all_methods_, name, is_ambiguous);
6398 // Return a pointer to the interface method table for this type for
6399 // the interface INTERFACE. IS_POINTER is true if this is for a
6403 Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface,
6406 go_assert(!interface->is_empty());
6408 Interface_method_tables** pimt = (is_pointer
6409 ? &this->interface_method_tables_
6410 : &this->pointer_interface_method_tables_);
6413 *pimt = new Interface_method_tables(5);
6415 std::pair<const Interface_type*, tree> val(interface, NULL_TREE);
6416 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
6420 // This is a new entry in the hash table.
6421 go_assert(ins.first->second == NULL_TREE);
6422 ins.first->second = gogo->interface_method_table_for_type(interface,
6427 tree decl = ins.first->second;
6428 if (decl == error_mark_node)
6429 return error_mark_node;
6430 go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL);
6431 return build_fold_addr_expr(decl);
6434 // Return whether a named type has any hidden fields.
6437 Named_type::named_type_has_hidden_fields(std::string* reason) const
6442 bool ret = this->type_->has_hidden_fields(this, reason);
6443 this->seen_ = false;
6447 // Look for a use of a complete type within another type. This is
6448 // used to check that we don't try to use a type within itself.
6450 class Find_type_use : public Traverse
6453 Find_type_use(Named_type* find_type)
6454 : Traverse(traverse_types),
6455 find_type_(find_type), found_(false)
6458 // Whether we found the type.
6461 { return this->found_; }
6468 // The type we are looking for.
6469 Named_type* find_type_;
6470 // Whether we found the type.
6474 // Check for FIND_TYPE in TYPE.
6477 Find_type_use::type(Type* type)
6479 if (type->named_type() != NULL && this->find_type_ == type->named_type())
6481 this->found_ = true;
6482 return TRAVERSE_EXIT;
6485 // It's OK if we see a reference to the type in any type which is
6486 // essentially a pointer: a pointer, a slice, a function, a map, or
6488 if (type->points_to() != NULL
6489 || type->is_slice_type()
6490 || type->function_type() != NULL
6491 || type->map_type() != NULL
6492 || type->channel_type() != NULL)
6493 return TRAVERSE_SKIP_COMPONENTS;
6495 // For an interface, a reference to the type in a method type should
6496 // be ignored, but we have to consider direct inheritance. When
6497 // this is called, there may be cases of direct inheritance
6498 // represented as a method with no name.
6499 if (type->interface_type() != NULL)
6501 const Typed_identifier_list* methods = type->interface_type()->methods();
6502 if (methods != NULL)
6504 for (Typed_identifier_list::const_iterator p = methods->begin();
6505 p != methods->end();
6508 if (p->name().empty())
6510 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
6511 return TRAVERSE_EXIT;
6515 return TRAVERSE_SKIP_COMPONENTS;
6518 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
6519 // to convert TYPE to the backend representation before we convert
6521 if (type->named_type() != NULL)
6523 switch (type->base()->classification())
6525 case Type::TYPE_ERROR:
6526 case Type::TYPE_BOOLEAN:
6527 case Type::TYPE_INTEGER:
6528 case Type::TYPE_FLOAT:
6529 case Type::TYPE_COMPLEX:
6530 case Type::TYPE_STRING:
6531 case Type::TYPE_NIL:
6534 case Type::TYPE_ARRAY:
6535 case Type::TYPE_STRUCT:
6536 this->find_type_->add_dependency(type->named_type());
6539 case Type::TYPE_VOID:
6540 case Type::TYPE_SINK:
6541 case Type::TYPE_FUNCTION:
6542 case Type::TYPE_POINTER:
6543 case Type::TYPE_CALL_MULTIPLE_RESULT:
6544 case Type::TYPE_MAP:
6545 case Type::TYPE_CHANNEL:
6546 case Type::TYPE_INTERFACE:
6547 case Type::TYPE_NAMED:
6548 case Type::TYPE_FORWARD:
6554 return TRAVERSE_CONTINUE;
6557 // Verify that a named type does not refer to itself.
6560 Named_type::do_verify()
6562 Find_type_use find(this);
6563 Type::traverse(this->type_, &find);
6566 error_at(this->location_, "invalid recursive type %qs",
6567 this->message_name().c_str());
6568 this->is_error_ = true;
6572 // Check whether any of the local methods overloads an existing
6573 // struct field or interface method. We don't need to check the
6574 // list of methods against itself: that is handled by the Bindings
6576 if (this->local_methods_ != NULL)
6578 Struct_type* st = this->type_->struct_type();
6579 bool found_dup = false;
6582 for (Bindings::const_declarations_iterator p =
6583 this->local_methods_->begin_declarations();
6584 p != this->local_methods_->end_declarations();
6587 const std::string& name(p->first);
6588 if (st != NULL && st->find_local_field(name, NULL) != NULL)
6590 error_at(p->second->location(),
6591 "method %qs redeclares struct field name",
6592 Gogo::message_name(name).c_str());
6604 // Return whether this type is or contains a pointer.
6607 Named_type::do_has_pointer() const
6612 bool ret = this->type_->has_pointer();
6613 this->seen_ = false;
6617 // Return a hash code. This is used for method lookup. We simply
6618 // hash on the name itself.
6621 Named_type::do_hash_for_method(Gogo* gogo) const
6623 const std::string& name(this->named_object()->name());
6624 unsigned int ret = Type::hash_string(name, 0);
6626 // GOGO will be NULL here when called from Type_hash_identical.
6627 // That is OK because that is only used for internal hash tables
6628 // where we are going to be comparing named types for equality. In
6629 // other cases, which are cases where the runtime is going to
6630 // compare hash codes to see if the types are the same, we need to
6631 // include the package prefix and name in the hash.
6632 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
6634 const Package* package = this->named_object()->package();
6635 if (package == NULL)
6637 ret = Type::hash_string(gogo->unique_prefix(), ret);
6638 ret = Type::hash_string(gogo->package_name(), ret);
6642 ret = Type::hash_string(package->unique_prefix(), ret);
6643 ret = Type::hash_string(package->name(), ret);
6650 // Convert a named type to the backend representation. In order to
6651 // get dependencies right, we fill in a dummy structure for this type,
6652 // then convert all the dependencies, then complete this type. When
6653 // this function is complete, the size of the type is known.
6656 Named_type::convert(Gogo* gogo)
6658 if (this->is_error_ || this->is_converted_)
6661 this->create_placeholder(gogo);
6663 // Convert all the dependencies. If they refer indirectly back to
6664 // this type, they will pick up the intermediate tree we just
6666 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
6667 p != this->dependencies_.end();
6669 (*p)->convert(gogo);
6671 // Complete this type.
6672 Btype* bt = this->named_btype_;
6673 Type* base = this->type_->base();
6674 switch (base->classification())
6691 // The size of these types is already correct. We don't worry
6692 // about filling them in until later, when we also track
6693 // circular references.
6698 std::vector<Backend::Btyped_identifier> bfields;
6699 get_backend_struct_fields(gogo, base->struct_type()->fields(),
6701 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6702 bt = gogo->backend()->error_type();
6707 // Slice types were completed in create_placeholder.
6708 if (!base->is_slice_type())
6710 Btype* bet = base->array_type()->get_backend_element(gogo);
6711 Bexpression* blen = base->array_type()->get_backend_length(gogo);
6712 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
6713 bt = gogo->backend()->error_type();
6717 case TYPE_INTERFACE:
6718 // Interface types were completed in create_placeholder.
6726 case TYPE_CALL_MULTIPLE_RESULT:
6732 this->named_btype_ = bt;
6733 this->is_converted_ = true;
6736 // Create the placeholder for a named type. This is the first step in
6737 // converting to the backend representation.
6740 Named_type::create_placeholder(Gogo* gogo)
6742 if (this->is_error_)
6743 this->named_btype_ = gogo->backend()->error_type();
6745 if (this->named_btype_ != NULL)
6748 // Create the structure for this type. Note that because we call
6749 // base() here, we don't attempt to represent a named type defined
6750 // as another named type. Instead both named types will point to
6751 // different base representations.
6752 Type* base = this->type_->base();
6754 bool set_name = true;
6755 switch (base->classification())
6758 this->is_error_ = true;
6759 this->named_btype_ = gogo->backend()->error_type();
6769 // These are simple basic types, we can just create them
6771 bt = Type::get_named_base_btype(gogo, base);
6776 // All maps and channels have the same backend representation.
6777 bt = Type::get_named_base_btype(gogo, base);
6783 bool for_function = base->classification() == TYPE_FUNCTION;
6784 bt = gogo->backend()->placeholder_pointer_type(this->name(),
6792 bt = gogo->backend()->placeholder_struct_type(this->name(),
6798 if (base->is_slice_type())
6799 bt = gogo->backend()->placeholder_struct_type(this->name(),
6802 bt = gogo->backend()->placeholder_array_type(this->name(),
6807 case TYPE_INTERFACE:
6808 if (base->interface_type()->is_empty())
6809 bt = Interface_type::get_backend_empty_interface_type(gogo);
6812 bt = gogo->backend()->placeholder_struct_type(this->name(),
6820 case TYPE_CALL_MULTIPLE_RESULT:
6827 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
6829 this->named_btype_ = bt;
6831 if (base->is_slice_type())
6833 // We do not record slices as dependencies of other types,
6834 // because we can fill them in completely here with the final
6836 std::vector<Backend::Btyped_identifier> bfields;
6837 get_backend_slice_fields(gogo, base->array_type(), &bfields);
6838 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6839 this->named_btype_ = gogo->backend()->error_type();
6841 else if (base->interface_type() != NULL
6842 && !base->interface_type()->is_empty())
6844 // We do not record interfaces as dependencies of other types,
6845 // because we can fill them in completely here with the final
6847 std::vector<Backend::Btyped_identifier> bfields;
6848 get_backend_interface_fields(gogo, base->interface_type(), &bfields);
6849 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
6850 this->named_btype_ = gogo->backend()->error_type();
6854 // Get a tree for a named type.
6857 Named_type::do_get_backend(Gogo* gogo)
6859 if (this->is_error_)
6860 return gogo->backend()->error_type();
6862 Btype* bt = this->named_btype_;
6864 if (!gogo->named_types_are_converted())
6866 // We have not completed converting named types. NAMED_BTYPE_
6867 // is a placeholder and we shouldn't do anything further.
6871 // We don't build dependencies for types whose sizes do not
6872 // change or are not relevant, so we may see them here while
6873 // converting types.
6874 this->create_placeholder(gogo);
6875 bt = this->named_btype_;
6876 go_assert(bt != NULL);
6880 // We are not converting types. This should only be called if the
6881 // type has already been converted.
6882 if (!this->is_converted_)
6884 go_assert(saw_errors());
6885 return gogo->backend()->error_type();
6888 go_assert(bt != NULL);
6890 // Complete the tree.
6891 Type* base = this->type_->base();
6893 switch (base->classification())
6896 return gogo->backend()->error_type();
6909 case TYPE_INTERFACE:
6913 // Don't build a circular data structure. GENERIC can't handle
6915 if (this->seen_in_get_backend_)
6917 this->is_circular_ = true;
6918 return gogo->backend()->circular_pointer_type(bt, true);
6920 this->seen_in_get_backend_ = true;
6921 bt1 = Type::get_named_base_btype(gogo, base);
6922 this->seen_in_get_backend_ = false;
6923 if (this->is_circular_)
6924 bt1 = gogo->backend()->circular_pointer_type(bt, true);
6925 if (!gogo->backend()->set_placeholder_function_type(bt, bt1))
6926 bt = gogo->backend()->error_type();
6930 // Don't build a circular data structure. GENERIC can't handle
6932 if (this->seen_in_get_backend_)
6934 this->is_circular_ = true;
6935 return gogo->backend()->circular_pointer_type(bt, false);
6937 this->seen_in_get_backend_ = true;
6938 bt1 = Type::get_named_base_btype(gogo, base);
6939 this->seen_in_get_backend_ = false;
6940 if (this->is_circular_)
6941 bt1 = gogo->backend()->circular_pointer_type(bt, false);
6942 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
6943 bt = gogo->backend()->error_type();
6948 case TYPE_CALL_MULTIPLE_RESULT:
6957 // Build a type descriptor for a named type.
6960 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6962 // If NAME is not NULL, then we don't really want the type
6963 // descriptor for this type; we want the descriptor for the
6964 // underlying type, giving it the name NAME.
6965 return this->named_type_descriptor(gogo, this->type_,
6966 name == NULL ? this : name);
6969 // Add to the reflection string. This is used mostly for the name of
6970 // the type used in a type descriptor, not for actual reflection
6974 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
6976 if (!Linemap::is_predeclared_location(this->location()))
6978 const Package* package = this->named_object_->package();
6979 if (package != NULL)
6980 ret->append(package->name());
6982 ret->append(gogo->package_name());
6983 ret->push_back('.');
6985 if (this->in_function_ != NULL)
6987 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
6988 ret->push_back('$');
6990 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
6993 // Get the mangled name.
6996 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6998 Named_object* no = this->named_object_;
7000 if (Linemap::is_predeclared_location(this->location()))
7001 go_assert(this->in_function_ == NULL);
7004 const std::string& unique_prefix(no->package() == NULL
7005 ? gogo->unique_prefix()
7006 : no->package()->unique_prefix());
7007 const std::string& package_name(no->package() == NULL
7008 ? gogo->package_name()
7009 : no->package()->name());
7010 name = unique_prefix;
7011 name.append(1, '.');
7012 name.append(package_name);
7013 name.append(1, '.');
7014 if (this->in_function_ != NULL)
7016 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
7017 name.append(1, '$');
7020 name.append(Gogo::unpack_hidden_name(no->name()));
7022 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
7027 // Export the type. This is called to export a global type.
7030 Named_type::export_named_type(Export* exp, const std::string&) const
7032 // We don't need to write the name of the type here, because it will
7033 // be written by Export::write_type anyhow.
7034 exp->write_c_string("type ");
7035 exp->write_type(this);
7036 exp->write_c_string(";\n");
7039 // Import a named type.
7042 Named_type::import_named_type(Import* imp, Named_type** ptype)
7044 imp->require_c_string("type ");
7045 Type *type = imp->read_type();
7046 *ptype = type->named_type();
7047 go_assert(*ptype != NULL);
7048 imp->require_c_string(";\n");
7051 // Export the type when it is referenced by another type. In this
7052 // case Export::export_type will already have issued the name.
7055 Named_type::do_export(Export* exp) const
7057 exp->write_type(this->type_);
7059 // To save space, we only export the methods directly attached to
7061 Bindings* methods = this->local_methods_;
7062 if (methods == NULL)
7065 exp->write_c_string("\n");
7066 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
7067 p != methods->end_definitions();
7070 exp->write_c_string(" ");
7071 (*p)->export_named_object(exp);
7074 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
7075 p != methods->end_declarations();
7078 if (p->second->is_function_declaration())
7080 exp->write_c_string(" ");
7081 p->second->export_named_object(exp);
7086 // Make a named type.
7089 Type::make_named_type(Named_object* named_object, Type* type,
7092 return new Named_type(named_object, type, location);
7095 // Finalize the methods for TYPE. It will be a named type or a struct
7096 // type. This sets *ALL_METHODS to the list of methods, and builds
7097 // all required stubs.
7100 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
7101 Methods** all_methods)
7103 *all_methods = NULL;
7104 Types_seen types_seen;
7105 Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen,
7107 Type::build_stub_methods(gogo, type, *all_methods, location);
7110 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
7111 // build up the struct field indexes as we go. DEPTH is the depth of
7112 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
7113 // adding these methods for an anonymous field with pointer type.
7114 // NEEDS_STUB_METHOD is true if we need to use a stub method which
7115 // calls the real method. TYPES_SEEN is used to avoid infinite
7119 Type::add_methods_for_type(const Type* type,
7120 const Method::Field_indexes* field_indexes,
7122 bool is_embedded_pointer,
7123 bool needs_stub_method,
7124 Types_seen* types_seen,
7127 // Pointer types may not have methods.
7128 if (type->points_to() != NULL)
7131 const Named_type* nt = type->named_type();
7134 std::pair<Types_seen::iterator, bool> ins = types_seen->insert(nt);
7140 Type::add_local_methods_for_type(nt, field_indexes, depth,
7141 is_embedded_pointer, needs_stub_method,
7144 Type::add_embedded_methods_for_type(type, field_indexes, depth,
7145 is_embedded_pointer, needs_stub_method,
7146 types_seen, methods);
7148 // If we are called with depth > 0, then we are looking at an
7149 // anonymous field of a struct. If such a field has interface type,
7150 // then we need to add the interface methods. We don't want to add
7151 // them when depth == 0, because we will already handle them
7152 // following the usual rules for an interface type.
7154 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
7157 // Add the local methods for the named type NT to *METHODS. The
7158 // parameters are as for add_methods_to_type.
7161 Type::add_local_methods_for_type(const Named_type* nt,
7162 const Method::Field_indexes* field_indexes,
7164 bool is_embedded_pointer,
7165 bool needs_stub_method,
7168 const Bindings* local_methods = nt->local_methods();
7169 if (local_methods == NULL)
7172 if (*methods == NULL)
7173 *methods = new Methods();
7175 for (Bindings::const_declarations_iterator p =
7176 local_methods->begin_declarations();
7177 p != local_methods->end_declarations();
7180 Named_object* no = p->second;
7181 bool is_value_method = (is_embedded_pointer
7182 || !Type::method_expects_pointer(no));
7183 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
7185 || (depth > 0 && is_value_method)));
7186 if (!(*methods)->insert(no->name(), m))
7191 // Add the embedded methods for TYPE to *METHODS. These are the
7192 // methods attached to anonymous fields. The parameters are as for
7193 // add_methods_to_type.
7196 Type::add_embedded_methods_for_type(const Type* type,
7197 const Method::Field_indexes* field_indexes,
7199 bool is_embedded_pointer,
7200 bool needs_stub_method,
7201 Types_seen* types_seen,
7204 // Look for anonymous fields in TYPE. TYPE has fields if it is a
7206 const Struct_type* st = type->struct_type();
7210 const Struct_field_list* fields = st->fields();
7215 for (Struct_field_list::const_iterator pf = fields->begin();
7216 pf != fields->end();
7219 if (!pf->is_anonymous())
7222 Type* ftype = pf->type();
7223 bool is_pointer = false;
7224 if (ftype->points_to() != NULL)
7226 ftype = ftype->points_to();
7229 Named_type* fnt = ftype->named_type();
7232 // This is an error, but it will be diagnosed elsewhere.
7236 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
7237 sub_field_indexes->next = field_indexes;
7238 sub_field_indexes->field_index = i;
7240 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
7241 (is_embedded_pointer || is_pointer),
7250 // If TYPE is an interface type, then add its method to *METHODS.
7251 // This is for interface methods attached to an anonymous field. The
7252 // parameters are as for add_methods_for_type.
7255 Type::add_interface_methods_for_type(const Type* type,
7256 const Method::Field_indexes* field_indexes,
7260 const Interface_type* it = type->interface_type();
7264 const Typed_identifier_list* imethods = it->methods();
7265 if (imethods == NULL)
7268 if (*methods == NULL)
7269 *methods = new Methods();
7271 for (Typed_identifier_list::const_iterator pm = imethods->begin();
7272 pm != imethods->end();
7275 Function_type* fntype = pm->type()->function_type();
7278 // This is an error, but it should be reported elsewhere
7279 // when we look at the methods for IT.
7282 go_assert(!fntype->is_method());
7283 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
7284 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
7285 field_indexes, depth);
7286 if (!(*methods)->insert(pm->name(), m))
7291 // Build stub methods for TYPE as needed. METHODS is the set of
7292 // methods for the type. A stub method may be needed when a type
7293 // inherits a method from an anonymous field. When we need the
7294 // address of the method, as in a type descriptor, we need to build a
7295 // little stub which does the required field dereferences and jumps to
7296 // the real method. LOCATION is the location of the type definition.
7299 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
7302 if (methods == NULL)
7304 for (Methods::const_iterator p = methods->begin();
7305 p != methods->end();
7308 Method* m = p->second;
7309 if (m->is_ambiguous() || !m->needs_stub_method())
7312 const std::string& name(p->first);
7314 // Build a stub method.
7316 const Function_type* fntype = m->type();
7318 static unsigned int counter;
7320 snprintf(buf, sizeof buf, "$this%u", counter);
7323 Type* receiver_type = const_cast<Type*>(type);
7324 if (!m->is_value_method())
7325 receiver_type = Type::make_pointer_type(receiver_type);
7326 Location receiver_location = m->receiver_location();
7327 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
7330 const Typed_identifier_list* fnparams = fntype->parameters();
7331 Typed_identifier_list* stub_params;
7332 if (fnparams == NULL || fnparams->empty())
7336 // We give each stub parameter a unique name.
7337 stub_params = new Typed_identifier_list();
7338 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
7339 pp != fnparams->end();
7343 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
7344 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
7350 const Typed_identifier_list* fnresults = fntype->results();
7351 Typed_identifier_list* stub_results;
7352 if (fnresults == NULL || fnresults->empty())
7353 stub_results = NULL;
7356 // We create the result parameters without any names, since
7357 // we won't refer to them.
7358 stub_results = new Typed_identifier_list();
7359 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
7360 pr != fnresults->end();
7362 stub_results->push_back(Typed_identifier("", pr->type(),
7366 Function_type* stub_type = Type::make_function_type(receiver,
7369 fntype->location());
7370 if (fntype->is_varargs())
7371 stub_type->set_is_varargs();
7373 // We only create the function in the package which creates the
7375 const Package* package;
7376 if (type->named_type() == NULL)
7379 package = type->named_type()->named_object()->package();
7381 if (package != NULL)
7382 stub = Named_object::make_function_declaration(name, package,
7383 stub_type, location);
7386 stub = gogo->start_function(name, stub_type, false,
7387 fntype->location());
7388 Type::build_one_stub_method(gogo, m, buf, stub_params,
7389 fntype->is_varargs(), location);
7390 gogo->finish_function(fntype->location());
7393 m->set_stub_object(stub);
7397 // Build a stub method which adjusts the receiver as required to call
7398 // METHOD. RECEIVER_NAME is the name we used for the receiver.
7399 // PARAMS is the list of function parameters.
7402 Type::build_one_stub_method(Gogo* gogo, Method* method,
7403 const char* receiver_name,
7404 const Typed_identifier_list* params,
7408 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
7409 go_assert(receiver_object != NULL);
7411 Expression* expr = Expression::make_var_reference(receiver_object, location);
7412 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
7413 if (expr->type()->points_to() == NULL)
7414 expr = Expression::make_unary(OPERATOR_AND, expr, location);
7416 Expression_list* arguments;
7417 if (params == NULL || params->empty())
7421 arguments = new Expression_list();
7422 for (Typed_identifier_list::const_iterator p = params->begin();
7426 Named_object* param = gogo->lookup(p->name(), NULL);
7427 go_assert(param != NULL);
7428 Expression* param_ref = Expression::make_var_reference(param,
7430 arguments->push_back(param_ref);
7434 Expression* func = method->bind_method(expr, location);
7435 go_assert(func != NULL);
7436 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
7438 call->set_hidden_fields_are_ok();
7439 size_t count = call->result_count();
7441 gogo->add_statement(Statement::make_statement(call, true));
7444 Expression_list* retvals = new Expression_list();
7446 retvals->push_back(call);
7449 for (size_t i = 0; i < count; ++i)
7450 retvals->push_back(Expression::make_call_result(call, i));
7452 Return_statement* retstat = Statement::make_return_statement(retvals,
7455 // We can return values with hidden fields from a stub. This is
7456 // necessary if the method is itself hidden.
7457 retstat->set_hidden_fields_are_ok();
7459 gogo->add_statement(retstat);
7463 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
7464 // in reverse order.
7467 Type::apply_field_indexes(Expression* expr,
7468 const Method::Field_indexes* field_indexes,
7471 if (field_indexes == NULL)
7473 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
7474 Struct_type* stype = expr->type()->deref()->struct_type();
7475 go_assert(stype != NULL
7476 && field_indexes->field_index < stype->field_count());
7477 if (expr->type()->struct_type() == NULL)
7479 go_assert(expr->type()->points_to() != NULL);
7480 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
7481 go_assert(expr->type()->struct_type() == stype);
7483 return Expression::make_field_reference(expr, field_indexes->field_index,
7487 // Return whether NO is a method for which the receiver is a pointer.
7490 Type::method_expects_pointer(const Named_object* no)
7492 const Function_type *fntype;
7493 if (no->is_function())
7494 fntype = no->func_value()->type();
7495 else if (no->is_function_declaration())
7496 fntype = no->func_declaration_value()->type();
7499 return fntype->receiver()->type()->points_to() != NULL;
7502 // Given a set of methods for a type, METHODS, return the method NAME,
7503 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
7504 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
7505 // but is ambiguous (and return NULL).
7508 Type::method_function(const Methods* methods, const std::string& name,
7511 if (is_ambiguous != NULL)
7512 *is_ambiguous = false;
7513 if (methods == NULL)
7515 Methods::const_iterator p = methods->find(name);
7516 if (p == methods->end())
7518 Method* m = p->second;
7519 if (m->is_ambiguous())
7521 if (is_ambiguous != NULL)
7522 *is_ambiguous = true;
7528 // Look for field or method NAME for TYPE. Return an Expression for
7529 // the field or method bound to EXPR. If there is no such field or
7530 // method, give an appropriate error and return an error expression.
7533 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
7534 const std::string& name,
7537 if (type->deref()->is_error_type())
7538 return Expression::make_error(location);
7540 const Named_type* nt = type->deref()->named_type();
7541 const Struct_type* st = type->deref()->struct_type();
7542 const Interface_type* it = type->interface_type();
7544 // If this is a pointer to a pointer, then it is possible that the
7545 // pointed-to type has methods.
7549 && type->points_to() != NULL
7550 && type->points_to()->points_to() != NULL)
7552 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
7553 type = type->points_to();
7554 if (type->deref()->is_error_type())
7555 return Expression::make_error(location);
7556 nt = type->points_to()->named_type();
7557 st = type->points_to()->struct_type();
7560 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
7561 || expr->is_addressable());
7562 std::vector<const Named_type*> seen;
7563 bool is_method = false;
7564 bool found_pointer_method = false;
7567 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
7568 &seen, NULL, &is_method,
7569 &found_pointer_method, &ambig1, &ambig2))
7574 go_assert(st != NULL);
7575 if (type->struct_type() == NULL)
7577 go_assert(type->points_to() != NULL);
7578 expr = Expression::make_unary(OPERATOR_MULT, expr,
7580 go_assert(expr->type()->struct_type() == st);
7582 ret = st->field_reference(expr, name, location);
7584 else if (it != NULL && it->find_method(name) != NULL)
7585 ret = Expression::make_interface_field_reference(expr, name,
7591 m = nt->method_function(name, NULL);
7592 else if (st != NULL)
7593 m = st->method_function(name, NULL);
7596 go_assert(m != NULL);
7597 if (!m->is_value_method() && expr->type()->points_to() == NULL)
7598 expr = Expression::make_unary(OPERATOR_AND, expr, location);
7599 ret = m->bind_method(expr, location);
7601 go_assert(ret != NULL);
7606 if (!ambig1.empty())
7607 error_at(location, "%qs is ambiguous via %qs and %qs",
7608 Gogo::message_name(name).c_str(), ambig1.c_str(),
7610 else if (found_pointer_method)
7611 error_at(location, "method requires a pointer");
7612 else if (nt == NULL && st == NULL && it == NULL)
7614 ("reference to field %qs in object which "
7615 "has no fields or methods"),
7616 Gogo::message_name(name).c_str());
7620 if (!Gogo::is_hidden_name(name))
7621 is_unexported = false;
7624 std::string unpacked = Gogo::unpack_hidden_name(name);
7626 is_unexported = Type::is_unexported_field_or_method(gogo, type,
7631 error_at(location, "reference to unexported field or method %qs",
7632 Gogo::message_name(name).c_str());
7634 error_at(location, "reference to undefined field or method %qs",
7635 Gogo::message_name(name).c_str());
7637 return Expression::make_error(location);
7641 // Look in TYPE for a field or method named NAME, return true if one
7642 // is found. This looks through embedded anonymous fields and handles
7643 // ambiguity. If a method is found, sets *IS_METHOD to true;
7644 // otherwise, if a field is found, set it to false. If
7645 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
7646 // whose address can not be taken. SEEN is used to avoid infinite
7647 // recursion on invalid types.
7649 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
7650 // method we couldn't use because it requires a pointer. LEVEL is
7651 // used for recursive calls, and can be NULL for a non-recursive call.
7652 // When this function returns false because it finds that the name is
7653 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
7654 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
7655 // will be unchanged.
7657 // This function just returns whether or not there is a field or
7658 // method, and whether it is a field or method. It doesn't build an
7659 // expression to refer to it. If it is a method, we then look in the
7660 // list of all methods for the type. If it is a field, the search has
7661 // to be done again, looking only for fields, and building up the
7662 // expression as we go.
7665 Type::find_field_or_method(const Type* type,
7666 const std::string& name,
7667 bool receiver_can_be_pointer,
7668 std::vector<const Named_type*>* seen,
7671 bool* found_pointer_method,
7672 std::string* ambig1,
7673 std::string* ambig2)
7675 // Named types can have locally defined methods.
7676 const Named_type* nt = type->named_type();
7677 if (nt == NULL && type->points_to() != NULL)
7678 nt = type->points_to()->named_type();
7681 Named_object* no = nt->find_local_method(name);
7684 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
7690 // Record that we have found a pointer method in order to
7691 // give a better error message if we don't find anything
7693 *found_pointer_method = true;
7696 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
7702 // We've already seen this type when searching for methods.
7708 // Interface types can have methods.
7709 const Interface_type* it = type->interface_type();
7710 if (it != NULL && it->find_method(name) != NULL)
7716 // Struct types can have fields. They can also inherit fields and
7717 // methods from anonymous fields.
7718 const Struct_type* st = type->deref()->struct_type();
7721 const Struct_field_list* fields = st->fields();
7726 seen->push_back(nt);
7728 int found_level = 0;
7729 bool found_is_method = false;
7730 std::string found_ambig1;
7731 std::string found_ambig2;
7732 const Struct_field* found_parent = NULL;
7733 for (Struct_field_list::const_iterator pf = fields->begin();
7734 pf != fields->end();
7737 if (pf->is_field_name(name))
7745 if (!pf->is_anonymous())
7748 if (pf->type()->deref()->is_error_type()
7749 || pf->type()->deref()->is_undefined())
7752 Named_type* fnt = pf->type()->named_type();
7754 fnt = pf->type()->deref()->named_type();
7755 go_assert(fnt != NULL);
7757 int sublevel = level == NULL ? 1 : *level + 1;
7759 std::string subambig1;
7760 std::string subambig2;
7761 bool subfound = Type::find_field_or_method(fnt,
7763 receiver_can_be_pointer,
7767 found_pointer_method,
7772 if (!subambig1.empty())
7774 // The name was found via this field, but is ambiguous.
7775 // if the ambiguity is lower or at the same level as
7776 // anything else we have already found, then we want to
7777 // pass the ambiguity back to the caller.
7778 if (found_level == 0 || sublevel <= found_level)
7780 found_ambig1 = (Gogo::message_name(pf->field_name())
7782 found_ambig2 = (Gogo::message_name(pf->field_name())
7784 found_level = sublevel;
7790 // The name was found via this field. Use the level to see
7791 // if we want to use this one, or whether it introduces an
7793 if (found_level == 0 || sublevel < found_level)
7795 found_level = sublevel;
7796 found_is_method = sub_is_method;
7797 found_ambig1.clear();
7798 found_ambig2.clear();
7799 found_parent = &*pf;
7801 else if (sublevel > found_level)
7803 else if (found_ambig1.empty())
7805 // We found an ambiguity.
7806 go_assert(found_parent != NULL);
7807 found_ambig1 = Gogo::message_name(found_parent->field_name());
7808 found_ambig2 = Gogo::message_name(pf->field_name());
7812 // We found an ambiguity, but we already know of one.
7813 // Just report the earlier one.
7818 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
7819 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
7820 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
7821 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
7826 if (found_level == 0)
7828 else if (!found_ambig1.empty())
7830 go_assert(!found_ambig1.empty());
7831 ambig1->assign(found_ambig1);
7832 ambig2->assign(found_ambig2);
7834 *level = found_level;
7840 *level = found_level;
7841 *is_method = found_is_method;
7846 // Return whether NAME is an unexported field or method for TYPE.
7849 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
7850 const std::string& name,
7851 std::vector<const Named_type*>* seen)
7853 const Named_type* nt = type->named_type();
7855 nt = type->deref()->named_type();
7858 if (nt->is_unexported_local_method(gogo, name))
7861 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
7867 // We've already seen this type.
7873 const Interface_type* it = type->interface_type();
7874 if (it != NULL && it->is_unexported_method(gogo, name))
7877 type = type->deref();
7879 const Struct_type* st = type->struct_type();
7880 if (st != NULL && st->is_unexported_local_field(gogo, name))
7886 const Struct_field_list* fields = st->fields();
7891 seen->push_back(nt);
7893 for (Struct_field_list::const_iterator pf = fields->begin();
7894 pf != fields->end();
7897 if (pf->is_anonymous()
7898 && !pf->type()->deref()->is_error_type()
7899 && !pf->type()->deref()->is_undefined())
7901 Named_type* subtype = pf->type()->named_type();
7902 if (subtype == NULL)
7903 subtype = pf->type()->deref()->named_type();
7904 if (subtype == NULL)
7906 // This is an error, but it will be diagnosed elsewhere.
7909 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
7924 // Class Forward_declaration.
7926 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
7927 : Type(TYPE_FORWARD),
7928 named_object_(named_object->resolve()), warned_(false)
7930 go_assert(this->named_object_->is_unknown()
7931 || this->named_object_->is_type_declaration());
7934 // Return the named object.
7937 Forward_declaration_type::named_object()
7939 return this->named_object_->resolve();
7943 Forward_declaration_type::named_object() const
7945 return this->named_object_->resolve();
7948 // Return the name of the forward declared type.
7951 Forward_declaration_type::name() const
7953 return this->named_object()->name();
7956 // Warn about a use of a type which has been declared but not defined.
7959 Forward_declaration_type::warn() const
7961 Named_object* no = this->named_object_->resolve();
7962 if (no->is_unknown())
7964 // The name was not defined anywhere.
7967 error_at(this->named_object_->location(),
7968 "use of undefined type %qs",
7969 no->message_name().c_str());
7970 this->warned_ = true;
7973 else if (no->is_type_declaration())
7975 // The name was seen as a type, but the type was never defined.
7976 if (no->type_declaration_value()->using_type())
7978 error_at(this->named_object_->location(),
7979 "use of undefined type %qs",
7980 no->message_name().c_str());
7981 this->warned_ = true;
7986 // The name was defined, but not as a type.
7989 error_at(this->named_object_->location(), "expected type");
7990 this->warned_ = true;
7995 // Get the base type of a declaration. This gives an error if the
7996 // type has not yet been defined.
7999 Forward_declaration_type::real_type()
8001 if (this->is_defined())
8002 return this->named_object()->type_value();
8006 return Type::make_error_type();
8011 Forward_declaration_type::real_type() const
8013 if (this->is_defined())
8014 return this->named_object()->type_value();
8018 return Type::make_error_type();
8022 // Return whether the base type is defined.
8025 Forward_declaration_type::is_defined() const
8027 return this->named_object()->is_type();
8030 // Add a method. This is used when methods are defined before the
8034 Forward_declaration_type::add_method(const std::string& name,
8037 Named_object* no = this->named_object();
8038 if (no->is_unknown())
8039 no->declare_as_type();
8040 return no->type_declaration_value()->add_method(name, function);
8043 // Add a method declaration. This is used when methods are declared
8047 Forward_declaration_type::add_method_declaration(const std::string& name,
8048 Function_type* type,
8051 Named_object* no = this->named_object();
8052 if (no->is_unknown())
8053 no->declare_as_type();
8054 Type_declaration* td = no->type_declaration_value();
8055 return td->add_method_declaration(name, type, location);
8061 Forward_declaration_type::do_traverse(Traverse* traverse)
8063 if (this->is_defined()
8064 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
8065 return TRAVERSE_EXIT;
8066 return TRAVERSE_CONTINUE;
8069 // Get the backend representation for the type.
8072 Forward_declaration_type::do_get_backend(Gogo* gogo)
8074 if (this->is_defined())
8075 return Type::get_named_base_btype(gogo, this->real_type());
8078 return gogo->backend()->error_type();
8080 // We represent an undefined type as a struct with no fields. That
8081 // should work fine for the backend, since the same case can arise
8083 std::vector<Backend::Btyped_identifier> fields;
8084 Btype* bt = gogo->backend()->struct_type(fields);
8085 return gogo->backend()->named_type(this->name(), bt,
8086 this->named_object()->location());
8089 // Build a type descriptor for a forwarded type.
8092 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8094 Location ploc = Linemap::predeclared_location();
8095 if (!this->is_defined())
8096 return Expression::make_nil(ploc);
8099 Type* t = this->real_type();
8101 return this->named_type_descriptor(gogo, t, name);
8103 return Expression::make_type_descriptor(t, ploc);
8107 // The reflection string.
8110 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
8112 this->append_reflection(this->real_type(), gogo, ret);
8115 // The mangled name.
8118 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8120 if (this->is_defined())
8121 this->append_mangled_name(this->real_type(), gogo, ret);
8124 const Named_object* no = this->named_object();
8126 if (no->package() == NULL)
8127 name = gogo->package_name();
8129 name = no->package()->name();
8131 name += Gogo::unpack_hidden_name(no->name());
8133 snprintf(buf, sizeof buf, "N%u_",
8134 static_cast<unsigned int>(name.length()));
8140 // Export a forward declaration. This can happen when a defined type
8141 // refers to a type which is only declared (and is presumably defined
8142 // in some other file in the same package).
8145 Forward_declaration_type::do_export(Export*) const
8147 // If there is a base type, that should be exported instead of this.
8148 go_assert(!this->is_defined());
8150 // We don't output anything.
8153 // Make a forward declaration.
8156 Type::make_forward_declaration(Named_object* named_object)
8158 return new Forward_declaration_type(named_object);
8161 // Class Typed_identifier_list.
8163 // Sort the entries by name.
8165 struct Typed_identifier_list_sort
8169 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
8170 { return t1.name() < t2.name(); }
8174 Typed_identifier_list::sort_by_name()
8176 std::sort(this->entries_.begin(), this->entries_.end(),
8177 Typed_identifier_list_sort());
8183 Typed_identifier_list::traverse(Traverse* traverse)
8185 for (Typed_identifier_list::const_iterator p = this->begin();
8189 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
8190 return TRAVERSE_EXIT;
8192 return TRAVERSE_CONTINUE;
8197 Typed_identifier_list*
8198 Typed_identifier_list::copy() const
8200 Typed_identifier_list* ret = new Typed_identifier_list();
8201 for (Typed_identifier_list::const_iterator p = this->begin();
8204 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));