compiler: Remove obsolete hidden_fields_are_ok code.
[official-gcc.git] / gcc / go / gofrontend / types.cc
blob0d66abf50813e9311fc9e72438fccc872432bcec
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.
7 #include "go-system.h"
9 #include "go-c.h"
10 #include "gogo.h"
11 #include "operator.h"
12 #include "expressions.h"
13 #include "statements.h"
14 #include "export.h"
15 #include "import.h"
16 #include "backend.h"
17 #include "types.h"
19 // Forward declarations so that we don't have to make types.h #include
20 // backend.h.
22 static void
23 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
24 bool use_placeholder,
25 std::vector<Backend::Btyped_identifier>* bfields);
27 static void
28 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
29 std::vector<Backend::Btyped_identifier>* bfields);
31 static void
32 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
33 bool use_placeholder,
34 std::vector<Backend::Btyped_identifier>* bfields);
36 // Class Type.
38 Type::Type(Type_classification classification)
39 : classification_(classification), btype_(NULL), type_descriptor_var_(NULL),
40 gc_symbol_var_(NULL)
44 Type::~Type()
48 // Get the base type for a type--skip names and forward declarations.
50 Type*
51 Type::base()
53 switch (this->classification_)
55 case TYPE_NAMED:
56 return this->named_type()->named_base();
57 case TYPE_FORWARD:
58 return this->forward_declaration_type()->real_type()->base();
59 default:
60 return this;
64 const Type*
65 Type::base() const
67 switch (this->classification_)
69 case TYPE_NAMED:
70 return this->named_type()->named_base();
71 case TYPE_FORWARD:
72 return this->forward_declaration_type()->real_type()->base();
73 default:
74 return this;
78 // Skip defined forward declarations.
80 Type*
81 Type::forwarded()
83 Type* t = this;
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();
90 return t;
93 const Type*
94 Type::forwarded() const
96 const Type* t = this;
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();
103 return t;
106 // If this is a named type, return it. Otherwise, return NULL.
108 Named_type*
109 Type::named_type()
111 return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
114 const Named_type*
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.
122 bool
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.
131 bool
132 Type::is_basic_type() const
134 switch (this->classification_)
136 case TYPE_INTEGER:
137 case TYPE_FLOAT:
138 case TYPE_COMPLEX:
139 case TYPE_BOOLEAN:
140 case TYPE_STRING:
141 case TYPE_NIL:
142 return true;
144 case TYPE_ERROR:
145 case TYPE_VOID:
146 case TYPE_FUNCTION:
147 case TYPE_POINTER:
148 case TYPE_STRUCT:
149 case TYPE_ARRAY:
150 case TYPE_MAP:
151 case TYPE_CHANNEL:
152 case TYPE_INTERFACE:
153 return false;
155 case TYPE_NAMED:
156 case TYPE_FORWARD:
157 return this->base()->is_basic_type();
159 default:
160 go_unreachable();
164 // Return true if this is an abstract type.
166 bool
167 Type::is_abstract() const
169 switch (this->classification())
171 case TYPE_INTEGER:
172 return this->integer_type()->is_abstract();
173 case TYPE_FLOAT:
174 return this->float_type()->is_abstract();
175 case TYPE_COMPLEX:
176 return this->complex_type()->is_abstract();
177 case TYPE_STRING:
178 return this->is_abstract_string_type();
179 case TYPE_BOOLEAN:
180 return this->is_abstract_boolean_type();
181 default:
182 return false;
186 // Return a non-abstract version of an abstract type.
188 Type*
189 Type::make_non_abstract_type()
191 go_assert(this->is_abstract());
192 switch (this->classification())
194 case TYPE_INTEGER:
195 if (this->integer_type()->is_rune())
196 return Type::lookup_integer_type("int32");
197 else
198 return Type::lookup_integer_type("int");
199 case TYPE_FLOAT:
200 return Type::lookup_float_type("float64");
201 case TYPE_COMPLEX:
202 return Type::lookup_complex_type("complex128");
203 case TYPE_STRING:
204 return Type::lookup_string_type();
205 case TYPE_BOOLEAN:
206 return Type::lookup_bool_type();
207 default:
208 go_unreachable();
212 // Return true if this is an error type. Don't give an error if we
213 // try to dereference an undefined forwarding type, as this is called
214 // in the parser when the type may legitimately be undefined.
216 bool
217 Type::is_error_type() const
219 const Type* t = this->forwarded();
220 // Note that we return false for an undefined forward type.
221 switch (t->classification_)
223 case TYPE_ERROR:
224 return true;
225 case TYPE_NAMED:
226 return t->named_type()->is_named_error_type();
227 default:
228 return false;
232 // If this is a pointer type, return the type to which it points.
233 // Otherwise, return NULL.
235 Type*
236 Type::points_to() const
238 const Pointer_type* ptype = this->convert<const Pointer_type,
239 TYPE_POINTER>();
240 return ptype == NULL ? NULL : ptype->points_to();
243 // Return whether this is a slice type.
245 bool
246 Type::is_slice_type() const
248 return this->array_type() != NULL && this->array_type()->length() == NULL;
251 // Return whether this is the predeclared constant nil being used as a
252 // type.
254 bool
255 Type::is_nil_constant_as_type() const
257 const Type* t = this->forwarded();
258 if (t->forward_declaration_type() != NULL)
260 const Named_object* no = t->forward_declaration_type()->named_object();
261 if (no->is_unknown())
262 no = no->unknown_value()->real_named_object();
263 if (no != NULL
264 && no->is_const()
265 && no->const_value()->expr()->is_nil_expression())
266 return true;
268 return false;
271 // Traverse a type.
274 Type::traverse(Type* type, Traverse* traverse)
276 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
277 || (traverse->traverse_mask()
278 & Traverse::traverse_expressions) != 0);
279 if (traverse->remember_type(type))
281 // We have already traversed this type.
282 return TRAVERSE_CONTINUE;
284 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
286 int t = traverse->type(type);
287 if (t == TRAVERSE_EXIT)
288 return TRAVERSE_EXIT;
289 else if (t == TRAVERSE_SKIP_COMPONENTS)
290 return TRAVERSE_CONTINUE;
292 // An array type has an expression which we need to traverse if
293 // traverse_expressions is set.
294 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
295 return TRAVERSE_EXIT;
296 return TRAVERSE_CONTINUE;
299 // Default implementation for do_traverse for child class.
302 Type::do_traverse(Traverse*)
304 return TRAVERSE_CONTINUE;
307 // Return whether two types are identical. If ERRORS_ARE_IDENTICAL,
308 // then return true for all erroneous types; this is used to avoid
309 // cascading errors. If REASON is not NULL, optionally set *REASON to
310 // the reason the types are not identical.
312 bool
313 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
314 std::string* reason)
316 if (t1 == NULL || t2 == NULL)
318 // Something is wrong.
319 return errors_are_identical ? true : t1 == t2;
322 // Skip defined forward declarations.
323 t1 = t1->forwarded();
324 t2 = t2->forwarded();
326 // Ignore aliases for purposes of type identity.
327 if (t1->named_type() != NULL && t1->named_type()->is_alias())
328 t1 = t1->named_type()->real_type();
329 if (t2->named_type() != NULL && t2->named_type()->is_alias())
330 t2 = t2->named_type()->real_type();
332 if (t1 == t2)
333 return true;
335 // An undefined forward declaration is an error.
336 if (t1->forward_declaration_type() != NULL
337 || t2->forward_declaration_type() != NULL)
338 return errors_are_identical;
340 // Avoid cascading errors with error types.
341 if (t1->is_error_type() || t2->is_error_type())
343 if (errors_are_identical)
344 return true;
345 return t1->is_error_type() && t2->is_error_type();
348 // Get a good reason for the sink type. Note that the sink type on
349 // the left hand side of an assignment is handled in are_assignable.
350 if (t1->is_sink_type() || t2->is_sink_type())
352 if (reason != NULL)
353 *reason = "invalid use of _";
354 return false;
357 // A named type is only identical to itself.
358 if (t1->named_type() != NULL || t2->named_type() != NULL)
359 return false;
361 // Check type shapes.
362 if (t1->classification() != t2->classification())
363 return false;
365 switch (t1->classification())
367 case TYPE_VOID:
368 case TYPE_BOOLEAN:
369 case TYPE_STRING:
370 case TYPE_NIL:
371 // These types are always identical.
372 return true;
374 case TYPE_INTEGER:
375 return t1->integer_type()->is_identical(t2->integer_type());
377 case TYPE_FLOAT:
378 return t1->float_type()->is_identical(t2->float_type());
380 case TYPE_COMPLEX:
381 return t1->complex_type()->is_identical(t2->complex_type());
383 case TYPE_FUNCTION:
384 return t1->function_type()->is_identical(t2->function_type(),
385 false,
386 errors_are_identical,
387 reason);
389 case TYPE_POINTER:
390 return Type::are_identical(t1->points_to(), t2->points_to(),
391 errors_are_identical, reason);
393 case TYPE_STRUCT:
394 return t1->struct_type()->is_identical(t2->struct_type(),
395 errors_are_identical);
397 case TYPE_ARRAY:
398 return t1->array_type()->is_identical(t2->array_type(),
399 errors_are_identical);
401 case TYPE_MAP:
402 return t1->map_type()->is_identical(t2->map_type(),
403 errors_are_identical);
405 case TYPE_CHANNEL:
406 return t1->channel_type()->is_identical(t2->channel_type(),
407 errors_are_identical);
409 case TYPE_INTERFACE:
410 return t1->interface_type()->is_identical(t2->interface_type(),
411 errors_are_identical);
413 case TYPE_CALL_MULTIPLE_RESULT:
414 if (reason != NULL)
415 *reason = "invalid use of multiple-value function call";
416 return false;
418 default:
419 go_unreachable();
423 // Return true if it's OK to have a binary operation with types LHS
424 // and RHS. This is not used for shifts or comparisons.
426 bool
427 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
429 if (Type::are_identical(lhs, rhs, true, NULL))
430 return true;
432 // A constant of abstract bool type may be mixed with any bool type.
433 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
434 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
435 return true;
437 // A constant of abstract string type may be mixed with any string
438 // type.
439 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
440 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
441 return true;
443 lhs = lhs->base();
444 rhs = rhs->base();
446 // A constant of abstract integer, float, or complex type may be
447 // mixed with an integer, float, or complex type.
448 if ((rhs->is_abstract()
449 && (rhs->integer_type() != NULL
450 || rhs->float_type() != NULL
451 || rhs->complex_type() != NULL)
452 && (lhs->integer_type() != NULL
453 || lhs->float_type() != NULL
454 || lhs->complex_type() != NULL))
455 || (lhs->is_abstract()
456 && (lhs->integer_type() != NULL
457 || lhs->float_type() != NULL
458 || lhs->complex_type() != NULL)
459 && (rhs->integer_type() != NULL
460 || rhs->float_type() != NULL
461 || rhs->complex_type() != NULL)))
462 return true;
464 // The nil type may be compared to a pointer, an interface type, a
465 // slice type, a channel type, a map type, or a function type.
466 if (lhs->is_nil_type()
467 && (rhs->points_to() != NULL
468 || rhs->interface_type() != NULL
469 || rhs->is_slice_type()
470 || rhs->map_type() != NULL
471 || rhs->channel_type() != NULL
472 || rhs->function_type() != NULL))
473 return true;
474 if (rhs->is_nil_type()
475 && (lhs->points_to() != NULL
476 || lhs->interface_type() != NULL
477 || lhs->is_slice_type()
478 || lhs->map_type() != NULL
479 || lhs->channel_type() != NULL
480 || lhs->function_type() != NULL))
481 return true;
483 return false;
486 // Return true if a value with type T1 may be compared with a value of
487 // type T2. IS_EQUALITY_OP is true for == or !=, false for <, etc.
489 bool
490 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
491 const Type *t2, std::string *reason)
493 if (t1 != t2
494 && !Type::are_assignable(t1, t2, NULL)
495 && !Type::are_assignable(t2, t1, NULL))
497 if (reason != NULL)
498 *reason = "incompatible types in binary expression";
499 return false;
502 if (!is_equality_op)
504 if (t1->integer_type() == NULL
505 && t1->float_type() == NULL
506 && !t1->is_string_type())
508 if (reason != NULL)
509 *reason = _("invalid comparison of non-ordered type");
510 return false;
513 else if (t1->is_slice_type()
514 || t1->map_type() != NULL
515 || t1->function_type() != NULL
516 || t2->is_slice_type()
517 || t2->map_type() != NULL
518 || t2->function_type() != NULL)
520 if (!t1->is_nil_type() && !t2->is_nil_type())
522 if (reason != NULL)
524 if (t1->is_slice_type() || t2->is_slice_type())
525 *reason = _("slice can only be compared to nil");
526 else if (t1->map_type() != NULL || t2->map_type() != NULL)
527 *reason = _("map can only be compared to nil");
528 else
529 *reason = _("func can only be compared to nil");
531 // Match 6g error messages.
532 if (t1->interface_type() != NULL || t2->interface_type() != NULL)
534 char buf[200];
535 snprintf(buf, sizeof buf, _("invalid operation (%s)"),
536 reason->c_str());
537 *reason = buf;
540 return false;
543 else
545 if (!t1->is_boolean_type()
546 && t1->integer_type() == NULL
547 && t1->float_type() == NULL
548 && t1->complex_type() == NULL
549 && !t1->is_string_type()
550 && t1->points_to() == NULL
551 && t1->channel_type() == NULL
552 && t1->interface_type() == NULL
553 && t1->struct_type() == NULL
554 && t1->array_type() == NULL
555 && !t1->is_nil_type())
557 if (reason != NULL)
558 *reason = _("invalid comparison of non-comparable type");
559 return false;
562 if (t1->named_type() != NULL)
563 return t1->named_type()->named_type_is_comparable(reason);
564 else if (t2->named_type() != NULL)
565 return t2->named_type()->named_type_is_comparable(reason);
566 else if (t1->struct_type() != NULL)
568 const Struct_field_list* fields = t1->struct_type()->fields();
569 for (Struct_field_list::const_iterator p = fields->begin();
570 p != fields->end();
571 ++p)
573 if (!p->type()->is_comparable())
575 if (reason != NULL)
576 *reason = _("invalid comparison of non-comparable struct");
577 return false;
581 else if (t1->array_type() != NULL)
583 if (t1->array_type()->length()->is_nil_expression()
584 || !t1->array_type()->element_type()->is_comparable())
586 if (reason != NULL)
587 *reason = _("invalid comparison of non-comparable array");
588 return false;
593 return true;
596 // Return true if a value with type RHS may be assigned to a variable
597 // with type LHS. If REASON is not NULL, set *REASON to the reason
598 // the types are not assignable.
600 bool
601 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
603 // Do some checks first. Make sure the types are defined.
604 if (rhs != NULL && !rhs->is_undefined())
606 if (rhs->is_void_type())
608 if (reason != NULL)
609 *reason = "non-value used as value";
610 return false;
612 if (rhs->is_call_multiple_result_type())
614 if (reason != NULL)
615 reason->assign(_("multiple-value function call in "
616 "single-value context"));
617 return false;
621 // Any value may be assigned to the blank identifier.
622 if (lhs != NULL
623 && !lhs->is_undefined()
624 && lhs->is_sink_type())
625 return true;
627 // Identical types are assignable.
628 if (Type::are_identical(lhs, rhs, true, reason))
629 return true;
631 // The types are assignable if they have identical underlying types
632 // and either LHS or RHS is not a named type.
633 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
634 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
635 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
636 return true;
638 // The types are assignable if LHS is an interface type and RHS
639 // implements the required methods.
640 const Interface_type* lhs_interface_type = lhs->interface_type();
641 if (lhs_interface_type != NULL)
643 if (lhs_interface_type->implements_interface(rhs, reason))
644 return true;
645 const Interface_type* rhs_interface_type = rhs->interface_type();
646 if (rhs_interface_type != NULL
647 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
648 reason))
649 return true;
652 // The type are assignable if RHS is a bidirectional channel type,
653 // LHS is a channel type, they have identical element types, and
654 // either LHS or RHS is not a named type.
655 if (lhs->channel_type() != NULL
656 && rhs->channel_type() != NULL
657 && rhs->channel_type()->may_send()
658 && rhs->channel_type()->may_receive()
659 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
660 && Type::are_identical(lhs->channel_type()->element_type(),
661 rhs->channel_type()->element_type(),
662 true,
663 reason))
664 return true;
666 // The nil type may be assigned to a pointer, function, slice, map,
667 // channel, or interface type.
668 if (rhs->is_nil_type()
669 && (lhs->points_to() != NULL
670 || lhs->function_type() != NULL
671 || lhs->is_slice_type()
672 || lhs->map_type() != NULL
673 || lhs->channel_type() != NULL
674 || lhs->interface_type() != NULL))
675 return true;
677 // An untyped numeric constant may be assigned to a numeric type if
678 // it is representable in that type.
679 if ((rhs->is_abstract()
680 && (rhs->integer_type() != NULL
681 || rhs->float_type() != NULL
682 || rhs->complex_type() != NULL))
683 && (lhs->integer_type() != NULL
684 || lhs->float_type() != NULL
685 || lhs->complex_type() != NULL))
686 return true;
688 // Give some better error messages.
689 if (reason != NULL && reason->empty())
691 if (rhs->interface_type() != NULL)
692 reason->assign(_("need explicit conversion"));
693 else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
695 size_t len = (lhs->named_type()->name().length()
696 + rhs->named_type()->name().length()
697 + 100);
698 char* buf = new char[len];
699 snprintf(buf, len, _("cannot use type %s as type %s"),
700 rhs->named_type()->message_name().c_str(),
701 lhs->named_type()->message_name().c_str());
702 reason->assign(buf);
703 delete[] buf;
707 return false;
710 // Return true if a value with type RHS may be converted to type LHS.
711 // If REASON is not NULL, set *REASON to the reason the types are not
712 // convertible.
714 bool
715 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
717 // The types are convertible if they are assignable.
718 if (Type::are_assignable(lhs, rhs, reason))
719 return true;
721 // The types are convertible if they have identical underlying
722 // types.
723 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
724 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
725 return true;
727 // The types are convertible if they are both unnamed pointer types
728 // and their pointer base types have identical underlying types.
729 if (lhs->named_type() == NULL
730 && rhs->named_type() == NULL
731 && lhs->points_to() != NULL
732 && rhs->points_to() != NULL
733 && (lhs->points_to()->named_type() != NULL
734 || rhs->points_to()->named_type() != NULL)
735 && Type::are_identical(lhs->points_to()->base(),
736 rhs->points_to()->base(),
737 true,
738 reason))
739 return true;
741 // Integer and floating point types are convertible to each other.
742 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
743 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
744 return true;
746 // Complex types are convertible to each other.
747 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
748 return true;
750 // An integer, or []byte, or []rune, may be converted to a string.
751 if (lhs->is_string_type())
753 if (rhs->integer_type() != NULL)
754 return true;
755 if (rhs->is_slice_type())
757 const Type* e = rhs->array_type()->element_type()->forwarded();
758 if (e->integer_type() != NULL
759 && (e->integer_type()->is_byte()
760 || e->integer_type()->is_rune()))
761 return true;
765 // A string may be converted to []byte or []rune.
766 if (rhs->is_string_type() && lhs->is_slice_type())
768 const Type* e = lhs->array_type()->element_type()->forwarded();
769 if (e->integer_type() != NULL
770 && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
771 return true;
774 // An unsafe.Pointer type may be converted to any pointer type or to
775 // uintptr, and vice-versa.
776 if (lhs->is_unsafe_pointer_type()
777 && (rhs->points_to() != NULL
778 || (rhs->integer_type() != NULL
779 && rhs->forwarded() == Type::lookup_integer_type("uintptr"))))
780 return true;
781 if (rhs->is_unsafe_pointer_type()
782 && (lhs->points_to() != NULL
783 || (lhs->integer_type() != NULL
784 && lhs->forwarded() == Type::lookup_integer_type("uintptr"))))
785 return true;
787 // Give a better error message.
788 if (reason != NULL)
790 if (reason->empty())
791 *reason = "invalid type conversion";
792 else
794 std::string s = "invalid type conversion (";
795 s += *reason;
796 s += ')';
797 *reason = s;
801 return false;
804 // Return a hash code for the type to be used for method lookup.
806 unsigned int
807 Type::hash_for_method(Gogo* gogo) const
809 unsigned int ret = 0;
810 if (this->classification_ != TYPE_FORWARD)
811 ret += this->classification_;
812 return ret + this->do_hash_for_method(gogo);
815 // Default implementation of do_hash_for_method. This is appropriate
816 // for types with no subfields.
818 unsigned int
819 Type::do_hash_for_method(Gogo*) const
821 return 0;
824 // Return a hash code for a string, given a starting hash.
826 unsigned int
827 Type::hash_string(const std::string& s, unsigned int h)
829 const char* p = s.data();
830 size_t len = s.length();
831 for (; len > 0; --len)
833 h ^= *p++;
834 h*= 16777619;
836 return h;
839 // A hash table mapping unnamed types to the backend representation of
840 // those types.
842 Type::Type_btypes Type::type_btypes;
844 // Return the backend representation for this type.
846 Btype*
847 Type::get_backend(Gogo* gogo)
849 if (this->btype_ != NULL)
850 return this->btype_;
852 if (this->forward_declaration_type() != NULL
853 || this->named_type() != NULL)
854 return this->get_btype_without_hash(gogo);
856 if (this->is_error_type())
857 return gogo->backend()->error_type();
859 // To avoid confusing the backend, translate all identical Go types
860 // to the same backend representation. We use a hash table to do
861 // that. There is no need to use the hash table for named types, as
862 // named types are only identical to themselves.
864 std::pair<Type*, Type_btype_entry> val;
865 val.first = this;
866 val.second.btype = NULL;
867 val.second.is_placeholder = false;
868 std::pair<Type_btypes::iterator, bool> ins =
869 Type::type_btypes.insert(val);
870 if (!ins.second && ins.first->second.btype != NULL)
872 // Note that GOGO can be NULL here, but only when the GCC
873 // middle-end is asking for a frontend type. That will only
874 // happen for simple types, which should never require
875 // placeholders.
876 if (!ins.first->second.is_placeholder)
877 this->btype_ = ins.first->second.btype;
878 else if (gogo->named_types_are_converted())
880 this->finish_backend(gogo, ins.first->second.btype);
881 ins.first->second.is_placeholder = false;
884 return ins.first->second.btype;
887 Btype* bt = this->get_btype_without_hash(gogo);
889 if (ins.first->second.btype == NULL)
891 ins.first->second.btype = bt;
892 ins.first->second.is_placeholder = false;
894 else
896 // We have already created a backend representation for this
897 // type. This can happen when an unnamed type is defined using
898 // a named type which in turns uses an identical unnamed type.
899 // Use the representation we created earlier and ignore the one we just
900 // built.
901 if (this->btype_ == bt)
902 this->btype_ = ins.first->second.btype;
903 bt = ins.first->second.btype;
906 return bt;
909 // Return the backend representation for a type without looking in the
910 // hash table for identical types. This is used for named types,
911 // since a named type is never identical to any other type.
913 Btype*
914 Type::get_btype_without_hash(Gogo* gogo)
916 if (this->btype_ == NULL)
918 Btype* bt = this->do_get_backend(gogo);
920 // For a recursive function or pointer type, we will temporarily
921 // return a circular pointer type during the recursion. We
922 // don't want to record that for a forwarding type, as it may
923 // confuse us later.
924 if (this->forward_declaration_type() != NULL
925 && gogo->backend()->is_circular_pointer_type(bt))
926 return bt;
928 if (gogo == NULL || !gogo->named_types_are_converted())
929 return bt;
931 this->btype_ = bt;
933 return this->btype_;
936 // Get the backend representation of a type without forcing the
937 // creation of the backend representation of all supporting types.
938 // This will return a backend type that has the correct size but may
939 // be incomplete. E.g., a pointer will just be a placeholder pointer,
940 // and will not contain the final representation of the type to which
941 // it points. This is used while converting all named types to the
942 // backend representation, to avoid problems with indirect references
943 // to types which are not yet complete. When this is called, the
944 // sizes of all direct references (e.g., a struct field) should be
945 // known, but the sizes of indirect references (e.g., the type to
946 // which a pointer points) may not.
948 Btype*
949 Type::get_backend_placeholder(Gogo* gogo)
951 if (gogo->named_types_are_converted())
952 return this->get_backend(gogo);
953 if (this->btype_ != NULL)
954 return this->btype_;
956 Btype* bt;
957 switch (this->classification_)
959 case TYPE_ERROR:
960 case TYPE_VOID:
961 case TYPE_BOOLEAN:
962 case TYPE_INTEGER:
963 case TYPE_FLOAT:
964 case TYPE_COMPLEX:
965 case TYPE_STRING:
966 case TYPE_NIL:
967 // These are simple types that can just be created directly.
968 return this->get_backend(gogo);
970 case TYPE_MAP:
971 case TYPE_CHANNEL:
972 // All maps and channels have the same backend representation.
973 return this->get_backend(gogo);
975 case TYPE_NAMED:
976 case TYPE_FORWARD:
977 // Named types keep track of their own dependencies and manage
978 // their own placeholders.
979 return this->get_backend(gogo);
981 case TYPE_INTERFACE:
982 if (this->interface_type()->is_empty())
983 return Interface_type::get_backend_empty_interface_type(gogo);
984 break;
986 default:
987 break;
990 std::pair<Type*, Type_btype_entry> val;
991 val.first = this;
992 val.second.btype = NULL;
993 val.second.is_placeholder = false;
994 std::pair<Type_btypes::iterator, bool> ins =
995 Type::type_btypes.insert(val);
996 if (!ins.second && ins.first->second.btype != NULL)
997 return ins.first->second.btype;
999 switch (this->classification_)
1001 case TYPE_FUNCTION:
1003 // A Go function type is a pointer to a struct type.
1004 Location loc = this->function_type()->location();
1005 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1007 break;
1009 case TYPE_POINTER:
1011 Location loc = Linemap::unknown_location();
1012 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1014 break;
1016 case TYPE_STRUCT:
1017 // We don't have to make the struct itself be a placeholder. We
1018 // are promised that we know the sizes of the struct fields.
1019 // But we may have to use a placeholder for any particular
1020 // struct field.
1022 std::vector<Backend::Btyped_identifier> bfields;
1023 get_backend_struct_fields(gogo, this->struct_type()->fields(),
1024 true, &bfields);
1025 bt = gogo->backend()->struct_type(bfields);
1027 break;
1029 case TYPE_ARRAY:
1030 if (this->is_slice_type())
1032 std::vector<Backend::Btyped_identifier> bfields;
1033 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1034 bt = gogo->backend()->struct_type(bfields);
1036 else
1038 Btype* element = this->array_type()->get_backend_element(gogo, true);
1039 Bexpression* len = this->array_type()->get_backend_length(gogo);
1040 bt = gogo->backend()->array_type(element, len);
1042 break;
1044 case TYPE_INTERFACE:
1046 go_assert(!this->interface_type()->is_empty());
1047 std::vector<Backend::Btyped_identifier> bfields;
1048 get_backend_interface_fields(gogo, this->interface_type(), true,
1049 &bfields);
1050 bt = gogo->backend()->struct_type(bfields);
1052 break;
1054 case TYPE_SINK:
1055 case TYPE_CALL_MULTIPLE_RESULT:
1056 /* Note that various classifications were handled in the earlier
1057 switch. */
1058 default:
1059 go_unreachable();
1062 if (ins.first->second.btype == NULL)
1064 ins.first->second.btype = bt;
1065 ins.first->second.is_placeholder = true;
1067 else
1069 // A placeholder for this type got created along the way. Use
1070 // that one and ignore the one we just built.
1071 bt = ins.first->second.btype;
1074 return bt;
1077 // Complete the backend representation. This is called for a type
1078 // using a placeholder type.
1080 void
1081 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1083 switch (this->classification_)
1085 case TYPE_ERROR:
1086 case TYPE_VOID:
1087 case TYPE_BOOLEAN:
1088 case TYPE_INTEGER:
1089 case TYPE_FLOAT:
1090 case TYPE_COMPLEX:
1091 case TYPE_STRING:
1092 case TYPE_NIL:
1093 go_unreachable();
1095 case TYPE_FUNCTION:
1097 Btype* bt = this->do_get_backend(gogo);
1098 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1099 go_assert(saw_errors());
1101 break;
1103 case TYPE_POINTER:
1105 Btype* bt = this->do_get_backend(gogo);
1106 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1107 go_assert(saw_errors());
1109 break;
1111 case TYPE_STRUCT:
1112 // The struct type itself is done, but we have to make sure that
1113 // all the field types are converted.
1114 this->struct_type()->finish_backend_fields(gogo);
1115 break;
1117 case TYPE_ARRAY:
1118 // The array type itself is done, but make sure the element type
1119 // is converted.
1120 this->array_type()->finish_backend_element(gogo);
1121 break;
1123 case TYPE_MAP:
1124 case TYPE_CHANNEL:
1125 go_unreachable();
1127 case TYPE_INTERFACE:
1128 // The interface type itself is done, but make sure the method
1129 // types are converted.
1130 this->interface_type()->finish_backend_methods(gogo);
1131 break;
1133 case TYPE_NAMED:
1134 case TYPE_FORWARD:
1135 go_unreachable();
1137 case TYPE_SINK:
1138 case TYPE_CALL_MULTIPLE_RESULT:
1139 default:
1140 go_unreachable();
1143 this->btype_ = placeholder;
1146 // Return a pointer to the type descriptor for this type.
1148 Bexpression*
1149 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1151 Type* t = this->forwarded();
1152 if (t->named_type() != NULL && t->named_type()->is_alias())
1153 t = t->named_type()->real_type();
1154 if (t->type_descriptor_var_ == NULL)
1156 t->make_type_descriptor_var(gogo);
1157 go_assert(t->type_descriptor_var_ != NULL);
1159 Bexpression* var_expr =
1160 gogo->backend()->var_expression(t->type_descriptor_var_, location);
1161 return gogo->backend()->address_expression(var_expr, location);
1164 // A mapping from unnamed types to type descriptor variables.
1166 Type::Type_descriptor_vars Type::type_descriptor_vars;
1168 // Build the type descriptor for this type.
1170 void
1171 Type::make_type_descriptor_var(Gogo* gogo)
1173 go_assert(this->type_descriptor_var_ == NULL);
1175 Named_type* nt = this->named_type();
1177 // We can have multiple instances of unnamed types, but we only want
1178 // to emit the type descriptor once. We use a hash table. This is
1179 // not necessary for named types, as they are unique, and we store
1180 // the type descriptor in the type itself.
1181 Bvariable** phash = NULL;
1182 if (nt == NULL)
1184 Bvariable* bvnull = NULL;
1185 std::pair<Type_descriptor_vars::iterator, bool> ins =
1186 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1187 if (!ins.second)
1189 // We've already built a type descriptor for this type.
1190 this->type_descriptor_var_ = ins.first->second;
1191 return;
1193 phash = &ins.first->second;
1196 // The type descriptor symbol for the unsafe.Pointer type is defined in
1197 // libgo/go-unsafe-pointer.c, so we just return a reference to that
1198 // symbol if necessary.
1199 if (this->is_unsafe_pointer_type())
1201 Location bloc = Linemap::predeclared_location();
1203 Type* td_type = Type::make_type_descriptor_type();
1204 Btype* td_btype = td_type->get_backend(gogo);
1205 this->type_descriptor_var_ =
1206 gogo->backend()->immutable_struct_reference("__go_tdn_unsafe.Pointer",
1207 td_btype,
1208 bloc);
1210 if (phash != NULL)
1211 *phash = this->type_descriptor_var_;
1212 return;
1215 std::string var_name = this->type_descriptor_var_name(gogo, nt);
1217 // Build the contents of the type descriptor.
1218 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1220 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1222 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1224 const Package* dummy;
1225 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1227 this->type_descriptor_var_ =
1228 gogo->backend()->immutable_struct_reference(var_name,
1229 initializer_btype,
1230 loc);
1231 if (phash != NULL)
1232 *phash = this->type_descriptor_var_;
1233 return;
1236 // See if this type descriptor can appear in multiple packages.
1237 bool is_common = false;
1238 if (nt != NULL)
1240 // We create the descriptor for a builtin type whenever we need
1241 // it.
1242 is_common = nt->is_builtin();
1244 else
1246 // This is an unnamed type. The descriptor could be defined in
1247 // any package where it is needed, and the linker will pick one
1248 // descriptor to keep.
1249 is_common = true;
1252 // We are going to build the type descriptor in this package. We
1253 // must create the variable before we convert the initializer to the
1254 // backend representation, because the initializer may refer to the
1255 // type descriptor of this type. By setting type_descriptor_var_ we
1256 // ensure that type_descriptor_pointer will work if called while
1257 // converting INITIALIZER.
1259 this->type_descriptor_var_ =
1260 gogo->backend()->immutable_struct(var_name, false, is_common,
1261 initializer_btype, loc);
1262 if (phash != NULL)
1263 *phash = this->type_descriptor_var_;
1265 Translate_context context(gogo, NULL, NULL, NULL);
1266 context.set_is_const();
1267 Bexpression* binitializer = initializer->get_backend(&context);
1269 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1270 var_name, false, is_common,
1271 initializer_btype, loc,
1272 binitializer);
1275 // Return the name of the type descriptor variable. If NT is not
1276 // NULL, use it to get the name. Otherwise this is an unnamed type.
1278 std::string
1279 Type::type_descriptor_var_name(Gogo* gogo, Named_type* nt)
1281 if (nt == NULL)
1282 return "__go_td_" + this->mangled_name(gogo);
1284 Named_object* no = nt->named_object();
1285 unsigned int index;
1286 const Named_object* in_function = nt->in_function(&index);
1287 std::string ret = "__go_tdn_";
1288 if (nt->is_builtin())
1289 go_assert(in_function == NULL);
1290 else
1292 const std::string& pkgpath(no->package() == NULL
1293 ? gogo->pkgpath_symbol()
1294 : no->package()->pkgpath_symbol());
1295 ret.append(pkgpath);
1296 ret.append(1, '.');
1297 if (in_function != NULL)
1299 ret.append(Gogo::unpack_hidden_name(in_function->name()));
1300 ret.append(1, '.');
1301 if (index > 0)
1303 char buf[30];
1304 snprintf(buf, sizeof buf, "%u", index);
1305 ret.append(buf);
1306 ret.append(1, '.');
1311 // FIXME: This adds in pkgpath twice for hidden symbols, which is
1312 // pointless.
1313 const std::string& name(no->name());
1314 if (!Gogo::is_hidden_name(name))
1315 ret.append(name);
1316 else
1318 ret.append(1, '.');
1319 ret.append(Gogo::pkgpath_for_symbol(Gogo::hidden_name_pkgpath(name)));
1320 ret.append(1, '.');
1321 ret.append(Gogo::unpack_hidden_name(name));
1324 return ret;
1327 // Return true if this type descriptor is defined in a different
1328 // package. If this returns true it sets *PACKAGE to the package.
1330 bool
1331 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1332 const Package** package)
1334 if (nt != NULL)
1336 if (nt->named_object()->package() != NULL)
1338 // This is a named type defined in a different package. The
1339 // type descriptor should be defined in that package.
1340 *package = nt->named_object()->package();
1341 return true;
1344 else
1346 if (this->points_to() != NULL
1347 && this->points_to()->named_type() != NULL
1348 && this->points_to()->named_type()->named_object()->package() != NULL)
1350 // This is an unnamed pointer to a named type defined in a
1351 // different package. The descriptor should be defined in
1352 // that package.
1353 *package = this->points_to()->named_type()->named_object()->package();
1354 return true;
1357 return false;
1360 // Return a composite literal for a type descriptor.
1362 Expression*
1363 Type::type_descriptor(Gogo* gogo, Type* type)
1365 return type->do_type_descriptor(gogo, NULL);
1368 // Return a composite literal for a type descriptor with a name.
1370 Expression*
1371 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1373 go_assert(name != NULL && type->named_type() != name);
1374 return type->do_type_descriptor(gogo, name);
1377 // Generate the GC symbol for this TYPE. VALS is the data so far in this
1378 // symbol; extra values will be appended in do_gc_symbol. OFFSET is the
1379 // offset into the symbol where the GC data is located. STACK_SIZE is the
1380 // size of the GC stack when dealing with array types.
1382 void
1383 Type::gc_symbol(Gogo* gogo, Type* type, Expression_list** vals,
1384 Expression** offset, int stack_size)
1386 type->do_gc_symbol(gogo, vals, offset, stack_size);
1389 // Make a builtin struct type from a list of fields. The fields are
1390 // pairs of a name and a type.
1392 Struct_type*
1393 Type::make_builtin_struct_type(int nfields, ...)
1395 va_list ap;
1396 va_start(ap, nfields);
1398 Location bloc = Linemap::predeclared_location();
1399 Struct_field_list* sfl = new Struct_field_list();
1400 for (int i = 0; i < nfields; i++)
1402 const char* field_name = va_arg(ap, const char *);
1403 Type* type = va_arg(ap, Type*);
1404 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1407 va_end(ap);
1409 return Type::make_struct_type(sfl, bloc);
1412 // A list of builtin named types.
1414 std::vector<Named_type*> Type::named_builtin_types;
1416 // Make a builtin named type.
1418 Named_type*
1419 Type::make_builtin_named_type(const char* name, Type* type)
1421 Location bloc = Linemap::predeclared_location();
1422 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1423 Named_type* ret = no->type_value();
1424 Type::named_builtin_types.push_back(ret);
1425 return ret;
1428 // Convert the named builtin types.
1430 void
1431 Type::convert_builtin_named_types(Gogo* gogo)
1433 for (std::vector<Named_type*>::const_iterator p =
1434 Type::named_builtin_types.begin();
1435 p != Type::named_builtin_types.end();
1436 ++p)
1438 bool r = (*p)->verify();
1439 go_assert(r);
1440 (*p)->convert(gogo);
1444 // Return the type of a type descriptor. We should really tie this to
1445 // runtime.Type rather than copying it. This must match commonType in
1446 // libgo/go/runtime/type.go.
1448 Type*
1449 Type::make_type_descriptor_type()
1451 static Type* ret;
1452 if (ret == NULL)
1454 Location bloc = Linemap::predeclared_location();
1456 Type* uint8_type = Type::lookup_integer_type("uint8");
1457 Type* uint32_type = Type::lookup_integer_type("uint32");
1458 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1459 Type* string_type = Type::lookup_string_type();
1460 Type* pointer_string_type = Type::make_pointer_type(string_type);
1462 // This is an unnamed version of unsafe.Pointer. Perhaps we
1463 // should use the named version instead, although that would
1464 // require us to create the unsafe package if it has not been
1465 // imported. It probably doesn't matter.
1466 Type* void_type = Type::make_void_type();
1467 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1469 // Forward declaration for the type descriptor type.
1470 Named_object* named_type_descriptor_type =
1471 Named_object::make_type_declaration("commonType", NULL, bloc);
1472 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1473 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1475 // The type of a method on a concrete type.
1476 Struct_type* method_type =
1477 Type::make_builtin_struct_type(5,
1478 "name", pointer_string_type,
1479 "pkgPath", pointer_string_type,
1480 "mtyp", pointer_type_descriptor_type,
1481 "typ", pointer_type_descriptor_type,
1482 "tfn", unsafe_pointer_type);
1483 Named_type* named_method_type =
1484 Type::make_builtin_named_type("method", method_type);
1486 // Information for types with a name or methods.
1487 Type* slice_named_method_type =
1488 Type::make_array_type(named_method_type, NULL);
1489 Struct_type* uncommon_type =
1490 Type::make_builtin_struct_type(3,
1491 "name", pointer_string_type,
1492 "pkgPath", pointer_string_type,
1493 "methods", slice_named_method_type);
1494 Named_type* named_uncommon_type =
1495 Type::make_builtin_named_type("uncommonType", uncommon_type);
1497 Type* pointer_uncommon_type =
1498 Type::make_pointer_type(named_uncommon_type);
1500 // The type descriptor type.
1502 Struct_type* type_descriptor_type =
1503 Type::make_builtin_struct_type(12,
1504 "kind", uint8_type,
1505 "align", uint8_type,
1506 "fieldAlign", uint8_type,
1507 "size", uintptr_type,
1508 "hash", uint32_type,
1509 "hashfn", uintptr_type,
1510 "equalfn", uintptr_type,
1511 "gc", uintptr_type,
1512 "string", pointer_string_type,
1513 "", pointer_uncommon_type,
1514 "ptrToThis",
1515 pointer_type_descriptor_type,
1516 "zero", unsafe_pointer_type);
1518 Named_type* named = Type::make_builtin_named_type("commonType",
1519 type_descriptor_type);
1521 named_type_descriptor_type->set_type_value(named);
1523 ret = named;
1526 return ret;
1529 // Make the type of a pointer to a type descriptor as represented in
1530 // Go.
1532 Type*
1533 Type::make_type_descriptor_ptr_type()
1535 static Type* ret;
1536 if (ret == NULL)
1537 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1538 return ret;
1541 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1542 // hash code for this type and which compare whether two values of
1543 // this type are equal. If NAME is not NULL it is the name of this
1544 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1545 // functions, for convenience; they may be NULL.
1547 void
1548 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1549 Function_type* equal_fntype, Named_object** hash_fn,
1550 Named_object** equal_fn)
1552 if (hash_fntype == NULL || equal_fntype == NULL)
1554 Location bloc = Linemap::predeclared_location();
1556 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1557 Type* void_type = Type::make_void_type();
1558 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1560 if (hash_fntype == NULL)
1562 Typed_identifier_list* params = new Typed_identifier_list();
1563 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1564 bloc));
1565 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1567 Typed_identifier_list* results = new Typed_identifier_list();
1568 results->push_back(Typed_identifier("", uintptr_type, bloc));
1570 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1572 if (equal_fntype == NULL)
1574 Typed_identifier_list* params = new Typed_identifier_list();
1575 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1576 bloc));
1577 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1578 bloc));
1579 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1581 Typed_identifier_list* results = new Typed_identifier_list();
1582 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1583 bloc));
1585 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1589 const char* hash_fnname;
1590 const char* equal_fnname;
1591 if (this->compare_is_identity(gogo))
1593 hash_fnname = "__go_type_hash_identity";
1594 equal_fnname = "__go_type_equal_identity";
1596 else if (!this->is_comparable())
1598 hash_fnname = "__go_type_hash_error";
1599 equal_fnname = "__go_type_equal_error";
1601 else
1603 switch (this->base()->classification())
1605 case Type::TYPE_ERROR:
1606 case Type::TYPE_VOID:
1607 case Type::TYPE_NIL:
1608 case Type::TYPE_FUNCTION:
1609 case Type::TYPE_MAP:
1610 // For these types is_comparable should have returned false.
1611 go_unreachable();
1613 case Type::TYPE_BOOLEAN:
1614 case Type::TYPE_INTEGER:
1615 case Type::TYPE_POINTER:
1616 case Type::TYPE_CHANNEL:
1617 // For these types compare_is_identity should have returned true.
1618 go_unreachable();
1620 case Type::TYPE_FLOAT:
1621 hash_fnname = "__go_type_hash_float";
1622 equal_fnname = "__go_type_equal_float";
1623 break;
1625 case Type::TYPE_COMPLEX:
1626 hash_fnname = "__go_type_hash_complex";
1627 equal_fnname = "__go_type_equal_complex";
1628 break;
1630 case Type::TYPE_STRING:
1631 hash_fnname = "__go_type_hash_string";
1632 equal_fnname = "__go_type_equal_string";
1633 break;
1635 case Type::TYPE_STRUCT:
1637 // This is a struct which can not be compared using a
1638 // simple identity function. We need to build a function
1639 // for comparison.
1640 this->specific_type_functions(gogo, name, hash_fntype,
1641 equal_fntype, hash_fn, equal_fn);
1642 return;
1645 case Type::TYPE_ARRAY:
1646 if (this->is_slice_type())
1648 // Type::is_compatible_for_comparison should have
1649 // returned false.
1650 go_unreachable();
1652 else
1654 // This is an array which can not be compared using a
1655 // simple identity function. We need to build a
1656 // function for comparison.
1657 this->specific_type_functions(gogo, name, hash_fntype,
1658 equal_fntype, hash_fn, equal_fn);
1659 return;
1661 break;
1663 case Type::TYPE_INTERFACE:
1664 if (this->interface_type()->is_empty())
1666 hash_fnname = "__go_type_hash_empty_interface";
1667 equal_fnname = "__go_type_equal_empty_interface";
1669 else
1671 hash_fnname = "__go_type_hash_interface";
1672 equal_fnname = "__go_type_equal_interface";
1674 break;
1676 case Type::TYPE_NAMED:
1677 case Type::TYPE_FORWARD:
1678 go_unreachable();
1680 default:
1681 go_unreachable();
1686 Location bloc = Linemap::predeclared_location();
1687 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1688 hash_fntype, bloc);
1689 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1690 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1691 equal_fntype, bloc);
1692 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1695 // A hash table mapping types to the specific hash functions.
1697 Type::Type_functions Type::type_functions_table;
1699 // Handle a type function which is specific to a type: a struct or
1700 // array which can not use an identity comparison.
1702 void
1703 Type::specific_type_functions(Gogo* gogo, Named_type* name,
1704 Function_type* hash_fntype,
1705 Function_type* equal_fntype,
1706 Named_object** hash_fn,
1707 Named_object** equal_fn)
1709 Hash_equal_fn fnull(NULL, NULL);
1710 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1711 std::pair<Type_functions::iterator, bool> ins =
1712 Type::type_functions_table.insert(val);
1713 if (!ins.second)
1715 // We already have functions for this type
1716 *hash_fn = ins.first->second.first;
1717 *equal_fn = ins.first->second.second;
1718 return;
1721 std::string base_name;
1722 if (name == NULL)
1724 // Mangled names can have '.' if they happen to refer to named
1725 // types in some way. That's fine if this is simply a named
1726 // type, but otherwise it will confuse the code that builds
1727 // function identifiers. Remove '.' when necessary.
1728 base_name = this->mangled_name(gogo);
1729 size_t i;
1730 while ((i = base_name.find('.')) != std::string::npos)
1731 base_name[i] = '$';
1732 base_name = gogo->pack_hidden_name(base_name, false);
1734 else
1736 // This name is already hidden or not as appropriate.
1737 base_name = name->name();
1738 unsigned int index;
1739 const Named_object* in_function = name->in_function(&index);
1740 if (in_function != NULL)
1742 base_name += '$' + Gogo::unpack_hidden_name(in_function->name());
1743 if (index > 0)
1745 char buf[30];
1746 snprintf(buf, sizeof buf, "%u", index);
1747 base_name += '$';
1748 base_name += buf;
1752 std::string hash_name = base_name + "$hash";
1753 std::string equal_name = base_name + "$equal";
1755 Location bloc = Linemap::predeclared_location();
1757 const Package* package = NULL;
1758 bool is_defined_elsewhere =
1759 this->type_descriptor_defined_elsewhere(name, &package);
1760 if (is_defined_elsewhere)
1762 *hash_fn = Named_object::make_function_declaration(hash_name, package,
1763 hash_fntype, bloc);
1764 *equal_fn = Named_object::make_function_declaration(equal_name, package,
1765 equal_fntype, bloc);
1767 else
1769 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
1770 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
1771 bloc);
1774 ins.first->second.first = *hash_fn;
1775 ins.first->second.second = *equal_fn;
1777 if (!is_defined_elsewhere)
1779 if (gogo->in_global_scope())
1780 this->write_specific_type_functions(gogo, name, hash_name, hash_fntype,
1781 equal_name, equal_fntype);
1782 else
1783 gogo->queue_specific_type_function(this, name, hash_name, hash_fntype,
1784 equal_name, equal_fntype);
1788 // Write the hash and equality functions for a type which needs to be
1789 // written specially.
1791 void
1792 Type::write_specific_type_functions(Gogo* gogo, Named_type* name,
1793 const std::string& hash_name,
1794 Function_type* hash_fntype,
1795 const std::string& equal_name,
1796 Function_type* equal_fntype)
1798 Location bloc = Linemap::predeclared_location();
1800 if (gogo->specific_type_functions_are_written())
1802 go_assert(saw_errors());
1803 return;
1806 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
1807 bloc);
1808 gogo->start_block(bloc);
1810 if (name != NULL && name->real_type()->named_type() != NULL)
1811 this->write_named_hash(gogo, name, hash_fntype, equal_fntype);
1812 else if (this->struct_type() != NULL)
1813 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
1814 equal_fntype);
1815 else if (this->array_type() != NULL)
1816 this->array_type()->write_hash_function(gogo, name, hash_fntype,
1817 equal_fntype);
1818 else
1819 go_unreachable();
1821 Block* b = gogo->finish_block(bloc);
1822 gogo->add_block(b, bloc);
1823 gogo->lower_block(hash_fn, b);
1824 gogo->finish_function(bloc);
1826 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
1827 false, bloc);
1828 gogo->start_block(bloc);
1830 if (name != NULL && name->real_type()->named_type() != NULL)
1831 this->write_named_equal(gogo, name);
1832 else if (this->struct_type() != NULL)
1833 this->struct_type()->write_equal_function(gogo, name);
1834 else if (this->array_type() != NULL)
1835 this->array_type()->write_equal_function(gogo, name);
1836 else
1837 go_unreachable();
1839 b = gogo->finish_block(bloc);
1840 gogo->add_block(b, bloc);
1841 gogo->lower_block(equal_fn, b);
1842 gogo->finish_function(bloc);
1845 // Write a hash function that simply calls the hash function for a
1846 // named type. This is used when one named type is defined as
1847 // another. This ensures that this case works when the other named
1848 // type is defined in another package and relies on calling hash
1849 // functions defined only in that package.
1851 void
1852 Type::write_named_hash(Gogo* gogo, Named_type* name,
1853 Function_type* hash_fntype, Function_type* equal_fntype)
1855 Location bloc = Linemap::predeclared_location();
1857 Named_type* base_type = name->real_type()->named_type();
1858 go_assert(base_type != NULL);
1860 // The pointer to the type we are going to hash. This is an
1861 // unsafe.Pointer.
1862 Named_object* key_arg = gogo->lookup("key", NULL);
1863 go_assert(key_arg != NULL);
1865 // The size of the type we are going to hash.
1866 Named_object* keysz_arg = gogo->lookup("key_size", NULL);
1867 go_assert(keysz_arg != NULL);
1869 Named_object* hash_fn;
1870 Named_object* equal_fn;
1871 name->real_type()->type_functions(gogo, base_type, hash_fntype, equal_fntype,
1872 &hash_fn, &equal_fn);
1874 // Call the hash function for the base type.
1875 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
1876 Expression* keysz_ref = Expression::make_var_reference(keysz_arg, bloc);
1877 Expression_list* args = new Expression_list();
1878 args->push_back(key_ref);
1879 args->push_back(keysz_ref);
1880 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
1881 Expression* call = Expression::make_call(func, args, false, bloc);
1883 // Return the hash of the base type.
1884 Expression_list* vals = new Expression_list();
1885 vals->push_back(call);
1886 Statement* s = Statement::make_return_statement(vals, bloc);
1887 gogo->add_statement(s);
1890 // Write an equality function that simply calls the equality function
1891 // for a named type. This is used when one named type is defined as
1892 // another. This ensures that this case works when the other named
1893 // type is defined in another package and relies on calling equality
1894 // functions defined only in that package.
1896 void
1897 Type::write_named_equal(Gogo* gogo, Named_type* name)
1899 Location bloc = Linemap::predeclared_location();
1901 // The pointers to the types we are going to compare. These have
1902 // type unsafe.Pointer.
1903 Named_object* key1_arg = gogo->lookup("key1", NULL);
1904 Named_object* key2_arg = gogo->lookup("key2", NULL);
1905 go_assert(key1_arg != NULL && key2_arg != NULL);
1907 Named_type* base_type = name->real_type()->named_type();
1908 go_assert(base_type != NULL);
1910 // Build temporaries with the base type.
1911 Type* pt = Type::make_pointer_type(base_type);
1913 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
1914 ref = Expression::make_cast(pt, ref, bloc);
1915 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
1916 gogo->add_statement(p1);
1918 ref = Expression::make_var_reference(key2_arg, bloc);
1919 ref = Expression::make_cast(pt, ref, bloc);
1920 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
1921 gogo->add_statement(p2);
1923 // Compare the values for equality.
1924 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
1925 t1 = Expression::make_unary(OPERATOR_MULT, t1, bloc);
1927 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
1928 t2 = Expression::make_unary(OPERATOR_MULT, t2, bloc);
1930 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
1932 // Return the equality comparison.
1933 Expression_list* vals = new Expression_list();
1934 vals->push_back(cond);
1935 Statement* s = Statement::make_return_statement(vals, bloc);
1936 gogo->add_statement(s);
1939 // Return a composite literal for the type descriptor for a plain type
1940 // of kind RUNTIME_TYPE_KIND named NAME.
1942 Expression*
1943 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
1944 Named_type* name, const Methods* methods,
1945 bool only_value_methods)
1947 Location bloc = Linemap::predeclared_location();
1949 Type* td_type = Type::make_type_descriptor_type();
1950 const Struct_field_list* fields = td_type->struct_type()->fields();
1952 Expression_list* vals = new Expression_list();
1953 vals->reserve(9);
1955 if (!this->has_pointer())
1956 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
1957 Struct_field_list::const_iterator p = fields->begin();
1958 go_assert(p->is_field_name("kind"));
1959 mpz_t iv;
1960 mpz_init_set_ui(iv, runtime_type_kind);
1961 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1963 ++p;
1964 go_assert(p->is_field_name("align"));
1965 Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT;
1966 vals->push_back(Expression::make_type_info(this, type_info));
1968 ++p;
1969 go_assert(p->is_field_name("fieldAlign"));
1970 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
1971 vals->push_back(Expression::make_type_info(this, type_info));
1973 ++p;
1974 go_assert(p->is_field_name("size"));
1975 type_info = Expression::TYPE_INFO_SIZE;
1976 vals->push_back(Expression::make_type_info(this, type_info));
1978 ++p;
1979 go_assert(p->is_field_name("hash"));
1980 unsigned int h;
1981 if (name != NULL)
1982 h = name->hash_for_method(gogo);
1983 else
1984 h = this->hash_for_method(gogo);
1985 mpz_set_ui(iv, h);
1986 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1988 ++p;
1989 go_assert(p->is_field_name("hashfn"));
1990 Function_type* hash_fntype = p->type()->function_type();
1992 ++p;
1993 go_assert(p->is_field_name("equalfn"));
1994 Function_type* equal_fntype = p->type()->function_type();
1996 Named_object* hash_fn;
1997 Named_object* equal_fn;
1998 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
1999 &equal_fn);
2000 vals->push_back(Expression::make_func_code_reference(hash_fn, bloc));
2001 vals->push_back(Expression::make_func_code_reference(equal_fn, bloc));
2003 ++p;
2004 go_assert(p->is_field_name("gc"));
2005 vals->push_back(Expression::make_gc_symbol(this));
2007 ++p;
2008 go_assert(p->is_field_name("string"));
2009 Expression* s = Expression::make_string((name != NULL
2010 ? name->reflection(gogo)
2011 : this->reflection(gogo)),
2012 bloc);
2013 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2015 ++p;
2016 go_assert(p->is_field_name("uncommonType"));
2017 if (name == NULL && methods == NULL)
2018 vals->push_back(Expression::make_nil(bloc));
2019 else
2021 if (methods == NULL)
2022 methods = name->methods();
2023 vals->push_back(this->uncommon_type_constructor(gogo,
2024 p->type()->deref(),
2025 name, methods,
2026 only_value_methods));
2029 ++p;
2030 go_assert(p->is_field_name("ptrToThis"));
2031 if (name == NULL)
2032 vals->push_back(Expression::make_nil(bloc));
2033 else
2035 Type* pt = Type::make_pointer_type(name);
2036 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2039 ++p;
2040 go_assert(p->is_field_name("zero"));
2041 Expression* z = Expression::make_var_reference(gogo->zero_value(this), bloc);
2042 z = Expression::make_unary(OPERATOR_AND, z, bloc);
2043 Type* void_type = Type::make_void_type();
2044 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
2045 z = Expression::make_cast(unsafe_pointer_type, z, bloc);
2046 vals->push_back(z);
2048 ++p;
2049 go_assert(p == fields->end());
2051 mpz_clear(iv);
2053 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2056 // Return a pointer to the Garbage Collection information for this type.
2058 Bexpression*
2059 Type::gc_symbol_pointer(Gogo* gogo)
2061 Type* t = this->forwarded();
2062 if (t->named_type() != NULL && t->named_type()->is_alias())
2063 t = t->named_type()->real_type();
2064 if (t->gc_symbol_var_ == NULL)
2066 t->make_gc_symbol_var(gogo);
2067 go_assert(t->gc_symbol_var_ != NULL);
2069 Location bloc = Linemap::predeclared_location();
2070 Bexpression* var_expr =
2071 gogo->backend()->var_expression(t->gc_symbol_var_, bloc);
2072 return gogo->backend()->address_expression(var_expr, bloc);
2075 // A mapping from unnamed types to GC symbol variables.
2077 Type::GC_symbol_vars Type::gc_symbol_vars;
2079 // Build the GC symbol for this type.
2081 void
2082 Type::make_gc_symbol_var(Gogo* gogo)
2084 go_assert(this->gc_symbol_var_ == NULL);
2086 Named_type* nt = this->named_type();
2088 // We can have multiple instances of unnamed types and similar to type
2089 // descriptors, we only want to the emit the GC data once, so we use a
2090 // hash table.
2091 Bvariable** phash = NULL;
2092 if (nt == NULL)
2094 Bvariable* bvnull = NULL;
2095 std::pair<GC_symbol_vars::iterator, bool> ins =
2096 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2097 if (!ins.second)
2099 // We've already built a gc symbol for this type.
2100 this->gc_symbol_var_ = ins.first->second;
2101 return;
2103 phash = &ins.first->second;
2106 std::string sym_name = this->type_descriptor_var_name(gogo, nt) + "$gc";
2108 // Build the contents of the gc symbol.
2109 Expression* sym_init = this->gc_symbol_constructor(gogo);
2110 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2112 // If the type descriptor for this type is defined somewhere else, so is the
2113 // GC symbol.
2114 const Package* dummy;
2115 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2117 this->gc_symbol_var_ =
2118 gogo->backend()->implicit_variable_reference(sym_name, sym_btype);
2119 if (phash != NULL)
2120 *phash = this->gc_symbol_var_;
2121 return;
2124 // See if this gc symbol can appear in multiple packages.
2125 bool is_common = false;
2126 if (nt != NULL)
2128 // We create the symbol for a builtin type whenever we need
2129 // it.
2130 is_common = nt->is_builtin();
2132 else
2134 // This is an unnamed type. The descriptor could be defined in
2135 // any package where it is needed, and the linker will pick one
2136 // descriptor to keep.
2137 is_common = true;
2140 // Since we are building the GC symbol in this package, we must create the
2141 // variable before converting the initializer to its backend representation
2142 // because the initializer may refer to the GC symbol for this type.
2143 this->gc_symbol_var_ =
2144 gogo->backend()->implicit_variable(sym_name, sym_btype, false, true, is_common, 0);
2145 if (phash != NULL)
2146 *phash = this->gc_symbol_var_;
2148 Translate_context context(gogo, NULL, NULL, NULL);
2149 context.set_is_const();
2150 Bexpression* sym_binit = sym_init->get_backend(&context);
2151 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2152 sym_btype, false, true, is_common,
2153 sym_binit);
2156 // Return an array literal for the Garbage Collection information for this type.
2158 Expression*
2159 Type::gc_symbol_constructor(Gogo* gogo)
2161 Location bloc = Linemap::predeclared_location();
2163 // The common GC Symbol data starts with the width of the type and ends
2164 // with the GC Opcode GC_END.
2165 // However, for certain types, the GC symbol may include extra information
2166 // before the ending opcode, so we pass the expression list into
2167 // Type::gc_symbol to allow it to add extra information as is necessary.
2168 Expression_list* vals = new Expression_list;
2170 Type* uintptr_t = Type::lookup_integer_type("uintptr");
2171 // width
2172 vals->push_back(Expression::make_type_info(this,
2173 Expression::TYPE_INFO_SIZE));
2175 mpz_t off;
2176 mpz_init_set_ui(off, 0UL);
2177 Expression* offset = Expression::make_integer(&off, uintptr_t, bloc);
2178 mpz_clear(off);
2180 this->do_gc_symbol(gogo, &vals, &offset, 0);
2182 mpz_t end;
2183 mpz_init_set_ui(end, GC_END);
2184 vals->push_back(Expression::make_integer(&end, uintptr_t, bloc));
2185 mpz_clear(end);
2187 mpz_t lenval;
2188 mpz_init_set_ui(lenval, vals->size() + 1);
2189 Expression* len = Expression::make_integer(&lenval, NULL, bloc);
2190 mpz_clear(lenval);
2192 Array_type* gc_symbol_type = Type::make_array_type(uintptr_t, len);
2193 return Expression::make_array_composite_literal(gc_symbol_type, vals, bloc);
2196 // Advance the OFFSET of the GC symbol by this type's width.
2198 void
2199 Type::advance_gc_offset(Expression** offset)
2201 if (this->is_error_type())
2202 return;
2204 Location bloc = Linemap::predeclared_location();
2205 Expression* width =
2206 Expression::make_type_info(this, Expression::TYPE_INFO_SIZE);
2207 *offset = Expression::make_binary(OPERATOR_PLUS, *offset, width, bloc);
2210 // Return a composite literal for the uncommon type information for
2211 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
2212 // struct. If name is not NULL, it is the name of the type. If
2213 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
2214 // is true if only value methods should be included. At least one of
2215 // NAME and METHODS must not be NULL.
2217 Expression*
2218 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
2219 Named_type* name, const Methods* methods,
2220 bool only_value_methods) const
2222 Location bloc = Linemap::predeclared_location();
2224 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
2226 Expression_list* vals = new Expression_list();
2227 vals->reserve(3);
2229 Struct_field_list::const_iterator p = fields->begin();
2230 go_assert(p->is_field_name("name"));
2232 ++p;
2233 go_assert(p->is_field_name("pkgPath"));
2235 if (name == NULL)
2237 vals->push_back(Expression::make_nil(bloc));
2238 vals->push_back(Expression::make_nil(bloc));
2240 else
2242 Named_object* no = name->named_object();
2243 std::string n = Gogo::unpack_hidden_name(no->name());
2244 Expression* s = Expression::make_string(n, bloc);
2245 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2247 if (name->is_builtin())
2248 vals->push_back(Expression::make_nil(bloc));
2249 else
2251 const Package* package = no->package();
2252 const std::string& pkgpath(package == NULL
2253 ? gogo->pkgpath()
2254 : package->pkgpath());
2255 n.assign(pkgpath);
2256 unsigned int index;
2257 const Named_object* in_function = name->in_function(&index);
2258 if (in_function != NULL)
2260 n.append(1, '.');
2261 n.append(Gogo::unpack_hidden_name(in_function->name()));
2262 if (index > 0)
2264 char buf[30];
2265 snprintf(buf, sizeof buf, "%u", index);
2266 n.append(1, '.');
2267 n.append(buf);
2270 s = Expression::make_string(n, bloc);
2271 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2275 ++p;
2276 go_assert(p->is_field_name("methods"));
2277 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
2278 only_value_methods));
2280 ++p;
2281 go_assert(p == fields->end());
2283 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
2284 vals, bloc);
2285 return Expression::make_unary(OPERATOR_AND, r, bloc);
2288 // Sort methods by name.
2290 class Sort_methods
2292 public:
2293 bool
2294 operator()(const std::pair<std::string, const Method*>& m1,
2295 const std::pair<std::string, const Method*>& m2) const
2296 { return m1.first < m2.first; }
2299 // Return a composite literal for the type method table for this type.
2300 // METHODS_TYPE is the type of the table, and is a slice type.
2301 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
2302 // then only value methods are used.
2304 Expression*
2305 Type::methods_constructor(Gogo* gogo, Type* methods_type,
2306 const Methods* methods,
2307 bool only_value_methods) const
2309 Location bloc = Linemap::predeclared_location();
2311 std::vector<std::pair<std::string, const Method*> > smethods;
2312 if (methods != NULL)
2314 smethods.reserve(methods->count());
2315 for (Methods::const_iterator p = methods->begin();
2316 p != methods->end();
2317 ++p)
2319 if (p->second->is_ambiguous())
2320 continue;
2321 if (only_value_methods && !p->second->is_value_method())
2322 continue;
2324 // This is where we implement the magic //go:nointerface
2325 // comment. If we saw that comment, we don't add this
2326 // method to the type descriptor.
2327 if (p->second->nointerface())
2328 continue;
2330 smethods.push_back(std::make_pair(p->first, p->second));
2334 if (smethods.empty())
2335 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
2337 std::sort(smethods.begin(), smethods.end(), Sort_methods());
2339 Type* method_type = methods_type->array_type()->element_type();
2341 Expression_list* vals = new Expression_list();
2342 vals->reserve(smethods.size());
2343 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
2344 = smethods.begin();
2345 p != smethods.end();
2346 ++p)
2347 vals->push_back(this->method_constructor(gogo, method_type, p->first,
2348 p->second, only_value_methods));
2350 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
2353 // Return a composite literal for a single method. METHOD_TYPE is the
2354 // type of the entry. METHOD_NAME is the name of the method and M is
2355 // the method information.
2357 Expression*
2358 Type::method_constructor(Gogo*, Type* method_type,
2359 const std::string& method_name,
2360 const Method* m,
2361 bool only_value_methods) const
2363 Location bloc = Linemap::predeclared_location();
2365 const Struct_field_list* fields = method_type->struct_type()->fields();
2367 Expression_list* vals = new Expression_list();
2368 vals->reserve(5);
2370 Struct_field_list::const_iterator p = fields->begin();
2371 go_assert(p->is_field_name("name"));
2372 const std::string n = Gogo::unpack_hidden_name(method_name);
2373 Expression* s = Expression::make_string(n, bloc);
2374 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2376 ++p;
2377 go_assert(p->is_field_name("pkgPath"));
2378 if (!Gogo::is_hidden_name(method_name))
2379 vals->push_back(Expression::make_nil(bloc));
2380 else
2382 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
2383 bloc);
2384 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2387 Named_object* no = (m->needs_stub_method()
2388 ? m->stub_object()
2389 : m->named_object());
2391 Function_type* mtype;
2392 if (no->is_function())
2393 mtype = no->func_value()->type();
2394 else
2395 mtype = no->func_declaration_value()->type();
2396 go_assert(mtype->is_method());
2397 Type* nonmethod_type = mtype->copy_without_receiver();
2399 ++p;
2400 go_assert(p->is_field_name("mtyp"));
2401 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
2403 ++p;
2404 go_assert(p->is_field_name("typ"));
2405 bool want_pointer_receiver = !only_value_methods && m->is_value_method();
2406 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
2407 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
2409 ++p;
2410 go_assert(p->is_field_name("tfn"));
2411 vals->push_back(Expression::make_func_code_reference(no, bloc));
2413 ++p;
2414 go_assert(p == fields->end());
2416 return Expression::make_struct_composite_literal(method_type, vals, bloc);
2419 // Return a composite literal for the type descriptor of a plain type.
2420 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
2421 // NULL, it is the name to use as well as the list of methods.
2423 Expression*
2424 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
2425 Named_type* name)
2427 return this->type_descriptor_constructor(gogo, runtime_type_kind,
2428 name, NULL, true);
2431 // Return the type reflection string for this type.
2433 std::string
2434 Type::reflection(Gogo* gogo) const
2436 std::string ret;
2438 // The do_reflection virtual function should set RET to the
2439 // reflection string.
2440 this->do_reflection(gogo, &ret);
2442 return ret;
2445 // Return a mangled name for the type.
2447 std::string
2448 Type::mangled_name(Gogo* gogo) const
2450 std::string ret;
2452 // The do_mangled_name virtual function should set RET to the
2453 // mangled name. For a composite type it should append a code for
2454 // the composition and then call do_mangled_name on the components.
2455 this->do_mangled_name(gogo, &ret);
2457 return ret;
2460 // Return whether the backend size of the type is known.
2462 bool
2463 Type::is_backend_type_size_known(Gogo* gogo)
2465 switch (this->classification_)
2467 case TYPE_ERROR:
2468 case TYPE_VOID:
2469 case TYPE_BOOLEAN:
2470 case TYPE_INTEGER:
2471 case TYPE_FLOAT:
2472 case TYPE_COMPLEX:
2473 case TYPE_STRING:
2474 case TYPE_FUNCTION:
2475 case TYPE_POINTER:
2476 case TYPE_NIL:
2477 case TYPE_MAP:
2478 case TYPE_CHANNEL:
2479 case TYPE_INTERFACE:
2480 return true;
2482 case TYPE_STRUCT:
2484 const Struct_field_list* fields = this->struct_type()->fields();
2485 for (Struct_field_list::const_iterator pf = fields->begin();
2486 pf != fields->end();
2487 ++pf)
2488 if (!pf->type()->is_backend_type_size_known(gogo))
2489 return false;
2490 return true;
2493 case TYPE_ARRAY:
2495 const Array_type* at = this->array_type();
2496 if (at->length() == NULL)
2497 return true;
2498 else
2500 Numeric_constant nc;
2501 if (!at->length()->numeric_constant_value(&nc))
2502 return false;
2503 mpz_t ival;
2504 if (!nc.to_int(&ival))
2505 return false;
2506 mpz_clear(ival);
2507 return at->element_type()->is_backend_type_size_known(gogo);
2511 case TYPE_NAMED:
2512 this->named_type()->convert(gogo);
2513 return this->named_type()->is_named_backend_type_size_known();
2515 case TYPE_FORWARD:
2517 Forward_declaration_type* fdt = this->forward_declaration_type();
2518 return fdt->real_type()->is_backend_type_size_known(gogo);
2521 case TYPE_SINK:
2522 case TYPE_CALL_MULTIPLE_RESULT:
2523 go_unreachable();
2525 default:
2526 go_unreachable();
2530 // If the size of the type can be determined, set *PSIZE to the size
2531 // in bytes and return true. Otherwise, return false. This queries
2532 // the backend.
2534 bool
2535 Type::backend_type_size(Gogo* gogo, unsigned long *psize)
2537 if (!this->is_backend_type_size_known(gogo))
2538 return false;
2539 Btype* bt = this->get_backend_placeholder(gogo);
2540 size_t size = gogo->backend()->type_size(bt);
2541 *psize = static_cast<unsigned long>(size);
2542 if (*psize != size)
2543 return false;
2544 return true;
2547 // If the alignment of the type can be determined, set *PALIGN to
2548 // the alignment in bytes and return true. Otherwise, return false.
2550 bool
2551 Type::backend_type_align(Gogo* gogo, unsigned long *palign)
2553 if (!this->is_backend_type_size_known(gogo))
2554 return false;
2555 Btype* bt = this->get_backend_placeholder(gogo);
2556 size_t align = gogo->backend()->type_alignment(bt);
2557 *palign = static_cast<unsigned long>(align);
2558 if (*palign != align)
2559 return false;
2560 return true;
2563 // Like backend_type_align, but return the alignment when used as a
2564 // field.
2566 bool
2567 Type::backend_type_field_align(Gogo* gogo, unsigned long *palign)
2569 if (!this->is_backend_type_size_known(gogo))
2570 return false;
2571 Btype* bt = this->get_backend_placeholder(gogo);
2572 size_t a = gogo->backend()->type_field_alignment(bt);
2573 *palign = static_cast<unsigned long>(a);
2574 if (*palign != a)
2575 return false;
2576 return true;
2579 // Default function to export a type.
2581 void
2582 Type::do_export(Export*) const
2584 go_unreachable();
2587 // Import a type.
2589 Type*
2590 Type::import_type(Import* imp)
2592 if (imp->match_c_string("("))
2593 return Function_type::do_import(imp);
2594 else if (imp->match_c_string("*"))
2595 return Pointer_type::do_import(imp);
2596 else if (imp->match_c_string("struct "))
2597 return Struct_type::do_import(imp);
2598 else if (imp->match_c_string("["))
2599 return Array_type::do_import(imp);
2600 else if (imp->match_c_string("map "))
2601 return Map_type::do_import(imp);
2602 else if (imp->match_c_string("chan "))
2603 return Channel_type::do_import(imp);
2604 else if (imp->match_c_string("interface"))
2605 return Interface_type::do_import(imp);
2606 else
2608 error_at(imp->location(), "import error: expected type");
2609 return Type::make_error_type();
2613 // A type used to indicate a parsing error. This exists to simplify
2614 // later error detection.
2616 class Error_type : public Type
2618 public:
2619 Error_type()
2620 : Type(TYPE_ERROR)
2623 protected:
2624 bool
2625 do_compare_is_identity(Gogo*)
2626 { return false; }
2628 Btype*
2629 do_get_backend(Gogo* gogo)
2630 { return gogo->backend()->error_type(); }
2632 Expression*
2633 do_type_descriptor(Gogo*, Named_type*)
2634 { return Expression::make_error(Linemap::predeclared_location()); }
2636 void
2637 do_reflection(Gogo*, std::string*) const
2638 { go_assert(saw_errors()); }
2640 void
2641 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
2642 { go_assert(saw_errors()); }
2644 void
2645 do_mangled_name(Gogo*, std::string* ret) const
2646 { ret->push_back('E'); }
2649 Type*
2650 Type::make_error_type()
2652 static Error_type singleton_error_type;
2653 return &singleton_error_type;
2656 // The void type.
2658 class Void_type : public Type
2660 public:
2661 Void_type()
2662 : Type(TYPE_VOID)
2665 protected:
2666 bool
2667 do_compare_is_identity(Gogo*)
2668 { return false; }
2670 Btype*
2671 do_get_backend(Gogo* gogo)
2672 { return gogo->backend()->void_type(); }
2674 Expression*
2675 do_type_descriptor(Gogo*, Named_type*)
2676 { go_unreachable(); }
2678 void
2679 do_reflection(Gogo*, std::string*) const
2682 void
2683 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
2686 void
2687 do_mangled_name(Gogo*, std::string* ret) const
2688 { ret->push_back('v'); }
2691 Type*
2692 Type::make_void_type()
2694 static Void_type singleton_void_type;
2695 return &singleton_void_type;
2698 // The boolean type.
2700 class Boolean_type : public Type
2702 public:
2703 Boolean_type()
2704 : Type(TYPE_BOOLEAN)
2707 protected:
2708 bool
2709 do_compare_is_identity(Gogo*)
2710 { return true; }
2712 Btype*
2713 do_get_backend(Gogo* gogo)
2714 { return gogo->backend()->bool_type(); }
2716 Expression*
2717 do_type_descriptor(Gogo*, Named_type* name);
2719 // We should not be asked for the reflection string of a basic type.
2720 void
2721 do_reflection(Gogo*, std::string* ret) const
2722 { ret->append("bool"); }
2724 void
2725 do_gc_symbol(Gogo*, Expression_list**, Expression**, int);
2727 void
2728 do_mangled_name(Gogo*, std::string* ret) const
2729 { ret->push_back('b'); }
2732 // Make the type descriptor.
2734 Expression*
2735 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2737 if (name != NULL)
2738 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
2739 else
2741 Named_object* no = gogo->lookup_global("bool");
2742 go_assert(no != NULL);
2743 return Type::type_descriptor(gogo, no->type_value());
2747 // Update the offset of the GC symbol.
2749 void
2750 Boolean_type::do_gc_symbol(Gogo*, Expression_list**, Expression** offset, int)
2751 { this->advance_gc_offset(offset); }
2753 Type*
2754 Type::make_boolean_type()
2756 static Boolean_type boolean_type;
2757 return &boolean_type;
2760 // The named type "bool".
2762 static Named_type* named_bool_type;
2764 // Get the named type "bool".
2766 Named_type*
2767 Type::lookup_bool_type()
2769 return named_bool_type;
2772 // Make the named type "bool".
2774 Named_type*
2775 Type::make_named_bool_type()
2777 Type* bool_type = Type::make_boolean_type();
2778 Named_object* named_object =
2779 Named_object::make_type("bool", NULL, bool_type,
2780 Linemap::predeclared_location());
2781 Named_type* named_type = named_object->type_value();
2782 named_bool_type = named_type;
2783 return named_type;
2786 // Class Integer_type.
2788 Integer_type::Named_integer_types Integer_type::named_integer_types;
2790 // Create a new integer type. Non-abstract integer types always have
2791 // names.
2793 Named_type*
2794 Integer_type::create_integer_type(const char* name, bool is_unsigned,
2795 int bits, int runtime_type_kind)
2797 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
2798 runtime_type_kind);
2799 std::string sname(name);
2800 Named_object* named_object =
2801 Named_object::make_type(sname, NULL, integer_type,
2802 Linemap::predeclared_location());
2803 Named_type* named_type = named_object->type_value();
2804 std::pair<Named_integer_types::iterator, bool> ins =
2805 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
2806 go_assert(ins.second);
2807 return named_type;
2810 // Look up an existing integer type.
2812 Named_type*
2813 Integer_type::lookup_integer_type(const char* name)
2815 Named_integer_types::const_iterator p =
2816 Integer_type::named_integer_types.find(name);
2817 go_assert(p != Integer_type::named_integer_types.end());
2818 return p->second;
2821 // Create a new abstract integer type.
2823 Integer_type*
2824 Integer_type::create_abstract_integer_type()
2826 static Integer_type* abstract_type;
2827 if (abstract_type == NULL)
2829 Type* int_type = Type::lookup_integer_type("int");
2830 abstract_type = new Integer_type(true, false,
2831 int_type->integer_type()->bits(),
2832 RUNTIME_TYPE_KIND_INT);
2834 return abstract_type;
2837 // Create a new abstract character type.
2839 Integer_type*
2840 Integer_type::create_abstract_character_type()
2842 static Integer_type* abstract_type;
2843 if (abstract_type == NULL)
2845 abstract_type = new Integer_type(true, false, 32,
2846 RUNTIME_TYPE_KIND_INT32);
2847 abstract_type->set_is_rune();
2849 return abstract_type;
2852 // Integer type compatibility.
2854 bool
2855 Integer_type::is_identical(const Integer_type* t) const
2857 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
2858 return false;
2859 return this->is_abstract_ == t->is_abstract_;
2862 // Hash code.
2864 unsigned int
2865 Integer_type::do_hash_for_method(Gogo*) const
2867 return ((this->bits_ << 4)
2868 + ((this->is_unsigned_ ? 1 : 0) << 8)
2869 + ((this->is_abstract_ ? 1 : 0) << 9));
2872 // Convert an Integer_type to the backend representation.
2874 Btype*
2875 Integer_type::do_get_backend(Gogo* gogo)
2877 if (this->is_abstract_)
2879 go_assert(saw_errors());
2880 return gogo->backend()->error_type();
2882 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
2885 // The type descriptor for an integer type. Integer types are always
2886 // named.
2888 Expression*
2889 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2891 go_assert(name != NULL || saw_errors());
2892 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2895 // We should not be asked for the reflection string of a basic type.
2897 void
2898 Integer_type::do_reflection(Gogo*, std::string*) const
2900 go_assert(saw_errors());
2903 // Mangled name.
2905 void
2906 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
2908 char buf[100];
2909 snprintf(buf, sizeof buf, "i%s%s%de",
2910 this->is_abstract_ ? "a" : "",
2911 this->is_unsigned_ ? "u" : "",
2912 this->bits_);
2913 ret->append(buf);
2916 // Make an integer type.
2918 Named_type*
2919 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
2920 int runtime_type_kind)
2922 return Integer_type::create_integer_type(name, is_unsigned, bits,
2923 runtime_type_kind);
2926 // Make an abstract integer type.
2928 Integer_type*
2929 Type::make_abstract_integer_type()
2931 return Integer_type::create_abstract_integer_type();
2934 // Make an abstract character type.
2936 Integer_type*
2937 Type::make_abstract_character_type()
2939 return Integer_type::create_abstract_character_type();
2942 // Look up an integer type.
2944 Named_type*
2945 Type::lookup_integer_type(const char* name)
2947 return Integer_type::lookup_integer_type(name);
2950 // Class Float_type.
2952 Float_type::Named_float_types Float_type::named_float_types;
2954 // Create a new float type. Non-abstract float types always have
2955 // names.
2957 Named_type*
2958 Float_type::create_float_type(const char* name, int bits,
2959 int runtime_type_kind)
2961 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
2962 std::string sname(name);
2963 Named_object* named_object =
2964 Named_object::make_type(sname, NULL, float_type,
2965 Linemap::predeclared_location());
2966 Named_type* named_type = named_object->type_value();
2967 std::pair<Named_float_types::iterator, bool> ins =
2968 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
2969 go_assert(ins.second);
2970 return named_type;
2973 // Look up an existing float type.
2975 Named_type*
2976 Float_type::lookup_float_type(const char* name)
2978 Named_float_types::const_iterator p =
2979 Float_type::named_float_types.find(name);
2980 go_assert(p != Float_type::named_float_types.end());
2981 return p->second;
2984 // Create a new abstract float type.
2986 Float_type*
2987 Float_type::create_abstract_float_type()
2989 static Float_type* abstract_type;
2990 if (abstract_type == NULL)
2991 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
2992 return abstract_type;
2995 // Whether this type is identical with T.
2997 bool
2998 Float_type::is_identical(const Float_type* t) const
3000 if (this->bits_ != t->bits_)
3001 return false;
3002 return this->is_abstract_ == t->is_abstract_;
3005 // Hash code.
3007 unsigned int
3008 Float_type::do_hash_for_method(Gogo*) const
3010 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
3013 // Convert to the backend representation.
3015 Btype*
3016 Float_type::do_get_backend(Gogo* gogo)
3018 return gogo->backend()->float_type(this->bits_);
3021 // The type descriptor for a float type. Float types are always named.
3023 Expression*
3024 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3026 go_assert(name != NULL || saw_errors());
3027 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
3030 // We should not be asked for the reflection string of a basic type.
3032 void
3033 Float_type::do_reflection(Gogo*, std::string*) const
3035 go_assert(saw_errors());
3038 // Mangled name.
3040 void
3041 Float_type::do_mangled_name(Gogo*, std::string* ret) const
3043 char buf[100];
3044 snprintf(buf, sizeof buf, "f%s%de",
3045 this->is_abstract_ ? "a" : "",
3046 this->bits_);
3047 ret->append(buf);
3050 // Make a floating point type.
3052 Named_type*
3053 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
3055 return Float_type::create_float_type(name, bits, runtime_type_kind);
3058 // Make an abstract float type.
3060 Float_type*
3061 Type::make_abstract_float_type()
3063 return Float_type::create_abstract_float_type();
3066 // Look up a float type.
3068 Named_type*
3069 Type::lookup_float_type(const char* name)
3071 return Float_type::lookup_float_type(name);
3074 // Class Complex_type.
3076 Complex_type::Named_complex_types Complex_type::named_complex_types;
3078 // Create a new complex type. Non-abstract complex types always have
3079 // names.
3081 Named_type*
3082 Complex_type::create_complex_type(const char* name, int bits,
3083 int runtime_type_kind)
3085 Complex_type* complex_type = new Complex_type(false, bits,
3086 runtime_type_kind);
3087 std::string sname(name);
3088 Named_object* named_object =
3089 Named_object::make_type(sname, NULL, complex_type,
3090 Linemap::predeclared_location());
3091 Named_type* named_type = named_object->type_value();
3092 std::pair<Named_complex_types::iterator, bool> ins =
3093 Complex_type::named_complex_types.insert(std::make_pair(sname,
3094 named_type));
3095 go_assert(ins.second);
3096 return named_type;
3099 // Look up an existing complex type.
3101 Named_type*
3102 Complex_type::lookup_complex_type(const char* name)
3104 Named_complex_types::const_iterator p =
3105 Complex_type::named_complex_types.find(name);
3106 go_assert(p != Complex_type::named_complex_types.end());
3107 return p->second;
3110 // Create a new abstract complex type.
3112 Complex_type*
3113 Complex_type::create_abstract_complex_type()
3115 static Complex_type* abstract_type;
3116 if (abstract_type == NULL)
3117 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
3118 return abstract_type;
3121 // Whether this type is identical with T.
3123 bool
3124 Complex_type::is_identical(const Complex_type *t) const
3126 if (this->bits_ != t->bits_)
3127 return false;
3128 return this->is_abstract_ == t->is_abstract_;
3131 // Hash code.
3133 unsigned int
3134 Complex_type::do_hash_for_method(Gogo*) const
3136 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
3139 // Convert to the backend representation.
3141 Btype*
3142 Complex_type::do_get_backend(Gogo* gogo)
3144 return gogo->backend()->complex_type(this->bits_);
3147 // The type descriptor for a complex type. Complex types are always
3148 // named.
3150 Expression*
3151 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3153 go_assert(name != NULL || saw_errors());
3154 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
3157 // We should not be asked for the reflection string of a basic type.
3159 void
3160 Complex_type::do_reflection(Gogo*, std::string*) const
3162 go_assert(saw_errors());
3165 // Mangled name.
3167 void
3168 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
3170 char buf[100];
3171 snprintf(buf, sizeof buf, "c%s%de",
3172 this->is_abstract_ ? "a" : "",
3173 this->bits_);
3174 ret->append(buf);
3177 // Make a complex type.
3179 Named_type*
3180 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
3182 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
3185 // Make an abstract complex type.
3187 Complex_type*
3188 Type::make_abstract_complex_type()
3190 return Complex_type::create_abstract_complex_type();
3193 // Look up a complex type.
3195 Named_type*
3196 Type::lookup_complex_type(const char* name)
3198 return Complex_type::lookup_complex_type(name);
3201 // Class String_type.
3203 // Convert String_type to the backend representation. A string is a
3204 // struct with two fields: a pointer to the characters and a length.
3206 Btype*
3207 String_type::do_get_backend(Gogo* gogo)
3209 static Btype* backend_string_type;
3210 if (backend_string_type == NULL)
3212 std::vector<Backend::Btyped_identifier> fields(2);
3214 Type* b = gogo->lookup_global("byte")->type_value();
3215 Type* pb = Type::make_pointer_type(b);
3217 // We aren't going to get back to this field to finish the
3218 // backend representation, so force it to be finished now.
3219 if (!gogo->named_types_are_converted())
3221 Btype* bt = pb->get_backend_placeholder(gogo);
3222 pb->finish_backend(gogo, bt);
3225 fields[0].name = "__data";
3226 fields[0].btype = pb->get_backend(gogo);
3227 fields[0].location = Linemap::predeclared_location();
3229 Type* int_type = Type::lookup_integer_type("int");
3230 fields[1].name = "__length";
3231 fields[1].btype = int_type->get_backend(gogo);
3232 fields[1].location = fields[0].location;
3234 backend_string_type = gogo->backend()->struct_type(fields);
3236 return backend_string_type;
3239 // The type descriptor for the string type.
3241 Expression*
3242 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3244 if (name != NULL)
3245 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
3246 else
3248 Named_object* no = gogo->lookup_global("string");
3249 go_assert(no != NULL);
3250 return Type::type_descriptor(gogo, no->type_value());
3254 // We should not be asked for the reflection string of a basic type.
3256 void
3257 String_type::do_reflection(Gogo*, std::string* ret) const
3259 ret->append("string");
3262 // Generate GC symbol for strings.
3264 void
3265 String_type::do_gc_symbol(Gogo*, Expression_list** vals,
3266 Expression** offset, int)
3268 Location bloc = Linemap::predeclared_location();
3269 Type* uintptr_type = Type::lookup_integer_type("uintptr");
3270 mpz_t opval;
3271 mpz_init_set_ui(opval, GC_STRING);
3272 (*vals)->push_back(Expression::make_integer(&opval, uintptr_type, bloc));
3273 mpz_clear(opval);
3274 (*vals)->push_back(*offset);
3275 this->advance_gc_offset(offset);
3278 // Mangled name of a string type.
3280 void
3281 String_type::do_mangled_name(Gogo*, std::string* ret) const
3283 ret->push_back('z');
3286 // Make a string type.
3288 Type*
3289 Type::make_string_type()
3291 static String_type string_type;
3292 return &string_type;
3295 // The named type "string".
3297 static Named_type* named_string_type;
3299 // Get the named type "string".
3301 Named_type*
3302 Type::lookup_string_type()
3304 return named_string_type;
3307 // Make the named type string.
3309 Named_type*
3310 Type::make_named_string_type()
3312 Type* string_type = Type::make_string_type();
3313 Named_object* named_object =
3314 Named_object::make_type("string", NULL, string_type,
3315 Linemap::predeclared_location());
3316 Named_type* named_type = named_object->type_value();
3317 named_string_type = named_type;
3318 return named_type;
3321 // The sink type. This is the type of the blank identifier _. Any
3322 // type may be assigned to it.
3324 class Sink_type : public Type
3326 public:
3327 Sink_type()
3328 : Type(TYPE_SINK)
3331 protected:
3332 bool
3333 do_compare_is_identity(Gogo*)
3334 { return false; }
3336 Btype*
3337 do_get_backend(Gogo*)
3338 { go_unreachable(); }
3340 Expression*
3341 do_type_descriptor(Gogo*, Named_type*)
3342 { go_unreachable(); }
3344 void
3345 do_reflection(Gogo*, std::string*) const
3346 { go_unreachable(); }
3348 void
3349 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
3350 { go_unreachable(); }
3352 void
3353 do_mangled_name(Gogo*, std::string*) const
3354 { go_unreachable(); }
3357 // Make the sink type.
3359 Type*
3360 Type::make_sink_type()
3362 static Sink_type sink_type;
3363 return &sink_type;
3366 // Class Function_type.
3368 // Traversal.
3371 Function_type::do_traverse(Traverse* traverse)
3373 if (this->receiver_ != NULL
3374 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
3375 return TRAVERSE_EXIT;
3376 if (this->parameters_ != NULL
3377 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
3378 return TRAVERSE_EXIT;
3379 if (this->results_ != NULL
3380 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
3381 return TRAVERSE_EXIT;
3382 return TRAVERSE_CONTINUE;
3385 // Returns whether T is a valid redeclaration of this type. If this
3386 // returns false, and REASON is not NULL, *REASON may be set to a
3387 // brief explanation of why it returned false.
3389 bool
3390 Function_type::is_valid_redeclaration(const Function_type* t,
3391 std::string* reason) const
3393 if (!this->is_identical(t, false, true, reason))
3394 return false;
3396 // A redeclaration of a function is required to use the same names
3397 // for the receiver and parameters.
3398 if (this->receiver() != NULL
3399 && this->receiver()->name() != t->receiver()->name())
3401 if (reason != NULL)
3402 *reason = "receiver name changed";
3403 return false;
3406 const Typed_identifier_list* parms1 = this->parameters();
3407 const Typed_identifier_list* parms2 = t->parameters();
3408 if (parms1 != NULL)
3410 Typed_identifier_list::const_iterator p1 = parms1->begin();
3411 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3412 p2 != parms2->end();
3413 ++p2, ++p1)
3415 if (p1->name() != p2->name())
3417 if (reason != NULL)
3418 *reason = "parameter name changed";
3419 return false;
3422 // This is called at parse time, so we may have unknown
3423 // types.
3424 Type* t1 = p1->type()->forwarded();
3425 Type* t2 = p2->type()->forwarded();
3426 if (t1 != t2
3427 && t1->forward_declaration_type() != NULL
3428 && (t2->forward_declaration_type() == NULL
3429 || (t1->forward_declaration_type()->named_object()
3430 != t2->forward_declaration_type()->named_object())))
3431 return false;
3435 const Typed_identifier_list* results1 = this->results();
3436 const Typed_identifier_list* results2 = t->results();
3437 if (results1 != NULL)
3439 Typed_identifier_list::const_iterator res1 = results1->begin();
3440 for (Typed_identifier_list::const_iterator res2 = results2->begin();
3441 res2 != results2->end();
3442 ++res2, ++res1)
3444 if (res1->name() != res2->name())
3446 if (reason != NULL)
3447 *reason = "result name changed";
3448 return false;
3451 // This is called at parse time, so we may have unknown
3452 // types.
3453 Type* t1 = res1->type()->forwarded();
3454 Type* t2 = res2->type()->forwarded();
3455 if (t1 != t2
3456 && t1->forward_declaration_type() != NULL
3457 && (t2->forward_declaration_type() == NULL
3458 || (t1->forward_declaration_type()->named_object()
3459 != t2->forward_declaration_type()->named_object())))
3460 return false;
3464 return true;
3467 // Check whether T is the same as this type.
3469 bool
3470 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
3471 bool errors_are_identical,
3472 std::string* reason) const
3474 if (!ignore_receiver)
3476 const Typed_identifier* r1 = this->receiver();
3477 const Typed_identifier* r2 = t->receiver();
3478 if ((r1 != NULL) != (r2 != NULL))
3480 if (reason != NULL)
3481 *reason = _("different receiver types");
3482 return false;
3484 if (r1 != NULL)
3486 if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
3487 reason))
3489 if (reason != NULL && !reason->empty())
3490 *reason = "receiver: " + *reason;
3491 return false;
3496 const Typed_identifier_list* parms1 = this->parameters();
3497 const Typed_identifier_list* parms2 = t->parameters();
3498 if ((parms1 != NULL) != (parms2 != NULL))
3500 if (reason != NULL)
3501 *reason = _("different number of parameters");
3502 return false;
3504 if (parms1 != NULL)
3506 Typed_identifier_list::const_iterator p1 = parms1->begin();
3507 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3508 p2 != parms2->end();
3509 ++p2, ++p1)
3511 if (p1 == parms1->end())
3513 if (reason != NULL)
3514 *reason = _("different number of parameters");
3515 return false;
3518 if (!Type::are_identical(p1->type(), p2->type(),
3519 errors_are_identical, NULL))
3521 if (reason != NULL)
3522 *reason = _("different parameter types");
3523 return false;
3526 if (p1 != parms1->end())
3528 if (reason != NULL)
3529 *reason = _("different number of parameters");
3530 return false;
3534 if (this->is_varargs() != t->is_varargs())
3536 if (reason != NULL)
3537 *reason = _("different varargs");
3538 return false;
3541 const Typed_identifier_list* results1 = this->results();
3542 const Typed_identifier_list* results2 = t->results();
3543 if ((results1 != NULL) != (results2 != NULL))
3545 if (reason != NULL)
3546 *reason = _("different number of results");
3547 return false;
3549 if (results1 != NULL)
3551 Typed_identifier_list::const_iterator res1 = results1->begin();
3552 for (Typed_identifier_list::const_iterator res2 = results2->begin();
3553 res2 != results2->end();
3554 ++res2, ++res1)
3556 if (res1 == results1->end())
3558 if (reason != NULL)
3559 *reason = _("different number of results");
3560 return false;
3563 if (!Type::are_identical(res1->type(), res2->type(),
3564 errors_are_identical, NULL))
3566 if (reason != NULL)
3567 *reason = _("different result types");
3568 return false;
3571 if (res1 != results1->end())
3573 if (reason != NULL)
3574 *reason = _("different number of results");
3575 return false;
3579 return true;
3582 // Hash code.
3584 unsigned int
3585 Function_type::do_hash_for_method(Gogo* gogo) const
3587 unsigned int ret = 0;
3588 // We ignore the receiver type for hash codes, because we need to
3589 // get the same hash code for a method in an interface and a method
3590 // declared for a type. The former will not have a receiver.
3591 if (this->parameters_ != NULL)
3593 int shift = 1;
3594 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3595 p != this->parameters_->end();
3596 ++p, ++shift)
3597 ret += p->type()->hash_for_method(gogo) << shift;
3599 if (this->results_ != NULL)
3601 int shift = 2;
3602 for (Typed_identifier_list::const_iterator p = this->results_->begin();
3603 p != this->results_->end();
3604 ++p, ++shift)
3605 ret += p->type()->hash_for_method(gogo) << shift;
3607 if (this->is_varargs_)
3608 ret += 1;
3609 ret <<= 4;
3610 return ret;
3613 // Hash result parameters.
3615 unsigned int
3616 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
3618 unsigned int hash = 0;
3619 for (Typed_identifier_list::const_iterator p = t->begin();
3620 p != t->end();
3621 ++p)
3623 hash <<= 2;
3624 hash = Type::hash_string(p->name(), hash);
3625 hash += p->type()->hash_for_method(NULL);
3627 return hash;
3630 // Compare result parameters so that can map identical result
3631 // parameters to a single struct type.
3633 bool
3634 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
3635 const Typed_identifier_list* b) const
3637 if (a->size() != b->size())
3638 return false;
3639 Typed_identifier_list::const_iterator pa = a->begin();
3640 for (Typed_identifier_list::const_iterator pb = b->begin();
3641 pb != b->end();
3642 ++pa, ++pb)
3644 if (pa->name() != pb->name()
3645 || !Type::are_identical(pa->type(), pb->type(), true, NULL))
3646 return false;
3648 return true;
3651 // Hash from results to a backend struct type.
3653 Function_type::Results_structs Function_type::results_structs;
3655 // Get the backend representation for a function type.
3657 Btype*
3658 Function_type::get_backend_fntype(Gogo* gogo)
3660 if (this->fnbtype_ == NULL)
3662 Backend::Btyped_identifier breceiver;
3663 if (this->receiver_ != NULL)
3665 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
3667 // We always pass the address of the receiver parameter, in
3668 // order to make interface calls work with unknown types.
3669 Type* rtype = this->receiver_->type();
3670 if (rtype->points_to() == NULL)
3671 rtype = Type::make_pointer_type(rtype);
3672 breceiver.btype = rtype->get_backend(gogo);
3673 breceiver.location = this->receiver_->location();
3676 std::vector<Backend::Btyped_identifier> bparameters;
3677 if (this->parameters_ != NULL)
3679 bparameters.resize(this->parameters_->size());
3680 size_t i = 0;
3681 for (Typed_identifier_list::const_iterator p =
3682 this->parameters_->begin(); p != this->parameters_->end();
3683 ++p, ++i)
3685 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
3686 bparameters[i].btype = p->type()->get_backend(gogo);
3687 bparameters[i].location = p->location();
3689 go_assert(i == bparameters.size());
3692 std::vector<Backend::Btyped_identifier> bresults;
3693 Btype* bresult_struct = NULL;
3694 if (this->results_ != NULL)
3696 bresults.resize(this->results_->size());
3697 size_t i = 0;
3698 for (Typed_identifier_list::const_iterator p =
3699 this->results_->begin();
3700 p != this->results_->end();
3701 ++p, ++i)
3703 bresults[i].name = Gogo::unpack_hidden_name(p->name());
3704 bresults[i].btype = p->type()->get_backend(gogo);
3705 bresults[i].location = p->location();
3707 go_assert(i == bresults.size());
3709 if (this->results_->size() > 1)
3711 // Use the same results struct for all functions that
3712 // return the same set of results. This is useful to
3713 // unify calls to interface methods with other calls.
3714 std::pair<Typed_identifier_list*, Btype*> val;
3715 val.first = this->results_;
3716 val.second = NULL;
3717 std::pair<Results_structs::iterator, bool> ins =
3718 Function_type::results_structs.insert(val);
3719 if (ins.second)
3721 // Build a new struct type.
3722 Struct_field_list* sfl = new Struct_field_list;
3723 for (Typed_identifier_list::const_iterator p =
3724 this->results_->begin();
3725 p != this->results_->end();
3726 ++p)
3728 Typed_identifier tid = *p;
3729 if (tid.name().empty())
3730 tid = Typed_identifier("UNNAMED", tid.type(),
3731 tid.location());
3732 sfl->push_back(Struct_field(tid));
3734 Struct_type* st = Type::make_struct_type(sfl,
3735 this->location());
3736 ins.first->second = st->get_backend(gogo);
3738 bresult_struct = ins.first->second;
3742 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
3743 bresults, bresult_struct,
3744 this->location());
3748 return this->fnbtype_;
3751 // Get the backend representation for a Go function type.
3753 Btype*
3754 Function_type::do_get_backend(Gogo* gogo)
3756 // When we do anything with a function value other than call it, it
3757 // is represented as a pointer to a struct whose first field is the
3758 // actual function. So that is what we return as the type of a Go
3759 // function.
3761 Location loc = this->location();
3762 Btype* struct_type =
3763 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
3764 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
3766 std::vector<Backend::Btyped_identifier> fields(1);
3767 fields[0].name = "code";
3768 fields[0].btype = this->get_backend_fntype(gogo);
3769 fields[0].location = loc;
3770 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
3771 return gogo->backend()->error_type();
3772 return ptr_struct_type;
3775 // The type of a function type descriptor.
3777 Type*
3778 Function_type::make_function_type_descriptor_type()
3780 static Type* ret;
3781 if (ret == NULL)
3783 Type* tdt = Type::make_type_descriptor_type();
3784 Type* ptdt = Type::make_type_descriptor_ptr_type();
3786 Type* bool_type = Type::lookup_bool_type();
3788 Type* slice_type = Type::make_array_type(ptdt, NULL);
3790 Struct_type* s = Type::make_builtin_struct_type(4,
3791 "", tdt,
3792 "dotdotdot", bool_type,
3793 "in", slice_type,
3794 "out", slice_type);
3796 ret = Type::make_builtin_named_type("FuncType", s);
3799 return ret;
3802 // The type descriptor for a function type.
3804 Expression*
3805 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3807 Location bloc = Linemap::predeclared_location();
3809 Type* ftdt = Function_type::make_function_type_descriptor_type();
3811 const Struct_field_list* fields = ftdt->struct_type()->fields();
3813 Expression_list* vals = new Expression_list();
3814 vals->reserve(4);
3816 Struct_field_list::const_iterator p = fields->begin();
3817 go_assert(p->is_field_name("commonType"));
3818 vals->push_back(this->type_descriptor_constructor(gogo,
3819 RUNTIME_TYPE_KIND_FUNC,
3820 name, NULL, true));
3822 ++p;
3823 go_assert(p->is_field_name("dotdotdot"));
3824 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
3826 ++p;
3827 go_assert(p->is_field_name("in"));
3828 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
3829 this->parameters()));
3831 ++p;
3832 go_assert(p->is_field_name("out"));
3833 vals->push_back(this->type_descriptor_params(p->type(), NULL,
3834 this->results()));
3836 ++p;
3837 go_assert(p == fields->end());
3839 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
3842 // Return a composite literal for the parameters or results of a type
3843 // descriptor.
3845 Expression*
3846 Function_type::type_descriptor_params(Type* params_type,
3847 const Typed_identifier* receiver,
3848 const Typed_identifier_list* params)
3850 Location bloc = Linemap::predeclared_location();
3852 if (receiver == NULL && params == NULL)
3853 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
3855 Expression_list* vals = new Expression_list();
3856 vals->reserve((params == NULL ? 0 : params->size())
3857 + (receiver != NULL ? 1 : 0));
3859 if (receiver != NULL)
3860 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
3862 if (params != NULL)
3864 for (Typed_identifier_list::const_iterator p = params->begin();
3865 p != params->end();
3866 ++p)
3867 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
3870 return Expression::make_slice_composite_literal(params_type, vals, bloc);
3873 // The reflection string.
3875 void
3876 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
3878 // FIXME: Turn this off until we straighten out the type of the
3879 // struct field used in a go statement which calls a method.
3880 // go_assert(this->receiver_ == NULL);
3882 ret->append("func");
3884 if (this->receiver_ != NULL)
3886 ret->push_back('(');
3887 this->append_reflection(this->receiver_->type(), gogo, ret);
3888 ret->push_back(')');
3891 ret->push_back('(');
3892 const Typed_identifier_list* params = this->parameters();
3893 if (params != NULL)
3895 bool is_varargs = this->is_varargs_;
3896 for (Typed_identifier_list::const_iterator p = params->begin();
3897 p != params->end();
3898 ++p)
3900 if (p != params->begin())
3901 ret->append(", ");
3902 if (!is_varargs || p + 1 != params->end())
3903 this->append_reflection(p->type(), gogo, ret);
3904 else
3906 ret->append("...");
3907 this->append_reflection(p->type()->array_type()->element_type(),
3908 gogo, ret);
3912 ret->push_back(')');
3914 const Typed_identifier_list* results = this->results();
3915 if (results != NULL && !results->empty())
3917 if (results->size() == 1)
3918 ret->push_back(' ');
3919 else
3920 ret->append(" (");
3921 for (Typed_identifier_list::const_iterator p = results->begin();
3922 p != results->end();
3923 ++p)
3925 if (p != results->begin())
3926 ret->append(", ");
3927 this->append_reflection(p->type(), gogo, ret);
3929 if (results->size() > 1)
3930 ret->push_back(')');
3934 // Generate GC symbol for a function type.
3936 void
3937 Function_type::do_gc_symbol(Gogo*, Expression_list** vals,
3938 Expression** offset, int)
3940 Location bloc = Linemap::predeclared_location();
3941 Type* uintptr_type = Type::lookup_integer_type("uintptr");
3943 // We use GC_APTR here because we do not currently have a way to describe the
3944 // the type of the possible function closure. FIXME.
3945 mpz_t opval;
3946 mpz_init_set_ui(opval, GC_APTR);
3947 (*vals)->push_back(Expression::make_integer(&opval, uintptr_type, bloc));
3948 mpz_clear(opval);
3949 (*vals)->push_back(*offset);
3950 this->advance_gc_offset(offset);
3953 // Mangled name.
3955 void
3956 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3958 ret->push_back('F');
3960 if (this->receiver_ != NULL)
3962 ret->push_back('m');
3963 this->append_mangled_name(this->receiver_->type(), gogo, ret);
3966 const Typed_identifier_list* params = this->parameters();
3967 if (params != NULL)
3969 ret->push_back('p');
3970 for (Typed_identifier_list::const_iterator p = params->begin();
3971 p != params->end();
3972 ++p)
3973 this->append_mangled_name(p->type(), gogo, ret);
3974 if (this->is_varargs_)
3975 ret->push_back('V');
3976 ret->push_back('e');
3979 const Typed_identifier_list* results = this->results();
3980 if (results != NULL)
3982 ret->push_back('r');
3983 for (Typed_identifier_list::const_iterator p = results->begin();
3984 p != results->end();
3985 ++p)
3986 this->append_mangled_name(p->type(), gogo, ret);
3987 ret->push_back('e');
3990 ret->push_back('e');
3993 // Export a function type.
3995 void
3996 Function_type::do_export(Export* exp) const
3998 // We don't write out the receiver. The only function types which
3999 // should have a receiver are the ones associated with explicitly
4000 // defined methods. For those the receiver type is written out by
4001 // Function::export_func.
4003 exp->write_c_string("(");
4004 bool first = true;
4005 if (this->parameters_ != NULL)
4007 bool is_varargs = this->is_varargs_;
4008 for (Typed_identifier_list::const_iterator p =
4009 this->parameters_->begin();
4010 p != this->parameters_->end();
4011 ++p)
4013 if (first)
4014 first = false;
4015 else
4016 exp->write_c_string(", ");
4017 exp->write_name(p->name());
4018 exp->write_c_string(" ");
4019 if (!is_varargs || p + 1 != this->parameters_->end())
4020 exp->write_type(p->type());
4021 else
4023 exp->write_c_string("...");
4024 exp->write_type(p->type()->array_type()->element_type());
4028 exp->write_c_string(")");
4030 const Typed_identifier_list* results = this->results_;
4031 if (results != NULL)
4033 exp->write_c_string(" ");
4034 if (results->size() == 1 && results->begin()->name().empty())
4035 exp->write_type(results->begin()->type());
4036 else
4038 first = true;
4039 exp->write_c_string("(");
4040 for (Typed_identifier_list::const_iterator p = results->begin();
4041 p != results->end();
4042 ++p)
4044 if (first)
4045 first = false;
4046 else
4047 exp->write_c_string(", ");
4048 exp->write_name(p->name());
4049 exp->write_c_string(" ");
4050 exp->write_type(p->type());
4052 exp->write_c_string(")");
4057 // Import a function type.
4059 Function_type*
4060 Function_type::do_import(Import* imp)
4062 imp->require_c_string("(");
4063 Typed_identifier_list* parameters;
4064 bool is_varargs = false;
4065 if (imp->peek_char() == ')')
4066 parameters = NULL;
4067 else
4069 parameters = new Typed_identifier_list();
4070 while (true)
4072 std::string name = imp->read_name();
4073 imp->require_c_string(" ");
4075 if (imp->match_c_string("..."))
4077 imp->advance(3);
4078 is_varargs = true;
4081 Type* ptype = imp->read_type();
4082 if (is_varargs)
4083 ptype = Type::make_array_type(ptype, NULL);
4084 parameters->push_back(Typed_identifier(name, ptype,
4085 imp->location()));
4086 if (imp->peek_char() != ',')
4087 break;
4088 go_assert(!is_varargs);
4089 imp->require_c_string(", ");
4092 imp->require_c_string(")");
4094 Typed_identifier_list* results;
4095 if (imp->peek_char() != ' ')
4096 results = NULL;
4097 else
4099 imp->advance(1);
4100 results = new Typed_identifier_list;
4101 if (imp->peek_char() != '(')
4103 Type* rtype = imp->read_type();
4104 results->push_back(Typed_identifier("", rtype, imp->location()));
4106 else
4108 imp->advance(1);
4109 while (true)
4111 std::string name = imp->read_name();
4112 imp->require_c_string(" ");
4113 Type* rtype = imp->read_type();
4114 results->push_back(Typed_identifier(name, rtype,
4115 imp->location()));
4116 if (imp->peek_char() != ',')
4117 break;
4118 imp->require_c_string(", ");
4120 imp->require_c_string(")");
4124 Function_type* ret = Type::make_function_type(NULL, parameters, results,
4125 imp->location());
4126 if (is_varargs)
4127 ret->set_is_varargs();
4128 return ret;
4131 // Make a copy of a function type without a receiver.
4133 Function_type*
4134 Function_type::copy_without_receiver() const
4136 go_assert(this->is_method());
4137 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
4138 this->results_,
4139 this->location_);
4140 if (this->is_varargs())
4141 ret->set_is_varargs();
4142 if (this->is_builtin())
4143 ret->set_is_builtin();
4144 return ret;
4147 // Make a copy of a function type with a receiver.
4149 Function_type*
4150 Function_type::copy_with_receiver(Type* receiver_type) const
4152 go_assert(!this->is_method());
4153 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
4154 this->location_);
4155 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
4156 this->results_,
4157 this->location_);
4158 if (this->is_varargs_)
4159 ret->set_is_varargs();
4160 return ret;
4163 // Make a copy of a function type with the receiver as the first
4164 // parameter.
4166 Function_type*
4167 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
4169 go_assert(this->is_method());
4170 Typed_identifier_list* new_params = new Typed_identifier_list();
4171 Type* rtype = this->receiver_->type();
4172 if (want_pointer_receiver)
4173 rtype = Type::make_pointer_type(rtype);
4174 Typed_identifier receiver(this->receiver_->name(), rtype,
4175 this->receiver_->location());
4176 new_params->push_back(receiver);
4177 const Typed_identifier_list* orig_params = this->parameters_;
4178 if (orig_params != NULL && !orig_params->empty())
4180 for (Typed_identifier_list::const_iterator p = orig_params->begin();
4181 p != orig_params->end();
4182 ++p)
4183 new_params->push_back(*p);
4185 return Type::make_function_type(NULL, new_params, this->results_,
4186 this->location_);
4189 // Make a copy of a function type ignoring any receiver and adding a
4190 // closure parameter.
4192 Function_type*
4193 Function_type::copy_with_names() const
4195 Typed_identifier_list* new_params = new Typed_identifier_list();
4196 const Typed_identifier_list* orig_params = this->parameters_;
4197 if (orig_params != NULL && !orig_params->empty())
4199 static int count;
4200 char buf[50];
4201 for (Typed_identifier_list::const_iterator p = orig_params->begin();
4202 p != orig_params->end();
4203 ++p)
4205 snprintf(buf, sizeof buf, "pt.%u", count);
4206 ++count;
4207 new_params->push_back(Typed_identifier(buf, p->type(),
4208 p->location()));
4212 const Typed_identifier_list* orig_results = this->results_;
4213 Typed_identifier_list* new_results;
4214 if (orig_results == NULL || orig_results->empty())
4215 new_results = NULL;
4216 else
4218 new_results = new Typed_identifier_list();
4219 for (Typed_identifier_list::const_iterator p = orig_results->begin();
4220 p != orig_results->end();
4221 ++p)
4222 new_results->push_back(Typed_identifier("", p->type(),
4223 p->location()));
4226 return Type::make_function_type(NULL, new_params, new_results,
4227 this->location());
4230 // Make a function type.
4232 Function_type*
4233 Type::make_function_type(Typed_identifier* receiver,
4234 Typed_identifier_list* parameters,
4235 Typed_identifier_list* results,
4236 Location location)
4238 return new Function_type(receiver, parameters, results, location);
4241 // Make a backend function type.
4243 Backend_function_type*
4244 Type::make_backend_function_type(Typed_identifier* receiver,
4245 Typed_identifier_list* parameters,
4246 Typed_identifier_list* results,
4247 Location location)
4249 return new Backend_function_type(receiver, parameters, results, location);
4252 // Class Pointer_type.
4254 // Traversal.
4257 Pointer_type::do_traverse(Traverse* traverse)
4259 return Type::traverse(this->to_type_, traverse);
4262 // Hash code.
4264 unsigned int
4265 Pointer_type::do_hash_for_method(Gogo* gogo) const
4267 return this->to_type_->hash_for_method(gogo) << 4;
4270 // Get the backend representation for a pointer type.
4272 Btype*
4273 Pointer_type::do_get_backend(Gogo* gogo)
4275 Btype* to_btype = this->to_type_->get_backend(gogo);
4276 return gogo->backend()->pointer_type(to_btype);
4279 // The type of a pointer type descriptor.
4281 Type*
4282 Pointer_type::make_pointer_type_descriptor_type()
4284 static Type* ret;
4285 if (ret == NULL)
4287 Type* tdt = Type::make_type_descriptor_type();
4288 Type* ptdt = Type::make_type_descriptor_ptr_type();
4290 Struct_type* s = Type::make_builtin_struct_type(2,
4291 "", tdt,
4292 "elem", ptdt);
4294 ret = Type::make_builtin_named_type("PtrType", s);
4297 return ret;
4300 // The type descriptor for a pointer type.
4302 Expression*
4303 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4305 if (this->is_unsafe_pointer_type())
4307 go_assert(name != NULL);
4308 return this->plain_type_descriptor(gogo,
4309 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
4310 name);
4312 else
4314 Location bloc = Linemap::predeclared_location();
4316 const Methods* methods;
4317 Type* deref = this->points_to();
4318 if (deref->named_type() != NULL)
4319 methods = deref->named_type()->methods();
4320 else if (deref->struct_type() != NULL)
4321 methods = deref->struct_type()->methods();
4322 else
4323 methods = NULL;
4325 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
4327 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
4329 Expression_list* vals = new Expression_list();
4330 vals->reserve(2);
4332 Struct_field_list::const_iterator p = fields->begin();
4333 go_assert(p->is_field_name("commonType"));
4334 vals->push_back(this->type_descriptor_constructor(gogo,
4335 RUNTIME_TYPE_KIND_PTR,
4336 name, methods, false));
4338 ++p;
4339 go_assert(p->is_field_name("elem"));
4340 vals->push_back(Expression::make_type_descriptor(deref, bloc));
4342 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
4346 // Reflection string.
4348 void
4349 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
4351 ret->push_back('*');
4352 this->append_reflection(this->to_type_, gogo, ret);
4355 // Generate GC symbol for pointer types.
4357 void
4358 Pointer_type::do_gc_symbol(Gogo*, Expression_list** vals,
4359 Expression** offset, int)
4361 Location loc = Linemap::predeclared_location();
4362 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4364 mpz_t opval;
4365 mpz_init_set_ui(opval, this->to_type_->has_pointer() ? GC_PTR : GC_APTR);
4366 (*vals)->push_back(Expression::make_integer(&opval, uintptr_type, loc));
4367 mpz_clear(opval);
4368 (*vals)->push_back(*offset);
4370 if (this->to_type_->has_pointer())
4371 (*vals)->push_back(Expression::make_gc_symbol(this->to_type_));
4372 this->advance_gc_offset(offset);
4375 // Mangled name.
4377 void
4378 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4380 ret->push_back('p');
4381 this->append_mangled_name(this->to_type_, gogo, ret);
4384 // Export.
4386 void
4387 Pointer_type::do_export(Export* exp) const
4389 exp->write_c_string("*");
4390 if (this->is_unsafe_pointer_type())
4391 exp->write_c_string("any");
4392 else
4393 exp->write_type(this->to_type_);
4396 // Import.
4398 Pointer_type*
4399 Pointer_type::do_import(Import* imp)
4401 imp->require_c_string("*");
4402 if (imp->match_c_string("any"))
4404 imp->advance(3);
4405 return Type::make_pointer_type(Type::make_void_type());
4407 Type* to = imp->read_type();
4408 return Type::make_pointer_type(to);
4411 // Make a pointer type.
4413 Pointer_type*
4414 Type::make_pointer_type(Type* to_type)
4416 typedef Unordered_map(Type*, Pointer_type*) Hashtable;
4417 static Hashtable pointer_types;
4418 Hashtable::const_iterator p = pointer_types.find(to_type);
4419 if (p != pointer_types.end())
4420 return p->second;
4421 Pointer_type* ret = new Pointer_type(to_type);
4422 pointer_types[to_type] = ret;
4423 return ret;
4426 // The nil type. We use a special type for nil because it is not the
4427 // same as any other type. In C term nil has type void*, but there is
4428 // no such type in Go.
4430 class Nil_type : public Type
4432 public:
4433 Nil_type()
4434 : Type(TYPE_NIL)
4437 protected:
4438 bool
4439 do_compare_is_identity(Gogo*)
4440 { return false; }
4442 Btype*
4443 do_get_backend(Gogo* gogo)
4444 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
4446 Expression*
4447 do_type_descriptor(Gogo*, Named_type*)
4448 { go_unreachable(); }
4450 void
4451 do_reflection(Gogo*, std::string*) const
4452 { go_unreachable(); }
4454 void
4455 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
4456 { go_unreachable(); }
4458 void
4459 do_mangled_name(Gogo*, std::string* ret) const
4460 { ret->push_back('n'); }
4463 // Make the nil type.
4465 Type*
4466 Type::make_nil_type()
4468 static Nil_type singleton_nil_type;
4469 return &singleton_nil_type;
4472 // The type of a function call which returns multiple values. This is
4473 // really a struct, but we don't want to confuse a function call which
4474 // returns a struct with a function call which returns multiple
4475 // values.
4477 class Call_multiple_result_type : public Type
4479 public:
4480 Call_multiple_result_type(Call_expression* call)
4481 : Type(TYPE_CALL_MULTIPLE_RESULT),
4482 call_(call)
4485 protected:
4486 bool
4487 do_has_pointer() const
4489 go_assert(saw_errors());
4490 return false;
4493 bool
4494 do_compare_is_identity(Gogo*)
4495 { return false; }
4497 Btype*
4498 do_get_backend(Gogo* gogo)
4500 go_assert(saw_errors());
4501 return gogo->backend()->error_type();
4504 Expression*
4505 do_type_descriptor(Gogo*, Named_type*)
4507 go_assert(saw_errors());
4508 return Expression::make_error(Linemap::unknown_location());
4511 void
4512 do_reflection(Gogo*, std::string*) const
4513 { go_assert(saw_errors()); }
4515 void
4516 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
4517 { go_unreachable(); }
4519 void
4520 do_mangled_name(Gogo*, std::string*) const
4521 { go_assert(saw_errors()); }
4523 private:
4524 // The expression being called.
4525 Call_expression* call_;
4528 // Make a call result type.
4530 Type*
4531 Type::make_call_multiple_result_type(Call_expression* call)
4533 return new Call_multiple_result_type(call);
4536 // Class Struct_field.
4538 // Get the name of a field.
4540 const std::string&
4541 Struct_field::field_name() const
4543 const std::string& name(this->typed_identifier_.name());
4544 if (!name.empty())
4545 return name;
4546 else
4548 // This is called during parsing, before anything is lowered, so
4549 // we have to be pretty careful to avoid dereferencing an
4550 // unknown type name.
4551 Type* t = this->typed_identifier_.type();
4552 Type* dt = t;
4553 if (t->classification() == Type::TYPE_POINTER)
4555 // Very ugly.
4556 Pointer_type* ptype = static_cast<Pointer_type*>(t);
4557 dt = ptype->points_to();
4559 if (dt->forward_declaration_type() != NULL)
4560 return dt->forward_declaration_type()->name();
4561 else if (dt->named_type() != NULL)
4562 return dt->named_type()->name();
4563 else if (t->is_error_type() || dt->is_error_type())
4565 static const std::string error_string = "*error*";
4566 return error_string;
4568 else
4570 // Avoid crashing in the erroneous case where T is named but
4571 // DT is not.
4572 go_assert(t != dt);
4573 if (t->forward_declaration_type() != NULL)
4574 return t->forward_declaration_type()->name();
4575 else if (t->named_type() != NULL)
4576 return t->named_type()->name();
4577 else
4578 go_unreachable();
4583 // Return whether this field is named NAME.
4585 bool
4586 Struct_field::is_field_name(const std::string& name) const
4588 const std::string& me(this->typed_identifier_.name());
4589 if (!me.empty())
4590 return me == name;
4591 else
4593 Type* t = this->typed_identifier_.type();
4594 if (t->points_to() != NULL)
4595 t = t->points_to();
4596 Named_type* nt = t->named_type();
4597 if (nt != NULL && nt->name() == name)
4598 return true;
4600 // This is a horrible hack caused by the fact that we don't pack
4601 // the names of builtin types. FIXME.
4602 if (!this->is_imported_
4603 && nt != NULL
4604 && nt->is_builtin()
4605 && nt->name() == Gogo::unpack_hidden_name(name))
4606 return true;
4608 return false;
4612 // Return whether this field is an unexported field named NAME.
4614 bool
4615 Struct_field::is_unexported_field_name(Gogo* gogo,
4616 const std::string& name) const
4618 const std::string& field_name(this->field_name());
4619 if (Gogo::is_hidden_name(field_name)
4620 && name == Gogo::unpack_hidden_name(field_name)
4621 && gogo->pack_hidden_name(name, false) != field_name)
4622 return true;
4624 // Check for the name of a builtin type. This is like the test in
4625 // is_field_name, only there we return false if this->is_imported_,
4626 // and here we return true.
4627 if (this->is_imported_ && this->is_anonymous())
4629 Type* t = this->typed_identifier_.type();
4630 if (t->points_to() != NULL)
4631 t = t->points_to();
4632 Named_type* nt = t->named_type();
4633 if (nt != NULL
4634 && nt->is_builtin()
4635 && nt->name() == Gogo::unpack_hidden_name(name))
4636 return true;
4639 return false;
4642 // Return whether this field is an embedded built-in type.
4644 bool
4645 Struct_field::is_embedded_builtin(Gogo* gogo) const
4647 const std::string& name(this->field_name());
4648 // We know that a field is an embedded type if it is anonymous.
4649 // We can decide if it is a built-in type by checking to see if it is
4650 // registered globally under the field's name.
4651 // This allows us to distinguish between embedded built-in types and
4652 // embedded types that are aliases to built-in types.
4653 return (this->is_anonymous()
4654 && !Gogo::is_hidden_name(name)
4655 && gogo->lookup_global(name.c_str()) != NULL);
4658 // Class Struct_type.
4660 // A hash table used to find identical unnamed structs so that they
4661 // share method tables.
4663 Struct_type::Identical_structs Struct_type::identical_structs;
4665 // A hash table used to merge method sets for identical unnamed
4666 // structs.
4668 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
4670 // Traversal.
4673 Struct_type::do_traverse(Traverse* traverse)
4675 Struct_field_list* fields = this->fields_;
4676 if (fields != NULL)
4678 for (Struct_field_list::iterator p = fields->begin();
4679 p != fields->end();
4680 ++p)
4682 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
4683 return TRAVERSE_EXIT;
4686 return TRAVERSE_CONTINUE;
4689 // Verify that the struct type is complete and valid.
4691 bool
4692 Struct_type::do_verify()
4694 Struct_field_list* fields = this->fields_;
4695 if (fields == NULL)
4696 return true;
4697 for (Struct_field_list::iterator p = fields->begin();
4698 p != fields->end();
4699 ++p)
4701 Type* t = p->type();
4702 if (p->is_anonymous())
4704 if (t->named_type() != NULL && t->points_to() != NULL)
4706 error_at(p->location(), "embedded type may not be a pointer");
4707 p->set_type(Type::make_error_type());
4709 else if (t->points_to() != NULL
4710 && t->points_to()->interface_type() != NULL)
4712 error_at(p->location(),
4713 "embedded type may not be pointer to interface");
4714 p->set_type(Type::make_error_type());
4718 return true;
4721 // Whether this contains a pointer.
4723 bool
4724 Struct_type::do_has_pointer() const
4726 const Struct_field_list* fields = this->fields();
4727 if (fields == NULL)
4728 return false;
4729 for (Struct_field_list::const_iterator p = fields->begin();
4730 p != fields->end();
4731 ++p)
4733 if (p->type()->has_pointer())
4734 return true;
4736 return false;
4739 // Whether this type is identical to T.
4741 bool
4742 Struct_type::is_identical(const Struct_type* t,
4743 bool errors_are_identical) const
4745 const Struct_field_list* fields1 = this->fields();
4746 const Struct_field_list* fields2 = t->fields();
4747 if (fields1 == NULL || fields2 == NULL)
4748 return fields1 == fields2;
4749 Struct_field_list::const_iterator pf2 = fields2->begin();
4750 for (Struct_field_list::const_iterator pf1 = fields1->begin();
4751 pf1 != fields1->end();
4752 ++pf1, ++pf2)
4754 if (pf2 == fields2->end())
4755 return false;
4756 if (pf1->field_name() != pf2->field_name())
4757 return false;
4758 if (pf1->is_anonymous() != pf2->is_anonymous()
4759 || !Type::are_identical(pf1->type(), pf2->type(),
4760 errors_are_identical, NULL))
4761 return false;
4762 if (!pf1->has_tag())
4764 if (pf2->has_tag())
4765 return false;
4767 else
4769 if (!pf2->has_tag())
4770 return false;
4771 if (pf1->tag() != pf2->tag())
4772 return false;
4775 if (pf2 != fields2->end())
4776 return false;
4777 return true;
4780 // Whether comparisons of this struct type are simple identity
4781 // comparisons.
4783 bool
4784 Struct_type::do_compare_is_identity(Gogo* gogo)
4786 const Struct_field_list* fields = this->fields_;
4787 if (fields == NULL)
4788 return true;
4789 unsigned long offset = 0;
4790 for (Struct_field_list::const_iterator pf = fields->begin();
4791 pf != fields->end();
4792 ++pf)
4794 if (Gogo::is_sink_name(pf->field_name()))
4795 return false;
4797 if (!pf->type()->compare_is_identity(gogo))
4798 return false;
4800 unsigned long field_align;
4801 if (!pf->type()->backend_type_align(gogo, &field_align))
4802 return false;
4803 if ((offset & (field_align - 1)) != 0)
4805 // This struct has padding. We don't guarantee that that
4806 // padding is zero-initialized for a stack variable, so we
4807 // can't use memcmp to compare struct values.
4808 return false;
4811 unsigned long field_size;
4812 if (!pf->type()->backend_type_size(gogo, &field_size))
4813 return false;
4814 offset += field_size;
4817 unsigned long struct_size;
4818 if (!this->backend_type_size(gogo, &struct_size))
4819 return false;
4820 if (offset != struct_size)
4822 // Trailing padding may not be zero when on the stack.
4823 return false;
4826 return true;
4829 // Build identity and hash functions for this struct.
4831 // Hash code.
4833 unsigned int
4834 Struct_type::do_hash_for_method(Gogo* gogo) const
4836 unsigned int ret = 0;
4837 if (this->fields() != NULL)
4839 for (Struct_field_list::const_iterator pf = this->fields()->begin();
4840 pf != this->fields()->end();
4841 ++pf)
4842 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
4844 return ret <<= 2;
4847 // Find the local field NAME.
4849 const Struct_field*
4850 Struct_type::find_local_field(const std::string& name,
4851 unsigned int *pindex) const
4853 const Struct_field_list* fields = this->fields_;
4854 if (fields == NULL)
4855 return NULL;
4856 unsigned int i = 0;
4857 for (Struct_field_list::const_iterator pf = fields->begin();
4858 pf != fields->end();
4859 ++pf, ++i)
4861 if (pf->is_field_name(name))
4863 if (pindex != NULL)
4864 *pindex = i;
4865 return &*pf;
4868 return NULL;
4871 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
4873 Field_reference_expression*
4874 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
4875 Location location) const
4877 unsigned int depth;
4878 return this->field_reference_depth(struct_expr, name, location, NULL,
4879 &depth);
4882 // Return an expression for a field, along with the depth at which it
4883 // was found.
4885 Field_reference_expression*
4886 Struct_type::field_reference_depth(Expression* struct_expr,
4887 const std::string& name,
4888 Location location,
4889 Saw_named_type* saw,
4890 unsigned int* depth) const
4892 const Struct_field_list* fields = this->fields_;
4893 if (fields == NULL)
4894 return NULL;
4896 // Look for a field with this name.
4897 unsigned int i = 0;
4898 for (Struct_field_list::const_iterator pf = fields->begin();
4899 pf != fields->end();
4900 ++pf, ++i)
4902 if (pf->is_field_name(name))
4904 *depth = 0;
4905 return Expression::make_field_reference(struct_expr, i, location);
4909 // Look for an anonymous field which contains a field with this
4910 // name.
4911 unsigned int found_depth = 0;
4912 Field_reference_expression* ret = NULL;
4913 i = 0;
4914 for (Struct_field_list::const_iterator pf = fields->begin();
4915 pf != fields->end();
4916 ++pf, ++i)
4918 if (!pf->is_anonymous())
4919 continue;
4921 Struct_type* st = pf->type()->deref()->struct_type();
4922 if (st == NULL)
4923 continue;
4925 Saw_named_type* hold_saw = saw;
4926 Saw_named_type saw_here;
4927 Named_type* nt = pf->type()->named_type();
4928 if (nt == NULL)
4929 nt = pf->type()->deref()->named_type();
4930 if (nt != NULL)
4932 Saw_named_type* q;
4933 for (q = saw; q != NULL; q = q->next)
4935 if (q->nt == nt)
4937 // If this is an error, it will be reported
4938 // elsewhere.
4939 break;
4942 if (q != NULL)
4943 continue;
4944 saw_here.next = saw;
4945 saw_here.nt = nt;
4946 saw = &saw_here;
4949 // Look for a reference using a NULL struct expression. If we
4950 // find one, fill in the struct expression with a reference to
4951 // this field.
4952 unsigned int subdepth;
4953 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
4954 location,
4955 saw,
4956 &subdepth);
4958 saw = hold_saw;
4960 if (sub == NULL)
4961 continue;
4963 if (ret == NULL || subdepth < found_depth)
4965 if (ret != NULL)
4966 delete ret;
4967 ret = sub;
4968 found_depth = subdepth;
4969 Expression* here = Expression::make_field_reference(struct_expr, i,
4970 location);
4971 if (pf->type()->points_to() != NULL)
4972 here = Expression::make_unary(OPERATOR_MULT, here, location);
4973 while (sub->expr() != NULL)
4975 sub = sub->expr()->deref()->field_reference_expression();
4976 go_assert(sub != NULL);
4978 sub->set_struct_expression(here);
4979 sub->set_implicit(true);
4981 else if (subdepth > found_depth)
4982 delete sub;
4983 else
4985 // We do not handle ambiguity here--it should be handled by
4986 // Type::bind_field_or_method.
4987 delete sub;
4988 found_depth = 0;
4989 ret = NULL;
4993 if (ret != NULL)
4994 *depth = found_depth + 1;
4996 return ret;
4999 // Return the total number of fields, including embedded fields.
5001 unsigned int
5002 Struct_type::total_field_count() const
5004 if (this->fields_ == NULL)
5005 return 0;
5006 unsigned int ret = 0;
5007 for (Struct_field_list::const_iterator pf = this->fields_->begin();
5008 pf != this->fields_->end();
5009 ++pf)
5011 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
5012 ++ret;
5013 else
5014 ret += pf->type()->struct_type()->total_field_count();
5016 return ret;
5019 // Return whether NAME is an unexported field, for better error reporting.
5021 bool
5022 Struct_type::is_unexported_local_field(Gogo* gogo,
5023 const std::string& name) const
5025 const Struct_field_list* fields = this->fields_;
5026 if (fields != NULL)
5028 for (Struct_field_list::const_iterator pf = fields->begin();
5029 pf != fields->end();
5030 ++pf)
5031 if (pf->is_unexported_field_name(gogo, name))
5032 return true;
5034 return false;
5037 // Finalize the methods of an unnamed struct.
5039 void
5040 Struct_type::finalize_methods(Gogo* gogo)
5042 if (this->all_methods_ != NULL)
5043 return;
5045 // It is possible to have multiple identical structs that have
5046 // methods. We want them to share method tables. Otherwise we will
5047 // emit identical methods more than once, which is bad since they
5048 // will even have the same names.
5049 std::pair<Identical_structs::iterator, bool> ins =
5050 Struct_type::identical_structs.insert(std::make_pair(this, this));
5051 if (!ins.second)
5053 // An identical struct was already entered into the hash table.
5054 // Note that finalize_methods is, fortunately, not recursive.
5055 this->all_methods_ = ins.first->second->all_methods_;
5056 return;
5059 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
5062 // Return the method NAME, or NULL if there isn't one or if it is
5063 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
5064 // ambiguous.
5066 Method*
5067 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
5069 return Type::method_function(this->all_methods_, name, is_ambiguous);
5072 // Return a pointer to the interface method table for this type for
5073 // the interface INTERFACE. IS_POINTER is true if this is for a
5074 // pointer to THIS.
5076 Expression*
5077 Struct_type::interface_method_table(Interface_type* interface,
5078 bool is_pointer)
5080 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
5081 val(this, NULL);
5082 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
5083 Struct_type::struct_method_tables.insert(val);
5085 Struct_method_table_pair* smtp;
5086 if (!ins.second)
5087 smtp = ins.first->second;
5088 else
5090 smtp = new Struct_method_table_pair();
5091 smtp->first = NULL;
5092 smtp->second = NULL;
5093 ins.first->second = smtp;
5096 return Type::interface_method_table(this, interface, is_pointer,
5097 &smtp->first, &smtp->second);
5100 // Convert struct fields to the backend representation. This is not
5101 // declared in types.h so that types.h doesn't have to #include
5102 // backend.h.
5104 static void
5105 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
5106 bool use_placeholder,
5107 std::vector<Backend::Btyped_identifier>* bfields)
5109 bfields->resize(fields->size());
5110 size_t i = 0;
5111 for (Struct_field_list::const_iterator p = fields->begin();
5112 p != fields->end();
5113 ++p, ++i)
5115 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
5116 (*bfields)[i].btype = (use_placeholder
5117 ? p->type()->get_backend_placeholder(gogo)
5118 : p->type()->get_backend(gogo));
5119 (*bfields)[i].location = p->location();
5121 go_assert(i == fields->size());
5124 // Get the backend representation for a struct type.
5126 Btype*
5127 Struct_type::do_get_backend(Gogo* gogo)
5129 std::vector<Backend::Btyped_identifier> bfields;
5130 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
5131 return gogo->backend()->struct_type(bfields);
5134 // Finish the backend representation of the fields of a struct.
5136 void
5137 Struct_type::finish_backend_fields(Gogo* gogo)
5139 const Struct_field_list* fields = this->fields_;
5140 if (fields != NULL)
5142 for (Struct_field_list::const_iterator p = fields->begin();
5143 p != fields->end();
5144 ++p)
5145 p->type()->get_backend(gogo);
5149 // The type of a struct type descriptor.
5151 Type*
5152 Struct_type::make_struct_type_descriptor_type()
5154 static Type* ret;
5155 if (ret == NULL)
5157 Type* tdt = Type::make_type_descriptor_type();
5158 Type* ptdt = Type::make_type_descriptor_ptr_type();
5160 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5161 Type* string_type = Type::lookup_string_type();
5162 Type* pointer_string_type = Type::make_pointer_type(string_type);
5164 Struct_type* sf =
5165 Type::make_builtin_struct_type(5,
5166 "name", pointer_string_type,
5167 "pkgPath", pointer_string_type,
5168 "typ", ptdt,
5169 "tag", pointer_string_type,
5170 "offset", uintptr_type);
5171 Type* nsf = Type::make_builtin_named_type("structField", sf);
5173 Type* slice_type = Type::make_array_type(nsf, NULL);
5175 Struct_type* s = Type::make_builtin_struct_type(2,
5176 "", tdt,
5177 "fields", slice_type);
5179 ret = Type::make_builtin_named_type("StructType", s);
5182 return ret;
5185 // Build a type descriptor for a struct type.
5187 Expression*
5188 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5190 Location bloc = Linemap::predeclared_location();
5192 Type* stdt = Struct_type::make_struct_type_descriptor_type();
5194 const Struct_field_list* fields = stdt->struct_type()->fields();
5196 Expression_list* vals = new Expression_list();
5197 vals->reserve(2);
5199 const Methods* methods = this->methods();
5200 // A named struct should not have methods--the methods should attach
5201 // to the named type.
5202 go_assert(methods == NULL || name == NULL);
5204 Struct_field_list::const_iterator ps = fields->begin();
5205 go_assert(ps->is_field_name("commonType"));
5206 vals->push_back(this->type_descriptor_constructor(gogo,
5207 RUNTIME_TYPE_KIND_STRUCT,
5208 name, methods, true));
5210 ++ps;
5211 go_assert(ps->is_field_name("fields"));
5213 Expression_list* elements = new Expression_list();
5214 elements->reserve(this->fields_->size());
5215 Type* element_type = ps->type()->array_type()->element_type();
5216 for (Struct_field_list::const_iterator pf = this->fields_->begin();
5217 pf != this->fields_->end();
5218 ++pf)
5220 const Struct_field_list* f = element_type->struct_type()->fields();
5222 Expression_list* fvals = new Expression_list();
5223 fvals->reserve(5);
5225 Struct_field_list::const_iterator q = f->begin();
5226 go_assert(q->is_field_name("name"));
5227 if (pf->is_anonymous())
5228 fvals->push_back(Expression::make_nil(bloc));
5229 else
5231 std::string n = Gogo::unpack_hidden_name(pf->field_name());
5232 Expression* s = Expression::make_string(n, bloc);
5233 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
5236 ++q;
5237 go_assert(q->is_field_name("pkgPath"));
5238 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
5239 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
5240 fvals->push_back(Expression::make_nil(bloc));
5241 else
5243 std::string n;
5244 if (is_embedded_builtin)
5245 n = gogo->package_name();
5246 else
5247 n = Gogo::hidden_name_pkgpath(pf->field_name());
5248 Expression* s = Expression::make_string(n, bloc);
5249 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
5252 ++q;
5253 go_assert(q->is_field_name("typ"));
5254 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
5256 ++q;
5257 go_assert(q->is_field_name("tag"));
5258 if (!pf->has_tag())
5259 fvals->push_back(Expression::make_nil(bloc));
5260 else
5262 Expression* s = Expression::make_string(pf->tag(), bloc);
5263 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
5266 ++q;
5267 go_assert(q->is_field_name("offset"));
5268 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
5270 Expression* v = Expression::make_struct_composite_literal(element_type,
5271 fvals, bloc);
5272 elements->push_back(v);
5275 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
5276 elements, bloc));
5278 return Expression::make_struct_composite_literal(stdt, vals, bloc);
5281 // Write the hash function for a struct which can not use the identity
5282 // function.
5284 void
5285 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
5286 Function_type* hash_fntype,
5287 Function_type* equal_fntype)
5289 Location bloc = Linemap::predeclared_location();
5291 // The pointer to the struct that we are going to hash. This is an
5292 // argument to the hash function we are implementing here.
5293 Named_object* key_arg = gogo->lookup("key", NULL);
5294 go_assert(key_arg != NULL);
5295 Type* key_arg_type = key_arg->var_value()->type();
5297 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5299 // Get a 0.
5300 mpz_t ival;
5301 mpz_init_set_ui(ival, 0);
5302 Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
5303 mpz_clear(ival);
5305 // Make a temporary to hold the return value, initialized to 0.
5306 Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
5307 bloc);
5308 gogo->add_statement(retval);
5310 // Make a temporary to hold the key as a uintptr.
5311 Expression* ref = Expression::make_var_reference(key_arg, bloc);
5312 ref = Expression::make_cast(uintptr_type, ref, bloc);
5313 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
5314 bloc);
5315 gogo->add_statement(key);
5317 // Loop over the struct fields.
5318 bool first = true;
5319 const Struct_field_list* fields = this->fields_;
5320 for (Struct_field_list::const_iterator pf = fields->begin();
5321 pf != fields->end();
5322 ++pf)
5324 if (Gogo::is_sink_name(pf->field_name()))
5325 continue;
5327 if (first)
5328 first = false;
5329 else
5331 // Multiply retval by 33.
5332 mpz_init_set_ui(ival, 33);
5333 Expression* i33 = Expression::make_integer(&ival, uintptr_type,
5334 bloc);
5335 mpz_clear(ival);
5337 ref = Expression::make_temporary_reference(retval, bloc);
5338 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ,
5339 ref, i33, bloc);
5340 gogo->add_statement(s);
5343 // Get a pointer to the value of this field.
5344 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
5345 ref = Expression::make_temporary_reference(key, bloc);
5346 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
5347 bloc);
5348 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
5350 // Get the size of this field.
5351 Expression* size = Expression::make_type_info(pf->type(),
5352 Expression::TYPE_INFO_SIZE);
5354 // Get the hash function to use for the type of this field.
5355 Named_object* hash_fn;
5356 Named_object* equal_fn;
5357 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
5358 equal_fntype, &hash_fn, &equal_fn);
5360 // Call the hash function for the field.
5361 Expression_list* args = new Expression_list();
5362 args->push_back(subkey);
5363 args->push_back(size);
5364 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
5365 Expression* call = Expression::make_call(func, args, false, bloc);
5367 // Add the field's hash value to retval.
5368 Temporary_reference_expression* tref =
5369 Expression::make_temporary_reference(retval, bloc);
5370 tref->set_is_lvalue();
5371 Statement* s = Statement::make_assignment_operation(OPERATOR_PLUSEQ,
5372 tref, call, bloc);
5373 gogo->add_statement(s);
5376 // Return retval to the caller of the hash function.
5377 Expression_list* vals = new Expression_list();
5378 ref = Expression::make_temporary_reference(retval, bloc);
5379 vals->push_back(ref);
5380 Statement* s = Statement::make_return_statement(vals, bloc);
5381 gogo->add_statement(s);
5384 // Write the equality function for a struct which can not use the
5385 // identity function.
5387 void
5388 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
5390 Location bloc = Linemap::predeclared_location();
5392 // The pointers to the structs we are going to compare.
5393 Named_object* key1_arg = gogo->lookup("key1", NULL);
5394 Named_object* key2_arg = gogo->lookup("key2", NULL);
5395 go_assert(key1_arg != NULL && key2_arg != NULL);
5397 // Build temporaries with the right types.
5398 Type* pt = Type::make_pointer_type(name != NULL
5399 ? static_cast<Type*>(name)
5400 : static_cast<Type*>(this));
5402 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
5403 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5404 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
5405 gogo->add_statement(p1);
5407 ref = Expression::make_var_reference(key2_arg, bloc);
5408 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5409 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
5410 gogo->add_statement(p2);
5412 const Struct_field_list* fields = this->fields_;
5413 unsigned int field_index = 0;
5414 for (Struct_field_list::const_iterator pf = fields->begin();
5415 pf != fields->end();
5416 ++pf, ++field_index)
5418 if (Gogo::is_sink_name(pf->field_name()))
5419 continue;
5421 // Compare one field in both P1 and P2.
5422 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
5423 f1 = Expression::make_unary(OPERATOR_MULT, f1, bloc);
5424 f1 = Expression::make_field_reference(f1, field_index, bloc);
5426 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
5427 f2 = Expression::make_unary(OPERATOR_MULT, f2, bloc);
5428 f2 = Expression::make_field_reference(f2, field_index, bloc);
5430 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
5432 // If the values are not equal, return false.
5433 gogo->start_block(bloc);
5434 Expression_list* vals = new Expression_list();
5435 vals->push_back(Expression::make_boolean(false, bloc));
5436 Statement* s = Statement::make_return_statement(vals, bloc);
5437 gogo->add_statement(s);
5438 Block* then_block = gogo->finish_block(bloc);
5440 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
5441 gogo->add_statement(s);
5444 // All the fields are equal, so return true.
5445 Expression_list* vals = new Expression_list();
5446 vals->push_back(Expression::make_boolean(true, bloc));
5447 Statement* s = Statement::make_return_statement(vals, bloc);
5448 gogo->add_statement(s);
5451 // Reflection string.
5453 void
5454 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
5456 ret->append("struct {");
5458 for (Struct_field_list::const_iterator p = this->fields_->begin();
5459 p != this->fields_->end();
5460 ++p)
5462 if (p != this->fields_->begin())
5463 ret->push_back(';');
5464 ret->push_back(' ');
5465 if (p->is_anonymous())
5466 ret->push_back('?');
5467 else
5468 ret->append(Gogo::unpack_hidden_name(p->field_name()));
5469 ret->push_back(' ');
5470 this->append_reflection(p->type(), gogo, ret);
5472 if (p->has_tag())
5474 const std::string& tag(p->tag());
5475 ret->append(" \"");
5476 for (std::string::const_iterator p = tag.begin();
5477 p != tag.end();
5478 ++p)
5480 if (*p == '\0')
5481 ret->append("\\x00");
5482 else if (*p == '\n')
5483 ret->append("\\n");
5484 else if (*p == '\t')
5485 ret->append("\\t");
5486 else if (*p == '"')
5487 ret->append("\\\"");
5488 else if (*p == '\\')
5489 ret->append("\\\\");
5490 else
5491 ret->push_back(*p);
5493 ret->push_back('"');
5497 if (!this->fields_->empty())
5498 ret->push_back(' ');
5500 ret->push_back('}');
5503 // Generate GC symbol for struct types.
5505 void
5506 Struct_type::do_gc_symbol(Gogo* gogo, Expression_list** vals,
5507 Expression** offset, int stack_size)
5509 Location bloc = Linemap::predeclared_location();
5510 const Struct_field_list* sfl = this->fields();
5511 for (Struct_field_list::const_iterator p = sfl->begin();
5512 p != sfl->end();
5513 ++p)
5515 Expression* field_offset =
5516 Expression::make_struct_field_offset(this, &*p);
5517 Expression* o =
5518 Expression::make_binary(OPERATOR_PLUS, *offset, field_offset, bloc);
5519 Type::gc_symbol(gogo, p->type(), vals, &o, stack_size);
5521 this->advance_gc_offset(offset);
5524 // Mangled name.
5526 void
5527 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5529 ret->push_back('S');
5531 const Struct_field_list* fields = this->fields_;
5532 if (fields != NULL)
5534 for (Struct_field_list::const_iterator p = fields->begin();
5535 p != fields->end();
5536 ++p)
5538 if (p->is_anonymous())
5539 ret->append("0_");
5540 else
5542 std::string n = Gogo::unpack_hidden_name(p->field_name());
5543 char buf[20];
5544 snprintf(buf, sizeof buf, "%u_",
5545 static_cast<unsigned int>(n.length()));
5546 ret->append(buf);
5547 ret->append(n);
5549 this->append_mangled_name(p->type(), gogo, ret);
5550 if (p->has_tag())
5552 const std::string& tag(p->tag());
5553 std::string out;
5554 for (std::string::const_iterator p = tag.begin();
5555 p != tag.end();
5556 ++p)
5558 if (ISALNUM(*p) || *p == '_')
5559 out.push_back(*p);
5560 else
5562 char buf[20];
5563 snprintf(buf, sizeof buf, ".%x.",
5564 static_cast<unsigned int>(*p));
5565 out.append(buf);
5568 char buf[20];
5569 snprintf(buf, sizeof buf, "T%u_",
5570 static_cast<unsigned int>(out.length()));
5571 ret->append(buf);
5572 ret->append(out);
5577 ret->push_back('e');
5580 // If the offset of field INDEX in the backend implementation can be
5581 // determined, set *POFFSET to the offset in bytes and return true.
5582 // Otherwise, return false.
5584 bool
5585 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
5586 unsigned int* poffset)
5588 if (!this->is_backend_type_size_known(gogo))
5589 return false;
5590 Btype* bt = this->get_backend_placeholder(gogo);
5591 size_t offset = gogo->backend()->type_field_offset(bt, index);
5592 *poffset = static_cast<unsigned int>(offset);
5593 if (*poffset != offset)
5594 return false;
5595 return true;
5598 // Export.
5600 void
5601 Struct_type::do_export(Export* exp) const
5603 exp->write_c_string("struct { ");
5604 const Struct_field_list* fields = this->fields_;
5605 go_assert(fields != NULL);
5606 for (Struct_field_list::const_iterator p = fields->begin();
5607 p != fields->end();
5608 ++p)
5610 if (p->is_anonymous())
5611 exp->write_string("? ");
5612 else
5614 exp->write_string(p->field_name());
5615 exp->write_c_string(" ");
5617 exp->write_type(p->type());
5619 if (p->has_tag())
5621 exp->write_c_string(" ");
5622 Expression* expr =
5623 Expression::make_string(p->tag(), Linemap::predeclared_location());
5624 expr->export_expression(exp);
5625 delete expr;
5628 exp->write_c_string("; ");
5630 exp->write_c_string("}");
5633 // Import.
5635 Struct_type*
5636 Struct_type::do_import(Import* imp)
5638 imp->require_c_string("struct { ");
5639 Struct_field_list* fields = new Struct_field_list;
5640 if (imp->peek_char() != '}')
5642 while (true)
5644 std::string name;
5645 if (imp->match_c_string("? "))
5646 imp->advance(2);
5647 else
5649 name = imp->read_identifier();
5650 imp->require_c_string(" ");
5652 Type* ftype = imp->read_type();
5654 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
5655 sf.set_is_imported();
5657 if (imp->peek_char() == ' ')
5659 imp->advance(1);
5660 Expression* expr = Expression::import_expression(imp);
5661 String_expression* sexpr = expr->string_expression();
5662 go_assert(sexpr != NULL);
5663 sf.set_tag(sexpr->val());
5664 delete sexpr;
5667 imp->require_c_string("; ");
5668 fields->push_back(sf);
5669 if (imp->peek_char() == '}')
5670 break;
5673 imp->require_c_string("}");
5675 return Type::make_struct_type(fields, imp->location());
5678 // Make a struct type.
5680 Struct_type*
5681 Type::make_struct_type(Struct_field_list* fields,
5682 Location location)
5684 return new Struct_type(fields, location);
5687 // Class Array_type.
5689 // Whether two array types are identical.
5691 bool
5692 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
5694 if (!Type::are_identical(this->element_type(), t->element_type(),
5695 errors_are_identical, NULL))
5696 return false;
5698 Expression* l1 = this->length();
5699 Expression* l2 = t->length();
5701 // Slices of the same element type are identical.
5702 if (l1 == NULL && l2 == NULL)
5703 return true;
5705 // Arrays of the same element type are identical if they have the
5706 // same length.
5707 if (l1 != NULL && l2 != NULL)
5709 if (l1 == l2)
5710 return true;
5712 // Try to determine the lengths. If we can't, assume the arrays
5713 // are not identical.
5714 bool ret = false;
5715 Numeric_constant nc1, nc2;
5716 if (l1->numeric_constant_value(&nc1)
5717 && l2->numeric_constant_value(&nc2))
5719 mpz_t v1;
5720 if (nc1.to_int(&v1))
5722 mpz_t v2;
5723 if (nc2.to_int(&v2))
5725 ret = mpz_cmp(v1, v2) == 0;
5726 mpz_clear(v2);
5728 mpz_clear(v1);
5731 return ret;
5734 // Otherwise the arrays are not identical.
5735 return false;
5738 // Traversal.
5741 Array_type::do_traverse(Traverse* traverse)
5743 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
5744 return TRAVERSE_EXIT;
5745 if (this->length_ != NULL
5746 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
5747 return TRAVERSE_EXIT;
5748 return TRAVERSE_CONTINUE;
5751 // Check that the length is valid.
5753 bool
5754 Array_type::verify_length()
5756 if (this->length_ == NULL)
5757 return true;
5759 Type_context context(Type::lookup_integer_type("int"), false);
5760 this->length_->determine_type(&context);
5762 if (!this->length_->is_constant())
5764 error_at(this->length_->location(), "array bound is not constant");
5765 return false;
5768 Numeric_constant nc;
5769 if (!this->length_->numeric_constant_value(&nc))
5771 if (this->length_->type()->integer_type() != NULL
5772 || this->length_->type()->float_type() != NULL)
5773 error_at(this->length_->location(), "array bound is not constant");
5774 else
5775 error_at(this->length_->location(), "array bound is not numeric");
5776 return false;
5779 unsigned long val;
5780 switch (nc.to_unsigned_long(&val))
5782 case Numeric_constant::NC_UL_VALID:
5783 break;
5784 case Numeric_constant::NC_UL_NOTINT:
5785 error_at(this->length_->location(), "array bound truncated to integer");
5786 return false;
5787 case Numeric_constant::NC_UL_NEGATIVE:
5788 error_at(this->length_->location(), "negative array bound");
5789 return false;
5790 case Numeric_constant::NC_UL_BIG:
5791 error_at(this->length_->location(), "array bound overflows");
5792 return false;
5793 default:
5794 go_unreachable();
5797 Type* int_type = Type::lookup_integer_type("int");
5798 unsigned int tbits = int_type->integer_type()->bits();
5799 if (sizeof(val) <= tbits * 8
5800 && val >> (tbits - 1) != 0)
5802 error_at(this->length_->location(), "array bound overflows");
5803 return false;
5806 return true;
5809 // Verify the type.
5811 bool
5812 Array_type::do_verify()
5814 if (!this->verify_length())
5815 this->length_ = Expression::make_error(this->length_->location());
5816 return true;
5819 // Whether we can use memcmp to compare this array.
5821 bool
5822 Array_type::do_compare_is_identity(Gogo* gogo)
5824 if (this->length_ == NULL)
5825 return false;
5827 // Check for [...], which indicates that this is not a real type.
5828 if (this->length_->is_nil_expression())
5829 return false;
5831 if (!this->element_type_->compare_is_identity(gogo))
5832 return false;
5834 // If there is any padding, then we can't use memcmp.
5835 unsigned long size;
5836 unsigned long align;
5837 if (!this->element_type_->backend_type_size(gogo, &size)
5838 || !this->element_type_->backend_type_align(gogo, &align))
5839 return false;
5840 if ((size & (align - 1)) != 0)
5841 return false;
5843 return true;
5846 // Array type hash code.
5848 unsigned int
5849 Array_type::do_hash_for_method(Gogo* gogo) const
5851 // There is no very convenient way to get a hash code for the
5852 // length.
5853 return this->element_type_->hash_for_method(gogo) + 1;
5856 // Write the hash function for an array which can not use the identify
5857 // function.
5859 void
5860 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
5861 Function_type* hash_fntype,
5862 Function_type* equal_fntype)
5864 Location bloc = Linemap::predeclared_location();
5866 // The pointer to the array that we are going to hash. This is an
5867 // argument to the hash function we are implementing here.
5868 Named_object* key_arg = gogo->lookup("key", NULL);
5869 go_assert(key_arg != NULL);
5870 Type* key_arg_type = key_arg->var_value()->type();
5872 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5874 // Get a 0.
5875 mpz_t ival;
5876 mpz_init_set_ui(ival, 0);
5877 Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
5878 mpz_clear(ival);
5880 // Make a temporary to hold the return value, initialized to 0.
5881 Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
5882 bloc);
5883 gogo->add_statement(retval);
5885 // Make a temporary to hold the key as a uintptr.
5886 Expression* ref = Expression::make_var_reference(key_arg, bloc);
5887 ref = Expression::make_cast(uintptr_type, ref, bloc);
5888 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
5889 bloc);
5890 gogo->add_statement(key);
5892 // Loop over the array elements.
5893 // for i = range a
5894 Type* int_type = Type::lookup_integer_type("int");
5895 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
5896 gogo->add_statement(index);
5898 Expression* iref = Expression::make_temporary_reference(index, bloc);
5899 Expression* aref = Expression::make_var_reference(key_arg, bloc);
5900 Type* pt = Type::make_pointer_type(name != NULL
5901 ? static_cast<Type*>(name)
5902 : static_cast<Type*>(this));
5903 aref = Expression::make_cast(pt, aref, bloc);
5904 For_range_statement* for_range = Statement::make_for_range_statement(iref,
5905 NULL,
5906 aref,
5907 bloc);
5909 gogo->start_block(bloc);
5911 // Multiply retval by 33.
5912 mpz_init_set_ui(ival, 33);
5913 Expression* i33 = Expression::make_integer(&ival, uintptr_type, bloc);
5914 mpz_clear(ival);
5916 ref = Expression::make_temporary_reference(retval, bloc);
5917 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ, ref,
5918 i33, bloc);
5919 gogo->add_statement(s);
5921 // Get the hash function for the element type.
5922 Named_object* hash_fn;
5923 Named_object* equal_fn;
5924 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
5925 hash_fntype, equal_fntype, &hash_fn,
5926 &equal_fn);
5928 // Get a pointer to this element in the loop.
5929 Expression* subkey = Expression::make_temporary_reference(key, bloc);
5930 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
5932 // Get the size of each element.
5933 Expression* ele_size = Expression::make_type_info(this->element_type_,
5934 Expression::TYPE_INFO_SIZE);
5936 // Get the hash of this element.
5937 Expression_list* args = new Expression_list();
5938 args->push_back(subkey);
5939 args->push_back(ele_size);
5940 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
5941 Expression* call = Expression::make_call(func, args, false, bloc);
5943 // Add the element's hash value to retval.
5944 Temporary_reference_expression* tref =
5945 Expression::make_temporary_reference(retval, bloc);
5946 tref->set_is_lvalue();
5947 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, call, bloc);
5948 gogo->add_statement(s);
5950 // Increase the element pointer.
5951 tref = Expression::make_temporary_reference(key, bloc);
5952 tref->set_is_lvalue();
5953 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
5954 bloc);
5955 Block* statements = gogo->finish_block(bloc);
5957 for_range->add_statements(statements);
5958 gogo->add_statement(for_range);
5960 // Return retval to the caller of the hash function.
5961 Expression_list* vals = new Expression_list();
5962 ref = Expression::make_temporary_reference(retval, bloc);
5963 vals->push_back(ref);
5964 s = Statement::make_return_statement(vals, bloc);
5965 gogo->add_statement(s);
5968 // Write the equality function for an array which can not use the
5969 // identity function.
5971 void
5972 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
5974 Location bloc = Linemap::predeclared_location();
5976 // The pointers to the arrays we are going to compare.
5977 Named_object* key1_arg = gogo->lookup("key1", NULL);
5978 Named_object* key2_arg = gogo->lookup("key2", NULL);
5979 go_assert(key1_arg != NULL && key2_arg != NULL);
5981 // Build temporaries for the keys with the right types.
5982 Type* pt = Type::make_pointer_type(name != NULL
5983 ? static_cast<Type*>(name)
5984 : static_cast<Type*>(this));
5986 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
5987 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5988 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
5989 gogo->add_statement(p1);
5991 ref = Expression::make_var_reference(key2_arg, bloc);
5992 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5993 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
5994 gogo->add_statement(p2);
5996 // Loop over the array elements.
5997 // for i = range a
5998 Type* int_type = Type::lookup_integer_type("int");
5999 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
6000 gogo->add_statement(index);
6002 Expression* iref = Expression::make_temporary_reference(index, bloc);
6003 Expression* aref = Expression::make_temporary_reference(p1, bloc);
6004 For_range_statement* for_range = Statement::make_for_range_statement(iref,
6005 NULL,
6006 aref,
6007 bloc);
6009 gogo->start_block(bloc);
6011 // Compare element in P1 and P2.
6012 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
6013 e1 = Expression::make_unary(OPERATOR_MULT, e1, bloc);
6014 ref = Expression::make_temporary_reference(index, bloc);
6015 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
6017 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
6018 e2 = Expression::make_unary(OPERATOR_MULT, e2, bloc);
6019 ref = Expression::make_temporary_reference(index, bloc);
6020 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
6022 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
6024 // If the elements are not equal, return false.
6025 gogo->start_block(bloc);
6026 Expression_list* vals = new Expression_list();
6027 vals->push_back(Expression::make_boolean(false, bloc));
6028 Statement* s = Statement::make_return_statement(vals, bloc);
6029 gogo->add_statement(s);
6030 Block* then_block = gogo->finish_block(bloc);
6032 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6033 gogo->add_statement(s);
6035 Block* statements = gogo->finish_block(bloc);
6037 for_range->add_statements(statements);
6038 gogo->add_statement(for_range);
6040 // All the elements are equal, so return true.
6041 vals = new Expression_list();
6042 vals->push_back(Expression::make_boolean(true, bloc));
6043 s = Statement::make_return_statement(vals, bloc);
6044 gogo->add_statement(s);
6047 // Get the backend representation of the fields of a slice. This is
6048 // not declared in types.h so that types.h doesn't have to #include
6049 // backend.h.
6051 // We use int for the count and capacity fields. This matches 6g.
6052 // The language more or less assumes that we can't allocate space of a
6053 // size which does not fit in int.
6055 static void
6056 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
6057 std::vector<Backend::Btyped_identifier>* bfields)
6059 bfields->resize(3);
6061 Type* pet = Type::make_pointer_type(type->element_type());
6062 Btype* pbet = (use_placeholder
6063 ? pet->get_backend_placeholder(gogo)
6064 : pet->get_backend(gogo));
6065 Location ploc = Linemap::predeclared_location();
6067 Backend::Btyped_identifier* p = &(*bfields)[0];
6068 p->name = "__values";
6069 p->btype = pbet;
6070 p->location = ploc;
6072 Type* int_type = Type::lookup_integer_type("int");
6074 p = &(*bfields)[1];
6075 p->name = "__count";
6076 p->btype = int_type->get_backend(gogo);
6077 p->location = ploc;
6079 p = &(*bfields)[2];
6080 p->name = "__capacity";
6081 p->btype = int_type->get_backend(gogo);
6082 p->location = ploc;
6085 // Get the backend representation for the type of this array. A fixed array is
6086 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
6087 // just like an array in C. An open array is a struct with three
6088 // fields: a data pointer, the length, and the capacity.
6090 Btype*
6091 Array_type::do_get_backend(Gogo* gogo)
6093 if (this->length_ == NULL)
6095 std::vector<Backend::Btyped_identifier> bfields;
6096 get_backend_slice_fields(gogo, this, false, &bfields);
6097 return gogo->backend()->struct_type(bfields);
6099 else
6101 Btype* element = this->get_backend_element(gogo, false);
6102 Bexpression* len = this->get_backend_length(gogo);
6103 return gogo->backend()->array_type(element, len);
6107 // Return the backend representation of the element type.
6109 Btype*
6110 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
6112 if (use_placeholder)
6113 return this->element_type_->get_backend_placeholder(gogo);
6114 else
6115 return this->element_type_->get_backend(gogo);
6118 // Return the backend representation of the length. The length may be
6119 // computed using a function call, so we must only evaluate it once.
6121 Bexpression*
6122 Array_type::get_backend_length(Gogo* gogo)
6124 go_assert(this->length_ != NULL);
6125 if (this->blength_ == NULL)
6127 Numeric_constant nc;
6128 mpz_t val;
6129 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
6131 if (mpz_sgn(val) < 0)
6133 this->blength_ = gogo->backend()->error_expression();
6134 return this->blength_;
6136 Type* t = nc.type();
6137 if (t == NULL)
6138 t = Type::lookup_integer_type("int");
6139 else if (t->is_abstract())
6140 t = t->make_non_abstract_type();
6141 Btype* btype = t->get_backend(gogo);
6142 this->blength_ =
6143 gogo->backend()->integer_constant_expression(btype, val);
6144 mpz_clear(val);
6146 else
6148 // Make up a translation context for the array length
6149 // expression. FIXME: This won't work in general.
6150 Translate_context context(gogo, NULL, NULL, NULL);
6151 this->blength_ = this->length_->get_backend(&context);
6153 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
6154 this->blength_ =
6155 gogo->backend()->convert_expression(ibtype, this->blength_,
6156 this->length_->location());
6159 return this->blength_;
6162 // Finish backend representation of the array.
6164 void
6165 Array_type::finish_backend_element(Gogo* gogo)
6167 Type* et = this->array_type()->element_type();
6168 et->get_backend(gogo);
6169 if (this->is_slice_type())
6171 // This relies on the fact that we always use the same
6172 // structure for a pointer to any given type.
6173 Type* pet = Type::make_pointer_type(et);
6174 pet->get_backend(gogo);
6178 // Return an expression for a pointer to the values in ARRAY.
6180 Expression*
6181 Array_type::get_value_pointer(Gogo*, Expression* array) const
6183 if (this->length() != NULL)
6185 // Fixed array.
6186 go_assert(array->type()->array_type() != NULL);
6187 Type* etype = array->type()->array_type()->element_type();
6188 array = Expression::make_unary(OPERATOR_AND, array, array->location());
6189 return Expression::make_cast(Type::make_pointer_type(etype), array,
6190 array->location());
6193 // Slice.
6194 return Expression::make_slice_info(array,
6195 Expression::SLICE_INFO_VALUE_POINTER,
6196 array->location());
6199 // Return an expression for the length of the array ARRAY which has this
6200 // type.
6202 Expression*
6203 Array_type::get_length(Gogo*, Expression* array) const
6205 if (this->length_ != NULL)
6206 return this->length_;
6208 // This is a slice. We need to read the length field.
6209 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
6210 array->location());
6213 // Return an expression for the capacity of the array ARRAY which has this
6214 // type.
6216 Expression*
6217 Array_type::get_capacity(Gogo*, Expression* array) const
6219 if (this->length_ != NULL)
6220 return this->length_;
6222 // This is a slice. We need to read the capacity field.
6223 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
6224 array->location());
6227 // Export.
6229 void
6230 Array_type::do_export(Export* exp) const
6232 exp->write_c_string("[");
6233 if (this->length_ != NULL)
6234 this->length_->export_expression(exp);
6235 exp->write_c_string("] ");
6236 exp->write_type(this->element_type_);
6239 // Import.
6241 Array_type*
6242 Array_type::do_import(Import* imp)
6244 imp->require_c_string("[");
6245 Expression* length;
6246 if (imp->peek_char() == ']')
6247 length = NULL;
6248 else
6249 length = Expression::import_expression(imp);
6250 imp->require_c_string("] ");
6251 Type* element_type = imp->read_type();
6252 return Type::make_array_type(element_type, length);
6255 // The type of an array type descriptor.
6257 Type*
6258 Array_type::make_array_type_descriptor_type()
6260 static Type* ret;
6261 if (ret == NULL)
6263 Type* tdt = Type::make_type_descriptor_type();
6264 Type* ptdt = Type::make_type_descriptor_ptr_type();
6266 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6268 Struct_type* sf =
6269 Type::make_builtin_struct_type(4,
6270 "", tdt,
6271 "elem", ptdt,
6272 "slice", ptdt,
6273 "len", uintptr_type);
6275 ret = Type::make_builtin_named_type("ArrayType", sf);
6278 return ret;
6281 // The type of an slice type descriptor.
6283 Type*
6284 Array_type::make_slice_type_descriptor_type()
6286 static Type* ret;
6287 if (ret == NULL)
6289 Type* tdt = Type::make_type_descriptor_type();
6290 Type* ptdt = Type::make_type_descriptor_ptr_type();
6292 Struct_type* sf =
6293 Type::make_builtin_struct_type(2,
6294 "", tdt,
6295 "elem", ptdt);
6297 ret = Type::make_builtin_named_type("SliceType", sf);
6300 return ret;
6303 // Build a type descriptor for an array/slice type.
6305 Expression*
6306 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6308 if (this->length_ != NULL)
6309 return this->array_type_descriptor(gogo, name);
6310 else
6311 return this->slice_type_descriptor(gogo, name);
6314 // Build a type descriptor for an array type.
6316 Expression*
6317 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
6319 Location bloc = Linemap::predeclared_location();
6321 Type* atdt = Array_type::make_array_type_descriptor_type();
6323 const Struct_field_list* fields = atdt->struct_type()->fields();
6325 Expression_list* vals = new Expression_list();
6326 vals->reserve(3);
6328 Struct_field_list::const_iterator p = fields->begin();
6329 go_assert(p->is_field_name("commonType"));
6330 vals->push_back(this->type_descriptor_constructor(gogo,
6331 RUNTIME_TYPE_KIND_ARRAY,
6332 name, NULL, true));
6334 ++p;
6335 go_assert(p->is_field_name("elem"));
6336 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
6338 ++p;
6339 go_assert(p->is_field_name("slice"));
6340 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
6341 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
6343 ++p;
6344 go_assert(p->is_field_name("len"));
6345 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
6347 ++p;
6348 go_assert(p == fields->end());
6350 return Expression::make_struct_composite_literal(atdt, vals, bloc);
6353 // Build a type descriptor for a slice type.
6355 Expression*
6356 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
6358 Location bloc = Linemap::predeclared_location();
6360 Type* stdt = Array_type::make_slice_type_descriptor_type();
6362 const Struct_field_list* fields = stdt->struct_type()->fields();
6364 Expression_list* vals = new Expression_list();
6365 vals->reserve(2);
6367 Struct_field_list::const_iterator p = fields->begin();
6368 go_assert(p->is_field_name("commonType"));
6369 vals->push_back(this->type_descriptor_constructor(gogo,
6370 RUNTIME_TYPE_KIND_SLICE,
6371 name, NULL, true));
6373 ++p;
6374 go_assert(p->is_field_name("elem"));
6375 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
6377 ++p;
6378 go_assert(p == fields->end());
6380 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6383 // Reflection string.
6385 void
6386 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
6388 ret->push_back('[');
6389 if (this->length_ != NULL)
6391 Numeric_constant nc;
6392 unsigned long val;
6393 if (!this->length_->numeric_constant_value(&nc)
6394 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
6395 error_at(this->length_->location(), "invalid array length");
6396 else
6398 char buf[50];
6399 snprintf(buf, sizeof buf, "%lu", val);
6400 ret->append(buf);
6403 ret->push_back(']');
6405 this->append_reflection(this->element_type_, gogo, ret);
6408 // GC Symbol construction for array types.
6410 void
6411 Array_type::do_gc_symbol(Gogo* gogo, Expression_list** vals,
6412 Expression** offset, int stack_size)
6414 if (this->length_ == NULL)
6415 this->slice_gc_symbol(gogo, vals, offset, stack_size);
6416 else
6417 this->array_gc_symbol(gogo, vals, offset, stack_size);
6420 // Generate the GC Symbol for a slice.
6422 void
6423 Array_type::slice_gc_symbol(Gogo* gogo, Expression_list** vals,
6424 Expression** offset, int)
6426 Location bloc = Linemap::predeclared_location();
6428 // Differentiate between slices with zero-length and non-zero-length values.
6429 Type* element_type = this->element_type();
6430 Btype* ebtype = element_type->get_backend(gogo);
6431 size_t element_size = gogo->backend()->type_size(ebtype);
6433 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6434 mpz_t opval;
6435 mpz_init_set_ui(opval, element_size == 0 ? GC_APTR : GC_SLICE);
6436 (*vals)->push_back(Expression::make_integer(&opval, uintptr_type, bloc));
6437 mpz_clear(opval);
6438 (*vals)->push_back(*offset);
6440 if (element_size != 0)
6441 (*vals)->push_back(Expression::make_gc_symbol(element_type));
6442 this->advance_gc_offset(offset);
6445 // Generate the GC symbol for an array.
6447 void
6448 Array_type::array_gc_symbol(Gogo* gogo, Expression_list** vals,
6449 Expression** offset, int stack_size)
6451 Location bloc = Linemap::predeclared_location();
6453 Numeric_constant nc;
6454 unsigned long bound;
6455 if (!this->length_->numeric_constant_value(&nc)
6456 || nc.to_unsigned_long(&bound) == Numeric_constant::NC_UL_NOTINT)
6457 go_assert(saw_errors());
6459 Btype* pbtype = gogo->backend()->pointer_type(gogo->backend()->void_type());
6460 size_t pwidth = gogo->backend()->type_size(pbtype);
6461 size_t iwidth = gogo->backend()->type_size(this->get_backend(gogo));
6463 Type* element_type = this->element_type();
6464 if (bound < 1 || !element_type->has_pointer())
6465 this->advance_gc_offset(offset);
6466 else if (bound == 1 || iwidth <= 4 * pwidth)
6468 for (unsigned int i = 0; i < bound; ++i)
6469 Type::gc_symbol(gogo, element_type, vals, offset, stack_size);
6471 else
6473 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6475 mpz_t op;
6476 if (stack_size < GC_STACK_CAPACITY)
6478 mpz_init_set_ui(op, GC_ARRAY_START);
6479 (*vals)->push_back(Expression::make_integer(&op, uintptr_type, bloc));
6480 mpz_clear(op);
6481 (*vals)->push_back(*offset);
6482 Expression* uintptr_len =
6483 Expression::make_cast(uintptr_type, this->length_, bloc);
6484 (*vals)->push_back(uintptr_len);
6486 Expression* width =
6487 Expression::make_type_info(element_type,
6488 Expression::TYPE_INFO_SIZE);
6489 (*vals)->push_back(width);
6491 mpz_t zero;
6492 mpz_init_set_ui(zero, 0UL);
6493 Expression* offset2 =
6494 Expression::make_integer(&zero, uintptr_type, bloc);
6495 mpz_clear(zero);
6497 Type::gc_symbol(gogo, element_type, vals, &offset2, stack_size + 1);
6498 mpz_init_set_ui(op, GC_ARRAY_NEXT);
6499 (*vals)->push_back(Expression::make_integer(&op, uintptr_type, bloc));
6501 else
6503 mpz_init_set_ui(op, GC_REGION);
6504 (*vals)->push_back(Expression::make_integer(&op, uintptr_type, bloc));
6505 (*vals)->push_back(*offset);
6507 Expression* width =
6508 Expression::make_type_info(this, Expression::TYPE_INFO_SIZE);
6509 (*vals)->push_back(width);
6510 (*vals)->push_back(Expression::make_gc_symbol(this));
6512 mpz_clear(op);
6513 this->advance_gc_offset(offset);
6517 // Mangled name.
6519 void
6520 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6522 ret->push_back('A');
6523 this->append_mangled_name(this->element_type_, gogo, ret);
6524 if (this->length_ != NULL)
6526 Numeric_constant nc;
6527 unsigned long val;
6528 if (!this->length_->numeric_constant_value(&nc)
6529 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
6530 error_at(this->length_->location(), "invalid array length");
6531 else
6533 char buf[50];
6534 snprintf(buf, sizeof buf, "%lu", val);
6535 ret->append(buf);
6538 ret->push_back('e');
6541 // Make an array type.
6543 Array_type*
6544 Type::make_array_type(Type* element_type, Expression* length)
6546 return new Array_type(element_type, length);
6549 // Class Map_type.
6551 // Traversal.
6554 Map_type::do_traverse(Traverse* traverse)
6556 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
6557 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
6558 return TRAVERSE_EXIT;
6559 return TRAVERSE_CONTINUE;
6562 // Check that the map type is OK.
6564 bool
6565 Map_type::do_verify()
6567 // The runtime support uses "map[void]void".
6568 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
6569 error_at(this->location_, "invalid map key type");
6570 return true;
6573 // Whether two map types are identical.
6575 bool
6576 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
6578 return (Type::are_identical(this->key_type(), t->key_type(),
6579 errors_are_identical, NULL)
6580 && Type::are_identical(this->val_type(), t->val_type(),
6581 errors_are_identical, NULL));
6584 // Hash code.
6586 unsigned int
6587 Map_type::do_hash_for_method(Gogo* gogo) const
6589 return (this->key_type_->hash_for_method(gogo)
6590 + this->val_type_->hash_for_method(gogo)
6591 + 2);
6594 // Get the backend representation for a map type. A map type is
6595 // represented as a pointer to a struct. The struct is __go_map in
6596 // libgo/map.h.
6598 Btype*
6599 Map_type::do_get_backend(Gogo* gogo)
6601 static Btype* backend_map_type;
6602 if (backend_map_type == NULL)
6604 std::vector<Backend::Btyped_identifier> bfields(4);
6606 Location bloc = Linemap::predeclared_location();
6608 Type* pdt = Type::make_type_descriptor_ptr_type();
6609 bfields[0].name = "__descriptor";
6610 bfields[0].btype = pdt->get_backend(gogo);
6611 bfields[0].location = bloc;
6613 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6614 bfields[1].name = "__element_count";
6615 bfields[1].btype = uintptr_type->get_backend(gogo);
6616 bfields[1].location = bloc;
6618 bfields[2].name = "__bucket_count";
6619 bfields[2].btype = bfields[1].btype;
6620 bfields[2].location = bloc;
6622 Btype* bvt = gogo->backend()->void_type();
6623 Btype* bpvt = gogo->backend()->pointer_type(bvt);
6624 Btype* bppvt = gogo->backend()->pointer_type(bpvt);
6625 bfields[3].name = "__buckets";
6626 bfields[3].btype = bppvt;
6627 bfields[3].location = bloc;
6629 Btype *bt = gogo->backend()->struct_type(bfields);
6630 bt = gogo->backend()->named_type("__go_map", bt, bloc);
6631 backend_map_type = gogo->backend()->pointer_type(bt);
6633 return backend_map_type;
6636 // The type of a map type descriptor.
6638 Type*
6639 Map_type::make_map_type_descriptor_type()
6641 static Type* ret;
6642 if (ret == NULL)
6644 Type* tdt = Type::make_type_descriptor_type();
6645 Type* ptdt = Type::make_type_descriptor_ptr_type();
6647 Struct_type* sf =
6648 Type::make_builtin_struct_type(3,
6649 "", tdt,
6650 "key", ptdt,
6651 "elem", ptdt);
6653 ret = Type::make_builtin_named_type("MapType", sf);
6656 return ret;
6659 // Build a type descriptor for a map type.
6661 Expression*
6662 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6664 Location bloc = Linemap::predeclared_location();
6666 Type* mtdt = Map_type::make_map_type_descriptor_type();
6668 const Struct_field_list* fields = mtdt->struct_type()->fields();
6670 Expression_list* vals = new Expression_list();
6671 vals->reserve(3);
6673 Struct_field_list::const_iterator p = fields->begin();
6674 go_assert(p->is_field_name("commonType"));
6675 vals->push_back(this->type_descriptor_constructor(gogo,
6676 RUNTIME_TYPE_KIND_MAP,
6677 name, NULL, true));
6679 ++p;
6680 go_assert(p->is_field_name("key"));
6681 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
6683 ++p;
6684 go_assert(p->is_field_name("elem"));
6685 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
6687 ++p;
6688 go_assert(p == fields->end());
6690 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
6693 // A mapping from map types to map descriptors.
6695 Map_type::Map_descriptors Map_type::map_descriptors;
6697 // Build a map descriptor for this type. Return a pointer to it.
6699 Bexpression*
6700 Map_type::map_descriptor_pointer(Gogo* gogo, Location location)
6702 Bvariable* bvar = this->map_descriptor(gogo);
6703 Bexpression* var_expr = gogo->backend()->var_expression(bvar, location);
6704 return gogo->backend()->address_expression(var_expr, location);
6707 // Build a map descriptor for this type.
6709 Bvariable*
6710 Map_type::map_descriptor(Gogo* gogo)
6712 std::pair<Map_type*, Bvariable*> val(this, NULL);
6713 std::pair<Map_type::Map_descriptors::iterator, bool> ins =
6714 Map_type::map_descriptors.insert(val);
6715 if (!ins.second)
6716 return ins.first->second;
6718 Type* key_type = this->key_type_;
6719 Type* val_type = this->val_type_;
6721 // The map entry type is a struct with three fields. Build that
6722 // struct so that we can get the offsets of the key and value within
6723 // a map entry. The first field should technically be a pointer to
6724 // this type itself, but since we only care about field offsets we
6725 // just use pointer to bool.
6726 Type* pbool = Type::make_pointer_type(Type::make_boolean_type());
6727 Struct_type* map_entry_type =
6728 Type::make_builtin_struct_type(3,
6729 "__next", pbool,
6730 "__key", key_type,
6731 "__val", val_type);
6733 Type* map_descriptor_type = Map_type::make_map_descriptor_type();
6735 const Struct_field_list* fields =
6736 map_descriptor_type->struct_type()->fields();
6738 Expression_list* vals = new Expression_list();
6739 vals->reserve(4);
6741 Location bloc = Linemap::predeclared_location();
6743 Struct_field_list::const_iterator p = fields->begin();
6745 go_assert(p->is_field_name("__map_descriptor"));
6746 vals->push_back(Expression::make_type_descriptor(this, bloc));
6748 ++p;
6749 go_assert(p->is_field_name("__entry_size"));
6750 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
6751 vals->push_back(Expression::make_type_info(map_entry_type, type_info));
6753 Struct_field_list::const_iterator pf = map_entry_type->fields()->begin();
6754 ++pf;
6755 go_assert(pf->is_field_name("__key"));
6757 ++p;
6758 go_assert(p->is_field_name("__key_offset"));
6759 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6761 ++pf;
6762 go_assert(pf->is_field_name("__val"));
6764 ++p;
6765 go_assert(p->is_field_name("__val_offset"));
6766 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6768 ++p;
6769 go_assert(p == fields->end());
6771 Expression* initializer =
6772 Expression::make_struct_composite_literal(map_descriptor_type, vals, bloc);
6774 std::string mangled_name = "__go_map_" + this->mangled_name(gogo);
6775 Btype* map_descriptor_btype = map_descriptor_type->get_backend(gogo);
6776 Bvariable* bvar = gogo->backend()->immutable_struct(mangled_name, false,
6777 true,
6778 map_descriptor_btype,
6779 bloc);
6781 Translate_context context(gogo, NULL, NULL, NULL);
6782 context.set_is_const();
6783 Bexpression* binitializer = initializer->get_backend(&context);
6785 gogo->backend()->immutable_struct_set_init(bvar, mangled_name, false, true,
6786 map_descriptor_btype, bloc,
6787 binitializer);
6789 ins.first->second = bvar;
6790 return bvar;
6793 // Build the type of a map descriptor. This must match the struct
6794 // __go_map_descriptor in libgo/runtime/map.h.
6796 Type*
6797 Map_type::make_map_descriptor_type()
6799 static Type* ret;
6800 if (ret == NULL)
6802 Type* ptdt = Type::make_type_descriptor_ptr_type();
6803 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6804 Struct_type* sf =
6805 Type::make_builtin_struct_type(4,
6806 "__map_descriptor", ptdt,
6807 "__entry_size", uintptr_type,
6808 "__key_offset", uintptr_type,
6809 "__val_offset", uintptr_type);
6810 ret = Type::make_builtin_named_type("__go_map_descriptor", sf);
6812 return ret;
6815 // Reflection string for a map.
6817 void
6818 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
6820 ret->append("map[");
6821 this->append_reflection(this->key_type_, gogo, ret);
6822 ret->append("]");
6823 this->append_reflection(this->val_type_, gogo, ret);
6826 // Generate GC symbol for a map.
6828 void
6829 Map_type::do_gc_symbol(Gogo*, Expression_list** vals,
6830 Expression** offset, int)
6832 // TODO(cmang): Generate GC data for the Map elements.
6833 Location bloc = Linemap::predeclared_location();
6834 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6836 mpz_t opval;
6837 mpz_init_set_ui(opval, GC_APTR);
6838 (*vals)->push_back(Expression::make_integer(&opval, uintptr_type, bloc));
6839 mpz_clear(opval);
6840 (*vals)->push_back(*offset);
6841 this->advance_gc_offset(offset);
6844 // Mangled name for a map.
6846 void
6847 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6849 ret->push_back('M');
6850 this->append_mangled_name(this->key_type_, gogo, ret);
6851 ret->append("__");
6852 this->append_mangled_name(this->val_type_, gogo, ret);
6855 // Export a map type.
6857 void
6858 Map_type::do_export(Export* exp) const
6860 exp->write_c_string("map [");
6861 exp->write_type(this->key_type_);
6862 exp->write_c_string("] ");
6863 exp->write_type(this->val_type_);
6866 // Import a map type.
6868 Map_type*
6869 Map_type::do_import(Import* imp)
6871 imp->require_c_string("map [");
6872 Type* key_type = imp->read_type();
6873 imp->require_c_string("] ");
6874 Type* val_type = imp->read_type();
6875 return Type::make_map_type(key_type, val_type, imp->location());
6878 // Make a map type.
6880 Map_type*
6881 Type::make_map_type(Type* key_type, Type* val_type, Location location)
6883 return new Map_type(key_type, val_type, location);
6886 // Class Channel_type.
6888 // Hash code.
6890 unsigned int
6891 Channel_type::do_hash_for_method(Gogo* gogo) const
6893 unsigned int ret = 0;
6894 if (this->may_send_)
6895 ret += 1;
6896 if (this->may_receive_)
6897 ret += 2;
6898 if (this->element_type_ != NULL)
6899 ret += this->element_type_->hash_for_method(gogo) << 2;
6900 return ret << 3;
6903 // Whether this type is the same as T.
6905 bool
6906 Channel_type::is_identical(const Channel_type* t,
6907 bool errors_are_identical) const
6909 if (!Type::are_identical(this->element_type(), t->element_type(),
6910 errors_are_identical, NULL))
6911 return false;
6912 return (this->may_send_ == t->may_send_
6913 && this->may_receive_ == t->may_receive_);
6916 // Return the backend representation for a channel type. A channel is a pointer
6917 // to a __go_channel struct. The __go_channel struct is defined in
6918 // libgo/runtime/channel.h.
6920 Btype*
6921 Channel_type::do_get_backend(Gogo* gogo)
6923 static Btype* backend_channel_type;
6924 if (backend_channel_type == NULL)
6926 std::vector<Backend::Btyped_identifier> bfields;
6927 Btype* bt = gogo->backend()->struct_type(bfields);
6928 bt = gogo->backend()->named_type("__go_channel", bt,
6929 Linemap::predeclared_location());
6930 backend_channel_type = gogo->backend()->pointer_type(bt);
6932 return backend_channel_type;
6935 // Build a type descriptor for a channel type.
6937 Type*
6938 Channel_type::make_chan_type_descriptor_type()
6940 static Type* ret;
6941 if (ret == NULL)
6943 Type* tdt = Type::make_type_descriptor_type();
6944 Type* ptdt = Type::make_type_descriptor_ptr_type();
6946 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6948 Struct_type* sf =
6949 Type::make_builtin_struct_type(3,
6950 "", tdt,
6951 "elem", ptdt,
6952 "dir", uintptr_type);
6954 ret = Type::make_builtin_named_type("ChanType", sf);
6957 return ret;
6960 // Build a type descriptor for a map type.
6962 Expression*
6963 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6965 Location bloc = Linemap::predeclared_location();
6967 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
6969 const Struct_field_list* fields = ctdt->struct_type()->fields();
6971 Expression_list* vals = new Expression_list();
6972 vals->reserve(3);
6974 Struct_field_list::const_iterator p = fields->begin();
6975 go_assert(p->is_field_name("commonType"));
6976 vals->push_back(this->type_descriptor_constructor(gogo,
6977 RUNTIME_TYPE_KIND_CHAN,
6978 name, NULL, true));
6980 ++p;
6981 go_assert(p->is_field_name("elem"));
6982 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
6984 ++p;
6985 go_assert(p->is_field_name("dir"));
6986 // These bits must match the ones in libgo/runtime/go-type.h.
6987 int val = 0;
6988 if (this->may_receive_)
6989 val |= 1;
6990 if (this->may_send_)
6991 val |= 2;
6992 mpz_t iv;
6993 mpz_init_set_ui(iv, val);
6994 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
6995 mpz_clear(iv);
6997 ++p;
6998 go_assert(p == fields->end());
7000 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
7003 // Reflection string.
7005 void
7006 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
7008 if (!this->may_send_)
7009 ret->append("<-");
7010 ret->append("chan");
7011 if (!this->may_receive_)
7012 ret->append("<-");
7013 ret->push_back(' ');
7014 this->append_reflection(this->element_type_, gogo, ret);
7017 // Generate GC symbol for channels.
7019 void
7020 Channel_type::do_gc_symbol(Gogo*, Expression_list** vals,
7021 Expression** offset, int)
7023 Location bloc = Linemap::predeclared_location();
7024 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7026 mpz_t opval;
7027 mpz_init_set_ui(opval, GC_CHAN_PTR);
7028 (*vals)->push_back(Expression::make_integer(&opval, uintptr_type, bloc));
7029 mpz_clear(opval);
7030 (*vals)->push_back(*offset);
7032 Type* unsafeptr_type = Type::make_pointer_type(Type::make_void_type());
7033 Expression* type_descriptor =
7034 Expression::make_type_descriptor(this, bloc);
7035 type_descriptor =
7036 Expression::make_unsafe_cast(unsafeptr_type, type_descriptor, bloc);
7037 (*vals)->push_back(type_descriptor);
7038 this->advance_gc_offset(offset);
7041 // Mangled name.
7043 void
7044 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7046 ret->push_back('C');
7047 this->append_mangled_name(this->element_type_, gogo, ret);
7048 if (this->may_send_)
7049 ret->push_back('s');
7050 if (this->may_receive_)
7051 ret->push_back('r');
7052 ret->push_back('e');
7055 // Export.
7057 void
7058 Channel_type::do_export(Export* exp) const
7060 exp->write_c_string("chan ");
7061 if (this->may_send_ && !this->may_receive_)
7062 exp->write_c_string("-< ");
7063 else if (this->may_receive_ && !this->may_send_)
7064 exp->write_c_string("<- ");
7065 exp->write_type(this->element_type_);
7068 // Import.
7070 Channel_type*
7071 Channel_type::do_import(Import* imp)
7073 imp->require_c_string("chan ");
7075 bool may_send;
7076 bool may_receive;
7077 if (imp->match_c_string("-< "))
7079 imp->advance(3);
7080 may_send = true;
7081 may_receive = false;
7083 else if (imp->match_c_string("<- "))
7085 imp->advance(3);
7086 may_receive = true;
7087 may_send = false;
7089 else
7091 may_send = true;
7092 may_receive = true;
7095 Type* element_type = imp->read_type();
7097 return Type::make_channel_type(may_send, may_receive, element_type);
7100 // Make a new channel type.
7102 Channel_type*
7103 Type::make_channel_type(bool send, bool receive, Type* element_type)
7105 return new Channel_type(send, receive, element_type);
7108 // Class Interface_type.
7110 // Return the list of methods.
7112 const Typed_identifier_list*
7113 Interface_type::methods() const
7115 go_assert(this->methods_are_finalized_ || saw_errors());
7116 return this->all_methods_;
7119 // Return the number of methods.
7121 size_t
7122 Interface_type::method_count() const
7124 go_assert(this->methods_are_finalized_ || saw_errors());
7125 return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
7128 // Traversal.
7131 Interface_type::do_traverse(Traverse* traverse)
7133 Typed_identifier_list* methods = (this->methods_are_finalized_
7134 ? this->all_methods_
7135 : this->parse_methods_);
7136 if (methods == NULL)
7137 return TRAVERSE_CONTINUE;
7138 return methods->traverse(traverse);
7141 // Finalize the methods. This handles interface inheritance.
7143 void
7144 Interface_type::finalize_methods()
7146 if (this->methods_are_finalized_)
7147 return;
7148 this->methods_are_finalized_ = true;
7149 if (this->parse_methods_ == NULL)
7150 return;
7152 this->all_methods_ = new Typed_identifier_list();
7153 this->all_methods_->reserve(this->parse_methods_->size());
7154 Typed_identifier_list inherit;
7155 for (Typed_identifier_list::const_iterator pm =
7156 this->parse_methods_->begin();
7157 pm != this->parse_methods_->end();
7158 ++pm)
7160 const Typed_identifier* p = &*pm;
7161 if (p->name().empty())
7162 inherit.push_back(*p);
7163 else if (this->find_method(p->name()) == NULL)
7164 this->all_methods_->push_back(*p);
7165 else
7166 error_at(p->location(), "duplicate method %qs",
7167 Gogo::message_name(p->name()).c_str());
7170 std::vector<Named_type*> seen;
7171 seen.reserve(inherit.size());
7172 bool issued_recursive_error = false;
7173 while (!inherit.empty())
7175 Type* t = inherit.back().type();
7176 Location tl = inherit.back().location();
7177 inherit.pop_back();
7179 Interface_type* it = t->interface_type();
7180 if (it == NULL)
7182 if (!t->is_error())
7183 error_at(tl, "interface contains embedded non-interface");
7184 continue;
7186 if (it == this)
7188 if (!issued_recursive_error)
7190 error_at(tl, "invalid recursive interface");
7191 issued_recursive_error = true;
7193 continue;
7196 Named_type* nt = t->named_type();
7197 if (nt != NULL && it->parse_methods_ != NULL)
7199 std::vector<Named_type*>::const_iterator q;
7200 for (q = seen.begin(); q != seen.end(); ++q)
7202 if (*q == nt)
7204 error_at(tl, "inherited interface loop");
7205 break;
7208 if (q != seen.end())
7209 continue;
7210 seen.push_back(nt);
7213 const Typed_identifier_list* imethods = it->parse_methods_;
7214 if (imethods == NULL)
7215 continue;
7216 for (Typed_identifier_list::const_iterator q = imethods->begin();
7217 q != imethods->end();
7218 ++q)
7220 if (q->name().empty())
7221 inherit.push_back(*q);
7222 else if (this->find_method(q->name()) == NULL)
7223 this->all_methods_->push_back(Typed_identifier(q->name(),
7224 q->type(), tl));
7225 else
7226 error_at(tl, "inherited method %qs is ambiguous",
7227 Gogo::message_name(q->name()).c_str());
7231 if (!this->all_methods_->empty())
7232 this->all_methods_->sort_by_name();
7233 else
7235 delete this->all_methods_;
7236 this->all_methods_ = NULL;
7240 // Return the method NAME, or NULL.
7242 const Typed_identifier*
7243 Interface_type::find_method(const std::string& name) const
7245 go_assert(this->methods_are_finalized_);
7246 if (this->all_methods_ == NULL)
7247 return NULL;
7248 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
7249 p != this->all_methods_->end();
7250 ++p)
7251 if (p->name() == name)
7252 return &*p;
7253 return NULL;
7256 // Return the method index.
7258 size_t
7259 Interface_type::method_index(const std::string& name) const
7261 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
7262 size_t ret = 0;
7263 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
7264 p != this->all_methods_->end();
7265 ++p, ++ret)
7266 if (p->name() == name)
7267 return ret;
7268 go_unreachable();
7271 // Return whether NAME is an unexported method, for better error
7272 // reporting.
7274 bool
7275 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
7277 go_assert(this->methods_are_finalized_);
7278 if (this->all_methods_ == NULL)
7279 return false;
7280 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
7281 p != this->all_methods_->end();
7282 ++p)
7284 const std::string& method_name(p->name());
7285 if (Gogo::is_hidden_name(method_name)
7286 && name == Gogo::unpack_hidden_name(method_name)
7287 && gogo->pack_hidden_name(name, false) != method_name)
7288 return true;
7290 return false;
7293 // Whether this type is identical with T.
7295 bool
7296 Interface_type::is_identical(const Interface_type* t,
7297 bool errors_are_identical) const
7299 // If methods have not been finalized, then we are asking whether
7300 // func redeclarations are the same. This is an error, so for
7301 // simplicity we say they are never the same.
7302 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
7303 return false;
7305 // We require the same methods with the same types. The methods
7306 // have already been sorted.
7307 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
7308 return this->all_methods_ == t->all_methods_;
7310 if (this->assume_identical(this, t) || t->assume_identical(t, this))
7311 return true;
7313 Assume_identical* hold_ai = this->assume_identical_;
7314 Assume_identical ai;
7315 ai.t1 = this;
7316 ai.t2 = t;
7317 ai.next = hold_ai;
7318 this->assume_identical_ = &ai;
7320 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
7321 Typed_identifier_list::const_iterator p2;
7322 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
7324 if (p1 == this->all_methods_->end())
7325 break;
7326 if (p1->name() != p2->name()
7327 || !Type::are_identical(p1->type(), p2->type(),
7328 errors_are_identical, NULL))
7329 break;
7332 this->assume_identical_ = hold_ai;
7334 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
7337 // Return true if T1 and T2 are assumed to be identical during a type
7338 // comparison.
7340 bool
7341 Interface_type::assume_identical(const Interface_type* t1,
7342 const Interface_type* t2) const
7344 for (Assume_identical* p = this->assume_identical_;
7345 p != NULL;
7346 p = p->next)
7347 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
7348 return true;
7349 return false;
7352 // Whether we can assign the interface type T to this type. The types
7353 // are known to not be identical. An interface assignment is only
7354 // permitted if T is known to implement all methods in THIS.
7355 // Otherwise a type guard is required.
7357 bool
7358 Interface_type::is_compatible_for_assign(const Interface_type* t,
7359 std::string* reason) const
7361 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
7362 if (this->all_methods_ == NULL)
7363 return true;
7364 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
7365 p != this->all_methods_->end();
7366 ++p)
7368 const Typed_identifier* m = t->find_method(p->name());
7369 if (m == NULL)
7371 if (reason != NULL)
7373 char buf[200];
7374 snprintf(buf, sizeof buf,
7375 _("need explicit conversion; missing method %s%s%s"),
7376 open_quote, Gogo::message_name(p->name()).c_str(),
7377 close_quote);
7378 reason->assign(buf);
7380 return false;
7383 std::string subreason;
7384 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
7386 if (reason != NULL)
7388 std::string n = Gogo::message_name(p->name());
7389 size_t len = 100 + n.length() + subreason.length();
7390 char* buf = new char[len];
7391 if (subreason.empty())
7392 snprintf(buf, len, _("incompatible type for method %s%s%s"),
7393 open_quote, n.c_str(), close_quote);
7394 else
7395 snprintf(buf, len,
7396 _("incompatible type for method %s%s%s (%s)"),
7397 open_quote, n.c_str(), close_quote,
7398 subreason.c_str());
7399 reason->assign(buf);
7400 delete[] buf;
7402 return false;
7406 return true;
7409 // Hash code.
7411 unsigned int
7412 Interface_type::do_hash_for_method(Gogo*) const
7414 go_assert(this->methods_are_finalized_);
7415 unsigned int ret = 0;
7416 if (this->all_methods_ != NULL)
7418 for (Typed_identifier_list::const_iterator p =
7419 this->all_methods_->begin();
7420 p != this->all_methods_->end();
7421 ++p)
7423 ret = Type::hash_string(p->name(), ret);
7424 // We don't use the method type in the hash, to avoid
7425 // infinite recursion if an interface method uses a type
7426 // which is an interface which inherits from the interface
7427 // itself.
7428 // type T interface { F() interface {T}}
7429 ret <<= 1;
7432 return ret;
7435 // Return true if T implements the interface. If it does not, and
7436 // REASON is not NULL, set *REASON to a useful error message.
7438 bool
7439 Interface_type::implements_interface(const Type* t, std::string* reason) const
7441 go_assert(this->methods_are_finalized_);
7442 if (this->all_methods_ == NULL)
7443 return true;
7445 bool is_pointer = false;
7446 const Named_type* nt = t->named_type();
7447 const Struct_type* st = t->struct_type();
7448 // If we start with a named type, we don't dereference it to find
7449 // methods.
7450 if (nt == NULL)
7452 const Type* pt = t->points_to();
7453 if (pt != NULL)
7455 // If T is a pointer to a named type, then we need to look at
7456 // the type to which it points.
7457 is_pointer = true;
7458 nt = pt->named_type();
7459 st = pt->struct_type();
7463 // If we have a named type, get the methods from it rather than from
7464 // any struct type.
7465 if (nt != NULL)
7466 st = NULL;
7468 // Only named and struct types have methods.
7469 if (nt == NULL && st == NULL)
7471 if (reason != NULL)
7473 if (t->points_to() != NULL
7474 && t->points_to()->interface_type() != NULL)
7475 reason->assign(_("pointer to interface type has no methods"));
7476 else
7477 reason->assign(_("type has no methods"));
7479 return false;
7482 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
7484 if (reason != NULL)
7486 if (t->points_to() != NULL
7487 && t->points_to()->interface_type() != NULL)
7488 reason->assign(_("pointer to interface type has no methods"));
7489 else
7490 reason->assign(_("type has no methods"));
7492 return false;
7495 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
7496 p != this->all_methods_->end();
7497 ++p)
7499 bool is_ambiguous = false;
7500 Method* m = (nt != NULL
7501 ? nt->method_function(p->name(), &is_ambiguous)
7502 : st->method_function(p->name(), &is_ambiguous));
7503 if (m == NULL)
7505 if (reason != NULL)
7507 std::string n = Gogo::message_name(p->name());
7508 size_t len = n.length() + 100;
7509 char* buf = new char[len];
7510 if (is_ambiguous)
7511 snprintf(buf, len, _("ambiguous method %s%s%s"),
7512 open_quote, n.c_str(), close_quote);
7513 else
7514 snprintf(buf, len, _("missing method %s%s%s"),
7515 open_quote, n.c_str(), close_quote);
7516 reason->assign(buf);
7517 delete[] buf;
7519 return false;
7522 Function_type *p_fn_type = p->type()->function_type();
7523 Function_type* m_fn_type = m->type()->function_type();
7524 go_assert(p_fn_type != NULL && m_fn_type != NULL);
7525 std::string subreason;
7526 if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
7528 if (reason != NULL)
7530 std::string n = Gogo::message_name(p->name());
7531 size_t len = 100 + n.length() + subreason.length();
7532 char* buf = new char[len];
7533 if (subreason.empty())
7534 snprintf(buf, len, _("incompatible type for method %s%s%s"),
7535 open_quote, n.c_str(), close_quote);
7536 else
7537 snprintf(buf, len,
7538 _("incompatible type for method %s%s%s (%s)"),
7539 open_quote, n.c_str(), close_quote,
7540 subreason.c_str());
7541 reason->assign(buf);
7542 delete[] buf;
7544 return false;
7547 if (!is_pointer && !m->is_value_method())
7549 if (reason != NULL)
7551 std::string n = Gogo::message_name(p->name());
7552 size_t len = 100 + n.length();
7553 char* buf = new char[len];
7554 snprintf(buf, len,
7555 _("method %s%s%s requires a pointer receiver"),
7556 open_quote, n.c_str(), close_quote);
7557 reason->assign(buf);
7558 delete[] buf;
7560 return false;
7563 // If the magic //go:nointerface comment was used, the method
7564 // may not be used to implement interfaces.
7565 if (m->nointerface())
7567 if (reason != NULL)
7569 std::string n = Gogo::message_name(p->name());
7570 size_t len = 100 + n.length();
7571 char* buf = new char[len];
7572 snprintf(buf, len,
7573 _("method %s%s%s is marked go:nointerface"),
7574 open_quote, n.c_str(), close_quote);
7575 reason->assign(buf);
7576 delete[] buf;
7578 return false;
7582 return true;
7585 // Return the backend representation of the empty interface type. We
7586 // use the same struct for all empty interfaces.
7588 Btype*
7589 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
7591 static Btype* empty_interface_type;
7592 if (empty_interface_type == NULL)
7594 std::vector<Backend::Btyped_identifier> bfields(2);
7596 Location bloc = Linemap::predeclared_location();
7598 Type* pdt = Type::make_type_descriptor_ptr_type();
7599 bfields[0].name = "__type_descriptor";
7600 bfields[0].btype = pdt->get_backend(gogo);
7601 bfields[0].location = bloc;
7603 Type* vt = Type::make_pointer_type(Type::make_void_type());
7604 bfields[1].name = "__object";
7605 bfields[1].btype = vt->get_backend(gogo);
7606 bfields[1].location = bloc;
7608 empty_interface_type = gogo->backend()->struct_type(bfields);
7610 return empty_interface_type;
7613 // Return a pointer to the backend representation of the method table.
7615 Btype*
7616 Interface_type::get_backend_methods(Gogo* gogo)
7618 if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
7619 return this->bmethods_;
7621 Location loc = this->location();
7623 std::vector<Backend::Btyped_identifier>
7624 mfields(this->all_methods_->size() + 1);
7626 Type* pdt = Type::make_type_descriptor_ptr_type();
7627 mfields[0].name = "__type_descriptor";
7628 mfields[0].btype = pdt->get_backend(gogo);
7629 mfields[0].location = loc;
7631 std::string last_name = "";
7632 size_t i = 1;
7633 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
7634 p != this->all_methods_->end();
7635 ++p, ++i)
7637 // The type of the method in Go only includes the parameters.
7638 // The actual method also has a receiver, which is always a
7639 // pointer. We need to add that pointer type here in order to
7640 // generate the correct type for the backend.
7641 Function_type* ft = p->type()->function_type();
7642 go_assert(ft->receiver() == NULL);
7644 const Typed_identifier_list* params = ft->parameters();
7645 Typed_identifier_list* mparams = new Typed_identifier_list();
7646 if (params != NULL)
7647 mparams->reserve(params->size() + 1);
7648 Type* vt = Type::make_pointer_type(Type::make_void_type());
7649 mparams->push_back(Typed_identifier("", vt, ft->location()));
7650 if (params != NULL)
7652 for (Typed_identifier_list::const_iterator pp = params->begin();
7653 pp != params->end();
7654 ++pp)
7655 mparams->push_back(*pp);
7658 Typed_identifier_list* mresults = (ft->results() == NULL
7659 ? NULL
7660 : ft->results()->copy());
7661 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
7662 ft->location());
7664 mfields[i].name = Gogo::unpack_hidden_name(p->name());
7665 mfields[i].btype = mft->get_backend_fntype(gogo);
7666 mfields[i].location = loc;
7668 // Sanity check: the names should be sorted.
7669 go_assert(p->name() > last_name);
7670 last_name = p->name();
7673 Btype* st = gogo->backend()->struct_type(mfields);
7674 Btype* ret = gogo->backend()->pointer_type(st);
7676 if (this->bmethods_ != NULL && this->bmethods_is_placeholder_)
7677 gogo->backend()->set_placeholder_pointer_type(this->bmethods_, ret);
7678 this->bmethods_ = ret;
7679 this->bmethods_is_placeholder_ = false;
7680 return ret;
7683 // Return a placeholder for the pointer to the backend methods table.
7685 Btype*
7686 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
7688 if (this->bmethods_ == NULL)
7690 Location loc = this->location();
7691 this->bmethods_ = gogo->backend()->placeholder_pointer_type("", loc,
7692 false);
7693 this->bmethods_is_placeholder_ = true;
7695 return this->bmethods_;
7698 // Return the fields of a non-empty interface type. This is not
7699 // declared in types.h so that types.h doesn't have to #include
7700 // backend.h.
7702 static void
7703 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
7704 bool use_placeholder,
7705 std::vector<Backend::Btyped_identifier>* bfields)
7707 Location loc = type->location();
7709 bfields->resize(2);
7711 (*bfields)[0].name = "__methods";
7712 (*bfields)[0].btype = (use_placeholder
7713 ? type->get_backend_methods_placeholder(gogo)
7714 : type->get_backend_methods(gogo));
7715 (*bfields)[0].location = loc;
7717 Type* vt = Type::make_pointer_type(Type::make_void_type());
7718 (*bfields)[1].name = "__object";
7719 (*bfields)[1].btype = vt->get_backend(gogo);
7720 (*bfields)[1].location = Linemap::predeclared_location();
7723 // Return the backend representation for an interface type. An interface is a
7724 // pointer to a struct. The struct has three fields. The first field is a
7725 // pointer to the type descriptor for the dynamic type of the object.
7726 // The second field is a pointer to a table of methods for the
7727 // interface to be used with the object. The third field is the value
7728 // of the object itself.
7730 Btype*
7731 Interface_type::do_get_backend(Gogo* gogo)
7733 if (this->is_empty())
7734 return Interface_type::get_backend_empty_interface_type(gogo);
7735 else
7737 if (this->interface_btype_ != NULL)
7738 return this->interface_btype_;
7739 this->interface_btype_ =
7740 gogo->backend()->placeholder_struct_type("", this->location_);
7741 std::vector<Backend::Btyped_identifier> bfields;
7742 get_backend_interface_fields(gogo, this, false, &bfields);
7743 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
7744 bfields))
7745 this->interface_btype_ = gogo->backend()->error_type();
7746 return this->interface_btype_;
7750 // Finish the backend representation of the methods.
7752 void
7753 Interface_type::finish_backend_methods(Gogo* gogo)
7755 if (!this->is_empty())
7757 const Typed_identifier_list* methods = this->methods();
7758 if (methods != NULL)
7760 for (Typed_identifier_list::const_iterator p = methods->begin();
7761 p != methods->end();
7762 ++p)
7763 p->type()->get_backend(gogo);
7766 // Getting the backend methods now will set the placeholder
7767 // pointer.
7768 this->get_backend_methods(gogo);
7772 // The type of an interface type descriptor.
7774 Type*
7775 Interface_type::make_interface_type_descriptor_type()
7777 static Type* ret;
7778 if (ret == NULL)
7780 Type* tdt = Type::make_type_descriptor_type();
7781 Type* ptdt = Type::make_type_descriptor_ptr_type();
7783 Type* string_type = Type::lookup_string_type();
7784 Type* pointer_string_type = Type::make_pointer_type(string_type);
7786 Struct_type* sm =
7787 Type::make_builtin_struct_type(3,
7788 "name", pointer_string_type,
7789 "pkgPath", pointer_string_type,
7790 "typ", ptdt);
7792 Type* nsm = Type::make_builtin_named_type("imethod", sm);
7794 Type* slice_nsm = Type::make_array_type(nsm, NULL);
7796 Struct_type* s = Type::make_builtin_struct_type(2,
7797 "", tdt,
7798 "methods", slice_nsm);
7800 ret = Type::make_builtin_named_type("InterfaceType", s);
7803 return ret;
7806 // Build a type descriptor for an interface type.
7808 Expression*
7809 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7811 Location bloc = Linemap::predeclared_location();
7813 Type* itdt = Interface_type::make_interface_type_descriptor_type();
7815 const Struct_field_list* ifields = itdt->struct_type()->fields();
7817 Expression_list* ivals = new Expression_list();
7818 ivals->reserve(2);
7820 Struct_field_list::const_iterator pif = ifields->begin();
7821 go_assert(pif->is_field_name("commonType"));
7822 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
7823 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
7824 true));
7826 ++pif;
7827 go_assert(pif->is_field_name("methods"));
7829 Expression_list* methods = new Expression_list();
7830 if (this->all_methods_ != NULL)
7832 Type* elemtype = pif->type()->array_type()->element_type();
7834 methods->reserve(this->all_methods_->size());
7835 for (Typed_identifier_list::const_iterator pm =
7836 this->all_methods_->begin();
7837 pm != this->all_methods_->end();
7838 ++pm)
7840 const Struct_field_list* mfields = elemtype->struct_type()->fields();
7842 Expression_list* mvals = new Expression_list();
7843 mvals->reserve(3);
7845 Struct_field_list::const_iterator pmf = mfields->begin();
7846 go_assert(pmf->is_field_name("name"));
7847 std::string s = Gogo::unpack_hidden_name(pm->name());
7848 Expression* e = Expression::make_string(s, bloc);
7849 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7851 ++pmf;
7852 go_assert(pmf->is_field_name("pkgPath"));
7853 if (!Gogo::is_hidden_name(pm->name()))
7854 mvals->push_back(Expression::make_nil(bloc));
7855 else
7857 s = Gogo::hidden_name_pkgpath(pm->name());
7858 e = Expression::make_string(s, bloc);
7859 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7862 ++pmf;
7863 go_assert(pmf->is_field_name("typ"));
7864 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
7866 ++pmf;
7867 go_assert(pmf == mfields->end());
7869 e = Expression::make_struct_composite_literal(elemtype, mvals,
7870 bloc);
7871 methods->push_back(e);
7875 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
7876 methods, bloc));
7878 ++pif;
7879 go_assert(pif == ifields->end());
7881 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
7884 // Reflection string.
7886 void
7887 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
7889 ret->append("interface {");
7890 const Typed_identifier_list* methods = this->parse_methods_;
7891 if (methods != NULL)
7893 ret->push_back(' ');
7894 for (Typed_identifier_list::const_iterator p = methods->begin();
7895 p != methods->end();
7896 ++p)
7898 if (p != methods->begin())
7899 ret->append("; ");
7900 if (p->name().empty())
7901 this->append_reflection(p->type(), gogo, ret);
7902 else
7904 if (!Gogo::is_hidden_name(p->name()))
7905 ret->append(p->name());
7906 else if (gogo->pkgpath_from_option())
7907 ret->append(p->name().substr(1));
7908 else
7910 // If no -fgo-pkgpath option, backward compatibility
7911 // for how this used to work before -fgo-pkgpath was
7912 // introduced.
7913 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
7914 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
7915 ret->push_back('.');
7916 ret->append(Gogo::unpack_hidden_name(p->name()));
7918 std::string sub = p->type()->reflection(gogo);
7919 go_assert(sub.compare(0, 4, "func") == 0);
7920 sub = sub.substr(4);
7921 ret->append(sub);
7924 ret->push_back(' ');
7926 ret->append("}");
7929 // Generate GC symbol for interface types.
7931 void
7932 Interface_type::do_gc_symbol(Gogo*, Expression_list** vals,
7933 Expression** offset, int)
7935 Location bloc = Linemap::predeclared_location();
7936 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7938 mpz_t opval;
7939 mpz_init_set_ui(opval, this->is_empty() ? GC_EFACE : GC_IFACE);
7940 (*vals)->push_back(Expression::make_integer(&opval, uintptr_type,
7941 bloc));
7942 mpz_clear(opval);
7943 (*vals)->push_back(*offset);
7944 this->advance_gc_offset(offset);
7947 // Mangled name.
7949 void
7950 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7952 go_assert(this->methods_are_finalized_);
7954 ret->push_back('I');
7956 const Typed_identifier_list* methods = this->all_methods_;
7957 if (methods != NULL && !this->seen_)
7959 this->seen_ = true;
7960 for (Typed_identifier_list::const_iterator p = methods->begin();
7961 p != methods->end();
7962 ++p)
7964 if (!p->name().empty())
7966 std::string n;
7967 if (!Gogo::is_hidden_name(p->name()))
7968 n = p->name();
7969 else
7971 n = ".";
7972 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
7973 n.append(Gogo::pkgpath_for_symbol(pkgpath));
7974 n.append(1, '.');
7975 n.append(Gogo::unpack_hidden_name(p->name()));
7977 char buf[20];
7978 snprintf(buf, sizeof buf, "%u_",
7979 static_cast<unsigned int>(n.length()));
7980 ret->append(buf);
7981 ret->append(n);
7983 this->append_mangled_name(p->type(), gogo, ret);
7985 this->seen_ = false;
7988 ret->push_back('e');
7991 // Export.
7993 void
7994 Interface_type::do_export(Export* exp) const
7996 exp->write_c_string("interface { ");
7998 const Typed_identifier_list* methods = this->parse_methods_;
7999 if (methods != NULL)
8001 for (Typed_identifier_list::const_iterator pm = methods->begin();
8002 pm != methods->end();
8003 ++pm)
8005 if (pm->name().empty())
8007 exp->write_c_string("? ");
8008 exp->write_type(pm->type());
8010 else
8012 exp->write_string(pm->name());
8013 exp->write_c_string(" (");
8015 const Function_type* fntype = pm->type()->function_type();
8017 bool first = true;
8018 const Typed_identifier_list* parameters = fntype->parameters();
8019 if (parameters != NULL)
8021 bool is_varargs = fntype->is_varargs();
8022 for (Typed_identifier_list::const_iterator pp =
8023 parameters->begin();
8024 pp != parameters->end();
8025 ++pp)
8027 if (first)
8028 first = false;
8029 else
8030 exp->write_c_string(", ");
8031 exp->write_name(pp->name());
8032 exp->write_c_string(" ");
8033 if (!is_varargs || pp + 1 != parameters->end())
8034 exp->write_type(pp->type());
8035 else
8037 exp->write_c_string("...");
8038 Type *pptype = pp->type();
8039 exp->write_type(pptype->array_type()->element_type());
8044 exp->write_c_string(")");
8046 const Typed_identifier_list* results = fntype->results();
8047 if (results != NULL)
8049 exp->write_c_string(" ");
8050 if (results->size() == 1 && results->begin()->name().empty())
8051 exp->write_type(results->begin()->type());
8052 else
8054 first = true;
8055 exp->write_c_string("(");
8056 for (Typed_identifier_list::const_iterator p =
8057 results->begin();
8058 p != results->end();
8059 ++p)
8061 if (first)
8062 first = false;
8063 else
8064 exp->write_c_string(", ");
8065 exp->write_name(p->name());
8066 exp->write_c_string(" ");
8067 exp->write_type(p->type());
8069 exp->write_c_string(")");
8074 exp->write_c_string("; ");
8078 exp->write_c_string("}");
8081 // Import an interface type.
8083 Interface_type*
8084 Interface_type::do_import(Import* imp)
8086 imp->require_c_string("interface { ");
8088 Typed_identifier_list* methods = new Typed_identifier_list;
8089 while (imp->peek_char() != '}')
8091 std::string name = imp->read_identifier();
8093 if (name == "?")
8095 imp->require_c_string(" ");
8096 Type* t = imp->read_type();
8097 methods->push_back(Typed_identifier("", t, imp->location()));
8098 imp->require_c_string("; ");
8099 continue;
8102 imp->require_c_string(" (");
8104 Typed_identifier_list* parameters;
8105 bool is_varargs = false;
8106 if (imp->peek_char() == ')')
8107 parameters = NULL;
8108 else
8110 parameters = new Typed_identifier_list;
8111 while (true)
8113 std::string name = imp->read_name();
8114 imp->require_c_string(" ");
8116 if (imp->match_c_string("..."))
8118 imp->advance(3);
8119 is_varargs = true;
8122 Type* ptype = imp->read_type();
8123 if (is_varargs)
8124 ptype = Type::make_array_type(ptype, NULL);
8125 parameters->push_back(Typed_identifier(name, ptype,
8126 imp->location()));
8127 if (imp->peek_char() != ',')
8128 break;
8129 go_assert(!is_varargs);
8130 imp->require_c_string(", ");
8133 imp->require_c_string(")");
8135 Typed_identifier_list* results;
8136 if (imp->peek_char() != ' ')
8137 results = NULL;
8138 else
8140 results = new Typed_identifier_list;
8141 imp->advance(1);
8142 if (imp->peek_char() != '(')
8144 Type* rtype = imp->read_type();
8145 results->push_back(Typed_identifier("", rtype, imp->location()));
8147 else
8149 imp->advance(1);
8150 while (true)
8152 std::string name = imp->read_name();
8153 imp->require_c_string(" ");
8154 Type* rtype = imp->read_type();
8155 results->push_back(Typed_identifier(name, rtype,
8156 imp->location()));
8157 if (imp->peek_char() != ',')
8158 break;
8159 imp->require_c_string(", ");
8161 imp->require_c_string(")");
8165 Function_type* fntype = Type::make_function_type(NULL, parameters,
8166 results,
8167 imp->location());
8168 if (is_varargs)
8169 fntype->set_is_varargs();
8170 methods->push_back(Typed_identifier(name, fntype, imp->location()));
8172 imp->require_c_string("; ");
8175 imp->require_c_string("}");
8177 if (methods->empty())
8179 delete methods;
8180 methods = NULL;
8183 return Type::make_interface_type(methods, imp->location());
8186 // Make an interface type.
8188 Interface_type*
8189 Type::make_interface_type(Typed_identifier_list* methods,
8190 Location location)
8192 return new Interface_type(methods, location);
8195 // Make an empty interface type.
8197 Interface_type*
8198 Type::make_empty_interface_type(Location location)
8200 Interface_type* ret = new Interface_type(NULL, location);
8201 ret->finalize_methods();
8202 return ret;
8205 // Class Method.
8207 // Bind a method to an object.
8209 Expression*
8210 Method::bind_method(Expression* expr, Location location) const
8212 if (this->stub_ == NULL)
8214 // When there is no stub object, the binding is determined by
8215 // the child class.
8216 return this->do_bind_method(expr, location);
8218 return Expression::make_bound_method(expr, this, this->stub_, location);
8221 // Return the named object associated with a method. This may only be
8222 // called after methods are finalized.
8224 Named_object*
8225 Method::named_object() const
8227 if (this->stub_ != NULL)
8228 return this->stub_;
8229 return this->do_named_object();
8232 // Class Named_method.
8234 // The type of the method.
8236 Function_type*
8237 Named_method::do_type() const
8239 if (this->named_object_->is_function())
8240 return this->named_object_->func_value()->type();
8241 else if (this->named_object_->is_function_declaration())
8242 return this->named_object_->func_declaration_value()->type();
8243 else
8244 go_unreachable();
8247 // Return the location of the method receiver.
8249 Location
8250 Named_method::do_receiver_location() const
8252 return this->do_type()->receiver()->location();
8255 // Bind a method to an object.
8257 Expression*
8258 Named_method::do_bind_method(Expression* expr, Location location) const
8260 Named_object* no = this->named_object_;
8261 Bound_method_expression* bme = Expression::make_bound_method(expr, this,
8262 no, location);
8263 // If this is not a local method, and it does not use a stub, then
8264 // the real method expects a different type. We need to cast the
8265 // first argument.
8266 if (this->depth() > 0 && !this->needs_stub_method())
8268 Function_type* ftype = this->do_type();
8269 go_assert(ftype->is_method());
8270 Type* frtype = ftype->receiver()->type();
8271 bme->set_first_argument_type(frtype);
8273 return bme;
8276 // Return whether this method should not participate in interfaces.
8278 bool
8279 Named_method::do_nointerface() const
8281 Named_object* no = this->named_object_;
8282 return no->is_function() && no->func_value()->nointerface();
8285 // Class Interface_method.
8287 // Bind a method to an object.
8289 Expression*
8290 Interface_method::do_bind_method(Expression* expr,
8291 Location location) const
8293 return Expression::make_interface_field_reference(expr, this->name_,
8294 location);
8297 // Class Methods.
8299 // Insert a new method. Return true if it was inserted, false
8300 // otherwise.
8302 bool
8303 Methods::insert(const std::string& name, Method* m)
8305 std::pair<Method_map::iterator, bool> ins =
8306 this->methods_.insert(std::make_pair(name, m));
8307 if (ins.second)
8308 return true;
8309 else
8311 Method* old_method = ins.first->second;
8312 if (m->depth() < old_method->depth())
8314 delete old_method;
8315 ins.first->second = m;
8316 return true;
8318 else
8320 if (m->depth() == old_method->depth())
8321 old_method->set_is_ambiguous();
8322 return false;
8327 // Return the number of unambiguous methods.
8329 size_t
8330 Methods::count() const
8332 size_t ret = 0;
8333 for (Method_map::const_iterator p = this->methods_.begin();
8334 p != this->methods_.end();
8335 ++p)
8336 if (!p->second->is_ambiguous())
8337 ++ret;
8338 return ret;
8341 // Class Named_type.
8343 // Return the name of the type.
8345 const std::string&
8346 Named_type::name() const
8348 return this->named_object_->name();
8351 // Return the name of the type to use in an error message.
8353 std::string
8354 Named_type::message_name() const
8356 return this->named_object_->message_name();
8359 // Whether this is an alias. There are currently only two aliases so
8360 // we just recognize them by name.
8362 bool
8363 Named_type::is_alias() const
8365 if (!this->is_builtin())
8366 return false;
8367 const std::string& name(this->name());
8368 return name == "byte" || name == "rune";
8371 // Return the base type for this type. We have to be careful about
8372 // circular type definitions, which are invalid but may be seen here.
8374 Type*
8375 Named_type::named_base()
8377 if (this->seen_)
8378 return this;
8379 this->seen_ = true;
8380 Type* ret = this->type_->base();
8381 this->seen_ = false;
8382 return ret;
8385 const Type*
8386 Named_type::named_base() const
8388 if (this->seen_)
8389 return this;
8390 this->seen_ = true;
8391 const Type* ret = this->type_->base();
8392 this->seen_ = false;
8393 return ret;
8396 // Return whether this is an error type. We have to be careful about
8397 // circular type definitions, which are invalid but may be seen here.
8399 bool
8400 Named_type::is_named_error_type() const
8402 if (this->seen_)
8403 return false;
8404 this->seen_ = true;
8405 bool ret = this->type_->is_error_type();
8406 this->seen_ = false;
8407 return ret;
8410 // Whether this type is comparable. We have to be careful about
8411 // circular type definitions.
8413 bool
8414 Named_type::named_type_is_comparable(std::string* reason) const
8416 if (this->seen_)
8417 return false;
8418 this->seen_ = true;
8419 bool ret = Type::are_compatible_for_comparison(true, this->type_,
8420 this->type_, reason);
8421 this->seen_ = false;
8422 return ret;
8425 // Add a method to this type.
8427 Named_object*
8428 Named_type::add_method(const std::string& name, Function* function)
8430 if (this->local_methods_ == NULL)
8431 this->local_methods_ = new Bindings(NULL);
8432 return this->local_methods_->add_function(name, NULL, function);
8435 // Add a method declaration to this type.
8437 Named_object*
8438 Named_type::add_method_declaration(const std::string& name, Package* package,
8439 Function_type* type,
8440 Location location)
8442 if (this->local_methods_ == NULL)
8443 this->local_methods_ = new Bindings(NULL);
8444 return this->local_methods_->add_function_declaration(name, package, type,
8445 location);
8448 // Add an existing method to this type.
8450 void
8451 Named_type::add_existing_method(Named_object* no)
8453 if (this->local_methods_ == NULL)
8454 this->local_methods_ = new Bindings(NULL);
8455 this->local_methods_->add_named_object(no);
8458 // Look for a local method NAME, and returns its named object, or NULL
8459 // if not there.
8461 Named_object*
8462 Named_type::find_local_method(const std::string& name) const
8464 if (this->local_methods_ == NULL)
8465 return NULL;
8466 return this->local_methods_->lookup(name);
8469 // Return whether NAME is an unexported field or method, for better
8470 // error reporting.
8472 bool
8473 Named_type::is_unexported_local_method(Gogo* gogo,
8474 const std::string& name) const
8476 Bindings* methods = this->local_methods_;
8477 if (methods != NULL)
8479 for (Bindings::const_declarations_iterator p =
8480 methods->begin_declarations();
8481 p != methods->end_declarations();
8482 ++p)
8484 if (Gogo::is_hidden_name(p->first)
8485 && name == Gogo::unpack_hidden_name(p->first)
8486 && gogo->pack_hidden_name(name, false) != p->first)
8487 return true;
8490 return false;
8493 // Build the complete list of methods for this type, which means
8494 // recursively including all methods for anonymous fields. Create all
8495 // stub methods.
8497 void
8498 Named_type::finalize_methods(Gogo* gogo)
8500 if (this->all_methods_ != NULL)
8501 return;
8503 if (this->local_methods_ != NULL
8504 && (this->points_to() != NULL || this->interface_type() != NULL))
8506 const Bindings* lm = this->local_methods_;
8507 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
8508 p != lm->end_declarations();
8509 ++p)
8510 error_at(p->second->location(),
8511 "invalid pointer or interface receiver type");
8512 delete this->local_methods_;
8513 this->local_methods_ = NULL;
8514 return;
8517 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
8520 // Return the method NAME, or NULL if there isn't one or if it is
8521 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
8522 // ambiguous.
8524 Method*
8525 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
8527 return Type::method_function(this->all_methods_, name, is_ambiguous);
8530 // Return a pointer to the interface method table for this type for
8531 // the interface INTERFACE. IS_POINTER is true if this is for a
8532 // pointer to THIS.
8534 Expression*
8535 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
8537 return Type::interface_method_table(this, interface, is_pointer,
8538 &this->interface_method_tables_,
8539 &this->pointer_interface_method_tables_);
8542 // Look for a use of a complete type within another type. This is
8543 // used to check that we don't try to use a type within itself.
8545 class Find_type_use : public Traverse
8547 public:
8548 Find_type_use(Named_type* find_type)
8549 : Traverse(traverse_types),
8550 find_type_(find_type), found_(false)
8553 // Whether we found the type.
8554 bool
8555 found() const
8556 { return this->found_; }
8558 protected:
8560 type(Type*);
8562 private:
8563 // The type we are looking for.
8564 Named_type* find_type_;
8565 // Whether we found the type.
8566 bool found_;
8569 // Check for FIND_TYPE in TYPE.
8572 Find_type_use::type(Type* type)
8574 if (type->named_type() != NULL && this->find_type_ == type->named_type())
8576 this->found_ = true;
8577 return TRAVERSE_EXIT;
8580 // It's OK if we see a reference to the type in any type which is
8581 // essentially a pointer: a pointer, a slice, a function, a map, or
8582 // a channel.
8583 if (type->points_to() != NULL
8584 || type->is_slice_type()
8585 || type->function_type() != NULL
8586 || type->map_type() != NULL
8587 || type->channel_type() != NULL)
8588 return TRAVERSE_SKIP_COMPONENTS;
8590 // For an interface, a reference to the type in a method type should
8591 // be ignored, but we have to consider direct inheritance. When
8592 // this is called, there may be cases of direct inheritance
8593 // represented as a method with no name.
8594 if (type->interface_type() != NULL)
8596 const Typed_identifier_list* methods = type->interface_type()->methods();
8597 if (methods != NULL)
8599 for (Typed_identifier_list::const_iterator p = methods->begin();
8600 p != methods->end();
8601 ++p)
8603 if (p->name().empty())
8605 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
8606 return TRAVERSE_EXIT;
8610 return TRAVERSE_SKIP_COMPONENTS;
8613 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
8614 // to convert TYPE to the backend representation before we convert
8615 // FIND_TYPE_.
8616 if (type->named_type() != NULL)
8618 switch (type->base()->classification())
8620 case Type::TYPE_ERROR:
8621 case Type::TYPE_BOOLEAN:
8622 case Type::TYPE_INTEGER:
8623 case Type::TYPE_FLOAT:
8624 case Type::TYPE_COMPLEX:
8625 case Type::TYPE_STRING:
8626 case Type::TYPE_NIL:
8627 break;
8629 case Type::TYPE_ARRAY:
8630 case Type::TYPE_STRUCT:
8631 this->find_type_->add_dependency(type->named_type());
8632 break;
8634 case Type::TYPE_NAMED:
8635 case Type::TYPE_FORWARD:
8636 go_assert(saw_errors());
8637 break;
8639 case Type::TYPE_VOID:
8640 case Type::TYPE_SINK:
8641 case Type::TYPE_FUNCTION:
8642 case Type::TYPE_POINTER:
8643 case Type::TYPE_CALL_MULTIPLE_RESULT:
8644 case Type::TYPE_MAP:
8645 case Type::TYPE_CHANNEL:
8646 case Type::TYPE_INTERFACE:
8647 default:
8648 go_unreachable();
8652 return TRAVERSE_CONTINUE;
8655 // Verify that a named type does not refer to itself.
8657 bool
8658 Named_type::do_verify()
8660 if (this->is_verified_)
8661 return true;
8662 this->is_verified_ = true;
8664 Find_type_use find(this);
8665 Type::traverse(this->type_, &find);
8666 if (find.found())
8668 error_at(this->location_, "invalid recursive type %qs",
8669 this->message_name().c_str());
8670 this->is_error_ = true;
8671 return false;
8674 // Check whether any of the local methods overloads an existing
8675 // struct field or interface method. We don't need to check the
8676 // list of methods against itself: that is handled by the Bindings
8677 // code.
8678 if (this->local_methods_ != NULL)
8680 Struct_type* st = this->type_->struct_type();
8681 if (st != NULL)
8683 for (Bindings::const_declarations_iterator p =
8684 this->local_methods_->begin_declarations();
8685 p != this->local_methods_->end_declarations();
8686 ++p)
8688 const std::string& name(p->first);
8689 if (st != NULL && st->find_local_field(name, NULL) != NULL)
8691 error_at(p->second->location(),
8692 "method %qs redeclares struct field name",
8693 Gogo::message_name(name).c_str());
8699 return true;
8702 // Return whether this type is or contains a pointer.
8704 bool
8705 Named_type::do_has_pointer() const
8707 if (this->seen_)
8708 return false;
8709 this->seen_ = true;
8710 bool ret = this->type_->has_pointer();
8711 this->seen_ = false;
8712 return ret;
8715 // Return whether comparisons for this type can use the identity
8716 // function.
8718 bool
8719 Named_type::do_compare_is_identity(Gogo* gogo)
8721 // We don't use this->seen_ here because compare_is_identity may
8722 // call base() later, and that will mess up if seen_ is set here.
8723 if (this->seen_in_compare_is_identity_)
8724 return false;
8725 this->seen_in_compare_is_identity_ = true;
8726 bool ret = this->type_->compare_is_identity(gogo);
8727 this->seen_in_compare_is_identity_ = false;
8728 return ret;
8731 // Return a hash code. This is used for method lookup. We simply
8732 // hash on the name itself.
8734 unsigned int
8735 Named_type::do_hash_for_method(Gogo* gogo) const
8737 if (this->is_alias())
8738 return this->type_->named_type()->do_hash_for_method(gogo);
8740 const std::string& name(this->named_object()->name());
8741 unsigned int ret = Type::hash_string(name, 0);
8743 // GOGO will be NULL here when called from Type_hash_identical.
8744 // That is OK because that is only used for internal hash tables
8745 // where we are going to be comparing named types for equality. In
8746 // other cases, which are cases where the runtime is going to
8747 // compare hash codes to see if the types are the same, we need to
8748 // include the pkgpath in the hash.
8749 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
8751 const Package* package = this->named_object()->package();
8752 if (package == NULL)
8753 ret = Type::hash_string(gogo->pkgpath(), ret);
8754 else
8755 ret = Type::hash_string(package->pkgpath(), ret);
8758 return ret;
8761 // Convert a named type to the backend representation. In order to
8762 // get dependencies right, we fill in a dummy structure for this type,
8763 // then convert all the dependencies, then complete this type. When
8764 // this function is complete, the size of the type is known.
8766 void
8767 Named_type::convert(Gogo* gogo)
8769 if (this->is_error_ || this->is_converted_)
8770 return;
8772 this->create_placeholder(gogo);
8774 // If we are called to turn unsafe.Sizeof into a constant, we may
8775 // not have verified the type yet. We have to make sure it is
8776 // verified, since that sets the list of dependencies.
8777 this->verify();
8779 // Convert all the dependencies. If they refer indirectly back to
8780 // this type, they will pick up the intermediate representation we just
8781 // created.
8782 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
8783 p != this->dependencies_.end();
8784 ++p)
8785 (*p)->convert(gogo);
8787 // Complete this type.
8788 Btype* bt = this->named_btype_;
8789 Type* base = this->type_->base();
8790 switch (base->classification())
8792 case TYPE_VOID:
8793 case TYPE_BOOLEAN:
8794 case TYPE_INTEGER:
8795 case TYPE_FLOAT:
8796 case TYPE_COMPLEX:
8797 case TYPE_STRING:
8798 case TYPE_NIL:
8799 break;
8801 case TYPE_MAP:
8802 case TYPE_CHANNEL:
8803 break;
8805 case TYPE_FUNCTION:
8806 case TYPE_POINTER:
8807 // The size of these types is already correct. We don't worry
8808 // about filling them in until later, when we also track
8809 // circular references.
8810 break;
8812 case TYPE_STRUCT:
8814 std::vector<Backend::Btyped_identifier> bfields;
8815 get_backend_struct_fields(gogo, base->struct_type()->fields(),
8816 true, &bfields);
8817 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8818 bt = gogo->backend()->error_type();
8820 break;
8822 case TYPE_ARRAY:
8823 // Slice types were completed in create_placeholder.
8824 if (!base->is_slice_type())
8826 Btype* bet = base->array_type()->get_backend_element(gogo, true);
8827 Bexpression* blen = base->array_type()->get_backend_length(gogo);
8828 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
8829 bt = gogo->backend()->error_type();
8831 break;
8833 case TYPE_INTERFACE:
8834 // Interface types were completed in create_placeholder.
8835 break;
8837 case TYPE_ERROR:
8838 return;
8840 default:
8841 case TYPE_SINK:
8842 case TYPE_CALL_MULTIPLE_RESULT:
8843 case TYPE_NAMED:
8844 case TYPE_FORWARD:
8845 go_unreachable();
8848 this->named_btype_ = bt;
8849 this->is_converted_ = true;
8850 this->is_placeholder_ = false;
8853 // Create the placeholder for a named type. This is the first step in
8854 // converting to the backend representation.
8856 void
8857 Named_type::create_placeholder(Gogo* gogo)
8859 if (this->is_error_)
8860 this->named_btype_ = gogo->backend()->error_type();
8862 if (this->named_btype_ != NULL)
8863 return;
8865 // Create the structure for this type. Note that because we call
8866 // base() here, we don't attempt to represent a named type defined
8867 // as another named type. Instead both named types will point to
8868 // different base representations.
8869 Type* base = this->type_->base();
8870 Btype* bt;
8871 bool set_name = true;
8872 switch (base->classification())
8874 case TYPE_ERROR:
8875 this->is_error_ = true;
8876 this->named_btype_ = gogo->backend()->error_type();
8877 return;
8879 case TYPE_VOID:
8880 case TYPE_BOOLEAN:
8881 case TYPE_INTEGER:
8882 case TYPE_FLOAT:
8883 case TYPE_COMPLEX:
8884 case TYPE_STRING:
8885 case TYPE_NIL:
8886 // These are simple basic types, we can just create them
8887 // directly.
8888 bt = Type::get_named_base_btype(gogo, base);
8889 break;
8891 case TYPE_MAP:
8892 case TYPE_CHANNEL:
8893 // All maps and channels have the same backend representation.
8894 bt = Type::get_named_base_btype(gogo, base);
8895 break;
8897 case TYPE_FUNCTION:
8898 case TYPE_POINTER:
8900 bool for_function = base->classification() == TYPE_FUNCTION;
8901 bt = gogo->backend()->placeholder_pointer_type(this->name(),
8902 this->location_,
8903 for_function);
8904 set_name = false;
8906 break;
8908 case TYPE_STRUCT:
8909 bt = gogo->backend()->placeholder_struct_type(this->name(),
8910 this->location_);
8911 this->is_placeholder_ = true;
8912 set_name = false;
8913 break;
8915 case TYPE_ARRAY:
8916 if (base->is_slice_type())
8917 bt = gogo->backend()->placeholder_struct_type(this->name(),
8918 this->location_);
8919 else
8921 bt = gogo->backend()->placeholder_array_type(this->name(),
8922 this->location_);
8923 this->is_placeholder_ = true;
8925 set_name = false;
8926 break;
8928 case TYPE_INTERFACE:
8929 if (base->interface_type()->is_empty())
8930 bt = Interface_type::get_backend_empty_interface_type(gogo);
8931 else
8933 bt = gogo->backend()->placeholder_struct_type(this->name(),
8934 this->location_);
8935 set_name = false;
8937 break;
8939 default:
8940 case TYPE_SINK:
8941 case TYPE_CALL_MULTIPLE_RESULT:
8942 case TYPE_NAMED:
8943 case TYPE_FORWARD:
8944 go_unreachable();
8947 if (set_name)
8948 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
8950 this->named_btype_ = bt;
8952 if (base->is_slice_type())
8954 // We do not record slices as dependencies of other types,
8955 // because we can fill them in completely here with the final
8956 // size.
8957 std::vector<Backend::Btyped_identifier> bfields;
8958 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
8959 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8960 this->named_btype_ = gogo->backend()->error_type();
8962 else if (base->interface_type() != NULL
8963 && !base->interface_type()->is_empty())
8965 // We do not record interfaces as dependencies of other types,
8966 // because we can fill them in completely here with the final
8967 // size.
8968 std::vector<Backend::Btyped_identifier> bfields;
8969 get_backend_interface_fields(gogo, base->interface_type(), true,
8970 &bfields);
8971 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8972 this->named_btype_ = gogo->backend()->error_type();
8976 // Get the backend representation for a named type.
8978 Btype*
8979 Named_type::do_get_backend(Gogo* gogo)
8981 if (this->is_error_)
8982 return gogo->backend()->error_type();
8984 Btype* bt = this->named_btype_;
8986 if (!gogo->named_types_are_converted())
8988 // We have not completed converting named types. NAMED_BTYPE_
8989 // is a placeholder and we shouldn't do anything further.
8990 if (bt != NULL)
8991 return bt;
8993 // We don't build dependencies for types whose sizes do not
8994 // change or are not relevant, so we may see them here while
8995 // converting types.
8996 this->create_placeholder(gogo);
8997 bt = this->named_btype_;
8998 go_assert(bt != NULL);
8999 return bt;
9002 // We are not converting types. This should only be called if the
9003 // type has already been converted.
9004 if (!this->is_converted_)
9006 go_assert(saw_errors());
9007 return gogo->backend()->error_type();
9010 go_assert(bt != NULL);
9012 // Complete the backend representation.
9013 Type* base = this->type_->base();
9014 Btype* bt1;
9015 switch (base->classification())
9017 case TYPE_ERROR:
9018 return gogo->backend()->error_type();
9020 case TYPE_VOID:
9021 case TYPE_BOOLEAN:
9022 case TYPE_INTEGER:
9023 case TYPE_FLOAT:
9024 case TYPE_COMPLEX:
9025 case TYPE_STRING:
9026 case TYPE_NIL:
9027 case TYPE_MAP:
9028 case TYPE_CHANNEL:
9029 return bt;
9031 case TYPE_STRUCT:
9032 if (!this->seen_in_get_backend_)
9034 this->seen_in_get_backend_ = true;
9035 base->struct_type()->finish_backend_fields(gogo);
9036 this->seen_in_get_backend_ = false;
9038 return bt;
9040 case TYPE_ARRAY:
9041 if (!this->seen_in_get_backend_)
9043 this->seen_in_get_backend_ = true;
9044 base->array_type()->finish_backend_element(gogo);
9045 this->seen_in_get_backend_ = false;
9047 return bt;
9049 case TYPE_INTERFACE:
9050 if (!this->seen_in_get_backend_)
9052 this->seen_in_get_backend_ = true;
9053 base->interface_type()->finish_backend_methods(gogo);
9054 this->seen_in_get_backend_ = false;
9056 return bt;
9058 case TYPE_FUNCTION:
9059 // Don't build a circular data structure. GENERIC can't handle
9060 // it.
9061 if (this->seen_in_get_backend_)
9063 this->is_circular_ = true;
9064 return gogo->backend()->circular_pointer_type(bt, false);
9066 this->seen_in_get_backend_ = true;
9067 bt1 = Type::get_named_base_btype(gogo, base);
9068 this->seen_in_get_backend_ = false;
9069 if (this->is_circular_)
9070 bt1 = gogo->backend()->circular_pointer_type(bt, false);
9071 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
9072 bt = gogo->backend()->error_type();
9073 return bt;
9075 case TYPE_POINTER:
9076 // Don't build a circular data structure. GENERIC can't handle
9077 // it.
9078 if (this->seen_in_get_backend_)
9080 this->is_circular_ = true;
9081 return gogo->backend()->circular_pointer_type(bt, false);
9083 this->seen_in_get_backend_ = true;
9084 bt1 = Type::get_named_base_btype(gogo, base);
9085 this->seen_in_get_backend_ = false;
9086 if (this->is_circular_)
9087 bt1 = gogo->backend()->circular_pointer_type(bt, false);
9088 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
9089 bt = gogo->backend()->error_type();
9090 return bt;
9092 default:
9093 case TYPE_SINK:
9094 case TYPE_CALL_MULTIPLE_RESULT:
9095 case TYPE_NAMED:
9096 case TYPE_FORWARD:
9097 go_unreachable();
9100 go_unreachable();
9103 // Build a type descriptor for a named type.
9105 Expression*
9106 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9108 if (name == NULL && this->is_alias())
9109 return this->type_->type_descriptor(gogo, this->type_);
9111 // If NAME is not NULL, then we don't really want the type
9112 // descriptor for this type; we want the descriptor for the
9113 // underlying type, giving it the name NAME.
9114 return this->named_type_descriptor(gogo, this->type_,
9115 name == NULL ? this : name);
9118 // Add to the reflection string. This is used mostly for the name of
9119 // the type used in a type descriptor, not for actual reflection
9120 // strings.
9122 void
9123 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
9125 if (this->is_alias())
9127 this->append_reflection(this->type_, gogo, ret);
9128 return;
9130 if (!this->is_builtin())
9132 // We handle -fgo-prefix and -fgo-pkgpath differently here for
9133 // compatibility with how the compiler worked before
9134 // -fgo-pkgpath was introduced. When -fgo-pkgpath is specified,
9135 // we use it to make a unique reflection string, so that the
9136 // type canonicalization in the reflect package will work. In
9137 // order to be compatible with the gc compiler, we put tabs into
9138 // the package path, so that the reflect methods can discard it.
9139 const Package* package = this->named_object_->package();
9140 if (gogo->pkgpath_from_option())
9142 ret->push_back('\t');
9143 ret->append(package != NULL
9144 ? package->pkgpath_symbol()
9145 : gogo->pkgpath_symbol());
9146 ret->push_back('\t');
9148 ret->append(package != NULL
9149 ? package->package_name()
9150 : gogo->package_name());
9151 ret->push_back('.');
9153 if (this->in_function_ != NULL)
9155 ret->push_back('\t');
9156 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
9157 ret->push_back('$');
9158 if (this->in_function_index_ > 0)
9160 char buf[30];
9161 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
9162 ret->append(buf);
9163 ret->push_back('$');
9165 ret->push_back('\t');
9167 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
9170 // Generate GC symbol for named types.
9172 void
9173 Named_type::do_gc_symbol(Gogo* gogo, Expression_list** vals,
9174 Expression** offset, int stack)
9176 if (!this->seen_)
9178 this->seen_ = true;
9179 Type::gc_symbol(gogo, this->real_type(), vals, offset, stack);
9180 this->seen_ = false;
9184 // Get the mangled name.
9186 void
9187 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
9189 if (this->is_alias())
9191 this->append_mangled_name(this->type_, gogo, ret);
9192 return;
9194 Named_object* no = this->named_object_;
9195 std::string name;
9196 if (this->is_builtin())
9197 go_assert(this->in_function_ == NULL);
9198 else
9200 const std::string& pkgpath(no->package() == NULL
9201 ? gogo->pkgpath_symbol()
9202 : no->package()->pkgpath_symbol());
9203 name = pkgpath;
9204 name.append(1, '.');
9205 if (this->in_function_ != NULL)
9207 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
9208 name.append(1, '$');
9209 if (this->in_function_index_ > 0)
9211 char buf[30];
9212 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
9213 name.append(buf);
9214 name.append(1, '$');
9218 name.append(Gogo::unpack_hidden_name(no->name()));
9219 char buf[20];
9220 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
9221 ret->append(buf);
9222 ret->append(name);
9225 // Export the type. This is called to export a global type.
9227 void
9228 Named_type::export_named_type(Export* exp, const std::string&) const
9230 // We don't need to write the name of the type here, because it will
9231 // be written by Export::write_type anyhow.
9232 exp->write_c_string("type ");
9233 exp->write_type(this);
9234 exp->write_c_string(";\n");
9237 // Import a named type.
9239 void
9240 Named_type::import_named_type(Import* imp, Named_type** ptype)
9242 imp->require_c_string("type ");
9243 Type *type = imp->read_type();
9244 *ptype = type->named_type();
9245 go_assert(*ptype != NULL);
9246 imp->require_c_string(";\n");
9249 // Export the type when it is referenced by another type. In this
9250 // case Export::export_type will already have issued the name.
9252 void
9253 Named_type::do_export(Export* exp) const
9255 exp->write_type(this->type_);
9257 // To save space, we only export the methods directly attached to
9258 // this type.
9259 Bindings* methods = this->local_methods_;
9260 if (methods == NULL)
9261 return;
9263 exp->write_c_string("\n");
9264 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
9265 p != methods->end_definitions();
9266 ++p)
9268 exp->write_c_string(" ");
9269 (*p)->export_named_object(exp);
9272 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
9273 p != methods->end_declarations();
9274 ++p)
9276 if (p->second->is_function_declaration())
9278 exp->write_c_string(" ");
9279 p->second->export_named_object(exp);
9284 // Make a named type.
9286 Named_type*
9287 Type::make_named_type(Named_object* named_object, Type* type,
9288 Location location)
9290 return new Named_type(named_object, type, location);
9293 // Finalize the methods for TYPE. It will be a named type or a struct
9294 // type. This sets *ALL_METHODS to the list of methods, and builds
9295 // all required stubs.
9297 void
9298 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
9299 Methods** all_methods)
9301 *all_methods = new Methods();
9302 std::vector<const Named_type*> seen;
9303 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
9304 if ((*all_methods)->empty())
9306 delete *all_methods;
9307 *all_methods = NULL;
9309 Type::build_stub_methods(gogo, type, *all_methods, location);
9312 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
9313 // build up the struct field indexes as we go. DEPTH is the depth of
9314 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
9315 // adding these methods for an anonymous field with pointer type.
9316 // NEEDS_STUB_METHOD is true if we need to use a stub method which
9317 // calls the real method. TYPES_SEEN is used to avoid infinite
9318 // recursion.
9320 void
9321 Type::add_methods_for_type(const Type* type,
9322 const Method::Field_indexes* field_indexes,
9323 unsigned int depth,
9324 bool is_embedded_pointer,
9325 bool needs_stub_method,
9326 std::vector<const Named_type*>* seen,
9327 Methods* methods)
9329 // Pointer types may not have methods.
9330 if (type->points_to() != NULL)
9331 return;
9333 const Named_type* nt = type->named_type();
9334 if (nt != NULL)
9336 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9337 p != seen->end();
9338 ++p)
9340 if (*p == nt)
9341 return;
9344 seen->push_back(nt);
9346 Type::add_local_methods_for_type(nt, field_indexes, depth,
9347 is_embedded_pointer, needs_stub_method,
9348 methods);
9351 Type::add_embedded_methods_for_type(type, field_indexes, depth,
9352 is_embedded_pointer, needs_stub_method,
9353 seen, methods);
9355 // If we are called with depth > 0, then we are looking at an
9356 // anonymous field of a struct. If such a field has interface type,
9357 // then we need to add the interface methods. We don't want to add
9358 // them when depth == 0, because we will already handle them
9359 // following the usual rules for an interface type.
9360 if (depth > 0)
9361 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
9363 if (nt != NULL)
9364 seen->pop_back();
9367 // Add the local methods for the named type NT to *METHODS. The
9368 // parameters are as for add_methods_to_type.
9370 void
9371 Type::add_local_methods_for_type(const Named_type* nt,
9372 const Method::Field_indexes* field_indexes,
9373 unsigned int depth,
9374 bool is_embedded_pointer,
9375 bool needs_stub_method,
9376 Methods* methods)
9378 const Bindings* local_methods = nt->local_methods();
9379 if (local_methods == NULL)
9380 return;
9382 for (Bindings::const_declarations_iterator p =
9383 local_methods->begin_declarations();
9384 p != local_methods->end_declarations();
9385 ++p)
9387 Named_object* no = p->second;
9388 bool is_value_method = (is_embedded_pointer
9389 || !Type::method_expects_pointer(no));
9390 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
9391 (needs_stub_method || depth > 0));
9392 if (!methods->insert(no->name(), m))
9393 delete m;
9397 // Add the embedded methods for TYPE to *METHODS. These are the
9398 // methods attached to anonymous fields. The parameters are as for
9399 // add_methods_to_type.
9401 void
9402 Type::add_embedded_methods_for_type(const Type* type,
9403 const Method::Field_indexes* field_indexes,
9404 unsigned int depth,
9405 bool is_embedded_pointer,
9406 bool needs_stub_method,
9407 std::vector<const Named_type*>* seen,
9408 Methods* methods)
9410 // Look for anonymous fields in TYPE. TYPE has fields if it is a
9411 // struct.
9412 const Struct_type* st = type->struct_type();
9413 if (st == NULL)
9414 return;
9416 const Struct_field_list* fields = st->fields();
9417 if (fields == NULL)
9418 return;
9420 unsigned int i = 0;
9421 for (Struct_field_list::const_iterator pf = fields->begin();
9422 pf != fields->end();
9423 ++pf, ++i)
9425 if (!pf->is_anonymous())
9426 continue;
9428 Type* ftype = pf->type();
9429 bool is_pointer = false;
9430 if (ftype->points_to() != NULL)
9432 ftype = ftype->points_to();
9433 is_pointer = true;
9435 Named_type* fnt = ftype->named_type();
9436 if (fnt == NULL)
9438 // This is an error, but it will be diagnosed elsewhere.
9439 continue;
9442 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
9443 sub_field_indexes->next = field_indexes;
9444 sub_field_indexes->field_index = i;
9446 Methods tmp_methods;
9447 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
9448 (is_embedded_pointer || is_pointer),
9449 (needs_stub_method
9450 || is_pointer
9451 || i > 0),
9452 seen,
9453 &tmp_methods);
9454 // Check if there are promoted methods that conflict with field names and
9455 // don't add them to the method map.
9456 for (Methods::const_iterator p = tmp_methods.begin();
9457 p != tmp_methods.end();
9458 ++p)
9460 bool found = false;
9461 for (Struct_field_list::const_iterator fp = fields->begin();
9462 fp != fields->end();
9463 ++fp)
9465 if (fp->field_name() == p->first)
9467 found = true;
9468 break;
9471 if (!found &&
9472 !methods->insert(p->first, p->second))
9473 delete p->second;
9478 // If TYPE is an interface type, then add its method to *METHODS.
9479 // This is for interface methods attached to an anonymous field. The
9480 // parameters are as for add_methods_for_type.
9482 void
9483 Type::add_interface_methods_for_type(const Type* type,
9484 const Method::Field_indexes* field_indexes,
9485 unsigned int depth,
9486 Methods* methods)
9488 const Interface_type* it = type->interface_type();
9489 if (it == NULL)
9490 return;
9492 const Typed_identifier_list* imethods = it->methods();
9493 if (imethods == NULL)
9494 return;
9496 for (Typed_identifier_list::const_iterator pm = imethods->begin();
9497 pm != imethods->end();
9498 ++pm)
9500 Function_type* fntype = pm->type()->function_type();
9501 if (fntype == NULL)
9503 // This is an error, but it should be reported elsewhere
9504 // when we look at the methods for IT.
9505 continue;
9507 go_assert(!fntype->is_method());
9508 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
9509 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
9510 field_indexes, depth);
9511 if (!methods->insert(pm->name(), m))
9512 delete m;
9516 // Build stub methods for TYPE as needed. METHODS is the set of
9517 // methods for the type. A stub method may be needed when a type
9518 // inherits a method from an anonymous field. When we need the
9519 // address of the method, as in a type descriptor, we need to build a
9520 // little stub which does the required field dereferences and jumps to
9521 // the real method. LOCATION is the location of the type definition.
9523 void
9524 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
9525 Location location)
9527 if (methods == NULL)
9528 return;
9529 for (Methods::const_iterator p = methods->begin();
9530 p != methods->end();
9531 ++p)
9533 Method* m = p->second;
9534 if (m->is_ambiguous() || !m->needs_stub_method())
9535 continue;
9537 const std::string& name(p->first);
9539 // Build a stub method.
9541 const Function_type* fntype = m->type();
9543 static unsigned int counter;
9544 char buf[100];
9545 snprintf(buf, sizeof buf, "$this%u", counter);
9546 ++counter;
9548 Type* receiver_type = const_cast<Type*>(type);
9549 if (!m->is_value_method())
9550 receiver_type = Type::make_pointer_type(receiver_type);
9551 Location receiver_location = m->receiver_location();
9552 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
9553 receiver_location);
9555 const Typed_identifier_list* fnparams = fntype->parameters();
9556 Typed_identifier_list* stub_params;
9557 if (fnparams == NULL || fnparams->empty())
9558 stub_params = NULL;
9559 else
9561 // We give each stub parameter a unique name.
9562 stub_params = new Typed_identifier_list();
9563 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
9564 pp != fnparams->end();
9565 ++pp)
9567 char pbuf[100];
9568 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
9569 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
9570 pp->location()));
9571 ++counter;
9575 const Typed_identifier_list* fnresults = fntype->results();
9576 Typed_identifier_list* stub_results;
9577 if (fnresults == NULL || fnresults->empty())
9578 stub_results = NULL;
9579 else
9581 // We create the result parameters without any names, since
9582 // we won't refer to them.
9583 stub_results = new Typed_identifier_list();
9584 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
9585 pr != fnresults->end();
9586 ++pr)
9587 stub_results->push_back(Typed_identifier("", pr->type(),
9588 pr->location()));
9591 Function_type* stub_type = Type::make_function_type(receiver,
9592 stub_params,
9593 stub_results,
9594 fntype->location());
9595 if (fntype->is_varargs())
9596 stub_type->set_is_varargs();
9598 // We only create the function in the package which creates the
9599 // type.
9600 const Package* package;
9601 if (type->named_type() == NULL)
9602 package = NULL;
9603 else
9604 package = type->named_type()->named_object()->package();
9605 Named_object* stub;
9606 if (package != NULL)
9607 stub = Named_object::make_function_declaration(name, package,
9608 stub_type, location);
9609 else
9611 stub = gogo->start_function(name, stub_type, false,
9612 fntype->location());
9613 Type::build_one_stub_method(gogo, m, buf, stub_params,
9614 fntype->is_varargs(), location);
9615 gogo->finish_function(fntype->location());
9617 if (type->named_type() == NULL && stub->is_function())
9618 stub->func_value()->set_is_unnamed_type_stub_method();
9619 if (m->nointerface() && stub->is_function())
9620 stub->func_value()->set_nointerface();
9623 m->set_stub_object(stub);
9627 // Build a stub method which adjusts the receiver as required to call
9628 // METHOD. RECEIVER_NAME is the name we used for the receiver.
9629 // PARAMS is the list of function parameters.
9631 void
9632 Type::build_one_stub_method(Gogo* gogo, Method* method,
9633 const char* receiver_name,
9634 const Typed_identifier_list* params,
9635 bool is_varargs,
9636 Location location)
9638 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
9639 go_assert(receiver_object != NULL);
9641 Expression* expr = Expression::make_var_reference(receiver_object, location);
9642 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
9643 if (expr->type()->points_to() == NULL)
9644 expr = Expression::make_unary(OPERATOR_AND, expr, location);
9646 Expression_list* arguments;
9647 if (params == NULL || params->empty())
9648 arguments = NULL;
9649 else
9651 arguments = new Expression_list();
9652 for (Typed_identifier_list::const_iterator p = params->begin();
9653 p != params->end();
9654 ++p)
9656 Named_object* param = gogo->lookup(p->name(), NULL);
9657 go_assert(param != NULL);
9658 Expression* param_ref = Expression::make_var_reference(param,
9659 location);
9660 arguments->push_back(param_ref);
9664 Expression* func = method->bind_method(expr, location);
9665 go_assert(func != NULL);
9666 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
9667 location);
9669 gogo->add_statement(Statement::make_return_from_call(call, location));
9672 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
9673 // in reverse order.
9675 Expression*
9676 Type::apply_field_indexes(Expression* expr,
9677 const Method::Field_indexes* field_indexes,
9678 Location location)
9680 if (field_indexes == NULL)
9681 return expr;
9682 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
9683 Struct_type* stype = expr->type()->deref()->struct_type();
9684 go_assert(stype != NULL
9685 && field_indexes->field_index < stype->field_count());
9686 if (expr->type()->struct_type() == NULL)
9688 go_assert(expr->type()->points_to() != NULL);
9689 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
9690 go_assert(expr->type()->struct_type() == stype);
9692 return Expression::make_field_reference(expr, field_indexes->field_index,
9693 location);
9696 // Return whether NO is a method for which the receiver is a pointer.
9698 bool
9699 Type::method_expects_pointer(const Named_object* no)
9701 const Function_type *fntype;
9702 if (no->is_function())
9703 fntype = no->func_value()->type();
9704 else if (no->is_function_declaration())
9705 fntype = no->func_declaration_value()->type();
9706 else
9707 go_unreachable();
9708 return fntype->receiver()->type()->points_to() != NULL;
9711 // Given a set of methods for a type, METHODS, return the method NAME,
9712 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
9713 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
9714 // but is ambiguous (and return NULL).
9716 Method*
9717 Type::method_function(const Methods* methods, const std::string& name,
9718 bool* is_ambiguous)
9720 if (is_ambiguous != NULL)
9721 *is_ambiguous = false;
9722 if (methods == NULL)
9723 return NULL;
9724 Methods::const_iterator p = methods->find(name);
9725 if (p == methods->end())
9726 return NULL;
9727 Method* m = p->second;
9728 if (m->is_ambiguous())
9730 if (is_ambiguous != NULL)
9731 *is_ambiguous = true;
9732 return NULL;
9734 return m;
9737 // Return a pointer to the interface method table for TYPE for the
9738 // interface INTERFACE.
9740 Expression*
9741 Type::interface_method_table(Type* type,
9742 Interface_type *interface,
9743 bool is_pointer,
9744 Interface_method_tables** method_tables,
9745 Interface_method_tables** pointer_tables)
9747 go_assert(!interface->is_empty());
9749 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
9751 if (*pimt == NULL)
9752 *pimt = new Interface_method_tables(5);
9754 std::pair<Interface_type*, Expression*> val(interface, NULL);
9755 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
9757 Location loc = Linemap::predeclared_location();
9758 if (ins.second)
9760 // This is a new entry in the hash table.
9761 go_assert(ins.first->second == NULL);
9762 ins.first->second =
9763 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
9765 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
9768 // Look for field or method NAME for TYPE. Return an Expression for
9769 // the field or method bound to EXPR. If there is no such field or
9770 // method, give an appropriate error and return an error expression.
9772 Expression*
9773 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
9774 const std::string& name,
9775 Location location)
9777 if (type->deref()->is_error_type())
9778 return Expression::make_error(location);
9780 const Named_type* nt = type->deref()->named_type();
9781 const Struct_type* st = type->deref()->struct_type();
9782 const Interface_type* it = type->interface_type();
9784 // If this is a pointer to a pointer, then it is possible that the
9785 // pointed-to type has methods.
9786 bool dereferenced = false;
9787 if (nt == NULL
9788 && st == NULL
9789 && it == NULL
9790 && type->points_to() != NULL
9791 && type->points_to()->points_to() != NULL)
9793 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
9794 type = type->points_to();
9795 if (type->deref()->is_error_type())
9796 return Expression::make_error(location);
9797 nt = type->points_to()->named_type();
9798 st = type->points_to()->struct_type();
9799 dereferenced = true;
9802 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
9803 || expr->is_addressable());
9804 std::vector<const Named_type*> seen;
9805 bool is_method = false;
9806 bool found_pointer_method = false;
9807 std::string ambig1;
9808 std::string ambig2;
9809 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
9810 &seen, NULL, &is_method,
9811 &found_pointer_method, &ambig1, &ambig2))
9813 Expression* ret;
9814 if (!is_method)
9816 go_assert(st != NULL);
9817 if (type->struct_type() == NULL)
9819 go_assert(type->points_to() != NULL);
9820 expr = Expression::make_unary(OPERATOR_MULT, expr,
9821 location);
9822 go_assert(expr->type()->struct_type() == st);
9824 ret = st->field_reference(expr, name, location);
9826 else if (it != NULL && it->find_method(name) != NULL)
9827 ret = Expression::make_interface_field_reference(expr, name,
9828 location);
9829 else
9831 Method* m;
9832 if (nt != NULL)
9833 m = nt->method_function(name, NULL);
9834 else if (st != NULL)
9835 m = st->method_function(name, NULL);
9836 else
9837 go_unreachable();
9838 go_assert(m != NULL);
9839 if (dereferenced)
9841 error_at(location,
9842 "calling method %qs requires explicit dereference",
9843 Gogo::message_name(name).c_str());
9844 return Expression::make_error(location);
9846 if (!m->is_value_method() && expr->type()->points_to() == NULL)
9847 expr = Expression::make_unary(OPERATOR_AND, expr, location);
9848 ret = m->bind_method(expr, location);
9850 go_assert(ret != NULL);
9851 return ret;
9853 else
9855 if (Gogo::is_erroneous_name(name))
9857 // An error was already reported.
9859 else if (!ambig1.empty())
9860 error_at(location, "%qs is ambiguous via %qs and %qs",
9861 Gogo::message_name(name).c_str(), ambig1.c_str(),
9862 ambig2.c_str());
9863 else if (found_pointer_method)
9864 error_at(location, "method requires a pointer receiver");
9865 else if (nt == NULL && st == NULL && it == NULL)
9866 error_at(location,
9867 ("reference to field %qs in object which "
9868 "has no fields or methods"),
9869 Gogo::message_name(name).c_str());
9870 else
9872 bool is_unexported;
9873 // The test for 'a' and 'z' is to handle builtin names,
9874 // which are not hidden.
9875 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
9876 is_unexported = false;
9877 else
9879 std::string unpacked = Gogo::unpack_hidden_name(name);
9880 seen.clear();
9881 is_unexported = Type::is_unexported_field_or_method(gogo, type,
9882 unpacked,
9883 &seen);
9885 if (is_unexported)
9886 error_at(location, "reference to unexported field or method %qs",
9887 Gogo::message_name(name).c_str());
9888 else
9889 error_at(location, "reference to undefined field or method %qs",
9890 Gogo::message_name(name).c_str());
9892 return Expression::make_error(location);
9896 // Look in TYPE for a field or method named NAME, return true if one
9897 // is found. This looks through embedded anonymous fields and handles
9898 // ambiguity. If a method is found, sets *IS_METHOD to true;
9899 // otherwise, if a field is found, set it to false. If
9900 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
9901 // whose address can not be taken. SEEN is used to avoid infinite
9902 // recursion on invalid types.
9904 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
9905 // method we couldn't use because it requires a pointer. LEVEL is
9906 // used for recursive calls, and can be NULL for a non-recursive call.
9907 // When this function returns false because it finds that the name is
9908 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
9909 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
9910 // will be unchanged.
9912 // This function just returns whether or not there is a field or
9913 // method, and whether it is a field or method. It doesn't build an
9914 // expression to refer to it. If it is a method, we then look in the
9915 // list of all methods for the type. If it is a field, the search has
9916 // to be done again, looking only for fields, and building up the
9917 // expression as we go.
9919 bool
9920 Type::find_field_or_method(const Type* type,
9921 const std::string& name,
9922 bool receiver_can_be_pointer,
9923 std::vector<const Named_type*>* seen,
9924 int* level,
9925 bool* is_method,
9926 bool* found_pointer_method,
9927 std::string* ambig1,
9928 std::string* ambig2)
9930 // Named types can have locally defined methods.
9931 const Named_type* nt = type->named_type();
9932 if (nt == NULL && type->points_to() != NULL)
9933 nt = type->points_to()->named_type();
9934 if (nt != NULL)
9936 Named_object* no = nt->find_local_method(name);
9937 if (no != NULL)
9939 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
9941 *is_method = true;
9942 return true;
9945 // Record that we have found a pointer method in order to
9946 // give a better error message if we don't find anything
9947 // else.
9948 *found_pointer_method = true;
9951 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9952 p != seen->end();
9953 ++p)
9955 if (*p == nt)
9957 // We've already seen this type when searching for methods.
9958 return false;
9963 // Interface types can have methods.
9964 const Interface_type* it = type->interface_type();
9965 if (it != NULL && it->find_method(name) != NULL)
9967 *is_method = true;
9968 return true;
9971 // Struct types can have fields. They can also inherit fields and
9972 // methods from anonymous fields.
9973 const Struct_type* st = type->deref()->struct_type();
9974 if (st == NULL)
9975 return false;
9976 const Struct_field_list* fields = st->fields();
9977 if (fields == NULL)
9978 return false;
9980 if (nt != NULL)
9981 seen->push_back(nt);
9983 int found_level = 0;
9984 bool found_is_method = false;
9985 std::string found_ambig1;
9986 std::string found_ambig2;
9987 const Struct_field* found_parent = NULL;
9988 for (Struct_field_list::const_iterator pf = fields->begin();
9989 pf != fields->end();
9990 ++pf)
9992 if (pf->is_field_name(name))
9994 *is_method = false;
9995 if (nt != NULL)
9996 seen->pop_back();
9997 return true;
10000 if (!pf->is_anonymous())
10001 continue;
10003 if (pf->type()->deref()->is_error_type()
10004 || pf->type()->deref()->is_undefined())
10005 continue;
10007 Named_type* fnt = pf->type()->named_type();
10008 if (fnt == NULL)
10009 fnt = pf->type()->deref()->named_type();
10010 go_assert(fnt != NULL);
10012 // Methods with pointer receivers on embedded field are
10013 // inherited by the pointer to struct, and also by the struct
10014 // type if the field itself is a pointer.
10015 bool can_be_pointer = (receiver_can_be_pointer
10016 || pf->type()->points_to() != NULL);
10017 int sublevel = level == NULL ? 1 : *level + 1;
10018 bool sub_is_method;
10019 std::string subambig1;
10020 std::string subambig2;
10021 bool subfound = Type::find_field_or_method(fnt,
10022 name,
10023 can_be_pointer,
10024 seen,
10025 &sublevel,
10026 &sub_is_method,
10027 found_pointer_method,
10028 &subambig1,
10029 &subambig2);
10030 if (!subfound)
10032 if (!subambig1.empty())
10034 // The name was found via this field, but is ambiguous.
10035 // if the ambiguity is lower or at the same level as
10036 // anything else we have already found, then we want to
10037 // pass the ambiguity back to the caller.
10038 if (found_level == 0 || sublevel <= found_level)
10040 found_ambig1 = (Gogo::message_name(pf->field_name())
10041 + '.' + subambig1);
10042 found_ambig2 = (Gogo::message_name(pf->field_name())
10043 + '.' + subambig2);
10044 found_level = sublevel;
10048 else
10050 // The name was found via this field. Use the level to see
10051 // if we want to use this one, or whether it introduces an
10052 // ambiguity.
10053 if (found_level == 0 || sublevel < found_level)
10055 found_level = sublevel;
10056 found_is_method = sub_is_method;
10057 found_ambig1.clear();
10058 found_ambig2.clear();
10059 found_parent = &*pf;
10061 else if (sublevel > found_level)
10063 else if (found_ambig1.empty())
10065 // We found an ambiguity.
10066 go_assert(found_parent != NULL);
10067 found_ambig1 = Gogo::message_name(found_parent->field_name());
10068 found_ambig2 = Gogo::message_name(pf->field_name());
10070 else
10072 // We found an ambiguity, but we already know of one.
10073 // Just report the earlier one.
10078 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
10079 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
10080 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
10081 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
10083 if (nt != NULL)
10084 seen->pop_back();
10086 if (found_level == 0)
10087 return false;
10088 else if (!found_ambig1.empty())
10090 go_assert(!found_ambig1.empty());
10091 ambig1->assign(found_ambig1);
10092 ambig2->assign(found_ambig2);
10093 if (level != NULL)
10094 *level = found_level;
10095 return false;
10097 else
10099 if (level != NULL)
10100 *level = found_level;
10101 *is_method = found_is_method;
10102 return true;
10106 // Return whether NAME is an unexported field or method for TYPE.
10108 bool
10109 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
10110 const std::string& name,
10111 std::vector<const Named_type*>* seen)
10113 const Named_type* nt = type->named_type();
10114 if (nt == NULL)
10115 nt = type->deref()->named_type();
10116 if (nt != NULL)
10118 if (nt->is_unexported_local_method(gogo, name))
10119 return true;
10121 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
10122 p != seen->end();
10123 ++p)
10125 if (*p == nt)
10127 // We've already seen this type.
10128 return false;
10133 const Interface_type* it = type->interface_type();
10134 if (it != NULL && it->is_unexported_method(gogo, name))
10135 return true;
10137 type = type->deref();
10139 const Struct_type* st = type->struct_type();
10140 if (st != NULL && st->is_unexported_local_field(gogo, name))
10141 return true;
10143 if (st == NULL)
10144 return false;
10146 const Struct_field_list* fields = st->fields();
10147 if (fields == NULL)
10148 return false;
10150 if (nt != NULL)
10151 seen->push_back(nt);
10153 for (Struct_field_list::const_iterator pf = fields->begin();
10154 pf != fields->end();
10155 ++pf)
10157 if (pf->is_anonymous()
10158 && !pf->type()->deref()->is_error_type()
10159 && !pf->type()->deref()->is_undefined())
10161 Named_type* subtype = pf->type()->named_type();
10162 if (subtype == NULL)
10163 subtype = pf->type()->deref()->named_type();
10164 if (subtype == NULL)
10166 // This is an error, but it will be diagnosed elsewhere.
10167 continue;
10169 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
10171 if (nt != NULL)
10172 seen->pop_back();
10173 return true;
10178 if (nt != NULL)
10179 seen->pop_back();
10181 return false;
10184 // Class Forward_declaration.
10186 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
10187 : Type(TYPE_FORWARD),
10188 named_object_(named_object->resolve()), warned_(false)
10190 go_assert(this->named_object_->is_unknown()
10191 || this->named_object_->is_type_declaration());
10194 // Return the named object.
10196 Named_object*
10197 Forward_declaration_type::named_object()
10199 return this->named_object_->resolve();
10202 const Named_object*
10203 Forward_declaration_type::named_object() const
10205 return this->named_object_->resolve();
10208 // Return the name of the forward declared type.
10210 const std::string&
10211 Forward_declaration_type::name() const
10213 return this->named_object()->name();
10216 // Warn about a use of a type which has been declared but not defined.
10218 void
10219 Forward_declaration_type::warn() const
10221 Named_object* no = this->named_object_->resolve();
10222 if (no->is_unknown())
10224 // The name was not defined anywhere.
10225 if (!this->warned_)
10227 error_at(this->named_object_->location(),
10228 "use of undefined type %qs",
10229 no->message_name().c_str());
10230 this->warned_ = true;
10233 else if (no->is_type_declaration())
10235 // The name was seen as a type, but the type was never defined.
10236 if (no->type_declaration_value()->using_type())
10238 error_at(this->named_object_->location(),
10239 "use of undefined type %qs",
10240 no->message_name().c_str());
10241 this->warned_ = true;
10244 else
10246 // The name was defined, but not as a type.
10247 if (!this->warned_)
10249 error_at(this->named_object_->location(), "expected type");
10250 this->warned_ = true;
10255 // Get the base type of a declaration. This gives an error if the
10256 // type has not yet been defined.
10258 Type*
10259 Forward_declaration_type::real_type()
10261 if (this->is_defined())
10262 return this->named_object()->type_value();
10263 else
10265 this->warn();
10266 return Type::make_error_type();
10270 const Type*
10271 Forward_declaration_type::real_type() const
10273 if (this->is_defined())
10274 return this->named_object()->type_value();
10275 else
10277 this->warn();
10278 return Type::make_error_type();
10282 // Return whether the base type is defined.
10284 bool
10285 Forward_declaration_type::is_defined() const
10287 return this->named_object()->is_type();
10290 // Add a method. This is used when methods are defined before the
10291 // type.
10293 Named_object*
10294 Forward_declaration_type::add_method(const std::string& name,
10295 Function* function)
10297 Named_object* no = this->named_object();
10298 if (no->is_unknown())
10299 no->declare_as_type();
10300 return no->type_declaration_value()->add_method(name, function);
10303 // Add a method declaration. This is used when methods are declared
10304 // before the type.
10306 Named_object*
10307 Forward_declaration_type::add_method_declaration(const std::string& name,
10308 Package* package,
10309 Function_type* type,
10310 Location location)
10312 Named_object* no = this->named_object();
10313 if (no->is_unknown())
10314 no->declare_as_type();
10315 Type_declaration* td = no->type_declaration_value();
10316 return td->add_method_declaration(name, package, type, location);
10319 // Traversal.
10322 Forward_declaration_type::do_traverse(Traverse* traverse)
10324 if (this->is_defined()
10325 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
10326 return TRAVERSE_EXIT;
10327 return TRAVERSE_CONTINUE;
10330 // Verify the type.
10332 bool
10333 Forward_declaration_type::do_verify()
10335 if (!this->is_defined() && !this->is_nil_constant_as_type())
10337 this->warn();
10338 return false;
10340 return true;
10343 // Get the backend representation for the type.
10345 Btype*
10346 Forward_declaration_type::do_get_backend(Gogo* gogo)
10348 if (this->is_defined())
10349 return Type::get_named_base_btype(gogo, this->real_type());
10351 if (this->warned_)
10352 return gogo->backend()->error_type();
10354 // We represent an undefined type as a struct with no fields. That
10355 // should work fine for the backend, since the same case can arise
10356 // in C.
10357 std::vector<Backend::Btyped_identifier> fields;
10358 Btype* bt = gogo->backend()->struct_type(fields);
10359 return gogo->backend()->named_type(this->name(), bt,
10360 this->named_object()->location());
10363 // Build a type descriptor for a forwarded type.
10365 Expression*
10366 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
10368 Location ploc = Linemap::predeclared_location();
10369 if (!this->is_defined())
10370 return Expression::make_error(ploc);
10371 else
10373 Type* t = this->real_type();
10374 if (name != NULL)
10375 return this->named_type_descriptor(gogo, t, name);
10376 else
10377 return Expression::make_type_descriptor(t, ploc);
10381 // The reflection string.
10383 void
10384 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
10386 this->append_reflection(this->real_type(), gogo, ret);
10389 // The mangled name.
10391 void
10392 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
10394 if (this->is_defined())
10395 this->append_mangled_name(this->real_type(), gogo, ret);
10396 else
10398 const Named_object* no = this->named_object();
10399 std::string name;
10400 if (no->package() == NULL)
10401 name = gogo->pkgpath_symbol();
10402 else
10403 name = no->package()->pkgpath_symbol();
10404 name += '.';
10405 name += Gogo::unpack_hidden_name(no->name());
10406 char buf[20];
10407 snprintf(buf, sizeof buf, "N%u_",
10408 static_cast<unsigned int>(name.length()));
10409 ret->append(buf);
10410 ret->append(name);
10414 // Export a forward declaration. This can happen when a defined type
10415 // refers to a type which is only declared (and is presumably defined
10416 // in some other file in the same package).
10418 void
10419 Forward_declaration_type::do_export(Export*) const
10421 // If there is a base type, that should be exported instead of this.
10422 go_assert(!this->is_defined());
10424 // We don't output anything.
10427 // Make a forward declaration.
10429 Type*
10430 Type::make_forward_declaration(Named_object* named_object)
10432 return new Forward_declaration_type(named_object);
10435 // Class Typed_identifier_list.
10437 // Sort the entries by name.
10439 struct Typed_identifier_list_sort
10441 public:
10442 bool
10443 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
10444 { return t1.name() < t2.name(); }
10447 void
10448 Typed_identifier_list::sort_by_name()
10450 std::sort(this->entries_.begin(), this->entries_.end(),
10451 Typed_identifier_list_sort());
10454 // Traverse types.
10457 Typed_identifier_list::traverse(Traverse* traverse)
10459 for (Typed_identifier_list::const_iterator p = this->begin();
10460 p != this->end();
10461 ++p)
10463 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
10464 return TRAVERSE_EXIT;
10466 return TRAVERSE_CONTINUE;
10469 // Copy the list.
10471 Typed_identifier_list*
10472 Typed_identifier_list::copy() const
10474 Typed_identifier_list* ret = new Typed_identifier_list();
10475 for (Typed_identifier_list::const_iterator p = this->begin();
10476 p != this->end();
10477 ++p)
10478 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
10479 return ret;