compiler: Add precise type information on the heap.
[official-gcc.git] / gcc / go / gofrontend / types.cc
blob302faeee3538aa04bfcff62fcbe0589b0d772912
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 CHECK_HIDDEN_FIELDS is true, check whether any
598 // hidden fields are modified. If REASON is not NULL, set *REASON to
599 // the reason the types are not assignable.
601 bool
602 Type::are_assignable_check_hidden(const Type* lhs, const Type* rhs,
603 bool check_hidden_fields,
604 std::string* reason)
606 // Do some checks first. Make sure the types are defined.
607 if (rhs != NULL && !rhs->is_undefined())
609 if (rhs->is_void_type())
611 if (reason != NULL)
612 *reason = "non-value used as value";
613 return false;
615 if (rhs->is_call_multiple_result_type())
617 if (reason != NULL)
618 reason->assign(_("multiple-value function call in "
619 "single-value context"));
620 return false;
624 if (lhs != NULL && !lhs->is_undefined())
626 // Any value may be assigned to the blank identifier.
627 if (lhs->is_sink_type())
628 return true;
630 // All fields of a struct must be exported, or the assignment
631 // must be in the same package.
632 if (check_hidden_fields && rhs != NULL && !rhs->is_undefined())
634 if (lhs->has_hidden_fields(NULL, reason)
635 || rhs->has_hidden_fields(NULL, reason))
636 return false;
640 // Identical types are assignable.
641 if (Type::are_identical(lhs, rhs, true, reason))
642 return true;
644 // The types are assignable if they have identical underlying types
645 // and either LHS or RHS is not a named type.
646 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
647 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
648 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
649 return true;
651 // The types are assignable if LHS is an interface type and RHS
652 // implements the required methods.
653 const Interface_type* lhs_interface_type = lhs->interface_type();
654 if (lhs_interface_type != NULL)
656 if (lhs_interface_type->implements_interface(rhs, reason))
657 return true;
658 const Interface_type* rhs_interface_type = rhs->interface_type();
659 if (rhs_interface_type != NULL
660 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
661 reason))
662 return true;
665 // The type are assignable if RHS is a bidirectional channel type,
666 // LHS is a channel type, they have identical element types, and
667 // either LHS or RHS is not a named type.
668 if (lhs->channel_type() != NULL
669 && rhs->channel_type() != NULL
670 && rhs->channel_type()->may_send()
671 && rhs->channel_type()->may_receive()
672 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
673 && Type::are_identical(lhs->channel_type()->element_type(),
674 rhs->channel_type()->element_type(),
675 true,
676 reason))
677 return true;
679 // The nil type may be assigned to a pointer, function, slice, map,
680 // channel, or interface type.
681 if (rhs->is_nil_type()
682 && (lhs->points_to() != NULL
683 || lhs->function_type() != NULL
684 || lhs->is_slice_type()
685 || lhs->map_type() != NULL
686 || lhs->channel_type() != NULL
687 || lhs->interface_type() != NULL))
688 return true;
690 // An untyped numeric constant may be assigned to a numeric type if
691 // it is representable in that type.
692 if ((rhs->is_abstract()
693 && (rhs->integer_type() != NULL
694 || rhs->float_type() != NULL
695 || rhs->complex_type() != NULL))
696 && (lhs->integer_type() != NULL
697 || lhs->float_type() != NULL
698 || lhs->complex_type() != NULL))
699 return true;
701 // Give some better error messages.
702 if (reason != NULL && reason->empty())
704 if (rhs->interface_type() != NULL)
705 reason->assign(_("need explicit conversion"));
706 else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
708 size_t len = (lhs->named_type()->name().length()
709 + rhs->named_type()->name().length()
710 + 100);
711 char* buf = new char[len];
712 snprintf(buf, len, _("cannot use type %s as type %s"),
713 rhs->named_type()->message_name().c_str(),
714 lhs->named_type()->message_name().c_str());
715 reason->assign(buf);
716 delete[] buf;
720 return false;
723 // Return true if a value with type RHS may be assigned to a variable
724 // with type LHS. If REASON is not NULL, set *REASON to the reason
725 // the types are not assignable.
727 bool
728 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
730 return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
733 // Like are_assignable but don't check for hidden fields.
735 bool
736 Type::are_assignable_hidden_ok(const Type* lhs, const Type* rhs,
737 std::string* reason)
739 return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
742 // Return true if a value with type RHS may be converted to type LHS.
743 // If REASON is not NULL, set *REASON to the reason the types are not
744 // convertible.
746 bool
747 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
749 // The types are convertible if they are assignable.
750 if (Type::are_assignable(lhs, rhs, reason))
751 return true;
753 // The types are convertible if they have identical underlying
754 // types.
755 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
756 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
757 return true;
759 // The types are convertible if they are both unnamed pointer types
760 // and their pointer base types have identical underlying types.
761 if (lhs->named_type() == NULL
762 && rhs->named_type() == NULL
763 && lhs->points_to() != NULL
764 && rhs->points_to() != NULL
765 && (lhs->points_to()->named_type() != NULL
766 || rhs->points_to()->named_type() != NULL)
767 && Type::are_identical(lhs->points_to()->base(),
768 rhs->points_to()->base(),
769 true,
770 reason))
771 return true;
773 // Integer and floating point types are convertible to each other.
774 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
775 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
776 return true;
778 // Complex types are convertible to each other.
779 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
780 return true;
782 // An integer, or []byte, or []rune, may be converted to a string.
783 if (lhs->is_string_type())
785 if (rhs->integer_type() != NULL)
786 return true;
787 if (rhs->is_slice_type())
789 const Type* e = rhs->array_type()->element_type()->forwarded();
790 if (e->integer_type() != NULL
791 && (e->integer_type()->is_byte()
792 || e->integer_type()->is_rune()))
793 return true;
797 // A string may be converted to []byte or []rune.
798 if (rhs->is_string_type() && lhs->is_slice_type())
800 const Type* e = lhs->array_type()->element_type()->forwarded();
801 if (e->integer_type() != NULL
802 && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
803 return true;
806 // An unsafe.Pointer type may be converted to any pointer type or to
807 // uintptr, and vice-versa.
808 if (lhs->is_unsafe_pointer_type()
809 && (rhs->points_to() != NULL
810 || (rhs->integer_type() != NULL
811 && rhs->forwarded() == Type::lookup_integer_type("uintptr"))))
812 return true;
813 if (rhs->is_unsafe_pointer_type()
814 && (lhs->points_to() != NULL
815 || (lhs->integer_type() != NULL
816 && lhs->forwarded() == Type::lookup_integer_type("uintptr"))))
817 return true;
819 // Give a better error message.
820 if (reason != NULL)
822 if (reason->empty())
823 *reason = "invalid type conversion";
824 else
826 std::string s = "invalid type conversion (";
827 s += *reason;
828 s += ')';
829 *reason = s;
833 return false;
836 // Return whether this type has any hidden fields. This is only a
837 // possibility for a few types.
839 bool
840 Type::has_hidden_fields(const Named_type* within, std::string* reason) const
842 switch (this->forwarded()->classification_)
844 case TYPE_NAMED:
845 return this->named_type()->named_type_has_hidden_fields(reason);
846 case TYPE_STRUCT:
847 return this->struct_type()->struct_has_hidden_fields(within, reason);
848 case TYPE_ARRAY:
849 return this->array_type()->array_has_hidden_fields(within, reason);
850 default:
851 return false;
855 // Return a hash code for the type to be used for method lookup.
857 unsigned int
858 Type::hash_for_method(Gogo* gogo) const
860 unsigned int ret = 0;
861 if (this->classification_ != TYPE_FORWARD)
862 ret += this->classification_;
863 return ret + this->do_hash_for_method(gogo);
866 // Default implementation of do_hash_for_method. This is appropriate
867 // for types with no subfields.
869 unsigned int
870 Type::do_hash_for_method(Gogo*) const
872 return 0;
875 // Return a hash code for a string, given a starting hash.
877 unsigned int
878 Type::hash_string(const std::string& s, unsigned int h)
880 const char* p = s.data();
881 size_t len = s.length();
882 for (; len > 0; --len)
884 h ^= *p++;
885 h*= 16777619;
887 return h;
890 // A hash table mapping unnamed types to the backend representation of
891 // those types.
893 Type::Type_btypes Type::type_btypes;
895 // Return the backend representation for this type.
897 Btype*
898 Type::get_backend(Gogo* gogo)
900 if (this->btype_ != NULL)
901 return this->btype_;
903 if (this->forward_declaration_type() != NULL
904 || this->named_type() != NULL)
905 return this->get_btype_without_hash(gogo);
907 if (this->is_error_type())
908 return gogo->backend()->error_type();
910 // To avoid confusing the backend, translate all identical Go types
911 // to the same backend representation. We use a hash table to do
912 // that. There is no need to use the hash table for named types, as
913 // named types are only identical to themselves.
915 std::pair<Type*, Type_btype_entry> val;
916 val.first = this;
917 val.second.btype = NULL;
918 val.second.is_placeholder = false;
919 std::pair<Type_btypes::iterator, bool> ins =
920 Type::type_btypes.insert(val);
921 if (!ins.second && ins.first->second.btype != NULL)
923 // Note that GOGO can be NULL here, but only when the GCC
924 // middle-end is asking for a frontend type. That will only
925 // happen for simple types, which should never require
926 // placeholders.
927 if (!ins.first->second.is_placeholder)
928 this->btype_ = ins.first->second.btype;
929 else if (gogo->named_types_are_converted())
931 this->finish_backend(gogo, ins.first->second.btype);
932 ins.first->second.is_placeholder = false;
935 return ins.first->second.btype;
938 Btype* bt = this->get_btype_without_hash(gogo);
940 if (ins.first->second.btype == NULL)
942 ins.first->second.btype = bt;
943 ins.first->second.is_placeholder = false;
945 else
947 // We have already created a backend representation for this
948 // type. This can happen when an unnamed type is defined using
949 // a named type which in turns uses an identical unnamed type.
950 // Use the representation we created earlier and ignore the one we just
951 // built.
952 if (this->btype_ == bt)
953 this->btype_ = ins.first->second.btype;
954 bt = ins.first->second.btype;
957 return bt;
960 // Return the backend representation for a type without looking in the
961 // hash table for identical types. This is used for named types,
962 // since a named type is never identical to any other type.
964 Btype*
965 Type::get_btype_without_hash(Gogo* gogo)
967 if (this->btype_ == NULL)
969 Btype* bt = this->do_get_backend(gogo);
971 // For a recursive function or pointer type, we will temporarily
972 // return a circular pointer type during the recursion. We
973 // don't want to record that for a forwarding type, as it may
974 // confuse us later.
975 if (this->forward_declaration_type() != NULL
976 && gogo->backend()->is_circular_pointer_type(bt))
977 return bt;
979 if (gogo == NULL || !gogo->named_types_are_converted())
980 return bt;
982 this->btype_ = bt;
984 return this->btype_;
987 // Get the backend representation of a type without forcing the
988 // creation of the backend representation of all supporting types.
989 // This will return a backend type that has the correct size but may
990 // be incomplete. E.g., a pointer will just be a placeholder pointer,
991 // and will not contain the final representation of the type to which
992 // it points. This is used while converting all named types to the
993 // backend representation, to avoid problems with indirect references
994 // to types which are not yet complete. When this is called, the
995 // sizes of all direct references (e.g., a struct field) should be
996 // known, but the sizes of indirect references (e.g., the type to
997 // which a pointer points) may not.
999 Btype*
1000 Type::get_backend_placeholder(Gogo* gogo)
1002 if (gogo->named_types_are_converted())
1003 return this->get_backend(gogo);
1004 if (this->btype_ != NULL)
1005 return this->btype_;
1007 Btype* bt;
1008 switch (this->classification_)
1010 case TYPE_ERROR:
1011 case TYPE_VOID:
1012 case TYPE_BOOLEAN:
1013 case TYPE_INTEGER:
1014 case TYPE_FLOAT:
1015 case TYPE_COMPLEX:
1016 case TYPE_STRING:
1017 case TYPE_NIL:
1018 // These are simple types that can just be created directly.
1019 return this->get_backend(gogo);
1021 case TYPE_MAP:
1022 case TYPE_CHANNEL:
1023 // All maps and channels have the same backend representation.
1024 return this->get_backend(gogo);
1026 case TYPE_NAMED:
1027 case TYPE_FORWARD:
1028 // Named types keep track of their own dependencies and manage
1029 // their own placeholders.
1030 return this->get_backend(gogo);
1032 case TYPE_INTERFACE:
1033 if (this->interface_type()->is_empty())
1034 return Interface_type::get_backend_empty_interface_type(gogo);
1035 break;
1037 default:
1038 break;
1041 std::pair<Type*, Type_btype_entry> val;
1042 val.first = this;
1043 val.second.btype = NULL;
1044 val.second.is_placeholder = false;
1045 std::pair<Type_btypes::iterator, bool> ins =
1046 Type::type_btypes.insert(val);
1047 if (!ins.second && ins.first->second.btype != NULL)
1048 return ins.first->second.btype;
1050 switch (this->classification_)
1052 case TYPE_FUNCTION:
1054 // A Go function type is a pointer to a struct type.
1055 Location loc = this->function_type()->location();
1056 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1058 break;
1060 case TYPE_POINTER:
1062 Location loc = Linemap::unknown_location();
1063 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1065 break;
1067 case TYPE_STRUCT:
1068 // We don't have to make the struct itself be a placeholder. We
1069 // are promised that we know the sizes of the struct fields.
1070 // But we may have to use a placeholder for any particular
1071 // struct field.
1073 std::vector<Backend::Btyped_identifier> bfields;
1074 get_backend_struct_fields(gogo, this->struct_type()->fields(),
1075 true, &bfields);
1076 bt = gogo->backend()->struct_type(bfields);
1078 break;
1080 case TYPE_ARRAY:
1081 if (this->is_slice_type())
1083 std::vector<Backend::Btyped_identifier> bfields;
1084 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1085 bt = gogo->backend()->struct_type(bfields);
1087 else
1089 Btype* element = this->array_type()->get_backend_element(gogo, true);
1090 Bexpression* len = this->array_type()->get_backend_length(gogo);
1091 bt = gogo->backend()->array_type(element, len);
1093 break;
1095 case TYPE_INTERFACE:
1097 go_assert(!this->interface_type()->is_empty());
1098 std::vector<Backend::Btyped_identifier> bfields;
1099 get_backend_interface_fields(gogo, this->interface_type(), true,
1100 &bfields);
1101 bt = gogo->backend()->struct_type(bfields);
1103 break;
1105 case TYPE_SINK:
1106 case TYPE_CALL_MULTIPLE_RESULT:
1107 /* Note that various classifications were handled in the earlier
1108 switch. */
1109 default:
1110 go_unreachable();
1113 if (ins.first->second.btype == NULL)
1115 ins.first->second.btype = bt;
1116 ins.first->second.is_placeholder = true;
1118 else
1120 // A placeholder for this type got created along the way. Use
1121 // that one and ignore the one we just built.
1122 bt = ins.first->second.btype;
1125 return bt;
1128 // Complete the backend representation. This is called for a type
1129 // using a placeholder type.
1131 void
1132 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1134 switch (this->classification_)
1136 case TYPE_ERROR:
1137 case TYPE_VOID:
1138 case TYPE_BOOLEAN:
1139 case TYPE_INTEGER:
1140 case TYPE_FLOAT:
1141 case TYPE_COMPLEX:
1142 case TYPE_STRING:
1143 case TYPE_NIL:
1144 go_unreachable();
1146 case TYPE_FUNCTION:
1148 Btype* bt = this->do_get_backend(gogo);
1149 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1150 go_assert(saw_errors());
1152 break;
1154 case TYPE_POINTER:
1156 Btype* bt = this->do_get_backend(gogo);
1157 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1158 go_assert(saw_errors());
1160 break;
1162 case TYPE_STRUCT:
1163 // The struct type itself is done, but we have to make sure that
1164 // all the field types are converted.
1165 this->struct_type()->finish_backend_fields(gogo);
1166 break;
1168 case TYPE_ARRAY:
1169 // The array type itself is done, but make sure the element type
1170 // is converted.
1171 this->array_type()->finish_backend_element(gogo);
1172 break;
1174 case TYPE_MAP:
1175 case TYPE_CHANNEL:
1176 go_unreachable();
1178 case TYPE_INTERFACE:
1179 // The interface type itself is done, but make sure the method
1180 // types are converted.
1181 this->interface_type()->finish_backend_methods(gogo);
1182 break;
1184 case TYPE_NAMED:
1185 case TYPE_FORWARD:
1186 go_unreachable();
1188 case TYPE_SINK:
1189 case TYPE_CALL_MULTIPLE_RESULT:
1190 default:
1191 go_unreachable();
1194 this->btype_ = placeholder;
1197 // Return a pointer to the type descriptor for this type.
1199 Bexpression*
1200 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1202 Type* t = this->forwarded();
1203 if (t->named_type() != NULL && t->named_type()->is_alias())
1204 t = t->named_type()->real_type();
1205 if (t->type_descriptor_var_ == NULL)
1207 t->make_type_descriptor_var(gogo);
1208 go_assert(t->type_descriptor_var_ != NULL);
1210 Bexpression* var_expr =
1211 gogo->backend()->var_expression(t->type_descriptor_var_, location);
1212 return gogo->backend()->address_expression(var_expr, location);
1215 // A mapping from unnamed types to type descriptor variables.
1217 Type::Type_descriptor_vars Type::type_descriptor_vars;
1219 // Build the type descriptor for this type.
1221 void
1222 Type::make_type_descriptor_var(Gogo* gogo)
1224 go_assert(this->type_descriptor_var_ == NULL);
1226 Named_type* nt = this->named_type();
1228 // We can have multiple instances of unnamed types, but we only want
1229 // to emit the type descriptor once. We use a hash table. This is
1230 // not necessary for named types, as they are unique, and we store
1231 // the type descriptor in the type itself.
1232 Bvariable** phash = NULL;
1233 if (nt == NULL)
1235 Bvariable* bvnull = NULL;
1236 std::pair<Type_descriptor_vars::iterator, bool> ins =
1237 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1238 if (!ins.second)
1240 // We've already built a type descriptor for this type.
1241 this->type_descriptor_var_ = ins.first->second;
1242 return;
1244 phash = &ins.first->second;
1247 std::string var_name = this->type_descriptor_var_name(gogo, nt);
1249 // Build the contents of the type descriptor.
1250 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1252 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1254 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1256 const Package* dummy;
1257 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1259 this->type_descriptor_var_ =
1260 gogo->backend()->immutable_struct_reference(var_name,
1261 initializer_btype,
1262 loc);
1263 if (phash != NULL)
1264 *phash = this->type_descriptor_var_;
1265 return;
1268 // See if this type descriptor can appear in multiple packages.
1269 bool is_common = false;
1270 if (nt != NULL)
1272 // We create the descriptor for a builtin type whenever we need
1273 // it.
1274 is_common = nt->is_builtin();
1276 else
1278 // This is an unnamed type. The descriptor could be defined in
1279 // any package where it is needed, and the linker will pick one
1280 // descriptor to keep.
1281 is_common = true;
1284 // We are going to build the type descriptor in this package. We
1285 // must create the variable before we convert the initializer to the
1286 // backend representation, because the initializer may refer to the
1287 // type descriptor of this type. By setting type_descriptor_var_ we
1288 // ensure that type_descriptor_pointer will work if called while
1289 // converting INITIALIZER.
1291 this->type_descriptor_var_ =
1292 gogo->backend()->immutable_struct(var_name, false, is_common,
1293 initializer_btype, loc);
1294 if (phash != NULL)
1295 *phash = this->type_descriptor_var_;
1297 Translate_context context(gogo, NULL, NULL, NULL);
1298 context.set_is_const();
1299 Bexpression* binitializer = initializer->get_backend(&context);
1301 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1302 var_name, false, is_common,
1303 initializer_btype, loc,
1304 binitializer);
1307 // Return the name of the type descriptor variable. If NT is not
1308 // NULL, use it to get the name. Otherwise this is an unnamed type.
1310 std::string
1311 Type::type_descriptor_var_name(Gogo* gogo, Named_type* nt)
1313 if (nt == NULL)
1314 return "__go_td_" + this->mangled_name(gogo);
1316 Named_object* no = nt->named_object();
1317 unsigned int index;
1318 const Named_object* in_function = nt->in_function(&index);
1319 std::string ret = "__go_tdn_";
1320 if (nt->is_builtin())
1321 go_assert(in_function == NULL);
1322 else
1324 const std::string& pkgpath(no->package() == NULL
1325 ? gogo->pkgpath_symbol()
1326 : no->package()->pkgpath_symbol());
1327 ret.append(pkgpath);
1328 ret.append(1, '.');
1329 if (in_function != NULL)
1331 ret.append(Gogo::unpack_hidden_name(in_function->name()));
1332 ret.append(1, '.');
1333 if (index > 0)
1335 char buf[30];
1336 snprintf(buf, sizeof buf, "%u", index);
1337 ret.append(buf);
1338 ret.append(1, '.');
1343 // FIXME: This adds in pkgpath twice for hidden symbols, which is
1344 // pointless.
1345 const std::string& name(no->name());
1346 if (!Gogo::is_hidden_name(name))
1347 ret.append(name);
1348 else
1350 ret.append(1, '.');
1351 ret.append(Gogo::pkgpath_for_symbol(Gogo::hidden_name_pkgpath(name)));
1352 ret.append(1, '.');
1353 ret.append(Gogo::unpack_hidden_name(name));
1356 return ret;
1359 // Return true if this type descriptor is defined in a different
1360 // package. If this returns true it sets *PACKAGE to the package.
1362 bool
1363 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1364 const Package** package)
1366 if (nt != NULL)
1368 if (nt->named_object()->package() != NULL)
1370 // This is a named type defined in a different package. The
1371 // type descriptor should be defined in that package.
1372 *package = nt->named_object()->package();
1373 return true;
1376 else
1378 if (this->points_to() != NULL
1379 && this->points_to()->named_type() != NULL
1380 && this->points_to()->named_type()->named_object()->package() != NULL)
1382 // This is an unnamed pointer to a named type defined in a
1383 // different package. The descriptor should be defined in
1384 // that package.
1385 *package = this->points_to()->named_type()->named_object()->package();
1386 return true;
1389 return false;
1392 // Return a composite literal for a type descriptor.
1394 Expression*
1395 Type::type_descriptor(Gogo* gogo, Type* type)
1397 return type->do_type_descriptor(gogo, NULL);
1400 // Return a composite literal for a type descriptor with a name.
1402 Expression*
1403 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1405 go_assert(name != NULL && type->named_type() != name);
1406 return type->do_type_descriptor(gogo, name);
1409 // Generate the GC symbol for this TYPE. VALS is the data so far in this
1410 // symbol; extra values will be appended in do_gc_symbol. OFFSET is the
1411 // offset into the symbol where the GC data is located. STACK_SIZE is the
1412 // size of the GC stack when dealing with array types.
1414 void
1415 Type::gc_symbol(Gogo* gogo, Type* type, Expression_list** vals,
1416 Expression** offset, int stack_size)
1418 type->do_gc_symbol(gogo, vals, offset, stack_size);
1421 // Make a builtin struct type from a list of fields. The fields are
1422 // pairs of a name and a type.
1424 Struct_type*
1425 Type::make_builtin_struct_type(int nfields, ...)
1427 va_list ap;
1428 va_start(ap, nfields);
1430 Location bloc = Linemap::predeclared_location();
1431 Struct_field_list* sfl = new Struct_field_list();
1432 for (int i = 0; i < nfields; i++)
1434 const char* field_name = va_arg(ap, const char *);
1435 Type* type = va_arg(ap, Type*);
1436 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1439 va_end(ap);
1441 return Type::make_struct_type(sfl, bloc);
1444 // A list of builtin named types.
1446 std::vector<Named_type*> Type::named_builtin_types;
1448 // Make a builtin named type.
1450 Named_type*
1451 Type::make_builtin_named_type(const char* name, Type* type)
1453 Location bloc = Linemap::predeclared_location();
1454 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1455 Named_type* ret = no->type_value();
1456 Type::named_builtin_types.push_back(ret);
1457 return ret;
1460 // Convert the named builtin types.
1462 void
1463 Type::convert_builtin_named_types(Gogo* gogo)
1465 for (std::vector<Named_type*>::const_iterator p =
1466 Type::named_builtin_types.begin();
1467 p != Type::named_builtin_types.end();
1468 ++p)
1470 bool r = (*p)->verify();
1471 go_assert(r);
1472 (*p)->convert(gogo);
1476 // Return the type of a type descriptor. We should really tie this to
1477 // runtime.Type rather than copying it. This must match commonType in
1478 // libgo/go/runtime/type.go.
1480 Type*
1481 Type::make_type_descriptor_type()
1483 static Type* ret;
1484 if (ret == NULL)
1486 Location bloc = Linemap::predeclared_location();
1488 Type* uint8_type = Type::lookup_integer_type("uint8");
1489 Type* uint32_type = Type::lookup_integer_type("uint32");
1490 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1491 Type* string_type = Type::lookup_string_type();
1492 Type* pointer_string_type = Type::make_pointer_type(string_type);
1494 // This is an unnamed version of unsafe.Pointer. Perhaps we
1495 // should use the named version instead, although that would
1496 // require us to create the unsafe package if it has not been
1497 // imported. It probably doesn't matter.
1498 Type* void_type = Type::make_void_type();
1499 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1501 // Forward declaration for the type descriptor type.
1502 Named_object* named_type_descriptor_type =
1503 Named_object::make_type_declaration("commonType", NULL, bloc);
1504 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1505 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1507 // The type of a method on a concrete type.
1508 Struct_type* method_type =
1509 Type::make_builtin_struct_type(5,
1510 "name", pointer_string_type,
1511 "pkgPath", pointer_string_type,
1512 "mtyp", pointer_type_descriptor_type,
1513 "typ", pointer_type_descriptor_type,
1514 "tfn", unsafe_pointer_type);
1515 Named_type* named_method_type =
1516 Type::make_builtin_named_type("method", method_type);
1518 // Information for types with a name or methods.
1519 Type* slice_named_method_type =
1520 Type::make_array_type(named_method_type, NULL);
1521 Struct_type* uncommon_type =
1522 Type::make_builtin_struct_type(3,
1523 "name", pointer_string_type,
1524 "pkgPath", pointer_string_type,
1525 "methods", slice_named_method_type);
1526 Named_type* named_uncommon_type =
1527 Type::make_builtin_named_type("uncommonType", uncommon_type);
1529 Type* pointer_uncommon_type =
1530 Type::make_pointer_type(named_uncommon_type);
1532 // The type descriptor type.
1534 Struct_type* type_descriptor_type =
1535 Type::make_builtin_struct_type(12,
1536 "kind", uint8_type,
1537 "align", uint8_type,
1538 "fieldAlign", uint8_type,
1539 "size", uintptr_type,
1540 "hash", uint32_type,
1541 "hashfn", uintptr_type,
1542 "equalfn", uintptr_type,
1543 "gc", unsafe_pointer_type,
1544 "string", pointer_string_type,
1545 "", pointer_uncommon_type,
1546 "ptrToThis",
1547 pointer_type_descriptor_type,
1548 "zero", unsafe_pointer_type);
1550 Named_type* named = Type::make_builtin_named_type("commonType",
1551 type_descriptor_type);
1553 named_type_descriptor_type->set_type_value(named);
1555 ret = named;
1558 return ret;
1561 // Make the type of a pointer to a type descriptor as represented in
1562 // Go.
1564 Type*
1565 Type::make_type_descriptor_ptr_type()
1567 static Type* ret;
1568 if (ret == NULL)
1569 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1570 return ret;
1573 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1574 // hash code for this type and which compare whether two values of
1575 // this type are equal. If NAME is not NULL it is the name of this
1576 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1577 // functions, for convenience; they may be NULL.
1579 void
1580 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1581 Function_type* equal_fntype, Named_object** hash_fn,
1582 Named_object** equal_fn)
1584 if (hash_fntype == NULL || equal_fntype == NULL)
1586 Location bloc = Linemap::predeclared_location();
1588 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1589 Type* void_type = Type::make_void_type();
1590 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1592 if (hash_fntype == NULL)
1594 Typed_identifier_list* params = new Typed_identifier_list();
1595 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1596 bloc));
1597 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1599 Typed_identifier_list* results = new Typed_identifier_list();
1600 results->push_back(Typed_identifier("", uintptr_type, bloc));
1602 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1604 if (equal_fntype == NULL)
1606 Typed_identifier_list* params = new Typed_identifier_list();
1607 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1608 bloc));
1609 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1610 bloc));
1611 params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1613 Typed_identifier_list* results = new Typed_identifier_list();
1614 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1615 bloc));
1617 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1621 const char* hash_fnname;
1622 const char* equal_fnname;
1623 if (this->compare_is_identity(gogo))
1625 hash_fnname = "__go_type_hash_identity";
1626 equal_fnname = "__go_type_equal_identity";
1628 else if (!this->is_comparable())
1630 hash_fnname = "__go_type_hash_error";
1631 equal_fnname = "__go_type_equal_error";
1633 else
1635 switch (this->base()->classification())
1637 case Type::TYPE_ERROR:
1638 case Type::TYPE_VOID:
1639 case Type::TYPE_NIL:
1640 case Type::TYPE_FUNCTION:
1641 case Type::TYPE_MAP:
1642 // For these types is_comparable should have returned false.
1643 go_unreachable();
1645 case Type::TYPE_BOOLEAN:
1646 case Type::TYPE_INTEGER:
1647 case Type::TYPE_POINTER:
1648 case Type::TYPE_CHANNEL:
1649 // For these types compare_is_identity should have returned true.
1650 go_unreachable();
1652 case Type::TYPE_FLOAT:
1653 hash_fnname = "__go_type_hash_float";
1654 equal_fnname = "__go_type_equal_float";
1655 break;
1657 case Type::TYPE_COMPLEX:
1658 hash_fnname = "__go_type_hash_complex";
1659 equal_fnname = "__go_type_equal_complex";
1660 break;
1662 case Type::TYPE_STRING:
1663 hash_fnname = "__go_type_hash_string";
1664 equal_fnname = "__go_type_equal_string";
1665 break;
1667 case Type::TYPE_STRUCT:
1669 // This is a struct which can not be compared using a
1670 // simple identity function. We need to build a function
1671 // for comparison.
1672 this->specific_type_functions(gogo, name, hash_fntype,
1673 equal_fntype, hash_fn, equal_fn);
1674 return;
1677 case Type::TYPE_ARRAY:
1678 if (this->is_slice_type())
1680 // Type::is_compatible_for_comparison should have
1681 // returned false.
1682 go_unreachable();
1684 else
1686 // This is an array which can not be compared using a
1687 // simple identity function. We need to build a
1688 // function for comparison.
1689 this->specific_type_functions(gogo, name, hash_fntype,
1690 equal_fntype, hash_fn, equal_fn);
1691 return;
1693 break;
1695 case Type::TYPE_INTERFACE:
1696 if (this->interface_type()->is_empty())
1698 hash_fnname = "__go_type_hash_empty_interface";
1699 equal_fnname = "__go_type_equal_empty_interface";
1701 else
1703 hash_fnname = "__go_type_hash_interface";
1704 equal_fnname = "__go_type_equal_interface";
1706 break;
1708 case Type::TYPE_NAMED:
1709 case Type::TYPE_FORWARD:
1710 go_unreachable();
1712 default:
1713 go_unreachable();
1718 Location bloc = Linemap::predeclared_location();
1719 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1720 hash_fntype, bloc);
1721 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1722 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1723 equal_fntype, bloc);
1724 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1727 // A hash table mapping types to the specific hash functions.
1729 Type::Type_functions Type::type_functions_table;
1731 // Handle a type function which is specific to a type: a struct or
1732 // array which can not use an identity comparison.
1734 void
1735 Type::specific_type_functions(Gogo* gogo, Named_type* name,
1736 Function_type* hash_fntype,
1737 Function_type* equal_fntype,
1738 Named_object** hash_fn,
1739 Named_object** equal_fn)
1741 Hash_equal_fn fnull(NULL, NULL);
1742 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1743 std::pair<Type_functions::iterator, bool> ins =
1744 Type::type_functions_table.insert(val);
1745 if (!ins.second)
1747 // We already have functions for this type
1748 *hash_fn = ins.first->second.first;
1749 *equal_fn = ins.first->second.second;
1750 return;
1753 std::string base_name;
1754 if (name == NULL)
1756 // Mangled names can have '.' if they happen to refer to named
1757 // types in some way. That's fine if this is simply a named
1758 // type, but otherwise it will confuse the code that builds
1759 // function identifiers. Remove '.' when necessary.
1760 base_name = this->mangled_name(gogo);
1761 size_t i;
1762 while ((i = base_name.find('.')) != std::string::npos)
1763 base_name[i] = '$';
1764 base_name = gogo->pack_hidden_name(base_name, false);
1766 else
1768 // This name is already hidden or not as appropriate.
1769 base_name = name->name();
1770 unsigned int index;
1771 const Named_object* in_function = name->in_function(&index);
1772 if (in_function != NULL)
1774 base_name += '$' + Gogo::unpack_hidden_name(in_function->name());
1775 if (index > 0)
1777 char buf[30];
1778 snprintf(buf, sizeof buf, "%u", index);
1779 base_name += '$';
1780 base_name += buf;
1784 std::string hash_name = base_name + "$hash";
1785 std::string equal_name = base_name + "$equal";
1787 Location bloc = Linemap::predeclared_location();
1789 const Package* package = NULL;
1790 bool is_defined_elsewhere =
1791 this->type_descriptor_defined_elsewhere(name, &package);
1792 if (is_defined_elsewhere)
1794 *hash_fn = Named_object::make_function_declaration(hash_name, package,
1795 hash_fntype, bloc);
1796 *equal_fn = Named_object::make_function_declaration(equal_name, package,
1797 equal_fntype, bloc);
1799 else
1801 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
1802 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
1803 bloc);
1806 ins.first->second.first = *hash_fn;
1807 ins.first->second.second = *equal_fn;
1809 if (!is_defined_elsewhere)
1811 if (gogo->in_global_scope())
1812 this->write_specific_type_functions(gogo, name, hash_name, hash_fntype,
1813 equal_name, equal_fntype);
1814 else
1815 gogo->queue_specific_type_function(this, name, hash_name, hash_fntype,
1816 equal_name, equal_fntype);
1820 // Write the hash and equality functions for a type which needs to be
1821 // written specially.
1823 void
1824 Type::write_specific_type_functions(Gogo* gogo, Named_type* name,
1825 const std::string& hash_name,
1826 Function_type* hash_fntype,
1827 const std::string& equal_name,
1828 Function_type* equal_fntype)
1830 Location bloc = Linemap::predeclared_location();
1832 if (gogo->specific_type_functions_are_written())
1834 go_assert(saw_errors());
1835 return;
1838 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
1839 bloc);
1840 gogo->start_block(bloc);
1842 if (name != NULL && name->real_type()->named_type() != NULL)
1843 this->write_named_hash(gogo, name, hash_fntype, equal_fntype);
1844 else if (this->struct_type() != NULL)
1845 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
1846 equal_fntype);
1847 else if (this->array_type() != NULL)
1848 this->array_type()->write_hash_function(gogo, name, hash_fntype,
1849 equal_fntype);
1850 else
1851 go_unreachable();
1853 Block* b = gogo->finish_block(bloc);
1854 gogo->add_block(b, bloc);
1855 gogo->lower_block(hash_fn, b);
1856 gogo->finish_function(bloc);
1858 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
1859 false, bloc);
1860 gogo->start_block(bloc);
1862 if (name != NULL && name->real_type()->named_type() != NULL)
1863 this->write_named_equal(gogo, name);
1864 else if (this->struct_type() != NULL)
1865 this->struct_type()->write_equal_function(gogo, name);
1866 else if (this->array_type() != NULL)
1867 this->array_type()->write_equal_function(gogo, name);
1868 else
1869 go_unreachable();
1871 b = gogo->finish_block(bloc);
1872 gogo->add_block(b, bloc);
1873 gogo->lower_block(equal_fn, b);
1874 gogo->finish_function(bloc);
1877 // Write a hash function that simply calls the hash function for a
1878 // named type. This is used when one named type is defined as
1879 // another. This ensures that this case works when the other named
1880 // type is defined in another package and relies on calling hash
1881 // functions defined only in that package.
1883 void
1884 Type::write_named_hash(Gogo* gogo, Named_type* name,
1885 Function_type* hash_fntype, Function_type* equal_fntype)
1887 Location bloc = Linemap::predeclared_location();
1889 Named_type* base_type = name->real_type()->named_type();
1890 go_assert(base_type != NULL);
1892 // The pointer to the type we are going to hash. This is an
1893 // unsafe.Pointer.
1894 Named_object* key_arg = gogo->lookup("key", NULL);
1895 go_assert(key_arg != NULL);
1897 // The size of the type we are going to hash.
1898 Named_object* keysz_arg = gogo->lookup("key_size", NULL);
1899 go_assert(keysz_arg != NULL);
1901 Named_object* hash_fn;
1902 Named_object* equal_fn;
1903 name->real_type()->type_functions(gogo, base_type, hash_fntype, equal_fntype,
1904 &hash_fn, &equal_fn);
1906 // Call the hash function for the base type.
1907 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
1908 Expression* keysz_ref = Expression::make_var_reference(keysz_arg, bloc);
1909 Expression_list* args = new Expression_list();
1910 args->push_back(key_ref);
1911 args->push_back(keysz_ref);
1912 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
1913 Expression* call = Expression::make_call(func, args, false, bloc);
1915 // Return the hash of the base type.
1916 Expression_list* vals = new Expression_list();
1917 vals->push_back(call);
1918 Statement* s = Statement::make_return_statement(vals, bloc);
1919 gogo->add_statement(s);
1922 // Write an equality function that simply calls the equality function
1923 // for a named type. This is used when one named type is defined as
1924 // another. This ensures that this case works when the other named
1925 // type is defined in another package and relies on calling equality
1926 // functions defined only in that package.
1928 void
1929 Type::write_named_equal(Gogo* gogo, Named_type* name)
1931 Location bloc = Linemap::predeclared_location();
1933 // The pointers to the types we are going to compare. These have
1934 // type unsafe.Pointer.
1935 Named_object* key1_arg = gogo->lookup("key1", NULL);
1936 Named_object* key2_arg = gogo->lookup("key2", NULL);
1937 go_assert(key1_arg != NULL && key2_arg != NULL);
1939 Named_type* base_type = name->real_type()->named_type();
1940 go_assert(base_type != NULL);
1942 // Build temporaries with the base type.
1943 Type* pt = Type::make_pointer_type(base_type);
1945 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
1946 ref = Expression::make_cast(pt, ref, bloc);
1947 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
1948 gogo->add_statement(p1);
1950 ref = Expression::make_var_reference(key2_arg, bloc);
1951 ref = Expression::make_cast(pt, ref, bloc);
1952 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
1953 gogo->add_statement(p2);
1955 // Compare the values for equality.
1956 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
1957 t1 = Expression::make_unary(OPERATOR_MULT, t1, bloc);
1959 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
1960 t2 = Expression::make_unary(OPERATOR_MULT, t2, bloc);
1962 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
1964 // Return the equality comparison.
1965 Expression_list* vals = new Expression_list();
1966 vals->push_back(cond);
1967 Statement* s = Statement::make_return_statement(vals, bloc);
1968 gogo->add_statement(s);
1971 // Return a composite literal for the type descriptor for a plain type
1972 // of kind RUNTIME_TYPE_KIND named NAME.
1974 Expression*
1975 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
1976 Named_type* name, const Methods* methods,
1977 bool only_value_methods)
1979 Location bloc = Linemap::predeclared_location();
1981 Type* td_type = Type::make_type_descriptor_type();
1982 const Struct_field_list* fields = td_type->struct_type()->fields();
1984 Expression_list* vals = new Expression_list();
1985 vals->reserve(9);
1987 if (!this->has_pointer())
1988 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
1989 Struct_field_list::const_iterator p = fields->begin();
1990 go_assert(p->is_field_name("kind"));
1991 mpz_t iv;
1992 mpz_init_set_ui(iv, runtime_type_kind);
1993 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1995 ++p;
1996 go_assert(p->is_field_name("align"));
1997 Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT;
1998 vals->push_back(Expression::make_type_info(this, type_info));
2000 ++p;
2001 go_assert(p->is_field_name("fieldAlign"));
2002 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2003 vals->push_back(Expression::make_type_info(this, type_info));
2005 ++p;
2006 go_assert(p->is_field_name("size"));
2007 type_info = Expression::TYPE_INFO_SIZE;
2008 vals->push_back(Expression::make_type_info(this, type_info));
2010 ++p;
2011 go_assert(p->is_field_name("hash"));
2012 unsigned int h;
2013 if (name != NULL)
2014 h = name->hash_for_method(gogo);
2015 else
2016 h = this->hash_for_method(gogo);
2017 mpz_set_ui(iv, h);
2018 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
2020 ++p;
2021 go_assert(p->is_field_name("hashfn"));
2022 Function_type* hash_fntype = p->type()->function_type();
2024 ++p;
2025 go_assert(p->is_field_name("equalfn"));
2026 Function_type* equal_fntype = p->type()->function_type();
2028 Named_object* hash_fn;
2029 Named_object* equal_fn;
2030 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
2031 &equal_fn);
2032 vals->push_back(Expression::make_func_code_reference(hash_fn, bloc));
2033 vals->push_back(Expression::make_func_code_reference(equal_fn, bloc));
2035 ++p;
2036 go_assert(p->is_field_name("gc"));
2037 vals->push_back(Expression::make_gc_symbol(this));
2039 ++p;
2040 go_assert(p->is_field_name("string"));
2041 Expression* s = Expression::make_string((name != NULL
2042 ? name->reflection(gogo)
2043 : this->reflection(gogo)),
2044 bloc);
2045 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2047 ++p;
2048 go_assert(p->is_field_name("uncommonType"));
2049 if (name == NULL && methods == NULL)
2050 vals->push_back(Expression::make_nil(bloc));
2051 else
2053 if (methods == NULL)
2054 methods = name->methods();
2055 vals->push_back(this->uncommon_type_constructor(gogo,
2056 p->type()->deref(),
2057 name, methods,
2058 only_value_methods));
2061 ++p;
2062 go_assert(p->is_field_name("ptrToThis"));
2063 if (name == NULL)
2064 vals->push_back(Expression::make_nil(bloc));
2065 else
2067 Type* pt = Type::make_pointer_type(name);
2068 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2071 ++p;
2072 go_assert(p->is_field_name("zero"));
2073 Expression* z = Expression::make_var_reference(gogo->zero_value(this), bloc);
2074 z = Expression::make_unary(OPERATOR_AND, z, bloc);
2075 Type* void_type = Type::make_void_type();
2076 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
2077 z = Expression::make_cast(unsafe_pointer_type, z, bloc);
2078 vals->push_back(z);
2080 ++p;
2081 go_assert(p == fields->end());
2083 mpz_clear(iv);
2085 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2088 // Return a pointer to the Garbage Collection information for this type.
2090 Bexpression*
2091 Type::gc_symbol_pointer(Gogo* gogo)
2093 Type* t = this->forwarded();
2094 if (t->named_type() != NULL && t->named_type()->is_alias())
2095 t = t->named_type()->real_type();
2096 if (t->gc_symbol_var_ == NULL)
2098 t->make_gc_symbol_var(gogo);
2099 go_assert(t->gc_symbol_var_ != NULL);
2101 Location bloc = Linemap::predeclared_location();
2102 Bexpression* var_expr =
2103 gogo->backend()->var_expression(t->gc_symbol_var_, bloc);
2104 return gogo->backend()->address_expression(var_expr, bloc);
2107 // A mapping from unnamed types to GC symbol variables.
2109 Type::GC_symbol_vars Type::gc_symbol_vars;
2111 // Build the GC symbol for this type.
2113 void
2114 Type::make_gc_symbol_var(Gogo* gogo)
2116 go_assert(this->gc_symbol_var_ == NULL);
2118 Named_type* nt = this->named_type();
2120 // We can have multiple instances of unnamed types and similar to type
2121 // descriptors, we only want to the emit the GC data once, so we use a
2122 // hash table.
2123 Bvariable** phash = NULL;
2124 if (nt == NULL)
2126 Bvariable* bvnull = NULL;
2127 std::pair<GC_symbol_vars::iterator, bool> ins =
2128 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2129 if (!ins.second)
2131 // We've already built a gc symbol for this type.
2132 this->gc_symbol_var_ = ins.first->second;
2133 return;
2135 phash = &ins.first->second;
2138 std::string sym_name = this->type_descriptor_var_name(gogo, nt) + "$gc";
2140 // Build the contents of the gc symbol.
2141 Expression* sym_init = this->gc_symbol_constructor(gogo);
2142 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2144 // If the type descriptor for this type is defined somewhere else, so is the
2145 // GC symbol.
2146 const Package* dummy;
2147 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2149 this->gc_symbol_var_ =
2150 gogo->backend()->implicit_variable_reference(sym_name, sym_btype);
2151 if (phash != NULL)
2152 *phash = this->gc_symbol_var_;
2153 return;
2156 // See if this gc symbol can appear in multiple packages.
2157 bool is_common = false;
2158 if (nt != NULL)
2160 // We create the symbol for a builtin type whenever we need
2161 // it.
2162 is_common = nt->is_builtin();
2164 else
2166 // This is an unnamed type. The descriptor could be defined in
2167 // any package where it is needed, and the linker will pick one
2168 // descriptor to keep.
2169 is_common = true;
2172 // Since we are building the GC symbol in this package, we must create the
2173 // variable before converting the initializer to its backend representation
2174 // because the initializer may refer to the GC symbol for this type.
2175 this->gc_symbol_var_ =
2176 gogo->backend()->implicit_variable(sym_name, sym_btype, false, true, is_common, 0);
2177 if (phash != NULL)
2178 *phash = this->gc_symbol_var_;
2180 Translate_context context(gogo, NULL, NULL, NULL);
2181 context.set_is_const();
2182 Bexpression* sym_binit = sym_init->get_backend(&context);
2183 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2184 sym_btype, false, true, is_common,
2185 sym_binit);
2188 // Return an array literal for the Garbage Collection information for this type.
2190 Expression*
2191 Type::gc_symbol_constructor(Gogo* gogo)
2193 Location bloc = Linemap::predeclared_location();
2195 // The common GC Symbol data starts with the width of the type and ends
2196 // with the GC Opcode GC_END.
2197 // However, for certain types, the GC symbol may include extra information
2198 // before the ending opcode, so we pass the expression list into
2199 // Type::gc_symbol to allow it to add extra information as is necessary.
2200 Expression_list* vals = new Expression_list;
2202 Type* uintptr_t = Type::lookup_integer_type("uintptr");
2203 // width
2204 vals->push_back(Expression::make_type_info(this,
2205 Expression::TYPE_INFO_SIZE));
2207 mpz_t off;
2208 mpz_init_set_ui(off, 0UL);
2209 Expression* offset = Expression::make_integer(&off, uintptr_t, bloc);
2210 mpz_clear(off);
2212 this->do_gc_symbol(gogo, &vals, &offset, 0);
2214 mpz_t end;
2215 mpz_init_set_ui(end, GC_END);
2216 vals->push_back(Expression::make_integer(&end, uintptr_t, bloc));
2217 mpz_clear(end);
2219 mpz_t lenval;
2220 mpz_init_set_ui(lenval, vals->size() + 1);
2221 Expression* len = Expression::make_integer(&lenval, NULL, bloc);
2222 mpz_clear(lenval);
2224 Array_type* gc_symbol_type = Type::make_array_type(uintptr_t, len);
2225 return Expression::make_array_composite_literal(gc_symbol_type, vals, bloc);
2228 // Advance the OFFSET of the GC symbol by this type's width.
2230 void
2231 Type::advance_gc_offset(Expression** offset)
2233 if (this->is_error_type())
2234 return;
2236 Location bloc = Linemap::predeclared_location();
2237 Expression* width =
2238 Expression::make_type_info(this, Expression::TYPE_INFO_SIZE);
2239 *offset = Expression::make_binary(OPERATOR_PLUS, *offset, width, bloc);
2242 // Return a composite literal for the uncommon type information for
2243 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
2244 // struct. If name is not NULL, it is the name of the type. If
2245 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
2246 // is true if only value methods should be included. At least one of
2247 // NAME and METHODS must not be NULL.
2249 Expression*
2250 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
2251 Named_type* name, const Methods* methods,
2252 bool only_value_methods) const
2254 Location bloc = Linemap::predeclared_location();
2256 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
2258 Expression_list* vals = new Expression_list();
2259 vals->reserve(3);
2261 Struct_field_list::const_iterator p = fields->begin();
2262 go_assert(p->is_field_name("name"));
2264 ++p;
2265 go_assert(p->is_field_name("pkgPath"));
2267 if (name == NULL)
2269 vals->push_back(Expression::make_nil(bloc));
2270 vals->push_back(Expression::make_nil(bloc));
2272 else
2274 Named_object* no = name->named_object();
2275 std::string n = Gogo::unpack_hidden_name(no->name());
2276 Expression* s = Expression::make_string(n, bloc);
2277 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2279 if (name->is_builtin())
2280 vals->push_back(Expression::make_nil(bloc));
2281 else
2283 const Package* package = no->package();
2284 const std::string& pkgpath(package == NULL
2285 ? gogo->pkgpath()
2286 : package->pkgpath());
2287 n.assign(pkgpath);
2288 unsigned int index;
2289 const Named_object* in_function = name->in_function(&index);
2290 if (in_function != NULL)
2292 n.append(1, '.');
2293 n.append(Gogo::unpack_hidden_name(in_function->name()));
2294 if (index > 0)
2296 char buf[30];
2297 snprintf(buf, sizeof buf, "%u", index);
2298 n.append(1, '.');
2299 n.append(buf);
2302 s = Expression::make_string(n, bloc);
2303 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2307 ++p;
2308 go_assert(p->is_field_name("methods"));
2309 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
2310 only_value_methods));
2312 ++p;
2313 go_assert(p == fields->end());
2315 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
2316 vals, bloc);
2317 return Expression::make_unary(OPERATOR_AND, r, bloc);
2320 // Sort methods by name.
2322 class Sort_methods
2324 public:
2325 bool
2326 operator()(const std::pair<std::string, const Method*>& m1,
2327 const std::pair<std::string, const Method*>& m2) const
2328 { return m1.first < m2.first; }
2331 // Return a composite literal for the type method table for this type.
2332 // METHODS_TYPE is the type of the table, and is a slice type.
2333 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
2334 // then only value methods are used.
2336 Expression*
2337 Type::methods_constructor(Gogo* gogo, Type* methods_type,
2338 const Methods* methods,
2339 bool only_value_methods) const
2341 Location bloc = Linemap::predeclared_location();
2343 std::vector<std::pair<std::string, const Method*> > smethods;
2344 if (methods != NULL)
2346 smethods.reserve(methods->count());
2347 for (Methods::const_iterator p = methods->begin();
2348 p != methods->end();
2349 ++p)
2351 if (p->second->is_ambiguous())
2352 continue;
2353 if (only_value_methods && !p->second->is_value_method())
2354 continue;
2356 // This is where we implement the magic //go:nointerface
2357 // comment. If we saw that comment, we don't add this
2358 // method to the type descriptor.
2359 if (p->second->nointerface())
2360 continue;
2362 smethods.push_back(std::make_pair(p->first, p->second));
2366 if (smethods.empty())
2367 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
2369 std::sort(smethods.begin(), smethods.end(), Sort_methods());
2371 Type* method_type = methods_type->array_type()->element_type();
2373 Expression_list* vals = new Expression_list();
2374 vals->reserve(smethods.size());
2375 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
2376 = smethods.begin();
2377 p != smethods.end();
2378 ++p)
2379 vals->push_back(this->method_constructor(gogo, method_type, p->first,
2380 p->second, only_value_methods));
2382 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
2385 // Return a composite literal for a single method. METHOD_TYPE is the
2386 // type of the entry. METHOD_NAME is the name of the method and M is
2387 // the method information.
2389 Expression*
2390 Type::method_constructor(Gogo*, Type* method_type,
2391 const std::string& method_name,
2392 const Method* m,
2393 bool only_value_methods) const
2395 Location bloc = Linemap::predeclared_location();
2397 const Struct_field_list* fields = method_type->struct_type()->fields();
2399 Expression_list* vals = new Expression_list();
2400 vals->reserve(5);
2402 Struct_field_list::const_iterator p = fields->begin();
2403 go_assert(p->is_field_name("name"));
2404 const std::string n = Gogo::unpack_hidden_name(method_name);
2405 Expression* s = Expression::make_string(n, bloc);
2406 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2408 ++p;
2409 go_assert(p->is_field_name("pkgPath"));
2410 if (!Gogo::is_hidden_name(method_name))
2411 vals->push_back(Expression::make_nil(bloc));
2412 else
2414 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
2415 bloc);
2416 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2419 Named_object* no = (m->needs_stub_method()
2420 ? m->stub_object()
2421 : m->named_object());
2423 Function_type* mtype;
2424 if (no->is_function())
2425 mtype = no->func_value()->type();
2426 else
2427 mtype = no->func_declaration_value()->type();
2428 go_assert(mtype->is_method());
2429 Type* nonmethod_type = mtype->copy_without_receiver();
2431 ++p;
2432 go_assert(p->is_field_name("mtyp"));
2433 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
2435 ++p;
2436 go_assert(p->is_field_name("typ"));
2437 bool want_pointer_receiver = !only_value_methods && m->is_value_method();
2438 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
2439 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
2441 ++p;
2442 go_assert(p->is_field_name("tfn"));
2443 vals->push_back(Expression::make_func_code_reference(no, bloc));
2445 ++p;
2446 go_assert(p == fields->end());
2448 return Expression::make_struct_composite_literal(method_type, vals, bloc);
2451 // Return a composite literal for the type descriptor of a plain type.
2452 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
2453 // NULL, it is the name to use as well as the list of methods.
2455 Expression*
2456 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
2457 Named_type* name)
2459 return this->type_descriptor_constructor(gogo, runtime_type_kind,
2460 name, NULL, true);
2463 // Return the type reflection string for this type.
2465 std::string
2466 Type::reflection(Gogo* gogo) const
2468 std::string ret;
2470 // The do_reflection virtual function should set RET to the
2471 // reflection string.
2472 this->do_reflection(gogo, &ret);
2474 return ret;
2477 // Return a mangled name for the type.
2479 std::string
2480 Type::mangled_name(Gogo* gogo) const
2482 std::string ret;
2484 // The do_mangled_name virtual function should set RET to the
2485 // mangled name. For a composite type it should append a code for
2486 // the composition and then call do_mangled_name on the components.
2487 this->do_mangled_name(gogo, &ret);
2489 return ret;
2492 // Return whether the backend size of the type is known.
2494 bool
2495 Type::is_backend_type_size_known(Gogo* gogo)
2497 switch (this->classification_)
2499 case TYPE_ERROR:
2500 case TYPE_VOID:
2501 case TYPE_BOOLEAN:
2502 case TYPE_INTEGER:
2503 case TYPE_FLOAT:
2504 case TYPE_COMPLEX:
2505 case TYPE_STRING:
2506 case TYPE_FUNCTION:
2507 case TYPE_POINTER:
2508 case TYPE_NIL:
2509 case TYPE_MAP:
2510 case TYPE_CHANNEL:
2511 case TYPE_INTERFACE:
2512 return true;
2514 case TYPE_STRUCT:
2516 const Struct_field_list* fields = this->struct_type()->fields();
2517 for (Struct_field_list::const_iterator pf = fields->begin();
2518 pf != fields->end();
2519 ++pf)
2520 if (!pf->type()->is_backend_type_size_known(gogo))
2521 return false;
2522 return true;
2525 case TYPE_ARRAY:
2527 const Array_type* at = this->array_type();
2528 if (at->length() == NULL)
2529 return true;
2530 else
2532 Numeric_constant nc;
2533 if (!at->length()->numeric_constant_value(&nc))
2534 return false;
2535 mpz_t ival;
2536 if (!nc.to_int(&ival))
2537 return false;
2538 mpz_clear(ival);
2539 return at->element_type()->is_backend_type_size_known(gogo);
2543 case TYPE_NAMED:
2544 this->named_type()->convert(gogo);
2545 return this->named_type()->is_named_backend_type_size_known();
2547 case TYPE_FORWARD:
2549 Forward_declaration_type* fdt = this->forward_declaration_type();
2550 return fdt->real_type()->is_backend_type_size_known(gogo);
2553 case TYPE_SINK:
2554 case TYPE_CALL_MULTIPLE_RESULT:
2555 go_unreachable();
2557 default:
2558 go_unreachable();
2562 // If the size of the type can be determined, set *PSIZE to the size
2563 // in bytes and return true. Otherwise, return false. This queries
2564 // the backend.
2566 bool
2567 Type::backend_type_size(Gogo* gogo, unsigned long *psize)
2569 if (!this->is_backend_type_size_known(gogo))
2570 return false;
2571 Btype* bt = this->get_backend_placeholder(gogo);
2572 size_t size = gogo->backend()->type_size(bt);
2573 *psize = static_cast<unsigned long>(size);
2574 if (*psize != size)
2575 return false;
2576 return true;
2579 // If the alignment of the type can be determined, set *PALIGN to
2580 // the alignment in bytes and return true. Otherwise, return false.
2582 bool
2583 Type::backend_type_align(Gogo* gogo, unsigned long *palign)
2585 if (!this->is_backend_type_size_known(gogo))
2586 return false;
2587 Btype* bt = this->get_backend_placeholder(gogo);
2588 size_t align = gogo->backend()->type_alignment(bt);
2589 *palign = static_cast<unsigned long>(align);
2590 if (*palign != align)
2591 return false;
2592 return true;
2595 // Like backend_type_align, but return the alignment when used as a
2596 // field.
2598 bool
2599 Type::backend_type_field_align(Gogo* gogo, unsigned long *palign)
2601 if (!this->is_backend_type_size_known(gogo))
2602 return false;
2603 Btype* bt = this->get_backend_placeholder(gogo);
2604 size_t a = gogo->backend()->type_field_alignment(bt);
2605 *palign = static_cast<unsigned long>(a);
2606 if (*palign != a)
2607 return false;
2608 return true;
2611 // Default function to export a type.
2613 void
2614 Type::do_export(Export*) const
2616 go_unreachable();
2619 // Import a type.
2621 Type*
2622 Type::import_type(Import* imp)
2624 if (imp->match_c_string("("))
2625 return Function_type::do_import(imp);
2626 else if (imp->match_c_string("*"))
2627 return Pointer_type::do_import(imp);
2628 else if (imp->match_c_string("struct "))
2629 return Struct_type::do_import(imp);
2630 else if (imp->match_c_string("["))
2631 return Array_type::do_import(imp);
2632 else if (imp->match_c_string("map "))
2633 return Map_type::do_import(imp);
2634 else if (imp->match_c_string("chan "))
2635 return Channel_type::do_import(imp);
2636 else if (imp->match_c_string("interface"))
2637 return Interface_type::do_import(imp);
2638 else
2640 error_at(imp->location(), "import error: expected type");
2641 return Type::make_error_type();
2645 // A type used to indicate a parsing error. This exists to simplify
2646 // later error detection.
2648 class Error_type : public Type
2650 public:
2651 Error_type()
2652 : Type(TYPE_ERROR)
2655 protected:
2656 bool
2657 do_compare_is_identity(Gogo*)
2658 { return false; }
2660 Btype*
2661 do_get_backend(Gogo* gogo)
2662 { return gogo->backend()->error_type(); }
2664 Expression*
2665 do_type_descriptor(Gogo*, Named_type*)
2666 { return Expression::make_error(Linemap::predeclared_location()); }
2668 void
2669 do_reflection(Gogo*, std::string*) const
2670 { go_assert(saw_errors()); }
2672 void
2673 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
2674 { go_assert(saw_errors()); }
2676 void
2677 do_mangled_name(Gogo*, std::string* ret) const
2678 { ret->push_back('E'); }
2681 Type*
2682 Type::make_error_type()
2684 static Error_type singleton_error_type;
2685 return &singleton_error_type;
2688 // The void type.
2690 class Void_type : public Type
2692 public:
2693 Void_type()
2694 : Type(TYPE_VOID)
2697 protected:
2698 bool
2699 do_compare_is_identity(Gogo*)
2700 { return false; }
2702 Btype*
2703 do_get_backend(Gogo* gogo)
2704 { return gogo->backend()->void_type(); }
2706 Expression*
2707 do_type_descriptor(Gogo*, Named_type*)
2708 { go_unreachable(); }
2710 void
2711 do_reflection(Gogo*, std::string*) const
2714 void
2715 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
2718 void
2719 do_mangled_name(Gogo*, std::string* ret) const
2720 { ret->push_back('v'); }
2723 Type*
2724 Type::make_void_type()
2726 static Void_type singleton_void_type;
2727 return &singleton_void_type;
2730 // The boolean type.
2732 class Boolean_type : public Type
2734 public:
2735 Boolean_type()
2736 : Type(TYPE_BOOLEAN)
2739 protected:
2740 bool
2741 do_compare_is_identity(Gogo*)
2742 { return true; }
2744 Btype*
2745 do_get_backend(Gogo* gogo)
2746 { return gogo->backend()->bool_type(); }
2748 Expression*
2749 do_type_descriptor(Gogo*, Named_type* name);
2751 // We should not be asked for the reflection string of a basic type.
2752 void
2753 do_reflection(Gogo*, std::string* ret) const
2754 { ret->append("bool"); }
2756 void
2757 do_gc_symbol(Gogo*, Expression_list**, Expression**, int);
2759 void
2760 do_mangled_name(Gogo*, std::string* ret) const
2761 { ret->push_back('b'); }
2764 // Make the type descriptor.
2766 Expression*
2767 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2769 if (name != NULL)
2770 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
2771 else
2773 Named_object* no = gogo->lookup_global("bool");
2774 go_assert(no != NULL);
2775 return Type::type_descriptor(gogo, no->type_value());
2779 // Update the offset of the GC symbol.
2781 void
2782 Boolean_type::do_gc_symbol(Gogo*, Expression_list**, Expression** offset, int)
2783 { this->advance_gc_offset(offset); }
2785 Type*
2786 Type::make_boolean_type()
2788 static Boolean_type boolean_type;
2789 return &boolean_type;
2792 // The named type "bool".
2794 static Named_type* named_bool_type;
2796 // Get the named type "bool".
2798 Named_type*
2799 Type::lookup_bool_type()
2801 return named_bool_type;
2804 // Make the named type "bool".
2806 Named_type*
2807 Type::make_named_bool_type()
2809 Type* bool_type = Type::make_boolean_type();
2810 Named_object* named_object =
2811 Named_object::make_type("bool", NULL, bool_type,
2812 Linemap::predeclared_location());
2813 Named_type* named_type = named_object->type_value();
2814 named_bool_type = named_type;
2815 return named_type;
2818 // Class Integer_type.
2820 Integer_type::Named_integer_types Integer_type::named_integer_types;
2822 // Create a new integer type. Non-abstract integer types always have
2823 // names.
2825 Named_type*
2826 Integer_type::create_integer_type(const char* name, bool is_unsigned,
2827 int bits, int runtime_type_kind)
2829 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
2830 runtime_type_kind);
2831 std::string sname(name);
2832 Named_object* named_object =
2833 Named_object::make_type(sname, NULL, integer_type,
2834 Linemap::predeclared_location());
2835 Named_type* named_type = named_object->type_value();
2836 std::pair<Named_integer_types::iterator, bool> ins =
2837 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
2838 go_assert(ins.second);
2839 return named_type;
2842 // Look up an existing integer type.
2844 Named_type*
2845 Integer_type::lookup_integer_type(const char* name)
2847 Named_integer_types::const_iterator p =
2848 Integer_type::named_integer_types.find(name);
2849 go_assert(p != Integer_type::named_integer_types.end());
2850 return p->second;
2853 // Create a new abstract integer type.
2855 Integer_type*
2856 Integer_type::create_abstract_integer_type()
2858 static Integer_type* abstract_type;
2859 if (abstract_type == NULL)
2861 Type* int_type = Type::lookup_integer_type("int");
2862 abstract_type = new Integer_type(true, false,
2863 int_type->integer_type()->bits(),
2864 RUNTIME_TYPE_KIND_INT);
2866 return abstract_type;
2869 // Create a new abstract character type.
2871 Integer_type*
2872 Integer_type::create_abstract_character_type()
2874 static Integer_type* abstract_type;
2875 if (abstract_type == NULL)
2877 abstract_type = new Integer_type(true, false, 32,
2878 RUNTIME_TYPE_KIND_INT32);
2879 abstract_type->set_is_rune();
2881 return abstract_type;
2884 // Integer type compatibility.
2886 bool
2887 Integer_type::is_identical(const Integer_type* t) const
2889 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
2890 return false;
2891 return this->is_abstract_ == t->is_abstract_;
2894 // Hash code.
2896 unsigned int
2897 Integer_type::do_hash_for_method(Gogo*) const
2899 return ((this->bits_ << 4)
2900 + ((this->is_unsigned_ ? 1 : 0) << 8)
2901 + ((this->is_abstract_ ? 1 : 0) << 9));
2904 // Convert an Integer_type to the backend representation.
2906 Btype*
2907 Integer_type::do_get_backend(Gogo* gogo)
2909 if (this->is_abstract_)
2911 go_assert(saw_errors());
2912 return gogo->backend()->error_type();
2914 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
2917 // The type descriptor for an integer type. Integer types are always
2918 // named.
2920 Expression*
2921 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2923 go_assert(name != NULL || saw_errors());
2924 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2927 // We should not be asked for the reflection string of a basic type.
2929 void
2930 Integer_type::do_reflection(Gogo*, std::string*) const
2932 go_assert(saw_errors());
2935 // Mangled name.
2937 void
2938 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
2940 char buf[100];
2941 snprintf(buf, sizeof buf, "i%s%s%de",
2942 this->is_abstract_ ? "a" : "",
2943 this->is_unsigned_ ? "u" : "",
2944 this->bits_);
2945 ret->append(buf);
2948 // Make an integer type.
2950 Named_type*
2951 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
2952 int runtime_type_kind)
2954 return Integer_type::create_integer_type(name, is_unsigned, bits,
2955 runtime_type_kind);
2958 // Make an abstract integer type.
2960 Integer_type*
2961 Type::make_abstract_integer_type()
2963 return Integer_type::create_abstract_integer_type();
2966 // Make an abstract character type.
2968 Integer_type*
2969 Type::make_abstract_character_type()
2971 return Integer_type::create_abstract_character_type();
2974 // Look up an integer type.
2976 Named_type*
2977 Type::lookup_integer_type(const char* name)
2979 return Integer_type::lookup_integer_type(name);
2982 // Class Float_type.
2984 Float_type::Named_float_types Float_type::named_float_types;
2986 // Create a new float type. Non-abstract float types always have
2987 // names.
2989 Named_type*
2990 Float_type::create_float_type(const char* name, int bits,
2991 int runtime_type_kind)
2993 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
2994 std::string sname(name);
2995 Named_object* named_object =
2996 Named_object::make_type(sname, NULL, float_type,
2997 Linemap::predeclared_location());
2998 Named_type* named_type = named_object->type_value();
2999 std::pair<Named_float_types::iterator, bool> ins =
3000 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
3001 go_assert(ins.second);
3002 return named_type;
3005 // Look up an existing float type.
3007 Named_type*
3008 Float_type::lookup_float_type(const char* name)
3010 Named_float_types::const_iterator p =
3011 Float_type::named_float_types.find(name);
3012 go_assert(p != Float_type::named_float_types.end());
3013 return p->second;
3016 // Create a new abstract float type.
3018 Float_type*
3019 Float_type::create_abstract_float_type()
3021 static Float_type* abstract_type;
3022 if (abstract_type == NULL)
3023 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
3024 return abstract_type;
3027 // Whether this type is identical with T.
3029 bool
3030 Float_type::is_identical(const Float_type* t) const
3032 if (this->bits_ != t->bits_)
3033 return false;
3034 return this->is_abstract_ == t->is_abstract_;
3037 // Hash code.
3039 unsigned int
3040 Float_type::do_hash_for_method(Gogo*) const
3042 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
3045 // Convert to the backend representation.
3047 Btype*
3048 Float_type::do_get_backend(Gogo* gogo)
3050 return gogo->backend()->float_type(this->bits_);
3053 // The type descriptor for a float type. Float types are always named.
3055 Expression*
3056 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3058 go_assert(name != NULL || saw_errors());
3059 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
3062 // We should not be asked for the reflection string of a basic type.
3064 void
3065 Float_type::do_reflection(Gogo*, std::string*) const
3067 go_assert(saw_errors());
3070 // Mangled name.
3072 void
3073 Float_type::do_mangled_name(Gogo*, std::string* ret) const
3075 char buf[100];
3076 snprintf(buf, sizeof buf, "f%s%de",
3077 this->is_abstract_ ? "a" : "",
3078 this->bits_);
3079 ret->append(buf);
3082 // Make a floating point type.
3084 Named_type*
3085 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
3087 return Float_type::create_float_type(name, bits, runtime_type_kind);
3090 // Make an abstract float type.
3092 Float_type*
3093 Type::make_abstract_float_type()
3095 return Float_type::create_abstract_float_type();
3098 // Look up a float type.
3100 Named_type*
3101 Type::lookup_float_type(const char* name)
3103 return Float_type::lookup_float_type(name);
3106 // Class Complex_type.
3108 Complex_type::Named_complex_types Complex_type::named_complex_types;
3110 // Create a new complex type. Non-abstract complex types always have
3111 // names.
3113 Named_type*
3114 Complex_type::create_complex_type(const char* name, int bits,
3115 int runtime_type_kind)
3117 Complex_type* complex_type = new Complex_type(false, bits,
3118 runtime_type_kind);
3119 std::string sname(name);
3120 Named_object* named_object =
3121 Named_object::make_type(sname, NULL, complex_type,
3122 Linemap::predeclared_location());
3123 Named_type* named_type = named_object->type_value();
3124 std::pair<Named_complex_types::iterator, bool> ins =
3125 Complex_type::named_complex_types.insert(std::make_pair(sname,
3126 named_type));
3127 go_assert(ins.second);
3128 return named_type;
3131 // Look up an existing complex type.
3133 Named_type*
3134 Complex_type::lookup_complex_type(const char* name)
3136 Named_complex_types::const_iterator p =
3137 Complex_type::named_complex_types.find(name);
3138 go_assert(p != Complex_type::named_complex_types.end());
3139 return p->second;
3142 // Create a new abstract complex type.
3144 Complex_type*
3145 Complex_type::create_abstract_complex_type()
3147 static Complex_type* abstract_type;
3148 if (abstract_type == NULL)
3149 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
3150 return abstract_type;
3153 // Whether this type is identical with T.
3155 bool
3156 Complex_type::is_identical(const Complex_type *t) const
3158 if (this->bits_ != t->bits_)
3159 return false;
3160 return this->is_abstract_ == t->is_abstract_;
3163 // Hash code.
3165 unsigned int
3166 Complex_type::do_hash_for_method(Gogo*) const
3168 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
3171 // Convert to the backend representation.
3173 Btype*
3174 Complex_type::do_get_backend(Gogo* gogo)
3176 return gogo->backend()->complex_type(this->bits_);
3179 // The type descriptor for a complex type. Complex types are always
3180 // named.
3182 Expression*
3183 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3185 go_assert(name != NULL || saw_errors());
3186 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
3189 // We should not be asked for the reflection string of a basic type.
3191 void
3192 Complex_type::do_reflection(Gogo*, std::string*) const
3194 go_assert(saw_errors());
3197 // Mangled name.
3199 void
3200 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
3202 char buf[100];
3203 snprintf(buf, sizeof buf, "c%s%de",
3204 this->is_abstract_ ? "a" : "",
3205 this->bits_);
3206 ret->append(buf);
3209 // Make a complex type.
3211 Named_type*
3212 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
3214 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
3217 // Make an abstract complex type.
3219 Complex_type*
3220 Type::make_abstract_complex_type()
3222 return Complex_type::create_abstract_complex_type();
3225 // Look up a complex type.
3227 Named_type*
3228 Type::lookup_complex_type(const char* name)
3230 return Complex_type::lookup_complex_type(name);
3233 // Class String_type.
3235 // Convert String_type to the backend representation. A string is a
3236 // struct with two fields: a pointer to the characters and a length.
3238 Btype*
3239 String_type::do_get_backend(Gogo* gogo)
3241 static Btype* backend_string_type;
3242 if (backend_string_type == NULL)
3244 std::vector<Backend::Btyped_identifier> fields(2);
3246 Type* b = gogo->lookup_global("byte")->type_value();
3247 Type* pb = Type::make_pointer_type(b);
3249 // We aren't going to get back to this field to finish the
3250 // backend representation, so force it to be finished now.
3251 if (!gogo->named_types_are_converted())
3253 Btype* bt = pb->get_backend_placeholder(gogo);
3254 pb->finish_backend(gogo, bt);
3257 fields[0].name = "__data";
3258 fields[0].btype = pb->get_backend(gogo);
3259 fields[0].location = Linemap::predeclared_location();
3261 Type* int_type = Type::lookup_integer_type("int");
3262 fields[1].name = "__length";
3263 fields[1].btype = int_type->get_backend(gogo);
3264 fields[1].location = fields[0].location;
3266 backend_string_type = gogo->backend()->struct_type(fields);
3268 return backend_string_type;
3271 // The type descriptor for the string type.
3273 Expression*
3274 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3276 if (name != NULL)
3277 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
3278 else
3280 Named_object* no = gogo->lookup_global("string");
3281 go_assert(no != NULL);
3282 return Type::type_descriptor(gogo, no->type_value());
3286 // We should not be asked for the reflection string of a basic type.
3288 void
3289 String_type::do_reflection(Gogo*, std::string* ret) const
3291 ret->append("string");
3294 // Generate GC symbol for strings.
3296 void
3297 String_type::do_gc_symbol(Gogo*, Expression_list** vals,
3298 Expression** offset, int)
3300 Location bloc = Linemap::predeclared_location();
3301 Type* uintptr_type = Type::lookup_integer_type("uintptr");
3302 mpz_t opval;
3303 mpz_init_set_ui(opval, GC_STRING);
3304 (*vals)->push_back(Expression::make_integer(&opval, uintptr_type, bloc));
3305 mpz_clear(opval);
3306 (*vals)->push_back(*offset);
3307 this->advance_gc_offset(offset);
3310 // Mangled name of a string type.
3312 void
3313 String_type::do_mangled_name(Gogo*, std::string* ret) const
3315 ret->push_back('z');
3318 // Make a string type.
3320 Type*
3321 Type::make_string_type()
3323 static String_type string_type;
3324 return &string_type;
3327 // The named type "string".
3329 static Named_type* named_string_type;
3331 // Get the named type "string".
3333 Named_type*
3334 Type::lookup_string_type()
3336 return named_string_type;
3339 // Make the named type string.
3341 Named_type*
3342 Type::make_named_string_type()
3344 Type* string_type = Type::make_string_type();
3345 Named_object* named_object =
3346 Named_object::make_type("string", NULL, string_type,
3347 Linemap::predeclared_location());
3348 Named_type* named_type = named_object->type_value();
3349 named_string_type = named_type;
3350 return named_type;
3353 // The sink type. This is the type of the blank identifier _. Any
3354 // type may be assigned to it.
3356 class Sink_type : public Type
3358 public:
3359 Sink_type()
3360 : Type(TYPE_SINK)
3363 protected:
3364 bool
3365 do_compare_is_identity(Gogo*)
3366 { return false; }
3368 Btype*
3369 do_get_backend(Gogo*)
3370 { go_unreachable(); }
3372 Expression*
3373 do_type_descriptor(Gogo*, Named_type*)
3374 { go_unreachable(); }
3376 void
3377 do_reflection(Gogo*, std::string*) const
3378 { go_unreachable(); }
3380 void
3381 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
3382 { go_unreachable(); }
3384 void
3385 do_mangled_name(Gogo*, std::string*) const
3386 { go_unreachable(); }
3389 // Make the sink type.
3391 Type*
3392 Type::make_sink_type()
3394 static Sink_type sink_type;
3395 return &sink_type;
3398 // Class Function_type.
3400 // Traversal.
3403 Function_type::do_traverse(Traverse* traverse)
3405 if (this->receiver_ != NULL
3406 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
3407 return TRAVERSE_EXIT;
3408 if (this->parameters_ != NULL
3409 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
3410 return TRAVERSE_EXIT;
3411 if (this->results_ != NULL
3412 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
3413 return TRAVERSE_EXIT;
3414 return TRAVERSE_CONTINUE;
3417 // Returns whether T is a valid redeclaration of this type. If this
3418 // returns false, and REASON is not NULL, *REASON may be set to a
3419 // brief explanation of why it returned false.
3421 bool
3422 Function_type::is_valid_redeclaration(const Function_type* t,
3423 std::string* reason) const
3425 if (!this->is_identical(t, false, true, reason))
3426 return false;
3428 // A redeclaration of a function is required to use the same names
3429 // for the receiver and parameters.
3430 if (this->receiver() != NULL
3431 && this->receiver()->name() != t->receiver()->name())
3433 if (reason != NULL)
3434 *reason = "receiver name changed";
3435 return false;
3438 const Typed_identifier_list* parms1 = this->parameters();
3439 const Typed_identifier_list* parms2 = t->parameters();
3440 if (parms1 != NULL)
3442 Typed_identifier_list::const_iterator p1 = parms1->begin();
3443 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3444 p2 != parms2->end();
3445 ++p2, ++p1)
3447 if (p1->name() != p2->name())
3449 if (reason != NULL)
3450 *reason = "parameter name changed";
3451 return false;
3454 // This is called at parse time, so we may have unknown
3455 // types.
3456 Type* t1 = p1->type()->forwarded();
3457 Type* t2 = p2->type()->forwarded();
3458 if (t1 != t2
3459 && t1->forward_declaration_type() != NULL
3460 && (t2->forward_declaration_type() == NULL
3461 || (t1->forward_declaration_type()->named_object()
3462 != t2->forward_declaration_type()->named_object())))
3463 return false;
3467 const Typed_identifier_list* results1 = this->results();
3468 const Typed_identifier_list* results2 = t->results();
3469 if (results1 != NULL)
3471 Typed_identifier_list::const_iterator res1 = results1->begin();
3472 for (Typed_identifier_list::const_iterator res2 = results2->begin();
3473 res2 != results2->end();
3474 ++res2, ++res1)
3476 if (res1->name() != res2->name())
3478 if (reason != NULL)
3479 *reason = "result name changed";
3480 return false;
3483 // This is called at parse time, so we may have unknown
3484 // types.
3485 Type* t1 = res1->type()->forwarded();
3486 Type* t2 = res2->type()->forwarded();
3487 if (t1 != t2
3488 && t1->forward_declaration_type() != NULL
3489 && (t2->forward_declaration_type() == NULL
3490 || (t1->forward_declaration_type()->named_object()
3491 != t2->forward_declaration_type()->named_object())))
3492 return false;
3496 return true;
3499 // Check whether T is the same as this type.
3501 bool
3502 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
3503 bool errors_are_identical,
3504 std::string* reason) const
3506 if (!ignore_receiver)
3508 const Typed_identifier* r1 = this->receiver();
3509 const Typed_identifier* r2 = t->receiver();
3510 if ((r1 != NULL) != (r2 != NULL))
3512 if (reason != NULL)
3513 *reason = _("different receiver types");
3514 return false;
3516 if (r1 != NULL)
3518 if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
3519 reason))
3521 if (reason != NULL && !reason->empty())
3522 *reason = "receiver: " + *reason;
3523 return false;
3528 const Typed_identifier_list* parms1 = this->parameters();
3529 const Typed_identifier_list* parms2 = t->parameters();
3530 if ((parms1 != NULL) != (parms2 != NULL))
3532 if (reason != NULL)
3533 *reason = _("different number of parameters");
3534 return false;
3536 if (parms1 != NULL)
3538 Typed_identifier_list::const_iterator p1 = parms1->begin();
3539 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3540 p2 != parms2->end();
3541 ++p2, ++p1)
3543 if (p1 == parms1->end())
3545 if (reason != NULL)
3546 *reason = _("different number of parameters");
3547 return false;
3550 if (!Type::are_identical(p1->type(), p2->type(),
3551 errors_are_identical, NULL))
3553 if (reason != NULL)
3554 *reason = _("different parameter types");
3555 return false;
3558 if (p1 != parms1->end())
3560 if (reason != NULL)
3561 *reason = _("different number of parameters");
3562 return false;
3566 if (this->is_varargs() != t->is_varargs())
3568 if (reason != NULL)
3569 *reason = _("different varargs");
3570 return false;
3573 const Typed_identifier_list* results1 = this->results();
3574 const Typed_identifier_list* results2 = t->results();
3575 if ((results1 != NULL) != (results2 != NULL))
3577 if (reason != NULL)
3578 *reason = _("different number of results");
3579 return false;
3581 if (results1 != NULL)
3583 Typed_identifier_list::const_iterator res1 = results1->begin();
3584 for (Typed_identifier_list::const_iterator res2 = results2->begin();
3585 res2 != results2->end();
3586 ++res2, ++res1)
3588 if (res1 == results1->end())
3590 if (reason != NULL)
3591 *reason = _("different number of results");
3592 return false;
3595 if (!Type::are_identical(res1->type(), res2->type(),
3596 errors_are_identical, NULL))
3598 if (reason != NULL)
3599 *reason = _("different result types");
3600 return false;
3603 if (res1 != results1->end())
3605 if (reason != NULL)
3606 *reason = _("different number of results");
3607 return false;
3611 return true;
3614 // Hash code.
3616 unsigned int
3617 Function_type::do_hash_for_method(Gogo* gogo) const
3619 unsigned int ret = 0;
3620 // We ignore the receiver type for hash codes, because we need to
3621 // get the same hash code for a method in an interface and a method
3622 // declared for a type. The former will not have a receiver.
3623 if (this->parameters_ != NULL)
3625 int shift = 1;
3626 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3627 p != this->parameters_->end();
3628 ++p, ++shift)
3629 ret += p->type()->hash_for_method(gogo) << shift;
3631 if (this->results_ != NULL)
3633 int shift = 2;
3634 for (Typed_identifier_list::const_iterator p = this->results_->begin();
3635 p != this->results_->end();
3636 ++p, ++shift)
3637 ret += p->type()->hash_for_method(gogo) << shift;
3639 if (this->is_varargs_)
3640 ret += 1;
3641 ret <<= 4;
3642 return ret;
3645 // Hash result parameters.
3647 unsigned int
3648 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
3650 unsigned int hash = 0;
3651 for (Typed_identifier_list::const_iterator p = t->begin();
3652 p != t->end();
3653 ++p)
3655 hash <<= 2;
3656 hash = Type::hash_string(p->name(), hash);
3657 hash += p->type()->hash_for_method(NULL);
3659 return hash;
3662 // Compare result parameters so that can map identical result
3663 // parameters to a single struct type.
3665 bool
3666 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
3667 const Typed_identifier_list* b) const
3669 if (a->size() != b->size())
3670 return false;
3671 Typed_identifier_list::const_iterator pa = a->begin();
3672 for (Typed_identifier_list::const_iterator pb = b->begin();
3673 pb != b->end();
3674 ++pa, ++pb)
3676 if (pa->name() != pb->name()
3677 || !Type::are_identical(pa->type(), pb->type(), true, NULL))
3678 return false;
3680 return true;
3683 // Hash from results to a backend struct type.
3685 Function_type::Results_structs Function_type::results_structs;
3687 // Get the backend representation for a function type.
3689 Btype*
3690 Function_type::get_backend_fntype(Gogo* gogo)
3692 if (this->fnbtype_ == NULL)
3694 Backend::Btyped_identifier breceiver;
3695 if (this->receiver_ != NULL)
3697 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
3699 // We always pass the address of the receiver parameter, in
3700 // order to make interface calls work with unknown types.
3701 Type* rtype = this->receiver_->type();
3702 if (rtype->points_to() == NULL)
3703 rtype = Type::make_pointer_type(rtype);
3704 breceiver.btype = rtype->get_backend(gogo);
3705 breceiver.location = this->receiver_->location();
3708 std::vector<Backend::Btyped_identifier> bparameters;
3709 if (this->parameters_ != NULL)
3711 bparameters.resize(this->parameters_->size());
3712 size_t i = 0;
3713 for (Typed_identifier_list::const_iterator p =
3714 this->parameters_->begin(); p != this->parameters_->end();
3715 ++p, ++i)
3717 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
3718 bparameters[i].btype = p->type()->get_backend(gogo);
3719 bparameters[i].location = p->location();
3721 go_assert(i == bparameters.size());
3724 std::vector<Backend::Btyped_identifier> bresults;
3725 Btype* bresult_struct = NULL;
3726 if (this->results_ != NULL)
3728 bresults.resize(this->results_->size());
3729 size_t i = 0;
3730 for (Typed_identifier_list::const_iterator p =
3731 this->results_->begin();
3732 p != this->results_->end();
3733 ++p, ++i)
3735 bresults[i].name = Gogo::unpack_hidden_name(p->name());
3736 bresults[i].btype = p->type()->get_backend(gogo);
3737 bresults[i].location = p->location();
3739 go_assert(i == bresults.size());
3741 if (this->results_->size() > 1)
3743 // Use the same results struct for all functions that
3744 // return the same set of results. This is useful to
3745 // unify calls to interface methods with other calls.
3746 std::pair<Typed_identifier_list*, Btype*> val;
3747 val.first = this->results_;
3748 val.second = NULL;
3749 std::pair<Results_structs::iterator, bool> ins =
3750 Function_type::results_structs.insert(val);
3751 if (ins.second)
3753 // Build a new struct type.
3754 Struct_field_list* sfl = new Struct_field_list;
3755 for (Typed_identifier_list::const_iterator p =
3756 this->results_->begin();
3757 p != this->results_->end();
3758 ++p)
3760 Typed_identifier tid = *p;
3761 if (tid.name().empty())
3762 tid = Typed_identifier("UNNAMED", tid.type(),
3763 tid.location());
3764 sfl->push_back(Struct_field(tid));
3766 Struct_type* st = Type::make_struct_type(sfl,
3767 this->location());
3768 ins.first->second = st->get_backend(gogo);
3770 bresult_struct = ins.first->second;
3774 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
3775 bresults, bresult_struct,
3776 this->location());
3780 return this->fnbtype_;
3783 // Get the backend representation for a Go function type.
3785 Btype*
3786 Function_type::do_get_backend(Gogo* gogo)
3788 // When we do anything with a function value other than call it, it
3789 // is represented as a pointer to a struct whose first field is the
3790 // actual function. So that is what we return as the type of a Go
3791 // function.
3793 Location loc = this->location();
3794 Btype* struct_type =
3795 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
3796 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
3798 std::vector<Backend::Btyped_identifier> fields(1);
3799 fields[0].name = "code";
3800 fields[0].btype = this->get_backend_fntype(gogo);
3801 fields[0].location = loc;
3802 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
3803 return gogo->backend()->error_type();
3804 return ptr_struct_type;
3807 // The type of a function type descriptor.
3809 Type*
3810 Function_type::make_function_type_descriptor_type()
3812 static Type* ret;
3813 if (ret == NULL)
3815 Type* tdt = Type::make_type_descriptor_type();
3816 Type* ptdt = Type::make_type_descriptor_ptr_type();
3818 Type* bool_type = Type::lookup_bool_type();
3820 Type* slice_type = Type::make_array_type(ptdt, NULL);
3822 Struct_type* s = Type::make_builtin_struct_type(4,
3823 "", tdt,
3824 "dotdotdot", bool_type,
3825 "in", slice_type,
3826 "out", slice_type);
3828 ret = Type::make_builtin_named_type("FuncType", s);
3831 return ret;
3834 // The type descriptor for a function type.
3836 Expression*
3837 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3839 Location bloc = Linemap::predeclared_location();
3841 Type* ftdt = Function_type::make_function_type_descriptor_type();
3843 const Struct_field_list* fields = ftdt->struct_type()->fields();
3845 Expression_list* vals = new Expression_list();
3846 vals->reserve(4);
3848 Struct_field_list::const_iterator p = fields->begin();
3849 go_assert(p->is_field_name("commonType"));
3850 vals->push_back(this->type_descriptor_constructor(gogo,
3851 RUNTIME_TYPE_KIND_FUNC,
3852 name, NULL, true));
3854 ++p;
3855 go_assert(p->is_field_name("dotdotdot"));
3856 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
3858 ++p;
3859 go_assert(p->is_field_name("in"));
3860 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
3861 this->parameters()));
3863 ++p;
3864 go_assert(p->is_field_name("out"));
3865 vals->push_back(this->type_descriptor_params(p->type(), NULL,
3866 this->results()));
3868 ++p;
3869 go_assert(p == fields->end());
3871 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
3874 // Return a composite literal for the parameters or results of a type
3875 // descriptor.
3877 Expression*
3878 Function_type::type_descriptor_params(Type* params_type,
3879 const Typed_identifier* receiver,
3880 const Typed_identifier_list* params)
3882 Location bloc = Linemap::predeclared_location();
3884 if (receiver == NULL && params == NULL)
3885 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
3887 Expression_list* vals = new Expression_list();
3888 vals->reserve((params == NULL ? 0 : params->size())
3889 + (receiver != NULL ? 1 : 0));
3891 if (receiver != NULL)
3892 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
3894 if (params != NULL)
3896 for (Typed_identifier_list::const_iterator p = params->begin();
3897 p != params->end();
3898 ++p)
3899 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
3902 return Expression::make_slice_composite_literal(params_type, vals, bloc);
3905 // The reflection string.
3907 void
3908 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
3910 // FIXME: Turn this off until we straighten out the type of the
3911 // struct field used in a go statement which calls a method.
3912 // go_assert(this->receiver_ == NULL);
3914 ret->append("func");
3916 if (this->receiver_ != NULL)
3918 ret->push_back('(');
3919 this->append_reflection(this->receiver_->type(), gogo, ret);
3920 ret->push_back(')');
3923 ret->push_back('(');
3924 const Typed_identifier_list* params = this->parameters();
3925 if (params != NULL)
3927 bool is_varargs = this->is_varargs_;
3928 for (Typed_identifier_list::const_iterator p = params->begin();
3929 p != params->end();
3930 ++p)
3932 if (p != params->begin())
3933 ret->append(", ");
3934 if (!is_varargs || p + 1 != params->end())
3935 this->append_reflection(p->type(), gogo, ret);
3936 else
3938 ret->append("...");
3939 this->append_reflection(p->type()->array_type()->element_type(),
3940 gogo, ret);
3944 ret->push_back(')');
3946 const Typed_identifier_list* results = this->results();
3947 if (results != NULL && !results->empty())
3949 if (results->size() == 1)
3950 ret->push_back(' ');
3951 else
3952 ret->append(" (");
3953 for (Typed_identifier_list::const_iterator p = results->begin();
3954 p != results->end();
3955 ++p)
3957 if (p != results->begin())
3958 ret->append(", ");
3959 this->append_reflection(p->type(), gogo, ret);
3961 if (results->size() > 1)
3962 ret->push_back(')');
3966 // Generate GC symbol for a function type.
3968 void
3969 Function_type::do_gc_symbol(Gogo*, Expression_list** vals,
3970 Expression** offset, int)
3972 Location bloc = Linemap::predeclared_location();
3973 Type* uintptr_type = Type::lookup_integer_type("uintptr");
3975 // We use GC_APTR here because we do not currently have a way to describe the
3976 // the type of the possible function closure. FIXME.
3977 mpz_t opval;
3978 mpz_init_set_ui(opval, GC_APTR);
3979 (*vals)->push_back(Expression::make_integer(&opval, uintptr_type, bloc));
3980 mpz_clear(opval);
3981 (*vals)->push_back(*offset);
3982 this->advance_gc_offset(offset);
3985 // Mangled name.
3987 void
3988 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3990 ret->push_back('F');
3992 if (this->receiver_ != NULL)
3994 ret->push_back('m');
3995 this->append_mangled_name(this->receiver_->type(), gogo, ret);
3998 const Typed_identifier_list* params = this->parameters();
3999 if (params != NULL)
4001 ret->push_back('p');
4002 for (Typed_identifier_list::const_iterator p = params->begin();
4003 p != params->end();
4004 ++p)
4005 this->append_mangled_name(p->type(), gogo, ret);
4006 if (this->is_varargs_)
4007 ret->push_back('V');
4008 ret->push_back('e');
4011 const Typed_identifier_list* results = this->results();
4012 if (results != NULL)
4014 ret->push_back('r');
4015 for (Typed_identifier_list::const_iterator p = results->begin();
4016 p != results->end();
4017 ++p)
4018 this->append_mangled_name(p->type(), gogo, ret);
4019 ret->push_back('e');
4022 ret->push_back('e');
4025 // Export a function type.
4027 void
4028 Function_type::do_export(Export* exp) const
4030 // We don't write out the receiver. The only function types which
4031 // should have a receiver are the ones associated with explicitly
4032 // defined methods. For those the receiver type is written out by
4033 // Function::export_func.
4035 exp->write_c_string("(");
4036 bool first = true;
4037 if (this->parameters_ != NULL)
4039 bool is_varargs = this->is_varargs_;
4040 for (Typed_identifier_list::const_iterator p =
4041 this->parameters_->begin();
4042 p != this->parameters_->end();
4043 ++p)
4045 if (first)
4046 first = false;
4047 else
4048 exp->write_c_string(", ");
4049 exp->write_name(p->name());
4050 exp->write_c_string(" ");
4051 if (!is_varargs || p + 1 != this->parameters_->end())
4052 exp->write_type(p->type());
4053 else
4055 exp->write_c_string("...");
4056 exp->write_type(p->type()->array_type()->element_type());
4060 exp->write_c_string(")");
4062 const Typed_identifier_list* results = this->results_;
4063 if (results != NULL)
4065 exp->write_c_string(" ");
4066 if (results->size() == 1 && results->begin()->name().empty())
4067 exp->write_type(results->begin()->type());
4068 else
4070 first = true;
4071 exp->write_c_string("(");
4072 for (Typed_identifier_list::const_iterator p = results->begin();
4073 p != results->end();
4074 ++p)
4076 if (first)
4077 first = false;
4078 else
4079 exp->write_c_string(", ");
4080 exp->write_name(p->name());
4081 exp->write_c_string(" ");
4082 exp->write_type(p->type());
4084 exp->write_c_string(")");
4089 // Import a function type.
4091 Function_type*
4092 Function_type::do_import(Import* imp)
4094 imp->require_c_string("(");
4095 Typed_identifier_list* parameters;
4096 bool is_varargs = false;
4097 if (imp->peek_char() == ')')
4098 parameters = NULL;
4099 else
4101 parameters = new Typed_identifier_list();
4102 while (true)
4104 std::string name = imp->read_name();
4105 imp->require_c_string(" ");
4107 if (imp->match_c_string("..."))
4109 imp->advance(3);
4110 is_varargs = true;
4113 Type* ptype = imp->read_type();
4114 if (is_varargs)
4115 ptype = Type::make_array_type(ptype, NULL);
4116 parameters->push_back(Typed_identifier(name, ptype,
4117 imp->location()));
4118 if (imp->peek_char() != ',')
4119 break;
4120 go_assert(!is_varargs);
4121 imp->require_c_string(", ");
4124 imp->require_c_string(")");
4126 Typed_identifier_list* results;
4127 if (imp->peek_char() != ' ')
4128 results = NULL;
4129 else
4131 imp->advance(1);
4132 results = new Typed_identifier_list;
4133 if (imp->peek_char() != '(')
4135 Type* rtype = imp->read_type();
4136 results->push_back(Typed_identifier("", rtype, imp->location()));
4138 else
4140 imp->advance(1);
4141 while (true)
4143 std::string name = imp->read_name();
4144 imp->require_c_string(" ");
4145 Type* rtype = imp->read_type();
4146 results->push_back(Typed_identifier(name, rtype,
4147 imp->location()));
4148 if (imp->peek_char() != ',')
4149 break;
4150 imp->require_c_string(", ");
4152 imp->require_c_string(")");
4156 Function_type* ret = Type::make_function_type(NULL, parameters, results,
4157 imp->location());
4158 if (is_varargs)
4159 ret->set_is_varargs();
4160 return ret;
4163 // Make a copy of a function type without a receiver.
4165 Function_type*
4166 Function_type::copy_without_receiver() const
4168 go_assert(this->is_method());
4169 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
4170 this->results_,
4171 this->location_);
4172 if (this->is_varargs())
4173 ret->set_is_varargs();
4174 if (this->is_builtin())
4175 ret->set_is_builtin();
4176 return ret;
4179 // Make a copy of a function type with a receiver.
4181 Function_type*
4182 Function_type::copy_with_receiver(Type* receiver_type) const
4184 go_assert(!this->is_method());
4185 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
4186 this->location_);
4187 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
4188 this->results_,
4189 this->location_);
4190 if (this->is_varargs_)
4191 ret->set_is_varargs();
4192 return ret;
4195 // Make a copy of a function type with the receiver as the first
4196 // parameter.
4198 Function_type*
4199 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
4201 go_assert(this->is_method());
4202 Typed_identifier_list* new_params = new Typed_identifier_list();
4203 Type* rtype = this->receiver_->type();
4204 if (want_pointer_receiver)
4205 rtype = Type::make_pointer_type(rtype);
4206 Typed_identifier receiver(this->receiver_->name(), rtype,
4207 this->receiver_->location());
4208 new_params->push_back(receiver);
4209 const Typed_identifier_list* orig_params = this->parameters_;
4210 if (orig_params != NULL && !orig_params->empty())
4212 for (Typed_identifier_list::const_iterator p = orig_params->begin();
4213 p != orig_params->end();
4214 ++p)
4215 new_params->push_back(*p);
4217 return Type::make_function_type(NULL, new_params, this->results_,
4218 this->location_);
4221 // Make a copy of a function type ignoring any receiver and adding a
4222 // closure parameter.
4224 Function_type*
4225 Function_type::copy_with_names() const
4227 Typed_identifier_list* new_params = new Typed_identifier_list();
4228 const Typed_identifier_list* orig_params = this->parameters_;
4229 if (orig_params != NULL && !orig_params->empty())
4231 static int count;
4232 char buf[50];
4233 for (Typed_identifier_list::const_iterator p = orig_params->begin();
4234 p != orig_params->end();
4235 ++p)
4237 snprintf(buf, sizeof buf, "pt.%u", count);
4238 ++count;
4239 new_params->push_back(Typed_identifier(buf, p->type(),
4240 p->location()));
4244 const Typed_identifier_list* orig_results = this->results_;
4245 Typed_identifier_list* new_results;
4246 if (orig_results == NULL || orig_results->empty())
4247 new_results = NULL;
4248 else
4250 new_results = new Typed_identifier_list();
4251 for (Typed_identifier_list::const_iterator p = orig_results->begin();
4252 p != orig_results->end();
4253 ++p)
4254 new_results->push_back(Typed_identifier("", p->type(),
4255 p->location()));
4258 return Type::make_function_type(NULL, new_params, new_results,
4259 this->location());
4262 // Make a function type.
4264 Function_type*
4265 Type::make_function_type(Typed_identifier* receiver,
4266 Typed_identifier_list* parameters,
4267 Typed_identifier_list* results,
4268 Location location)
4270 return new Function_type(receiver, parameters, results, location);
4273 // Make a backend function type.
4275 Backend_function_type*
4276 Type::make_backend_function_type(Typed_identifier* receiver,
4277 Typed_identifier_list* parameters,
4278 Typed_identifier_list* results,
4279 Location location)
4281 return new Backend_function_type(receiver, parameters, results, location);
4284 // Class Pointer_type.
4286 // Traversal.
4289 Pointer_type::do_traverse(Traverse* traverse)
4291 return Type::traverse(this->to_type_, traverse);
4294 // Hash code.
4296 unsigned int
4297 Pointer_type::do_hash_for_method(Gogo* gogo) const
4299 return this->to_type_->hash_for_method(gogo) << 4;
4302 // Get the backend representation for a pointer type.
4304 Btype*
4305 Pointer_type::do_get_backend(Gogo* gogo)
4307 Btype* to_btype = this->to_type_->get_backend(gogo);
4308 return gogo->backend()->pointer_type(to_btype);
4311 // The type of a pointer type descriptor.
4313 Type*
4314 Pointer_type::make_pointer_type_descriptor_type()
4316 static Type* ret;
4317 if (ret == NULL)
4319 Type* tdt = Type::make_type_descriptor_type();
4320 Type* ptdt = Type::make_type_descriptor_ptr_type();
4322 Struct_type* s = Type::make_builtin_struct_type(2,
4323 "", tdt,
4324 "elem", ptdt);
4326 ret = Type::make_builtin_named_type("PtrType", s);
4329 return ret;
4332 // The type descriptor for a pointer type.
4334 Expression*
4335 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4337 if (this->is_unsafe_pointer_type())
4339 go_assert(name != NULL);
4340 return this->plain_type_descriptor(gogo,
4341 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
4342 name);
4344 else
4346 Location bloc = Linemap::predeclared_location();
4348 const Methods* methods;
4349 Type* deref = this->points_to();
4350 if (deref->named_type() != NULL)
4351 methods = deref->named_type()->methods();
4352 else if (deref->struct_type() != NULL)
4353 methods = deref->struct_type()->methods();
4354 else
4355 methods = NULL;
4357 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
4359 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
4361 Expression_list* vals = new Expression_list();
4362 vals->reserve(2);
4364 Struct_field_list::const_iterator p = fields->begin();
4365 go_assert(p->is_field_name("commonType"));
4366 vals->push_back(this->type_descriptor_constructor(gogo,
4367 RUNTIME_TYPE_KIND_PTR,
4368 name, methods, false));
4370 ++p;
4371 go_assert(p->is_field_name("elem"));
4372 vals->push_back(Expression::make_type_descriptor(deref, bloc));
4374 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
4378 // Reflection string.
4380 void
4381 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
4383 ret->push_back('*');
4384 this->append_reflection(this->to_type_, gogo, ret);
4387 // Generate GC symbol for pointer types.
4389 void
4390 Pointer_type::do_gc_symbol(Gogo*, Expression_list** vals,
4391 Expression** offset, int)
4393 Location loc = Linemap::predeclared_location();
4394 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4396 mpz_t opval;
4397 mpz_init_set_ui(opval, this->to_type_->has_pointer() ? GC_PTR : GC_APTR);
4398 (*vals)->push_back(Expression::make_integer(&opval, uintptr_type, loc));
4399 mpz_clear(opval);
4400 (*vals)->push_back(*offset);
4402 if (this->to_type_->has_pointer())
4403 (*vals)->push_back(Expression::make_gc_symbol(this->to_type_));
4404 this->advance_gc_offset(offset);
4407 // Mangled name.
4409 void
4410 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4412 ret->push_back('p');
4413 this->append_mangled_name(this->to_type_, gogo, ret);
4416 // Export.
4418 void
4419 Pointer_type::do_export(Export* exp) const
4421 exp->write_c_string("*");
4422 if (this->is_unsafe_pointer_type())
4423 exp->write_c_string("any");
4424 else
4425 exp->write_type(this->to_type_);
4428 // Import.
4430 Pointer_type*
4431 Pointer_type::do_import(Import* imp)
4433 imp->require_c_string("*");
4434 if (imp->match_c_string("any"))
4436 imp->advance(3);
4437 return Type::make_pointer_type(Type::make_void_type());
4439 Type* to = imp->read_type();
4440 return Type::make_pointer_type(to);
4443 // Make a pointer type.
4445 Pointer_type*
4446 Type::make_pointer_type(Type* to_type)
4448 typedef Unordered_map(Type*, Pointer_type*) Hashtable;
4449 static Hashtable pointer_types;
4450 Hashtable::const_iterator p = pointer_types.find(to_type);
4451 if (p != pointer_types.end())
4452 return p->second;
4453 Pointer_type* ret = new Pointer_type(to_type);
4454 pointer_types[to_type] = ret;
4455 return ret;
4458 // The nil type. We use a special type for nil because it is not the
4459 // same as any other type. In C term nil has type void*, but there is
4460 // no such type in Go.
4462 class Nil_type : public Type
4464 public:
4465 Nil_type()
4466 : Type(TYPE_NIL)
4469 protected:
4470 bool
4471 do_compare_is_identity(Gogo*)
4472 { return false; }
4474 Btype*
4475 do_get_backend(Gogo* gogo)
4476 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
4478 Expression*
4479 do_type_descriptor(Gogo*, Named_type*)
4480 { go_unreachable(); }
4482 void
4483 do_reflection(Gogo*, std::string*) const
4484 { go_unreachable(); }
4486 void
4487 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
4488 { go_unreachable(); }
4490 void
4491 do_mangled_name(Gogo*, std::string* ret) const
4492 { ret->push_back('n'); }
4495 // Make the nil type.
4497 Type*
4498 Type::make_nil_type()
4500 static Nil_type singleton_nil_type;
4501 return &singleton_nil_type;
4504 // The type of a function call which returns multiple values. This is
4505 // really a struct, but we don't want to confuse a function call which
4506 // returns a struct with a function call which returns multiple
4507 // values.
4509 class Call_multiple_result_type : public Type
4511 public:
4512 Call_multiple_result_type(Call_expression* call)
4513 : Type(TYPE_CALL_MULTIPLE_RESULT),
4514 call_(call)
4517 protected:
4518 bool
4519 do_has_pointer() const
4521 go_assert(saw_errors());
4522 return false;
4525 bool
4526 do_compare_is_identity(Gogo*)
4527 { return false; }
4529 Btype*
4530 do_get_backend(Gogo* gogo)
4532 go_assert(saw_errors());
4533 return gogo->backend()->error_type();
4536 Expression*
4537 do_type_descriptor(Gogo*, Named_type*)
4539 go_assert(saw_errors());
4540 return Expression::make_error(Linemap::unknown_location());
4543 void
4544 do_reflection(Gogo*, std::string*) const
4545 { go_assert(saw_errors()); }
4547 void
4548 do_gc_symbol(Gogo*, Expression_list**, Expression**, int)
4549 { go_unreachable(); }
4551 void
4552 do_mangled_name(Gogo*, std::string*) const
4553 { go_assert(saw_errors()); }
4555 private:
4556 // The expression being called.
4557 Call_expression* call_;
4560 // Make a call result type.
4562 Type*
4563 Type::make_call_multiple_result_type(Call_expression* call)
4565 return new Call_multiple_result_type(call);
4568 // Class Struct_field.
4570 // Get the name of a field.
4572 const std::string&
4573 Struct_field::field_name() const
4575 const std::string& name(this->typed_identifier_.name());
4576 if (!name.empty())
4577 return name;
4578 else
4580 // This is called during parsing, before anything is lowered, so
4581 // we have to be pretty careful to avoid dereferencing an
4582 // unknown type name.
4583 Type* t = this->typed_identifier_.type();
4584 Type* dt = t;
4585 if (t->classification() == Type::TYPE_POINTER)
4587 // Very ugly.
4588 Pointer_type* ptype = static_cast<Pointer_type*>(t);
4589 dt = ptype->points_to();
4591 if (dt->forward_declaration_type() != NULL)
4592 return dt->forward_declaration_type()->name();
4593 else if (dt->named_type() != NULL)
4594 return dt->named_type()->name();
4595 else if (t->is_error_type() || dt->is_error_type())
4597 static const std::string error_string = "*error*";
4598 return error_string;
4600 else
4602 // Avoid crashing in the erroneous case where T is named but
4603 // DT is not.
4604 go_assert(t != dt);
4605 if (t->forward_declaration_type() != NULL)
4606 return t->forward_declaration_type()->name();
4607 else if (t->named_type() != NULL)
4608 return t->named_type()->name();
4609 else
4610 go_unreachable();
4615 // Return whether this field is named NAME.
4617 bool
4618 Struct_field::is_field_name(const std::string& name) const
4620 const std::string& me(this->typed_identifier_.name());
4621 if (!me.empty())
4622 return me == name;
4623 else
4625 Type* t = this->typed_identifier_.type();
4626 if (t->points_to() != NULL)
4627 t = t->points_to();
4628 Named_type* nt = t->named_type();
4629 if (nt != NULL && nt->name() == name)
4630 return true;
4632 // This is a horrible hack caused by the fact that we don't pack
4633 // the names of builtin types. FIXME.
4634 if (!this->is_imported_
4635 && nt != NULL
4636 && nt->is_builtin()
4637 && nt->name() == Gogo::unpack_hidden_name(name))
4638 return true;
4640 return false;
4644 // Return whether this field is an unexported field named NAME.
4646 bool
4647 Struct_field::is_unexported_field_name(Gogo* gogo,
4648 const std::string& name) const
4650 const std::string& field_name(this->field_name());
4651 if (Gogo::is_hidden_name(field_name)
4652 && name == Gogo::unpack_hidden_name(field_name)
4653 && gogo->pack_hidden_name(name, false) != field_name)
4654 return true;
4656 // Check for the name of a builtin type. This is like the test in
4657 // is_field_name, only there we return false if this->is_imported_,
4658 // and here we return true.
4659 if (this->is_imported_ && this->is_anonymous())
4661 Type* t = this->typed_identifier_.type();
4662 if (t->points_to() != NULL)
4663 t = t->points_to();
4664 Named_type* nt = t->named_type();
4665 if (nt != NULL
4666 && nt->is_builtin()
4667 && nt->name() == Gogo::unpack_hidden_name(name))
4668 return true;
4671 return false;
4674 // Return whether this field is an embedded built-in type.
4676 bool
4677 Struct_field::is_embedded_builtin(Gogo* gogo) const
4679 const std::string& name(this->field_name());
4680 // We know that a field is an embedded type if it is anonymous.
4681 // We can decide if it is a built-in type by checking to see if it is
4682 // registered globally under the field's name.
4683 // This allows us to distinguish between embedded built-in types and
4684 // embedded types that are aliases to built-in types.
4685 return (this->is_anonymous()
4686 && !Gogo::is_hidden_name(name)
4687 && gogo->lookup_global(name.c_str()) != NULL);
4690 // Class Struct_type.
4692 // A hash table used to find identical unnamed structs so that they
4693 // share method tables.
4695 Struct_type::Identical_structs Struct_type::identical_structs;
4697 // A hash table used to merge method sets for identical unnamed
4698 // structs.
4700 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
4702 // Traversal.
4705 Struct_type::do_traverse(Traverse* traverse)
4707 Struct_field_list* fields = this->fields_;
4708 if (fields != NULL)
4710 for (Struct_field_list::iterator p = fields->begin();
4711 p != fields->end();
4712 ++p)
4714 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
4715 return TRAVERSE_EXIT;
4718 return TRAVERSE_CONTINUE;
4721 // Verify that the struct type is complete and valid.
4723 bool
4724 Struct_type::do_verify()
4726 Struct_field_list* fields = this->fields_;
4727 if (fields == NULL)
4728 return true;
4729 for (Struct_field_list::iterator p = fields->begin();
4730 p != fields->end();
4731 ++p)
4733 Type* t = p->type();
4734 if (p->is_anonymous())
4736 if (t->named_type() != NULL && t->points_to() != NULL)
4738 error_at(p->location(), "embedded type may not be a pointer");
4739 p->set_type(Type::make_error_type());
4741 else if (t->points_to() != NULL
4742 && t->points_to()->interface_type() != NULL)
4744 error_at(p->location(),
4745 "embedded type may not be pointer to interface");
4746 p->set_type(Type::make_error_type());
4750 return true;
4753 // Whether this contains a pointer.
4755 bool
4756 Struct_type::do_has_pointer() const
4758 const Struct_field_list* fields = this->fields();
4759 if (fields == NULL)
4760 return false;
4761 for (Struct_field_list::const_iterator p = fields->begin();
4762 p != fields->end();
4763 ++p)
4765 if (p->type()->has_pointer())
4766 return true;
4768 return false;
4771 // Whether this type is identical to T.
4773 bool
4774 Struct_type::is_identical(const Struct_type* t,
4775 bool errors_are_identical) const
4777 const Struct_field_list* fields1 = this->fields();
4778 const Struct_field_list* fields2 = t->fields();
4779 if (fields1 == NULL || fields2 == NULL)
4780 return fields1 == fields2;
4781 Struct_field_list::const_iterator pf2 = fields2->begin();
4782 for (Struct_field_list::const_iterator pf1 = fields1->begin();
4783 pf1 != fields1->end();
4784 ++pf1, ++pf2)
4786 if (pf2 == fields2->end())
4787 return false;
4788 if (pf1->field_name() != pf2->field_name())
4789 return false;
4790 if (pf1->is_anonymous() != pf2->is_anonymous()
4791 || !Type::are_identical(pf1->type(), pf2->type(),
4792 errors_are_identical, NULL))
4793 return false;
4794 if (!pf1->has_tag())
4796 if (pf2->has_tag())
4797 return false;
4799 else
4801 if (!pf2->has_tag())
4802 return false;
4803 if (pf1->tag() != pf2->tag())
4804 return false;
4807 if (pf2 != fields2->end())
4808 return false;
4809 return true;
4812 // Whether this struct type has any hidden fields.
4814 bool
4815 Struct_type::struct_has_hidden_fields(const Named_type* within,
4816 std::string* reason) const
4818 const Struct_field_list* fields = this->fields();
4819 if (fields == NULL)
4820 return false;
4821 const Package* within_package = (within == NULL
4822 ? NULL
4823 : within->named_object()->package());
4824 for (Struct_field_list::const_iterator pf = fields->begin();
4825 pf != fields->end();
4826 ++pf)
4828 if (within_package != NULL
4829 && !pf->is_anonymous()
4830 && Gogo::is_hidden_name(pf->field_name()))
4832 if (reason != NULL)
4834 std::string within_name = within->named_object()->message_name();
4835 std::string name = Gogo::message_name(pf->field_name());
4836 size_t bufsize = 200 + within_name.length() + name.length();
4837 char* buf = new char[bufsize];
4838 snprintf(buf, bufsize,
4839 _("implicit assignment of %s%s%s hidden field %s%s%s"),
4840 open_quote, within_name.c_str(), close_quote,
4841 open_quote, name.c_str(), close_quote);
4842 reason->assign(buf);
4843 delete[] buf;
4845 return true;
4848 if (pf->type()->has_hidden_fields(within, reason))
4849 return true;
4852 return false;
4855 // Whether comparisons of this struct type are simple identity
4856 // comparisons.
4858 bool
4859 Struct_type::do_compare_is_identity(Gogo* gogo)
4861 const Struct_field_list* fields = this->fields_;
4862 if (fields == NULL)
4863 return true;
4864 unsigned long offset = 0;
4865 for (Struct_field_list::const_iterator pf = fields->begin();
4866 pf != fields->end();
4867 ++pf)
4869 if (Gogo::is_sink_name(pf->field_name()))
4870 return false;
4872 if (!pf->type()->compare_is_identity(gogo))
4873 return false;
4875 unsigned long field_align;
4876 if (!pf->type()->backend_type_align(gogo, &field_align))
4877 return false;
4878 if ((offset & (field_align - 1)) != 0)
4880 // This struct has padding. We don't guarantee that that
4881 // padding is zero-initialized for a stack variable, so we
4882 // can't use memcmp to compare struct values.
4883 return false;
4886 unsigned long field_size;
4887 if (!pf->type()->backend_type_size(gogo, &field_size))
4888 return false;
4889 offset += field_size;
4892 unsigned long struct_size;
4893 if (!this->backend_type_size(gogo, &struct_size))
4894 return false;
4895 if (offset != struct_size)
4897 // Trailing padding may not be zero when on the stack.
4898 return false;
4901 return true;
4904 // Build identity and hash functions for this struct.
4906 // Hash code.
4908 unsigned int
4909 Struct_type::do_hash_for_method(Gogo* gogo) const
4911 unsigned int ret = 0;
4912 if (this->fields() != NULL)
4914 for (Struct_field_list::const_iterator pf = this->fields()->begin();
4915 pf != this->fields()->end();
4916 ++pf)
4917 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
4919 return ret <<= 2;
4922 // Find the local field NAME.
4924 const Struct_field*
4925 Struct_type::find_local_field(const std::string& name,
4926 unsigned int *pindex) const
4928 const Struct_field_list* fields = this->fields_;
4929 if (fields == NULL)
4930 return NULL;
4931 unsigned int i = 0;
4932 for (Struct_field_list::const_iterator pf = fields->begin();
4933 pf != fields->end();
4934 ++pf, ++i)
4936 if (pf->is_field_name(name))
4938 if (pindex != NULL)
4939 *pindex = i;
4940 return &*pf;
4943 return NULL;
4946 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
4948 Field_reference_expression*
4949 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
4950 Location location) const
4952 unsigned int depth;
4953 return this->field_reference_depth(struct_expr, name, location, NULL,
4954 &depth);
4957 // Return an expression for a field, along with the depth at which it
4958 // was found.
4960 Field_reference_expression*
4961 Struct_type::field_reference_depth(Expression* struct_expr,
4962 const std::string& name,
4963 Location location,
4964 Saw_named_type* saw,
4965 unsigned int* depth) const
4967 const Struct_field_list* fields = this->fields_;
4968 if (fields == NULL)
4969 return NULL;
4971 // Look for a field with this name.
4972 unsigned int i = 0;
4973 for (Struct_field_list::const_iterator pf = fields->begin();
4974 pf != fields->end();
4975 ++pf, ++i)
4977 if (pf->is_field_name(name))
4979 *depth = 0;
4980 return Expression::make_field_reference(struct_expr, i, location);
4984 // Look for an anonymous field which contains a field with this
4985 // name.
4986 unsigned int found_depth = 0;
4987 Field_reference_expression* ret = NULL;
4988 i = 0;
4989 for (Struct_field_list::const_iterator pf = fields->begin();
4990 pf != fields->end();
4991 ++pf, ++i)
4993 if (!pf->is_anonymous())
4994 continue;
4996 Struct_type* st = pf->type()->deref()->struct_type();
4997 if (st == NULL)
4998 continue;
5000 Saw_named_type* hold_saw = saw;
5001 Saw_named_type saw_here;
5002 Named_type* nt = pf->type()->named_type();
5003 if (nt == NULL)
5004 nt = pf->type()->deref()->named_type();
5005 if (nt != NULL)
5007 Saw_named_type* q;
5008 for (q = saw; q != NULL; q = q->next)
5010 if (q->nt == nt)
5012 // If this is an error, it will be reported
5013 // elsewhere.
5014 break;
5017 if (q != NULL)
5018 continue;
5019 saw_here.next = saw;
5020 saw_here.nt = nt;
5021 saw = &saw_here;
5024 // Look for a reference using a NULL struct expression. If we
5025 // find one, fill in the struct expression with a reference to
5026 // this field.
5027 unsigned int subdepth;
5028 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
5029 location,
5030 saw,
5031 &subdepth);
5033 saw = hold_saw;
5035 if (sub == NULL)
5036 continue;
5038 if (ret == NULL || subdepth < found_depth)
5040 if (ret != NULL)
5041 delete ret;
5042 ret = sub;
5043 found_depth = subdepth;
5044 Expression* here = Expression::make_field_reference(struct_expr, i,
5045 location);
5046 if (pf->type()->points_to() != NULL)
5047 here = Expression::make_unary(OPERATOR_MULT, here, location);
5048 while (sub->expr() != NULL)
5050 sub = sub->expr()->deref()->field_reference_expression();
5051 go_assert(sub != NULL);
5053 sub->set_struct_expression(here);
5054 sub->set_implicit(true);
5056 else if (subdepth > found_depth)
5057 delete sub;
5058 else
5060 // We do not handle ambiguity here--it should be handled by
5061 // Type::bind_field_or_method.
5062 delete sub;
5063 found_depth = 0;
5064 ret = NULL;
5068 if (ret != NULL)
5069 *depth = found_depth + 1;
5071 return ret;
5074 // Return the total number of fields, including embedded fields.
5076 unsigned int
5077 Struct_type::total_field_count() const
5079 if (this->fields_ == NULL)
5080 return 0;
5081 unsigned int ret = 0;
5082 for (Struct_field_list::const_iterator pf = this->fields_->begin();
5083 pf != this->fields_->end();
5084 ++pf)
5086 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
5087 ++ret;
5088 else
5089 ret += pf->type()->struct_type()->total_field_count();
5091 return ret;
5094 // Return whether NAME is an unexported field, for better error reporting.
5096 bool
5097 Struct_type::is_unexported_local_field(Gogo* gogo,
5098 const std::string& name) const
5100 const Struct_field_list* fields = this->fields_;
5101 if (fields != NULL)
5103 for (Struct_field_list::const_iterator pf = fields->begin();
5104 pf != fields->end();
5105 ++pf)
5106 if (pf->is_unexported_field_name(gogo, name))
5107 return true;
5109 return false;
5112 // Finalize the methods of an unnamed struct.
5114 void
5115 Struct_type::finalize_methods(Gogo* gogo)
5117 if (this->all_methods_ != NULL)
5118 return;
5120 // It is possible to have multiple identical structs that have
5121 // methods. We want them to share method tables. Otherwise we will
5122 // emit identical methods more than once, which is bad since they
5123 // will even have the same names.
5124 std::pair<Identical_structs::iterator, bool> ins =
5125 Struct_type::identical_structs.insert(std::make_pair(this, this));
5126 if (!ins.second)
5128 // An identical struct was already entered into the hash table.
5129 // Note that finalize_methods is, fortunately, not recursive.
5130 this->all_methods_ = ins.first->second->all_methods_;
5131 return;
5134 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
5137 // Return the method NAME, or NULL if there isn't one or if it is
5138 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
5139 // ambiguous.
5141 Method*
5142 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
5144 return Type::method_function(this->all_methods_, name, is_ambiguous);
5147 // Return a pointer to the interface method table for this type for
5148 // the interface INTERFACE. IS_POINTER is true if this is for a
5149 // pointer to THIS.
5151 Expression*
5152 Struct_type::interface_method_table(Interface_type* interface,
5153 bool is_pointer)
5155 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
5156 val(this, NULL);
5157 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
5158 Struct_type::struct_method_tables.insert(val);
5160 Struct_method_table_pair* smtp;
5161 if (!ins.second)
5162 smtp = ins.first->second;
5163 else
5165 smtp = new Struct_method_table_pair();
5166 smtp->first = NULL;
5167 smtp->second = NULL;
5168 ins.first->second = smtp;
5171 return Type::interface_method_table(this, interface, is_pointer,
5172 &smtp->first, &smtp->second);
5175 // Convert struct fields to the backend representation. This is not
5176 // declared in types.h so that types.h doesn't have to #include
5177 // backend.h.
5179 static void
5180 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
5181 bool use_placeholder,
5182 std::vector<Backend::Btyped_identifier>* bfields)
5184 bfields->resize(fields->size());
5185 size_t i = 0;
5186 for (Struct_field_list::const_iterator p = fields->begin();
5187 p != fields->end();
5188 ++p, ++i)
5190 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
5191 (*bfields)[i].btype = (use_placeholder
5192 ? p->type()->get_backend_placeholder(gogo)
5193 : p->type()->get_backend(gogo));
5194 (*bfields)[i].location = p->location();
5196 go_assert(i == fields->size());
5199 // Get the backend representation for a struct type.
5201 Btype*
5202 Struct_type::do_get_backend(Gogo* gogo)
5204 std::vector<Backend::Btyped_identifier> bfields;
5205 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
5206 return gogo->backend()->struct_type(bfields);
5209 // Finish the backend representation of the fields of a struct.
5211 void
5212 Struct_type::finish_backend_fields(Gogo* gogo)
5214 const Struct_field_list* fields = this->fields_;
5215 if (fields != NULL)
5217 for (Struct_field_list::const_iterator p = fields->begin();
5218 p != fields->end();
5219 ++p)
5220 p->type()->get_backend(gogo);
5224 // The type of a struct type descriptor.
5226 Type*
5227 Struct_type::make_struct_type_descriptor_type()
5229 static Type* ret;
5230 if (ret == NULL)
5232 Type* tdt = Type::make_type_descriptor_type();
5233 Type* ptdt = Type::make_type_descriptor_ptr_type();
5235 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5236 Type* string_type = Type::lookup_string_type();
5237 Type* pointer_string_type = Type::make_pointer_type(string_type);
5239 Struct_type* sf =
5240 Type::make_builtin_struct_type(5,
5241 "name", pointer_string_type,
5242 "pkgPath", pointer_string_type,
5243 "typ", ptdt,
5244 "tag", pointer_string_type,
5245 "offset", uintptr_type);
5246 Type* nsf = Type::make_builtin_named_type("structField", sf);
5248 Type* slice_type = Type::make_array_type(nsf, NULL);
5250 Struct_type* s = Type::make_builtin_struct_type(2,
5251 "", tdt,
5252 "fields", slice_type);
5254 ret = Type::make_builtin_named_type("StructType", s);
5257 return ret;
5260 // Build a type descriptor for a struct type.
5262 Expression*
5263 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5265 Location bloc = Linemap::predeclared_location();
5267 Type* stdt = Struct_type::make_struct_type_descriptor_type();
5269 const Struct_field_list* fields = stdt->struct_type()->fields();
5271 Expression_list* vals = new Expression_list();
5272 vals->reserve(2);
5274 const Methods* methods = this->methods();
5275 // A named struct should not have methods--the methods should attach
5276 // to the named type.
5277 go_assert(methods == NULL || name == NULL);
5279 Struct_field_list::const_iterator ps = fields->begin();
5280 go_assert(ps->is_field_name("commonType"));
5281 vals->push_back(this->type_descriptor_constructor(gogo,
5282 RUNTIME_TYPE_KIND_STRUCT,
5283 name, methods, true));
5285 ++ps;
5286 go_assert(ps->is_field_name("fields"));
5288 Expression_list* elements = new Expression_list();
5289 elements->reserve(this->fields_->size());
5290 Type* element_type = ps->type()->array_type()->element_type();
5291 for (Struct_field_list::const_iterator pf = this->fields_->begin();
5292 pf != this->fields_->end();
5293 ++pf)
5295 const Struct_field_list* f = element_type->struct_type()->fields();
5297 Expression_list* fvals = new Expression_list();
5298 fvals->reserve(5);
5300 Struct_field_list::const_iterator q = f->begin();
5301 go_assert(q->is_field_name("name"));
5302 if (pf->is_anonymous())
5303 fvals->push_back(Expression::make_nil(bloc));
5304 else
5306 std::string n = Gogo::unpack_hidden_name(pf->field_name());
5307 Expression* s = Expression::make_string(n, bloc);
5308 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
5311 ++q;
5312 go_assert(q->is_field_name("pkgPath"));
5313 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
5314 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
5315 fvals->push_back(Expression::make_nil(bloc));
5316 else
5318 std::string n;
5319 if (is_embedded_builtin)
5320 n = gogo->package_name();
5321 else
5322 n = Gogo::hidden_name_pkgpath(pf->field_name());
5323 Expression* s = Expression::make_string(n, bloc);
5324 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
5327 ++q;
5328 go_assert(q->is_field_name("typ"));
5329 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
5331 ++q;
5332 go_assert(q->is_field_name("tag"));
5333 if (!pf->has_tag())
5334 fvals->push_back(Expression::make_nil(bloc));
5335 else
5337 Expression* s = Expression::make_string(pf->tag(), bloc);
5338 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
5341 ++q;
5342 go_assert(q->is_field_name("offset"));
5343 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
5345 Expression* v = Expression::make_struct_composite_literal(element_type,
5346 fvals, bloc);
5347 elements->push_back(v);
5350 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
5351 elements, bloc));
5353 return Expression::make_struct_composite_literal(stdt, vals, bloc);
5356 // Write the hash function for a struct which can not use the identity
5357 // function.
5359 void
5360 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
5361 Function_type* hash_fntype,
5362 Function_type* equal_fntype)
5364 Location bloc = Linemap::predeclared_location();
5366 // The pointer to the struct that we are going to hash. This is an
5367 // argument to the hash function we are implementing here.
5368 Named_object* key_arg = gogo->lookup("key", NULL);
5369 go_assert(key_arg != NULL);
5370 Type* key_arg_type = key_arg->var_value()->type();
5372 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5374 // Get a 0.
5375 mpz_t ival;
5376 mpz_init_set_ui(ival, 0);
5377 Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
5378 mpz_clear(ival);
5380 // Make a temporary to hold the return value, initialized to 0.
5381 Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
5382 bloc);
5383 gogo->add_statement(retval);
5385 // Make a temporary to hold the key as a uintptr.
5386 Expression* ref = Expression::make_var_reference(key_arg, bloc);
5387 ref = Expression::make_cast(uintptr_type, ref, bloc);
5388 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
5389 bloc);
5390 gogo->add_statement(key);
5392 // Loop over the struct fields.
5393 bool first = true;
5394 const Struct_field_list* fields = this->fields_;
5395 for (Struct_field_list::const_iterator pf = fields->begin();
5396 pf != fields->end();
5397 ++pf)
5399 if (Gogo::is_sink_name(pf->field_name()))
5400 continue;
5402 if (first)
5403 first = false;
5404 else
5406 // Multiply retval by 33.
5407 mpz_init_set_ui(ival, 33);
5408 Expression* i33 = Expression::make_integer(&ival, uintptr_type,
5409 bloc);
5410 mpz_clear(ival);
5412 ref = Expression::make_temporary_reference(retval, bloc);
5413 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ,
5414 ref, i33, bloc);
5415 gogo->add_statement(s);
5418 // Get a pointer to the value of this field.
5419 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
5420 ref = Expression::make_temporary_reference(key, bloc);
5421 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
5422 bloc);
5423 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
5425 // Get the size of this field.
5426 Expression* size = Expression::make_type_info(pf->type(),
5427 Expression::TYPE_INFO_SIZE);
5429 // Get the hash function to use for the type of this field.
5430 Named_object* hash_fn;
5431 Named_object* equal_fn;
5432 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
5433 equal_fntype, &hash_fn, &equal_fn);
5435 // Call the hash function for the field.
5436 Expression_list* args = new Expression_list();
5437 args->push_back(subkey);
5438 args->push_back(size);
5439 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
5440 Expression* call = Expression::make_call(func, args, false, bloc);
5442 // Add the field's hash value to retval.
5443 Temporary_reference_expression* tref =
5444 Expression::make_temporary_reference(retval, bloc);
5445 tref->set_is_lvalue();
5446 Statement* s = Statement::make_assignment_operation(OPERATOR_PLUSEQ,
5447 tref, call, bloc);
5448 gogo->add_statement(s);
5451 // Return retval to the caller of the hash function.
5452 Expression_list* vals = new Expression_list();
5453 ref = Expression::make_temporary_reference(retval, bloc);
5454 vals->push_back(ref);
5455 Statement* s = Statement::make_return_statement(vals, bloc);
5456 gogo->add_statement(s);
5459 // Write the equality function for a struct which can not use the
5460 // identity function.
5462 void
5463 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
5465 Location bloc = Linemap::predeclared_location();
5467 // The pointers to the structs we are going to compare.
5468 Named_object* key1_arg = gogo->lookup("key1", NULL);
5469 Named_object* key2_arg = gogo->lookup("key2", NULL);
5470 go_assert(key1_arg != NULL && key2_arg != NULL);
5472 // Build temporaries with the right types.
5473 Type* pt = Type::make_pointer_type(name != NULL
5474 ? static_cast<Type*>(name)
5475 : static_cast<Type*>(this));
5477 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
5478 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5479 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
5480 gogo->add_statement(p1);
5482 ref = Expression::make_var_reference(key2_arg, bloc);
5483 ref = Expression::make_unsafe_cast(pt, ref, bloc);
5484 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
5485 gogo->add_statement(p2);
5487 const Struct_field_list* fields = this->fields_;
5488 unsigned int field_index = 0;
5489 for (Struct_field_list::const_iterator pf = fields->begin();
5490 pf != fields->end();
5491 ++pf, ++field_index)
5493 if (Gogo::is_sink_name(pf->field_name()))
5494 continue;
5496 // Compare one field in both P1 and P2.
5497 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
5498 f1 = Expression::make_unary(OPERATOR_MULT, f1, bloc);
5499 f1 = Expression::make_field_reference(f1, field_index, bloc);
5501 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
5502 f2 = Expression::make_unary(OPERATOR_MULT, f2, bloc);
5503 f2 = Expression::make_field_reference(f2, field_index, bloc);
5505 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
5507 // If the values are not equal, return false.
5508 gogo->start_block(bloc);
5509 Expression_list* vals = new Expression_list();
5510 vals->push_back(Expression::make_boolean(false, bloc));
5511 Statement* s = Statement::make_return_statement(vals, bloc);
5512 gogo->add_statement(s);
5513 Block* then_block = gogo->finish_block(bloc);
5515 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
5516 gogo->add_statement(s);
5519 // All the fields are equal, so return true.
5520 Expression_list* vals = new Expression_list();
5521 vals->push_back(Expression::make_boolean(true, bloc));
5522 Statement* s = Statement::make_return_statement(vals, bloc);
5523 gogo->add_statement(s);
5526 // Reflection string.
5528 void
5529 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
5531 ret->append("struct {");
5533 for (Struct_field_list::const_iterator p = this->fields_->begin();
5534 p != this->fields_->end();
5535 ++p)
5537 if (p != this->fields_->begin())
5538 ret->push_back(';');
5539 ret->push_back(' ');
5540 if (p->is_anonymous())
5541 ret->push_back('?');
5542 else
5543 ret->append(Gogo::unpack_hidden_name(p->field_name()));
5544 ret->push_back(' ');
5545 this->append_reflection(p->type(), gogo, ret);
5547 if (p->has_tag())
5549 const std::string& tag(p->tag());
5550 ret->append(" \"");
5551 for (std::string::const_iterator p = tag.begin();
5552 p != tag.end();
5553 ++p)
5555 if (*p == '\0')
5556 ret->append("\\x00");
5557 else if (*p == '\n')
5558 ret->append("\\n");
5559 else if (*p == '\t')
5560 ret->append("\\t");
5561 else if (*p == '"')
5562 ret->append("\\\"");
5563 else if (*p == '\\')
5564 ret->append("\\\\");
5565 else
5566 ret->push_back(*p);
5568 ret->push_back('"');
5572 if (!this->fields_->empty())
5573 ret->push_back(' ');
5575 ret->push_back('}');
5578 // Generate GC symbol for struct types.
5580 void
5581 Struct_type::do_gc_symbol(Gogo* gogo, Expression_list** vals,
5582 Expression** offset, int stack_size)
5584 Location bloc = Linemap::predeclared_location();
5585 const Struct_field_list* sfl = this->fields();
5586 for (Struct_field_list::const_iterator p = sfl->begin();
5587 p != sfl->end();
5588 ++p)
5590 Expression* field_offset =
5591 Expression::make_struct_field_offset(this, &*p);
5592 Expression* o =
5593 Expression::make_binary(OPERATOR_PLUS, *offset, field_offset, bloc);
5594 Type::gc_symbol(gogo, p->type(), vals, &o, stack_size);
5596 this->advance_gc_offset(offset);
5599 // Mangled name.
5601 void
5602 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5604 ret->push_back('S');
5606 const Struct_field_list* fields = this->fields_;
5607 if (fields != NULL)
5609 for (Struct_field_list::const_iterator p = fields->begin();
5610 p != fields->end();
5611 ++p)
5613 if (p->is_anonymous())
5614 ret->append("0_");
5615 else
5617 std::string n = Gogo::unpack_hidden_name(p->field_name());
5618 char buf[20];
5619 snprintf(buf, sizeof buf, "%u_",
5620 static_cast<unsigned int>(n.length()));
5621 ret->append(buf);
5622 ret->append(n);
5624 this->append_mangled_name(p->type(), gogo, ret);
5625 if (p->has_tag())
5627 const std::string& tag(p->tag());
5628 std::string out;
5629 for (std::string::const_iterator p = tag.begin();
5630 p != tag.end();
5631 ++p)
5633 if (ISALNUM(*p) || *p == '_')
5634 out.push_back(*p);
5635 else
5637 char buf[20];
5638 snprintf(buf, sizeof buf, ".%x.",
5639 static_cast<unsigned int>(*p));
5640 out.append(buf);
5643 char buf[20];
5644 snprintf(buf, sizeof buf, "T%u_",
5645 static_cast<unsigned int>(out.length()));
5646 ret->append(buf);
5647 ret->append(out);
5652 ret->push_back('e');
5655 // If the offset of field INDEX in the backend implementation can be
5656 // determined, set *POFFSET to the offset in bytes and return true.
5657 // Otherwise, return false.
5659 bool
5660 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
5661 unsigned int* poffset)
5663 if (!this->is_backend_type_size_known(gogo))
5664 return false;
5665 Btype* bt = this->get_backend_placeholder(gogo);
5666 size_t offset = gogo->backend()->type_field_offset(bt, index);
5667 *poffset = static_cast<unsigned int>(offset);
5668 if (*poffset != offset)
5669 return false;
5670 return true;
5673 // Export.
5675 void
5676 Struct_type::do_export(Export* exp) const
5678 exp->write_c_string("struct { ");
5679 const Struct_field_list* fields = this->fields_;
5680 go_assert(fields != NULL);
5681 for (Struct_field_list::const_iterator p = fields->begin();
5682 p != fields->end();
5683 ++p)
5685 if (p->is_anonymous())
5686 exp->write_string("? ");
5687 else
5689 exp->write_string(p->field_name());
5690 exp->write_c_string(" ");
5692 exp->write_type(p->type());
5694 if (p->has_tag())
5696 exp->write_c_string(" ");
5697 Expression* expr =
5698 Expression::make_string(p->tag(), Linemap::predeclared_location());
5699 expr->export_expression(exp);
5700 delete expr;
5703 exp->write_c_string("; ");
5705 exp->write_c_string("}");
5708 // Import.
5710 Struct_type*
5711 Struct_type::do_import(Import* imp)
5713 imp->require_c_string("struct { ");
5714 Struct_field_list* fields = new Struct_field_list;
5715 if (imp->peek_char() != '}')
5717 while (true)
5719 std::string name;
5720 if (imp->match_c_string("? "))
5721 imp->advance(2);
5722 else
5724 name = imp->read_identifier();
5725 imp->require_c_string(" ");
5727 Type* ftype = imp->read_type();
5729 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
5730 sf.set_is_imported();
5732 if (imp->peek_char() == ' ')
5734 imp->advance(1);
5735 Expression* expr = Expression::import_expression(imp);
5736 String_expression* sexpr = expr->string_expression();
5737 go_assert(sexpr != NULL);
5738 sf.set_tag(sexpr->val());
5739 delete sexpr;
5742 imp->require_c_string("; ");
5743 fields->push_back(sf);
5744 if (imp->peek_char() == '}')
5745 break;
5748 imp->require_c_string("}");
5750 return Type::make_struct_type(fields, imp->location());
5753 // Make a struct type.
5755 Struct_type*
5756 Type::make_struct_type(Struct_field_list* fields,
5757 Location location)
5759 return new Struct_type(fields, location);
5762 // Class Array_type.
5764 // Whether two array types are identical.
5766 bool
5767 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
5769 if (!Type::are_identical(this->element_type(), t->element_type(),
5770 errors_are_identical, NULL))
5771 return false;
5773 Expression* l1 = this->length();
5774 Expression* l2 = t->length();
5776 // Slices of the same element type are identical.
5777 if (l1 == NULL && l2 == NULL)
5778 return true;
5780 // Arrays of the same element type are identical if they have the
5781 // same length.
5782 if (l1 != NULL && l2 != NULL)
5784 if (l1 == l2)
5785 return true;
5787 // Try to determine the lengths. If we can't, assume the arrays
5788 // are not identical.
5789 bool ret = false;
5790 Numeric_constant nc1, nc2;
5791 if (l1->numeric_constant_value(&nc1)
5792 && l2->numeric_constant_value(&nc2))
5794 mpz_t v1;
5795 if (nc1.to_int(&v1))
5797 mpz_t v2;
5798 if (nc2.to_int(&v2))
5800 ret = mpz_cmp(v1, v2) == 0;
5801 mpz_clear(v2);
5803 mpz_clear(v1);
5806 return ret;
5809 // Otherwise the arrays are not identical.
5810 return false;
5813 // Traversal.
5816 Array_type::do_traverse(Traverse* traverse)
5818 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
5819 return TRAVERSE_EXIT;
5820 if (this->length_ != NULL
5821 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
5822 return TRAVERSE_EXIT;
5823 return TRAVERSE_CONTINUE;
5826 // Check that the length is valid.
5828 bool
5829 Array_type::verify_length()
5831 if (this->length_ == NULL)
5832 return true;
5834 Type_context context(Type::lookup_integer_type("int"), false);
5835 this->length_->determine_type(&context);
5837 if (!this->length_->is_constant())
5839 error_at(this->length_->location(), "array bound is not constant");
5840 return false;
5843 Numeric_constant nc;
5844 if (!this->length_->numeric_constant_value(&nc))
5846 if (this->length_->type()->integer_type() != NULL
5847 || this->length_->type()->float_type() != NULL)
5848 error_at(this->length_->location(), "array bound is not constant");
5849 else
5850 error_at(this->length_->location(), "array bound is not numeric");
5851 return false;
5854 unsigned long val;
5855 switch (nc.to_unsigned_long(&val))
5857 case Numeric_constant::NC_UL_VALID:
5858 break;
5859 case Numeric_constant::NC_UL_NOTINT:
5860 error_at(this->length_->location(), "array bound truncated to integer");
5861 return false;
5862 case Numeric_constant::NC_UL_NEGATIVE:
5863 error_at(this->length_->location(), "negative array bound");
5864 return false;
5865 case Numeric_constant::NC_UL_BIG:
5866 error_at(this->length_->location(), "array bound overflows");
5867 return false;
5868 default:
5869 go_unreachable();
5872 Type* int_type = Type::lookup_integer_type("int");
5873 unsigned int tbits = int_type->integer_type()->bits();
5874 if (sizeof(val) <= tbits * 8
5875 && val >> (tbits - 1) != 0)
5877 error_at(this->length_->location(), "array bound overflows");
5878 return false;
5881 return true;
5884 // Verify the type.
5886 bool
5887 Array_type::do_verify()
5889 if (!this->verify_length())
5890 this->length_ = Expression::make_error(this->length_->location());
5891 return true;
5894 // Whether we can use memcmp to compare this array.
5896 bool
5897 Array_type::do_compare_is_identity(Gogo* gogo)
5899 if (this->length_ == NULL)
5900 return false;
5902 // Check for [...], which indicates that this is not a real type.
5903 if (this->length_->is_nil_expression())
5904 return false;
5906 if (!this->element_type_->compare_is_identity(gogo))
5907 return false;
5909 // If there is any padding, then we can't use memcmp.
5910 unsigned long size;
5911 unsigned long align;
5912 if (!this->element_type_->backend_type_size(gogo, &size)
5913 || !this->element_type_->backend_type_align(gogo, &align))
5914 return false;
5915 if ((size & (align - 1)) != 0)
5916 return false;
5918 return true;
5921 // Array type hash code.
5923 unsigned int
5924 Array_type::do_hash_for_method(Gogo* gogo) const
5926 // There is no very convenient way to get a hash code for the
5927 // length.
5928 return this->element_type_->hash_for_method(gogo) + 1;
5931 // Write the hash function for an array which can not use the identify
5932 // function.
5934 void
5935 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
5936 Function_type* hash_fntype,
5937 Function_type* equal_fntype)
5939 Location bloc = Linemap::predeclared_location();
5941 // The pointer to the array that we are going to hash. This is an
5942 // argument to the hash function we are implementing here.
5943 Named_object* key_arg = gogo->lookup("key", NULL);
5944 go_assert(key_arg != NULL);
5945 Type* key_arg_type = key_arg->var_value()->type();
5947 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5949 // Get a 0.
5950 mpz_t ival;
5951 mpz_init_set_ui(ival, 0);
5952 Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
5953 mpz_clear(ival);
5955 // Make a temporary to hold the return value, initialized to 0.
5956 Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
5957 bloc);
5958 gogo->add_statement(retval);
5960 // Make a temporary to hold the key as a uintptr.
5961 Expression* ref = Expression::make_var_reference(key_arg, bloc);
5962 ref = Expression::make_cast(uintptr_type, ref, bloc);
5963 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
5964 bloc);
5965 gogo->add_statement(key);
5967 // Loop over the array elements.
5968 // for i = range a
5969 Type* int_type = Type::lookup_integer_type("int");
5970 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
5971 gogo->add_statement(index);
5973 Expression* iref = Expression::make_temporary_reference(index, bloc);
5974 Expression* aref = Expression::make_var_reference(key_arg, bloc);
5975 Type* pt = Type::make_pointer_type(name != NULL
5976 ? static_cast<Type*>(name)
5977 : static_cast<Type*>(this));
5978 aref = Expression::make_cast(pt, aref, bloc);
5979 For_range_statement* for_range = Statement::make_for_range_statement(iref,
5980 NULL,
5981 aref,
5982 bloc);
5984 gogo->start_block(bloc);
5986 // Multiply retval by 33.
5987 mpz_init_set_ui(ival, 33);
5988 Expression* i33 = Expression::make_integer(&ival, uintptr_type, bloc);
5989 mpz_clear(ival);
5991 ref = Expression::make_temporary_reference(retval, bloc);
5992 Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ, ref,
5993 i33, bloc);
5994 gogo->add_statement(s);
5996 // Get the hash function for the element type.
5997 Named_object* hash_fn;
5998 Named_object* equal_fn;
5999 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
6000 hash_fntype, equal_fntype, &hash_fn,
6001 &equal_fn);
6003 // Get a pointer to this element in the loop.
6004 Expression* subkey = Expression::make_temporary_reference(key, bloc);
6005 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6007 // Get the size of each element.
6008 Expression* ele_size = Expression::make_type_info(this->element_type_,
6009 Expression::TYPE_INFO_SIZE);
6011 // Get the hash of this element.
6012 Expression_list* args = new Expression_list();
6013 args->push_back(subkey);
6014 args->push_back(ele_size);
6015 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6016 Expression* call = Expression::make_call(func, args, false, bloc);
6018 // Add the element's hash value to retval.
6019 Temporary_reference_expression* tref =
6020 Expression::make_temporary_reference(retval, bloc);
6021 tref->set_is_lvalue();
6022 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, call, bloc);
6023 gogo->add_statement(s);
6025 // Increase the element pointer.
6026 tref = Expression::make_temporary_reference(key, bloc);
6027 tref->set_is_lvalue();
6028 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
6029 bloc);
6031 Block* statements = gogo->finish_block(bloc);
6033 for_range->add_statements(statements);
6034 gogo->add_statement(for_range);
6036 // Return retval to the caller of the hash function.
6037 Expression_list* vals = new Expression_list();
6038 ref = Expression::make_temporary_reference(retval, bloc);
6039 vals->push_back(ref);
6040 s = Statement::make_return_statement(vals, bloc);
6041 gogo->add_statement(s);
6044 // Write the equality function for an array which can not use the
6045 // identity function.
6047 void
6048 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
6050 Location bloc = Linemap::predeclared_location();
6052 // The pointers to the arrays we are going to compare.
6053 Named_object* key1_arg = gogo->lookup("key1", NULL);
6054 Named_object* key2_arg = gogo->lookup("key2", NULL);
6055 go_assert(key1_arg != NULL && key2_arg != NULL);
6057 // Build temporaries for the keys with the right types.
6058 Type* pt = Type::make_pointer_type(name != NULL
6059 ? static_cast<Type*>(name)
6060 : static_cast<Type*>(this));
6062 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6063 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6064 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6065 gogo->add_statement(p1);
6067 ref = Expression::make_var_reference(key2_arg, bloc);
6068 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6069 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6070 gogo->add_statement(p2);
6072 // Loop over the array elements.
6073 // for i = range a
6074 Type* int_type = Type::lookup_integer_type("int");
6075 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
6076 gogo->add_statement(index);
6078 Expression* iref = Expression::make_temporary_reference(index, bloc);
6079 Expression* aref = Expression::make_temporary_reference(p1, bloc);
6080 For_range_statement* for_range = Statement::make_for_range_statement(iref,
6081 NULL,
6082 aref,
6083 bloc);
6085 gogo->start_block(bloc);
6087 // Compare element in P1 and P2.
6088 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
6089 e1 = Expression::make_unary(OPERATOR_MULT, e1, bloc);
6090 ref = Expression::make_temporary_reference(index, bloc);
6091 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
6093 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
6094 e2 = Expression::make_unary(OPERATOR_MULT, e2, bloc);
6095 ref = Expression::make_temporary_reference(index, bloc);
6096 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
6098 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
6100 // If the elements are not equal, return false.
6101 gogo->start_block(bloc);
6102 Expression_list* vals = new Expression_list();
6103 vals->push_back(Expression::make_boolean(false, bloc));
6104 Statement* s = Statement::make_return_statement(vals, bloc);
6105 gogo->add_statement(s);
6106 Block* then_block = gogo->finish_block(bloc);
6108 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6109 gogo->add_statement(s);
6111 Block* statements = gogo->finish_block(bloc);
6113 for_range->add_statements(statements);
6114 gogo->add_statement(for_range);
6116 // All the elements are equal, so return true.
6117 vals = new Expression_list();
6118 vals->push_back(Expression::make_boolean(true, bloc));
6119 s = Statement::make_return_statement(vals, bloc);
6120 gogo->add_statement(s);
6123 // Get the backend representation of the fields of a slice. This is
6124 // not declared in types.h so that types.h doesn't have to #include
6125 // backend.h.
6127 // We use int for the count and capacity fields. This matches 6g.
6128 // The language more or less assumes that we can't allocate space of a
6129 // size which does not fit in int.
6131 static void
6132 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
6133 std::vector<Backend::Btyped_identifier>* bfields)
6135 bfields->resize(3);
6137 Type* pet = Type::make_pointer_type(type->element_type());
6138 Btype* pbet = (use_placeholder
6139 ? pet->get_backend_placeholder(gogo)
6140 : pet->get_backend(gogo));
6141 Location ploc = Linemap::predeclared_location();
6143 Backend::Btyped_identifier* p = &(*bfields)[0];
6144 p->name = "__values";
6145 p->btype = pbet;
6146 p->location = ploc;
6148 Type* int_type = Type::lookup_integer_type("int");
6150 p = &(*bfields)[1];
6151 p->name = "__count";
6152 p->btype = int_type->get_backend(gogo);
6153 p->location = ploc;
6155 p = &(*bfields)[2];
6156 p->name = "__capacity";
6157 p->btype = int_type->get_backend(gogo);
6158 p->location = ploc;
6161 // Get the backend representation for the type of this array. A fixed array is
6162 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
6163 // just like an array in C. An open array is a struct with three
6164 // fields: a data pointer, the length, and the capacity.
6166 Btype*
6167 Array_type::do_get_backend(Gogo* gogo)
6169 if (this->length_ == NULL)
6171 std::vector<Backend::Btyped_identifier> bfields;
6172 get_backend_slice_fields(gogo, this, false, &bfields);
6173 return gogo->backend()->struct_type(bfields);
6175 else
6177 Btype* element = this->get_backend_element(gogo, false);
6178 Bexpression* len = this->get_backend_length(gogo);
6179 return gogo->backend()->array_type(element, len);
6183 // Return the backend representation of the element type.
6185 Btype*
6186 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
6188 if (use_placeholder)
6189 return this->element_type_->get_backend_placeholder(gogo);
6190 else
6191 return this->element_type_->get_backend(gogo);
6194 // Return the backend representation of the length. The length may be
6195 // computed using a function call, so we must only evaluate it once.
6197 Bexpression*
6198 Array_type::get_backend_length(Gogo* gogo)
6200 go_assert(this->length_ != NULL);
6201 if (this->blength_ == NULL)
6203 Numeric_constant nc;
6204 mpz_t val;
6205 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
6207 if (mpz_sgn(val) < 0)
6209 this->blength_ = gogo->backend()->error_expression();
6210 return this->blength_;
6212 Type* t = nc.type();
6213 if (t == NULL)
6214 t = Type::lookup_integer_type("int");
6215 else if (t->is_abstract())
6216 t = t->make_non_abstract_type();
6217 Btype* btype = t->get_backend(gogo);
6218 this->blength_ =
6219 gogo->backend()->integer_constant_expression(btype, val);
6220 mpz_clear(val);
6222 else
6224 // Make up a translation context for the array length
6225 // expression. FIXME: This won't work in general.
6226 Translate_context context(gogo, NULL, NULL, NULL);
6227 this->blength_ = this->length_->get_backend(&context);
6229 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
6230 this->blength_ =
6231 gogo->backend()->convert_expression(ibtype, this->blength_,
6232 this->length_->location());
6235 return this->blength_;
6238 // Finish backend representation of the array.
6240 void
6241 Array_type::finish_backend_element(Gogo* gogo)
6243 Type* et = this->array_type()->element_type();
6244 et->get_backend(gogo);
6245 if (this->is_slice_type())
6247 // This relies on the fact that we always use the same
6248 // structure for a pointer to any given type.
6249 Type* pet = Type::make_pointer_type(et);
6250 pet->get_backend(gogo);
6254 // Return an expression for a pointer to the values in ARRAY.
6256 Expression*
6257 Array_type::get_value_pointer(Gogo*, Expression* array) const
6259 if (this->length() != NULL)
6261 // Fixed array.
6262 go_assert(array->type()->array_type() != NULL);
6263 Type* etype = array->type()->array_type()->element_type();
6264 array = Expression::make_unary(OPERATOR_AND, array, array->location());
6265 return Expression::make_cast(Type::make_pointer_type(etype), array,
6266 array->location());
6269 // Slice.
6270 return Expression::make_slice_info(array,
6271 Expression::SLICE_INFO_VALUE_POINTER,
6272 array->location());
6275 // Return an expression for the length of the array ARRAY which has this
6276 // type.
6278 Expression*
6279 Array_type::get_length(Gogo*, Expression* array) const
6281 if (this->length_ != NULL)
6282 return this->length_;
6284 // This is a slice. We need to read the length field.
6285 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
6286 array->location());
6289 // Return an expression for the capacity of the array ARRAY which has this
6290 // type.
6292 Expression*
6293 Array_type::get_capacity(Gogo*, Expression* array) const
6295 if (this->length_ != NULL)
6296 return this->length_;
6298 // This is a slice. We need to read the capacity field.
6299 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
6300 array->location());
6303 // Export.
6305 void
6306 Array_type::do_export(Export* exp) const
6308 exp->write_c_string("[");
6309 if (this->length_ != NULL)
6310 this->length_->export_expression(exp);
6311 exp->write_c_string("] ");
6312 exp->write_type(this->element_type_);
6315 // Import.
6317 Array_type*
6318 Array_type::do_import(Import* imp)
6320 imp->require_c_string("[");
6321 Expression* length;
6322 if (imp->peek_char() == ']')
6323 length = NULL;
6324 else
6325 length = Expression::import_expression(imp);
6326 imp->require_c_string("] ");
6327 Type* element_type = imp->read_type();
6328 return Type::make_array_type(element_type, length);
6331 // The type of an array type descriptor.
6333 Type*
6334 Array_type::make_array_type_descriptor_type()
6336 static Type* ret;
6337 if (ret == NULL)
6339 Type* tdt = Type::make_type_descriptor_type();
6340 Type* ptdt = Type::make_type_descriptor_ptr_type();
6342 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6344 Struct_type* sf =
6345 Type::make_builtin_struct_type(4,
6346 "", tdt,
6347 "elem", ptdt,
6348 "slice", ptdt,
6349 "len", uintptr_type);
6351 ret = Type::make_builtin_named_type("ArrayType", sf);
6354 return ret;
6357 // The type of an slice type descriptor.
6359 Type*
6360 Array_type::make_slice_type_descriptor_type()
6362 static Type* ret;
6363 if (ret == NULL)
6365 Type* tdt = Type::make_type_descriptor_type();
6366 Type* ptdt = Type::make_type_descriptor_ptr_type();
6368 Struct_type* sf =
6369 Type::make_builtin_struct_type(2,
6370 "", tdt,
6371 "elem", ptdt);
6373 ret = Type::make_builtin_named_type("SliceType", sf);
6376 return ret;
6379 // Build a type descriptor for an array/slice type.
6381 Expression*
6382 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6384 if (this->length_ != NULL)
6385 return this->array_type_descriptor(gogo, name);
6386 else
6387 return this->slice_type_descriptor(gogo, name);
6390 // Build a type descriptor for an array type.
6392 Expression*
6393 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
6395 Location bloc = Linemap::predeclared_location();
6397 Type* atdt = Array_type::make_array_type_descriptor_type();
6399 const Struct_field_list* fields = atdt->struct_type()->fields();
6401 Expression_list* vals = new Expression_list();
6402 vals->reserve(3);
6404 Struct_field_list::const_iterator p = fields->begin();
6405 go_assert(p->is_field_name("commonType"));
6406 vals->push_back(this->type_descriptor_constructor(gogo,
6407 RUNTIME_TYPE_KIND_ARRAY,
6408 name, NULL, true));
6410 ++p;
6411 go_assert(p->is_field_name("elem"));
6412 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
6414 ++p;
6415 go_assert(p->is_field_name("slice"));
6416 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
6417 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
6419 ++p;
6420 go_assert(p->is_field_name("len"));
6421 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
6423 ++p;
6424 go_assert(p == fields->end());
6426 return Expression::make_struct_composite_literal(atdt, vals, bloc);
6429 // Build a type descriptor for a slice type.
6431 Expression*
6432 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
6434 Location bloc = Linemap::predeclared_location();
6436 Type* stdt = Array_type::make_slice_type_descriptor_type();
6438 const Struct_field_list* fields = stdt->struct_type()->fields();
6440 Expression_list* vals = new Expression_list();
6441 vals->reserve(2);
6443 Struct_field_list::const_iterator p = fields->begin();
6444 go_assert(p->is_field_name("commonType"));
6445 vals->push_back(this->type_descriptor_constructor(gogo,
6446 RUNTIME_TYPE_KIND_SLICE,
6447 name, NULL, true));
6449 ++p;
6450 go_assert(p->is_field_name("elem"));
6451 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
6453 ++p;
6454 go_assert(p == fields->end());
6456 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6459 // Reflection string.
6461 void
6462 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
6464 ret->push_back('[');
6465 if (this->length_ != NULL)
6467 Numeric_constant nc;
6468 unsigned long val;
6469 if (!this->length_->numeric_constant_value(&nc)
6470 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
6471 error_at(this->length_->location(), "invalid array length");
6472 else
6474 char buf[50];
6475 snprintf(buf, sizeof buf, "%lu", val);
6476 ret->append(buf);
6479 ret->push_back(']');
6481 this->append_reflection(this->element_type_, gogo, ret);
6484 // GC Symbol construction for array types.
6486 void
6487 Array_type::do_gc_symbol(Gogo* gogo, Expression_list** vals,
6488 Expression** offset, int stack_size)
6490 if (this->length_ == NULL)
6491 this->slice_gc_symbol(gogo, vals, offset, stack_size);
6492 else
6493 this->array_gc_symbol(gogo, vals, offset, stack_size);
6496 // Generate the GC Symbol for a slice.
6498 void
6499 Array_type::slice_gc_symbol(Gogo* gogo, Expression_list** vals,
6500 Expression** offset, int)
6502 Location bloc = Linemap::predeclared_location();
6504 // Differentiate between slices with zero-length and non-zero-length values.
6505 Type* element_type = this->element_type();
6506 Btype* ebtype = element_type->get_backend(gogo);
6507 size_t element_size = gogo->backend()->type_size(ebtype);
6509 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6510 mpz_t opval;
6511 mpz_init_set_ui(opval, element_size == 0 ? GC_APTR : GC_SLICE);
6512 (*vals)->push_back(Expression::make_integer(&opval, uintptr_type, bloc));
6513 mpz_clear(opval);
6514 (*vals)->push_back(*offset);
6516 if (element_size != 0)
6517 (*vals)->push_back(Expression::make_gc_symbol(element_type));
6518 this->advance_gc_offset(offset);
6521 // Generate the GC symbol for an array.
6523 void
6524 Array_type::array_gc_symbol(Gogo* gogo, Expression_list** vals,
6525 Expression** offset, int stack_size)
6527 Location bloc = Linemap::predeclared_location();
6529 Numeric_constant nc;
6530 unsigned long bound;
6531 if (!this->length_->numeric_constant_value(&nc)
6532 || nc.to_unsigned_long(&bound) == Numeric_constant::NC_UL_NOTINT)
6533 go_assert(saw_errors());
6535 Btype* pbtype = gogo->backend()->pointer_type(gogo->backend()->void_type());
6536 size_t pwidth = gogo->backend()->type_size(pbtype);
6537 size_t iwidth = gogo->backend()->type_size(this->get_backend(gogo));
6539 Type* element_type = this->element_type();
6540 if (bound < 1 || !element_type->has_pointer())
6541 this->advance_gc_offset(offset);
6542 else if (bound == 1 || iwidth <= 4 * pwidth)
6544 for (unsigned int i = 0; i < bound; ++i)
6545 Type::gc_symbol(gogo, element_type, vals, offset, stack_size);
6547 else
6549 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6551 mpz_t op;
6552 if (stack_size < GC_STACK_CAPACITY)
6554 mpz_init_set_ui(op, GC_ARRAY_START);
6555 (*vals)->push_back(Expression::make_integer(&op, uintptr_type, bloc));
6556 mpz_clear(op);
6557 (*vals)->push_back(*offset);
6558 Expression* uintptr_len =
6559 Expression::make_cast(uintptr_type, this->length_, bloc);
6560 (*vals)->push_back(uintptr_len);
6562 Expression* width =
6563 Expression::make_type_info(element_type,
6564 Expression::TYPE_INFO_SIZE);
6565 (*vals)->push_back(width);
6567 mpz_t zero;
6568 mpz_init_set_ui(zero, 0UL);
6569 Expression* offset2 =
6570 Expression::make_integer(&zero, uintptr_type, bloc);
6571 mpz_clear(zero);
6573 Type::gc_symbol(gogo, element_type, vals, &offset2, stack_size + 1);
6574 mpz_init_set_ui(op, GC_ARRAY_NEXT);
6575 (*vals)->push_back(Expression::make_integer(&op, uintptr_type, bloc));
6577 else
6579 mpz_init_set_ui(op, GC_REGION);
6580 (*vals)->push_back(Expression::make_integer(&op, uintptr_type, bloc));
6581 (*vals)->push_back(*offset);
6583 Expression* width =
6584 Expression::make_type_info(this, Expression::TYPE_INFO_SIZE);
6585 (*vals)->push_back(width);
6586 (*vals)->push_back(Expression::make_gc_symbol(this));
6588 mpz_clear(op);
6589 this->advance_gc_offset(offset);
6593 // Mangled name.
6595 void
6596 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6598 ret->push_back('A');
6599 this->append_mangled_name(this->element_type_, gogo, ret);
6600 if (this->length_ != NULL)
6602 Numeric_constant nc;
6603 unsigned long val;
6604 if (!this->length_->numeric_constant_value(&nc)
6605 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
6606 error_at(this->length_->location(), "invalid array length");
6607 else
6609 char buf[50];
6610 snprintf(buf, sizeof buf, "%lu", val);
6611 ret->append(buf);
6614 ret->push_back('e');
6617 // Make an array type.
6619 Array_type*
6620 Type::make_array_type(Type* element_type, Expression* length)
6622 return new Array_type(element_type, length);
6625 // Class Map_type.
6627 // Traversal.
6630 Map_type::do_traverse(Traverse* traverse)
6632 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
6633 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
6634 return TRAVERSE_EXIT;
6635 return TRAVERSE_CONTINUE;
6638 // Check that the map type is OK.
6640 bool
6641 Map_type::do_verify()
6643 // The runtime support uses "map[void]void".
6644 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
6645 error_at(this->location_, "invalid map key type");
6646 return true;
6649 // Whether two map types are identical.
6651 bool
6652 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
6654 return (Type::are_identical(this->key_type(), t->key_type(),
6655 errors_are_identical, NULL)
6656 && Type::are_identical(this->val_type(), t->val_type(),
6657 errors_are_identical, NULL));
6660 // Hash code.
6662 unsigned int
6663 Map_type::do_hash_for_method(Gogo* gogo) const
6665 return (this->key_type_->hash_for_method(gogo)
6666 + this->val_type_->hash_for_method(gogo)
6667 + 2);
6670 // Get the backend representation for a map type. A map type is
6671 // represented as a pointer to a struct. The struct is __go_map in
6672 // libgo/map.h.
6674 Btype*
6675 Map_type::do_get_backend(Gogo* gogo)
6677 static Btype* backend_map_type;
6678 if (backend_map_type == NULL)
6680 std::vector<Backend::Btyped_identifier> bfields(4);
6682 Location bloc = Linemap::predeclared_location();
6684 Type* pdt = Type::make_type_descriptor_ptr_type();
6685 bfields[0].name = "__descriptor";
6686 bfields[0].btype = pdt->get_backend(gogo);
6687 bfields[0].location = bloc;
6689 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6690 bfields[1].name = "__element_count";
6691 bfields[1].btype = uintptr_type->get_backend(gogo);
6692 bfields[1].location = bloc;
6694 bfields[2].name = "__bucket_count";
6695 bfields[2].btype = bfields[1].btype;
6696 bfields[2].location = bloc;
6698 Btype* bvt = gogo->backend()->void_type();
6699 Btype* bpvt = gogo->backend()->pointer_type(bvt);
6700 Btype* bppvt = gogo->backend()->pointer_type(bpvt);
6701 bfields[3].name = "__buckets";
6702 bfields[3].btype = bppvt;
6703 bfields[3].location = bloc;
6705 Btype *bt = gogo->backend()->struct_type(bfields);
6706 bt = gogo->backend()->named_type("__go_map", bt, bloc);
6707 backend_map_type = gogo->backend()->pointer_type(bt);
6709 return backend_map_type;
6712 // The type of a map type descriptor.
6714 Type*
6715 Map_type::make_map_type_descriptor_type()
6717 static Type* ret;
6718 if (ret == NULL)
6720 Type* tdt = Type::make_type_descriptor_type();
6721 Type* ptdt = Type::make_type_descriptor_ptr_type();
6723 Struct_type* sf =
6724 Type::make_builtin_struct_type(3,
6725 "", tdt,
6726 "key", ptdt,
6727 "elem", ptdt);
6729 ret = Type::make_builtin_named_type("MapType", sf);
6732 return ret;
6735 // Build a type descriptor for a map type.
6737 Expression*
6738 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6740 Location bloc = Linemap::predeclared_location();
6742 Type* mtdt = Map_type::make_map_type_descriptor_type();
6744 const Struct_field_list* fields = mtdt->struct_type()->fields();
6746 Expression_list* vals = new Expression_list();
6747 vals->reserve(3);
6749 Struct_field_list::const_iterator p = fields->begin();
6750 go_assert(p->is_field_name("commonType"));
6751 vals->push_back(this->type_descriptor_constructor(gogo,
6752 RUNTIME_TYPE_KIND_MAP,
6753 name, NULL, true));
6755 ++p;
6756 go_assert(p->is_field_name("key"));
6757 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
6759 ++p;
6760 go_assert(p->is_field_name("elem"));
6761 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
6763 ++p;
6764 go_assert(p == fields->end());
6766 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
6769 // A mapping from map types to map descriptors.
6771 Map_type::Map_descriptors Map_type::map_descriptors;
6773 // Build a map descriptor for this type. Return a pointer to it.
6775 Bexpression*
6776 Map_type::map_descriptor_pointer(Gogo* gogo, Location location)
6778 Bvariable* bvar = this->map_descriptor(gogo);
6779 Bexpression* var_expr = gogo->backend()->var_expression(bvar, location);
6780 return gogo->backend()->address_expression(var_expr, location);
6783 // Build a map descriptor for this type.
6785 Bvariable*
6786 Map_type::map_descriptor(Gogo* gogo)
6788 std::pair<Map_type*, Bvariable*> val(this, NULL);
6789 std::pair<Map_type::Map_descriptors::iterator, bool> ins =
6790 Map_type::map_descriptors.insert(val);
6791 if (!ins.second)
6792 return ins.first->second;
6794 Type* key_type = this->key_type_;
6795 Type* val_type = this->val_type_;
6797 // The map entry type is a struct with three fields. Build that
6798 // struct so that we can get the offsets of the key and value within
6799 // a map entry. The first field should technically be a pointer to
6800 // this type itself, but since we only care about field offsets we
6801 // just use pointer to bool.
6802 Type* pbool = Type::make_pointer_type(Type::make_boolean_type());
6803 Struct_type* map_entry_type =
6804 Type::make_builtin_struct_type(3,
6805 "__next", pbool,
6806 "__key", key_type,
6807 "__val", val_type);
6809 Type* map_descriptor_type = Map_type::make_map_descriptor_type();
6811 const Struct_field_list* fields =
6812 map_descriptor_type->struct_type()->fields();
6814 Expression_list* vals = new Expression_list();
6815 vals->reserve(4);
6817 Location bloc = Linemap::predeclared_location();
6819 Struct_field_list::const_iterator p = fields->begin();
6821 go_assert(p->is_field_name("__map_descriptor"));
6822 vals->push_back(Expression::make_type_descriptor(this, bloc));
6824 ++p;
6825 go_assert(p->is_field_name("__entry_size"));
6826 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
6827 vals->push_back(Expression::make_type_info(map_entry_type, type_info));
6829 Struct_field_list::const_iterator pf = map_entry_type->fields()->begin();
6830 ++pf;
6831 go_assert(pf->is_field_name("__key"));
6833 ++p;
6834 go_assert(p->is_field_name("__key_offset"));
6835 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6837 ++pf;
6838 go_assert(pf->is_field_name("__val"));
6840 ++p;
6841 go_assert(p->is_field_name("__val_offset"));
6842 vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6844 ++p;
6845 go_assert(p == fields->end());
6847 Expression* initializer =
6848 Expression::make_struct_composite_literal(map_descriptor_type, vals, bloc);
6850 std::string mangled_name = "__go_map_" + this->mangled_name(gogo);
6851 Btype* map_descriptor_btype = map_descriptor_type->get_backend(gogo);
6852 Bvariable* bvar = gogo->backend()->immutable_struct(mangled_name, false,
6853 true,
6854 map_descriptor_btype,
6855 bloc);
6857 Translate_context context(gogo, NULL, NULL, NULL);
6858 context.set_is_const();
6859 Bexpression* binitializer = initializer->get_backend(&context);
6861 gogo->backend()->immutable_struct_set_init(bvar, mangled_name, false, true,
6862 map_descriptor_btype, bloc,
6863 binitializer);
6865 ins.first->second = bvar;
6866 return bvar;
6869 // Build the type of a map descriptor. This must match the struct
6870 // __go_map_descriptor in libgo/runtime/map.h.
6872 Type*
6873 Map_type::make_map_descriptor_type()
6875 static Type* ret;
6876 if (ret == NULL)
6878 Type* ptdt = Type::make_type_descriptor_ptr_type();
6879 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6880 Struct_type* sf =
6881 Type::make_builtin_struct_type(4,
6882 "__map_descriptor", ptdt,
6883 "__entry_size", uintptr_type,
6884 "__key_offset", uintptr_type,
6885 "__val_offset", uintptr_type);
6886 ret = Type::make_builtin_named_type("__go_map_descriptor", sf);
6888 return ret;
6891 // Reflection string for a map.
6893 void
6894 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
6896 ret->append("map[");
6897 this->append_reflection(this->key_type_, gogo, ret);
6898 ret->append("]");
6899 this->append_reflection(this->val_type_, gogo, ret);
6902 // Generate GC symbol for a map.
6904 void
6905 Map_type::do_gc_symbol(Gogo*, Expression_list** vals,
6906 Expression** offset, int)
6908 // TODO(cmang): Generate GC data for the Map elements.
6909 Location bloc = Linemap::predeclared_location();
6910 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6912 mpz_t opval;
6913 mpz_init_set_ui(opval, GC_APTR);
6914 (*vals)->push_back(Expression::make_integer(&opval, uintptr_type, bloc));
6915 mpz_clear(opval);
6916 (*vals)->push_back(*offset);
6917 this->advance_gc_offset(offset);
6920 // Mangled name for a map.
6922 void
6923 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6925 ret->push_back('M');
6926 this->append_mangled_name(this->key_type_, gogo, ret);
6927 ret->append("__");
6928 this->append_mangled_name(this->val_type_, gogo, ret);
6931 // Export a map type.
6933 void
6934 Map_type::do_export(Export* exp) const
6936 exp->write_c_string("map [");
6937 exp->write_type(this->key_type_);
6938 exp->write_c_string("] ");
6939 exp->write_type(this->val_type_);
6942 // Import a map type.
6944 Map_type*
6945 Map_type::do_import(Import* imp)
6947 imp->require_c_string("map [");
6948 Type* key_type = imp->read_type();
6949 imp->require_c_string("] ");
6950 Type* val_type = imp->read_type();
6951 return Type::make_map_type(key_type, val_type, imp->location());
6954 // Make a map type.
6956 Map_type*
6957 Type::make_map_type(Type* key_type, Type* val_type, Location location)
6959 return new Map_type(key_type, val_type, location);
6962 // Class Channel_type.
6964 // Hash code.
6966 unsigned int
6967 Channel_type::do_hash_for_method(Gogo* gogo) const
6969 unsigned int ret = 0;
6970 if (this->may_send_)
6971 ret += 1;
6972 if (this->may_receive_)
6973 ret += 2;
6974 if (this->element_type_ != NULL)
6975 ret += this->element_type_->hash_for_method(gogo) << 2;
6976 return ret << 3;
6979 // Whether this type is the same as T.
6981 bool
6982 Channel_type::is_identical(const Channel_type* t,
6983 bool errors_are_identical) const
6985 if (!Type::are_identical(this->element_type(), t->element_type(),
6986 errors_are_identical, NULL))
6987 return false;
6988 return (this->may_send_ == t->may_send_
6989 && this->may_receive_ == t->may_receive_);
6992 // Return the backend representation for a channel type. A channel is a pointer
6993 // to a __go_channel struct. The __go_channel struct is defined in
6994 // libgo/runtime/channel.h.
6996 Btype*
6997 Channel_type::do_get_backend(Gogo* gogo)
6999 static Btype* backend_channel_type;
7000 if (backend_channel_type == NULL)
7002 std::vector<Backend::Btyped_identifier> bfields;
7003 Btype* bt = gogo->backend()->struct_type(bfields);
7004 bt = gogo->backend()->named_type("__go_channel", bt,
7005 Linemap::predeclared_location());
7006 backend_channel_type = gogo->backend()->pointer_type(bt);
7008 return backend_channel_type;
7011 // Build a type descriptor for a channel type.
7013 Type*
7014 Channel_type::make_chan_type_descriptor_type()
7016 static Type* ret;
7017 if (ret == NULL)
7019 Type* tdt = Type::make_type_descriptor_type();
7020 Type* ptdt = Type::make_type_descriptor_ptr_type();
7022 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7024 Struct_type* sf =
7025 Type::make_builtin_struct_type(3,
7026 "", tdt,
7027 "elem", ptdt,
7028 "dir", uintptr_type);
7030 ret = Type::make_builtin_named_type("ChanType", sf);
7033 return ret;
7036 // Build a type descriptor for a map type.
7038 Expression*
7039 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7041 Location bloc = Linemap::predeclared_location();
7043 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
7045 const Struct_field_list* fields = ctdt->struct_type()->fields();
7047 Expression_list* vals = new Expression_list();
7048 vals->reserve(3);
7050 Struct_field_list::const_iterator p = fields->begin();
7051 go_assert(p->is_field_name("commonType"));
7052 vals->push_back(this->type_descriptor_constructor(gogo,
7053 RUNTIME_TYPE_KIND_CHAN,
7054 name, NULL, true));
7056 ++p;
7057 go_assert(p->is_field_name("elem"));
7058 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7060 ++p;
7061 go_assert(p->is_field_name("dir"));
7062 // These bits must match the ones in libgo/runtime/go-type.h.
7063 int val = 0;
7064 if (this->may_receive_)
7065 val |= 1;
7066 if (this->may_send_)
7067 val |= 2;
7068 mpz_t iv;
7069 mpz_init_set_ui(iv, val);
7070 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
7071 mpz_clear(iv);
7073 ++p;
7074 go_assert(p == fields->end());
7076 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
7079 // Reflection string.
7081 void
7082 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
7084 if (!this->may_send_)
7085 ret->append("<-");
7086 ret->append("chan");
7087 if (!this->may_receive_)
7088 ret->append("<-");
7089 ret->push_back(' ');
7090 this->append_reflection(this->element_type_, gogo, ret);
7093 // Generate GC symbol for channels.
7095 void
7096 Channel_type::do_gc_symbol(Gogo*, Expression_list** vals,
7097 Expression** offset, int)
7099 Location bloc = Linemap::predeclared_location();
7100 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7102 mpz_t opval;
7103 mpz_init_set_ui(opval, GC_CHAN_PTR);
7104 (*vals)->push_back(Expression::make_integer(&opval, uintptr_type, bloc));
7105 mpz_clear(opval);
7106 (*vals)->push_back(*offset);
7108 Type* unsafeptr_type = Type::make_pointer_type(Type::make_void_type());
7109 Expression* type_descriptor =
7110 Expression::make_type_descriptor(this, bloc);
7111 type_descriptor =
7112 Expression::make_unsafe_cast(unsafeptr_type, type_descriptor, bloc);
7113 (*vals)->push_back(type_descriptor);
7114 this->advance_gc_offset(offset);
7117 // Mangled name.
7119 void
7120 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7122 ret->push_back('C');
7123 this->append_mangled_name(this->element_type_, gogo, ret);
7124 if (this->may_send_)
7125 ret->push_back('s');
7126 if (this->may_receive_)
7127 ret->push_back('r');
7128 ret->push_back('e');
7131 // Export.
7133 void
7134 Channel_type::do_export(Export* exp) const
7136 exp->write_c_string("chan ");
7137 if (this->may_send_ && !this->may_receive_)
7138 exp->write_c_string("-< ");
7139 else if (this->may_receive_ && !this->may_send_)
7140 exp->write_c_string("<- ");
7141 exp->write_type(this->element_type_);
7144 // Import.
7146 Channel_type*
7147 Channel_type::do_import(Import* imp)
7149 imp->require_c_string("chan ");
7151 bool may_send;
7152 bool may_receive;
7153 if (imp->match_c_string("-< "))
7155 imp->advance(3);
7156 may_send = true;
7157 may_receive = false;
7159 else if (imp->match_c_string("<- "))
7161 imp->advance(3);
7162 may_receive = true;
7163 may_send = false;
7165 else
7167 may_send = true;
7168 may_receive = true;
7171 Type* element_type = imp->read_type();
7173 return Type::make_channel_type(may_send, may_receive, element_type);
7176 // Make a new channel type.
7178 Channel_type*
7179 Type::make_channel_type(bool send, bool receive, Type* element_type)
7181 return new Channel_type(send, receive, element_type);
7184 // Class Interface_type.
7186 // Return the list of methods.
7188 const Typed_identifier_list*
7189 Interface_type::methods() const
7191 go_assert(this->methods_are_finalized_ || saw_errors());
7192 return this->all_methods_;
7195 // Return the number of methods.
7197 size_t
7198 Interface_type::method_count() const
7200 go_assert(this->methods_are_finalized_ || saw_errors());
7201 return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
7204 // Traversal.
7207 Interface_type::do_traverse(Traverse* traverse)
7209 Typed_identifier_list* methods = (this->methods_are_finalized_
7210 ? this->all_methods_
7211 : this->parse_methods_);
7212 if (methods == NULL)
7213 return TRAVERSE_CONTINUE;
7214 return methods->traverse(traverse);
7217 // Finalize the methods. This handles interface inheritance.
7219 void
7220 Interface_type::finalize_methods()
7222 if (this->methods_are_finalized_)
7223 return;
7224 this->methods_are_finalized_ = true;
7225 if (this->parse_methods_ == NULL)
7226 return;
7228 this->all_methods_ = new Typed_identifier_list();
7229 this->all_methods_->reserve(this->parse_methods_->size());
7230 Typed_identifier_list inherit;
7231 for (Typed_identifier_list::const_iterator pm =
7232 this->parse_methods_->begin();
7233 pm != this->parse_methods_->end();
7234 ++pm)
7236 const Typed_identifier* p = &*pm;
7237 if (p->name().empty())
7238 inherit.push_back(*p);
7239 else if (this->find_method(p->name()) == NULL)
7240 this->all_methods_->push_back(*p);
7241 else
7242 error_at(p->location(), "duplicate method %qs",
7243 Gogo::message_name(p->name()).c_str());
7246 std::vector<Named_type*> seen;
7247 seen.reserve(inherit.size());
7248 bool issued_recursive_error = false;
7249 while (!inherit.empty())
7251 Type* t = inherit.back().type();
7252 Location tl = inherit.back().location();
7253 inherit.pop_back();
7255 Interface_type* it = t->interface_type();
7256 if (it == NULL)
7258 if (!t->is_error())
7259 error_at(tl, "interface contains embedded non-interface");
7260 continue;
7262 if (it == this)
7264 if (!issued_recursive_error)
7266 error_at(tl, "invalid recursive interface");
7267 issued_recursive_error = true;
7269 continue;
7272 Named_type* nt = t->named_type();
7273 if (nt != NULL && it->parse_methods_ != NULL)
7275 std::vector<Named_type*>::const_iterator q;
7276 for (q = seen.begin(); q != seen.end(); ++q)
7278 if (*q == nt)
7280 error_at(tl, "inherited interface loop");
7281 break;
7284 if (q != seen.end())
7285 continue;
7286 seen.push_back(nt);
7289 const Typed_identifier_list* imethods = it->parse_methods_;
7290 if (imethods == NULL)
7291 continue;
7292 for (Typed_identifier_list::const_iterator q = imethods->begin();
7293 q != imethods->end();
7294 ++q)
7296 if (q->name().empty())
7297 inherit.push_back(*q);
7298 else if (this->find_method(q->name()) == NULL)
7299 this->all_methods_->push_back(Typed_identifier(q->name(),
7300 q->type(), tl));
7301 else
7302 error_at(tl, "inherited method %qs is ambiguous",
7303 Gogo::message_name(q->name()).c_str());
7307 if (!this->all_methods_->empty())
7308 this->all_methods_->sort_by_name();
7309 else
7311 delete this->all_methods_;
7312 this->all_methods_ = NULL;
7316 // Return the method NAME, or NULL.
7318 const Typed_identifier*
7319 Interface_type::find_method(const std::string& name) const
7321 go_assert(this->methods_are_finalized_);
7322 if (this->all_methods_ == NULL)
7323 return NULL;
7324 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
7325 p != this->all_methods_->end();
7326 ++p)
7327 if (p->name() == name)
7328 return &*p;
7329 return NULL;
7332 // Return the method index.
7334 size_t
7335 Interface_type::method_index(const std::string& name) const
7337 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
7338 size_t ret = 0;
7339 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
7340 p != this->all_methods_->end();
7341 ++p, ++ret)
7342 if (p->name() == name)
7343 return ret;
7344 go_unreachable();
7347 // Return whether NAME is an unexported method, for better error
7348 // reporting.
7350 bool
7351 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
7353 go_assert(this->methods_are_finalized_);
7354 if (this->all_methods_ == NULL)
7355 return false;
7356 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
7357 p != this->all_methods_->end();
7358 ++p)
7360 const std::string& method_name(p->name());
7361 if (Gogo::is_hidden_name(method_name)
7362 && name == Gogo::unpack_hidden_name(method_name)
7363 && gogo->pack_hidden_name(name, false) != method_name)
7364 return true;
7366 return false;
7369 // Whether this type is identical with T.
7371 bool
7372 Interface_type::is_identical(const Interface_type* t,
7373 bool errors_are_identical) const
7375 // If methods have not been finalized, then we are asking whether
7376 // func redeclarations are the same. This is an error, so for
7377 // simplicity we say they are never the same.
7378 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
7379 return false;
7381 // We require the same methods with the same types. The methods
7382 // have already been sorted.
7383 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
7384 return this->all_methods_ == t->all_methods_;
7386 if (this->assume_identical(this, t) || t->assume_identical(t, this))
7387 return true;
7389 Assume_identical* hold_ai = this->assume_identical_;
7390 Assume_identical ai;
7391 ai.t1 = this;
7392 ai.t2 = t;
7393 ai.next = hold_ai;
7394 this->assume_identical_ = &ai;
7396 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
7397 Typed_identifier_list::const_iterator p2;
7398 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
7400 if (p1 == this->all_methods_->end())
7401 break;
7402 if (p1->name() != p2->name()
7403 || !Type::are_identical(p1->type(), p2->type(),
7404 errors_are_identical, NULL))
7405 break;
7408 this->assume_identical_ = hold_ai;
7410 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
7413 // Return true if T1 and T2 are assumed to be identical during a type
7414 // comparison.
7416 bool
7417 Interface_type::assume_identical(const Interface_type* t1,
7418 const Interface_type* t2) const
7420 for (Assume_identical* p = this->assume_identical_;
7421 p != NULL;
7422 p = p->next)
7423 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
7424 return true;
7425 return false;
7428 // Whether we can assign the interface type T to this type. The types
7429 // are known to not be identical. An interface assignment is only
7430 // permitted if T is known to implement all methods in THIS.
7431 // Otherwise a type guard is required.
7433 bool
7434 Interface_type::is_compatible_for_assign(const Interface_type* t,
7435 std::string* reason) const
7437 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
7438 if (this->all_methods_ == NULL)
7439 return true;
7440 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
7441 p != this->all_methods_->end();
7442 ++p)
7444 const Typed_identifier* m = t->find_method(p->name());
7445 if (m == NULL)
7447 if (reason != NULL)
7449 char buf[200];
7450 snprintf(buf, sizeof buf,
7451 _("need explicit conversion; missing method %s%s%s"),
7452 open_quote, Gogo::message_name(p->name()).c_str(),
7453 close_quote);
7454 reason->assign(buf);
7456 return false;
7459 std::string subreason;
7460 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
7462 if (reason != NULL)
7464 std::string n = Gogo::message_name(p->name());
7465 size_t len = 100 + n.length() + subreason.length();
7466 char* buf = new char[len];
7467 if (subreason.empty())
7468 snprintf(buf, len, _("incompatible type for method %s%s%s"),
7469 open_quote, n.c_str(), close_quote);
7470 else
7471 snprintf(buf, len,
7472 _("incompatible type for method %s%s%s (%s)"),
7473 open_quote, n.c_str(), close_quote,
7474 subreason.c_str());
7475 reason->assign(buf);
7476 delete[] buf;
7478 return false;
7482 return true;
7485 // Hash code.
7487 unsigned int
7488 Interface_type::do_hash_for_method(Gogo*) const
7490 go_assert(this->methods_are_finalized_);
7491 unsigned int ret = 0;
7492 if (this->all_methods_ != NULL)
7494 for (Typed_identifier_list::const_iterator p =
7495 this->all_methods_->begin();
7496 p != this->all_methods_->end();
7497 ++p)
7499 ret = Type::hash_string(p->name(), ret);
7500 // We don't use the method type in the hash, to avoid
7501 // infinite recursion if an interface method uses a type
7502 // which is an interface which inherits from the interface
7503 // itself.
7504 // type T interface { F() interface {T}}
7505 ret <<= 1;
7508 return ret;
7511 // Return true if T implements the interface. If it does not, and
7512 // REASON is not NULL, set *REASON to a useful error message.
7514 bool
7515 Interface_type::implements_interface(const Type* t, std::string* reason) const
7517 go_assert(this->methods_are_finalized_);
7518 if (this->all_methods_ == NULL)
7519 return true;
7521 bool is_pointer = false;
7522 const Named_type* nt = t->named_type();
7523 const Struct_type* st = t->struct_type();
7524 // If we start with a named type, we don't dereference it to find
7525 // methods.
7526 if (nt == NULL)
7528 const Type* pt = t->points_to();
7529 if (pt != NULL)
7531 // If T is a pointer to a named type, then we need to look at
7532 // the type to which it points.
7533 is_pointer = true;
7534 nt = pt->named_type();
7535 st = pt->struct_type();
7539 // If we have a named type, get the methods from it rather than from
7540 // any struct type.
7541 if (nt != NULL)
7542 st = NULL;
7544 // Only named and struct types have methods.
7545 if (nt == NULL && st == NULL)
7547 if (reason != NULL)
7549 if (t->points_to() != NULL
7550 && t->points_to()->interface_type() != NULL)
7551 reason->assign(_("pointer to interface type has no methods"));
7552 else
7553 reason->assign(_("type has no methods"));
7555 return false;
7558 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
7560 if (reason != NULL)
7562 if (t->points_to() != NULL
7563 && t->points_to()->interface_type() != NULL)
7564 reason->assign(_("pointer to interface type has no methods"));
7565 else
7566 reason->assign(_("type has no methods"));
7568 return false;
7571 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
7572 p != this->all_methods_->end();
7573 ++p)
7575 bool is_ambiguous = false;
7576 Method* m = (nt != NULL
7577 ? nt->method_function(p->name(), &is_ambiguous)
7578 : st->method_function(p->name(), &is_ambiguous));
7579 if (m == NULL)
7581 if (reason != NULL)
7583 std::string n = Gogo::message_name(p->name());
7584 size_t len = n.length() + 100;
7585 char* buf = new char[len];
7586 if (is_ambiguous)
7587 snprintf(buf, len, _("ambiguous method %s%s%s"),
7588 open_quote, n.c_str(), close_quote);
7589 else
7590 snprintf(buf, len, _("missing method %s%s%s"),
7591 open_quote, n.c_str(), close_quote);
7592 reason->assign(buf);
7593 delete[] buf;
7595 return false;
7598 Function_type *p_fn_type = p->type()->function_type();
7599 Function_type* m_fn_type = m->type()->function_type();
7600 go_assert(p_fn_type != NULL && m_fn_type != NULL);
7601 std::string subreason;
7602 if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
7604 if (reason != NULL)
7606 std::string n = Gogo::message_name(p->name());
7607 size_t len = 100 + n.length() + subreason.length();
7608 char* buf = new char[len];
7609 if (subreason.empty())
7610 snprintf(buf, len, _("incompatible type for method %s%s%s"),
7611 open_quote, n.c_str(), close_quote);
7612 else
7613 snprintf(buf, len,
7614 _("incompatible type for method %s%s%s (%s)"),
7615 open_quote, n.c_str(), close_quote,
7616 subreason.c_str());
7617 reason->assign(buf);
7618 delete[] buf;
7620 return false;
7623 if (!is_pointer && !m->is_value_method())
7625 if (reason != NULL)
7627 std::string n = Gogo::message_name(p->name());
7628 size_t len = 100 + n.length();
7629 char* buf = new char[len];
7630 snprintf(buf, len,
7631 _("method %s%s%s requires a pointer receiver"),
7632 open_quote, n.c_str(), close_quote);
7633 reason->assign(buf);
7634 delete[] buf;
7636 return false;
7639 // If the magic //go:nointerface comment was used, the method
7640 // may not be used to implement interfaces.
7641 if (m->nointerface())
7643 if (reason != NULL)
7645 std::string n = Gogo::message_name(p->name());
7646 size_t len = 100 + n.length();
7647 char* buf = new char[len];
7648 snprintf(buf, len,
7649 _("method %s%s%s is marked go:nointerface"),
7650 open_quote, n.c_str(), close_quote);
7651 reason->assign(buf);
7652 delete[] buf;
7654 return false;
7658 return true;
7661 // Return the backend representation of the empty interface type. We
7662 // use the same struct for all empty interfaces.
7664 Btype*
7665 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
7667 static Btype* empty_interface_type;
7668 if (empty_interface_type == NULL)
7670 std::vector<Backend::Btyped_identifier> bfields(2);
7672 Location bloc = Linemap::predeclared_location();
7674 Type* pdt = Type::make_type_descriptor_ptr_type();
7675 bfields[0].name = "__type_descriptor";
7676 bfields[0].btype = pdt->get_backend(gogo);
7677 bfields[0].location = bloc;
7679 Type* vt = Type::make_pointer_type(Type::make_void_type());
7680 bfields[1].name = "__object";
7681 bfields[1].btype = vt->get_backend(gogo);
7682 bfields[1].location = bloc;
7684 empty_interface_type = gogo->backend()->struct_type(bfields);
7686 return empty_interface_type;
7689 // Return a pointer to the backend representation of the method table.
7691 Btype*
7692 Interface_type::get_backend_methods(Gogo* gogo)
7694 if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
7695 return this->bmethods_;
7697 Location loc = this->location();
7699 std::vector<Backend::Btyped_identifier>
7700 mfields(this->all_methods_->size() + 1);
7702 Type* pdt = Type::make_type_descriptor_ptr_type();
7703 mfields[0].name = "__type_descriptor";
7704 mfields[0].btype = pdt->get_backend(gogo);
7705 mfields[0].location = loc;
7707 std::string last_name = "";
7708 size_t i = 1;
7709 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
7710 p != this->all_methods_->end();
7711 ++p, ++i)
7713 // The type of the method in Go only includes the parameters.
7714 // The actual method also has a receiver, which is always a
7715 // pointer. We need to add that pointer type here in order to
7716 // generate the correct type for the backend.
7717 Function_type* ft = p->type()->function_type();
7718 go_assert(ft->receiver() == NULL);
7720 const Typed_identifier_list* params = ft->parameters();
7721 Typed_identifier_list* mparams = new Typed_identifier_list();
7722 if (params != NULL)
7723 mparams->reserve(params->size() + 1);
7724 Type* vt = Type::make_pointer_type(Type::make_void_type());
7725 mparams->push_back(Typed_identifier("", vt, ft->location()));
7726 if (params != NULL)
7728 for (Typed_identifier_list::const_iterator pp = params->begin();
7729 pp != params->end();
7730 ++pp)
7731 mparams->push_back(*pp);
7734 Typed_identifier_list* mresults = (ft->results() == NULL
7735 ? NULL
7736 : ft->results()->copy());
7737 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
7738 ft->location());
7740 mfields[i].name = Gogo::unpack_hidden_name(p->name());
7741 mfields[i].btype = mft->get_backend_fntype(gogo);
7742 mfields[i].location = loc;
7744 // Sanity check: the names should be sorted.
7745 go_assert(p->name() > last_name);
7746 last_name = p->name();
7749 Btype* st = gogo->backend()->struct_type(mfields);
7750 Btype* ret = gogo->backend()->pointer_type(st);
7752 if (this->bmethods_ != NULL && this->bmethods_is_placeholder_)
7753 gogo->backend()->set_placeholder_pointer_type(this->bmethods_, ret);
7754 this->bmethods_ = ret;
7755 this->bmethods_is_placeholder_ = false;
7756 return ret;
7759 // Return a placeholder for the pointer to the backend methods table.
7761 Btype*
7762 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
7764 if (this->bmethods_ == NULL)
7766 Location loc = this->location();
7767 this->bmethods_ = gogo->backend()->placeholder_pointer_type("", loc,
7768 false);
7769 this->bmethods_is_placeholder_ = true;
7771 return this->bmethods_;
7774 // Return the fields of a non-empty interface type. This is not
7775 // declared in types.h so that types.h doesn't have to #include
7776 // backend.h.
7778 static void
7779 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
7780 bool use_placeholder,
7781 std::vector<Backend::Btyped_identifier>* bfields)
7783 Location loc = type->location();
7785 bfields->resize(2);
7787 (*bfields)[0].name = "__methods";
7788 (*bfields)[0].btype = (use_placeholder
7789 ? type->get_backend_methods_placeholder(gogo)
7790 : type->get_backend_methods(gogo));
7791 (*bfields)[0].location = loc;
7793 Type* vt = Type::make_pointer_type(Type::make_void_type());
7794 (*bfields)[1].name = "__object";
7795 (*bfields)[1].btype = vt->get_backend(gogo);
7796 (*bfields)[1].location = Linemap::predeclared_location();
7799 // Return the backend representation for an interface type. An interface is a
7800 // pointer to a struct. The struct has three fields. The first field is a
7801 // pointer to the type descriptor for the dynamic type of the object.
7802 // The second field is a pointer to a table of methods for the
7803 // interface to be used with the object. The third field is the value
7804 // of the object itself.
7806 Btype*
7807 Interface_type::do_get_backend(Gogo* gogo)
7809 if (this->is_empty())
7810 return Interface_type::get_backend_empty_interface_type(gogo);
7811 else
7813 if (this->interface_btype_ != NULL)
7814 return this->interface_btype_;
7815 this->interface_btype_ =
7816 gogo->backend()->placeholder_struct_type("", this->location_);
7817 std::vector<Backend::Btyped_identifier> bfields;
7818 get_backend_interface_fields(gogo, this, false, &bfields);
7819 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
7820 bfields))
7821 this->interface_btype_ = gogo->backend()->error_type();
7822 return this->interface_btype_;
7826 // Finish the backend representation of the methods.
7828 void
7829 Interface_type::finish_backend_methods(Gogo* gogo)
7831 if (!this->is_empty())
7833 const Typed_identifier_list* methods = this->methods();
7834 if (methods != NULL)
7836 for (Typed_identifier_list::const_iterator p = methods->begin();
7837 p != methods->end();
7838 ++p)
7839 p->type()->get_backend(gogo);
7842 // Getting the backend methods now will set the placeholder
7843 // pointer.
7844 this->get_backend_methods(gogo);
7848 // The type of an interface type descriptor.
7850 Type*
7851 Interface_type::make_interface_type_descriptor_type()
7853 static Type* ret;
7854 if (ret == NULL)
7856 Type* tdt = Type::make_type_descriptor_type();
7857 Type* ptdt = Type::make_type_descriptor_ptr_type();
7859 Type* string_type = Type::lookup_string_type();
7860 Type* pointer_string_type = Type::make_pointer_type(string_type);
7862 Struct_type* sm =
7863 Type::make_builtin_struct_type(3,
7864 "name", pointer_string_type,
7865 "pkgPath", pointer_string_type,
7866 "typ", ptdt);
7868 Type* nsm = Type::make_builtin_named_type("imethod", sm);
7870 Type* slice_nsm = Type::make_array_type(nsm, NULL);
7872 Struct_type* s = Type::make_builtin_struct_type(2,
7873 "", tdt,
7874 "methods", slice_nsm);
7876 ret = Type::make_builtin_named_type("InterfaceType", s);
7879 return ret;
7882 // Build a type descriptor for an interface type.
7884 Expression*
7885 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7887 Location bloc = Linemap::predeclared_location();
7889 Type* itdt = Interface_type::make_interface_type_descriptor_type();
7891 const Struct_field_list* ifields = itdt->struct_type()->fields();
7893 Expression_list* ivals = new Expression_list();
7894 ivals->reserve(2);
7896 Struct_field_list::const_iterator pif = ifields->begin();
7897 go_assert(pif->is_field_name("commonType"));
7898 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
7899 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
7900 true));
7902 ++pif;
7903 go_assert(pif->is_field_name("methods"));
7905 Expression_list* methods = new Expression_list();
7906 if (this->all_methods_ != NULL)
7908 Type* elemtype = pif->type()->array_type()->element_type();
7910 methods->reserve(this->all_methods_->size());
7911 for (Typed_identifier_list::const_iterator pm =
7912 this->all_methods_->begin();
7913 pm != this->all_methods_->end();
7914 ++pm)
7916 const Struct_field_list* mfields = elemtype->struct_type()->fields();
7918 Expression_list* mvals = new Expression_list();
7919 mvals->reserve(3);
7921 Struct_field_list::const_iterator pmf = mfields->begin();
7922 go_assert(pmf->is_field_name("name"));
7923 std::string s = Gogo::unpack_hidden_name(pm->name());
7924 Expression* e = Expression::make_string(s, bloc);
7925 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7927 ++pmf;
7928 go_assert(pmf->is_field_name("pkgPath"));
7929 if (!Gogo::is_hidden_name(pm->name()))
7930 mvals->push_back(Expression::make_nil(bloc));
7931 else
7933 s = Gogo::hidden_name_pkgpath(pm->name());
7934 e = Expression::make_string(s, bloc);
7935 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7938 ++pmf;
7939 go_assert(pmf->is_field_name("typ"));
7940 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
7942 ++pmf;
7943 go_assert(pmf == mfields->end());
7945 e = Expression::make_struct_composite_literal(elemtype, mvals,
7946 bloc);
7947 methods->push_back(e);
7951 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
7952 methods, bloc));
7954 ++pif;
7955 go_assert(pif == ifields->end());
7957 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
7960 // Reflection string.
7962 void
7963 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
7965 ret->append("interface {");
7966 const Typed_identifier_list* methods = this->parse_methods_;
7967 if (methods != NULL)
7969 ret->push_back(' ');
7970 for (Typed_identifier_list::const_iterator p = methods->begin();
7971 p != methods->end();
7972 ++p)
7974 if (p != methods->begin())
7975 ret->append("; ");
7976 if (p->name().empty())
7977 this->append_reflection(p->type(), gogo, ret);
7978 else
7980 if (!Gogo::is_hidden_name(p->name()))
7981 ret->append(p->name());
7982 else if (gogo->pkgpath_from_option())
7983 ret->append(p->name().substr(1));
7984 else
7986 // If no -fgo-pkgpath option, backward compatibility
7987 // for how this used to work before -fgo-pkgpath was
7988 // introduced.
7989 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
7990 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
7991 ret->push_back('.');
7992 ret->append(Gogo::unpack_hidden_name(p->name()));
7994 std::string sub = p->type()->reflection(gogo);
7995 go_assert(sub.compare(0, 4, "func") == 0);
7996 sub = sub.substr(4);
7997 ret->append(sub);
8000 ret->push_back(' ');
8002 ret->append("}");
8005 // Generate GC symbol for interface types.
8007 void
8008 Interface_type::do_gc_symbol(Gogo*, Expression_list** vals,
8009 Expression** offset, int)
8011 Location bloc = Linemap::predeclared_location();
8012 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8014 mpz_t opval;
8015 mpz_init_set_ui(opval, this->is_empty() ? GC_EFACE : GC_IFACE);
8016 (*vals)->push_back(Expression::make_integer(&opval, uintptr_type,
8017 bloc));
8018 mpz_clear(opval);
8019 (*vals)->push_back(*offset);
8020 this->advance_gc_offset(offset);
8023 // Mangled name.
8025 void
8026 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8028 go_assert(this->methods_are_finalized_);
8030 ret->push_back('I');
8032 const Typed_identifier_list* methods = this->all_methods_;
8033 if (methods != NULL && !this->seen_)
8035 this->seen_ = true;
8036 for (Typed_identifier_list::const_iterator p = methods->begin();
8037 p != methods->end();
8038 ++p)
8040 if (!p->name().empty())
8042 std::string n;
8043 if (!Gogo::is_hidden_name(p->name()))
8044 n = p->name();
8045 else
8047 n = ".";
8048 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
8049 n.append(Gogo::pkgpath_for_symbol(pkgpath));
8050 n.append(1, '.');
8051 n.append(Gogo::unpack_hidden_name(p->name()));
8053 char buf[20];
8054 snprintf(buf, sizeof buf, "%u_",
8055 static_cast<unsigned int>(n.length()));
8056 ret->append(buf);
8057 ret->append(n);
8059 this->append_mangled_name(p->type(), gogo, ret);
8061 this->seen_ = false;
8064 ret->push_back('e');
8067 // Export.
8069 void
8070 Interface_type::do_export(Export* exp) const
8072 exp->write_c_string("interface { ");
8074 const Typed_identifier_list* methods = this->parse_methods_;
8075 if (methods != NULL)
8077 for (Typed_identifier_list::const_iterator pm = methods->begin();
8078 pm != methods->end();
8079 ++pm)
8081 if (pm->name().empty())
8083 exp->write_c_string("? ");
8084 exp->write_type(pm->type());
8086 else
8088 exp->write_string(pm->name());
8089 exp->write_c_string(" (");
8091 const Function_type* fntype = pm->type()->function_type();
8093 bool first = true;
8094 const Typed_identifier_list* parameters = fntype->parameters();
8095 if (parameters != NULL)
8097 bool is_varargs = fntype->is_varargs();
8098 for (Typed_identifier_list::const_iterator pp =
8099 parameters->begin();
8100 pp != parameters->end();
8101 ++pp)
8103 if (first)
8104 first = false;
8105 else
8106 exp->write_c_string(", ");
8107 exp->write_name(pp->name());
8108 exp->write_c_string(" ");
8109 if (!is_varargs || pp + 1 != parameters->end())
8110 exp->write_type(pp->type());
8111 else
8113 exp->write_c_string("...");
8114 Type *pptype = pp->type();
8115 exp->write_type(pptype->array_type()->element_type());
8120 exp->write_c_string(")");
8122 const Typed_identifier_list* results = fntype->results();
8123 if (results != NULL)
8125 exp->write_c_string(" ");
8126 if (results->size() == 1 && results->begin()->name().empty())
8127 exp->write_type(results->begin()->type());
8128 else
8130 first = true;
8131 exp->write_c_string("(");
8132 for (Typed_identifier_list::const_iterator p =
8133 results->begin();
8134 p != results->end();
8135 ++p)
8137 if (first)
8138 first = false;
8139 else
8140 exp->write_c_string(", ");
8141 exp->write_name(p->name());
8142 exp->write_c_string(" ");
8143 exp->write_type(p->type());
8145 exp->write_c_string(")");
8150 exp->write_c_string("; ");
8154 exp->write_c_string("}");
8157 // Import an interface type.
8159 Interface_type*
8160 Interface_type::do_import(Import* imp)
8162 imp->require_c_string("interface { ");
8164 Typed_identifier_list* methods = new Typed_identifier_list;
8165 while (imp->peek_char() != '}')
8167 std::string name = imp->read_identifier();
8169 if (name == "?")
8171 imp->require_c_string(" ");
8172 Type* t = imp->read_type();
8173 methods->push_back(Typed_identifier("", t, imp->location()));
8174 imp->require_c_string("; ");
8175 continue;
8178 imp->require_c_string(" (");
8180 Typed_identifier_list* parameters;
8181 bool is_varargs = false;
8182 if (imp->peek_char() == ')')
8183 parameters = NULL;
8184 else
8186 parameters = new Typed_identifier_list;
8187 while (true)
8189 std::string name = imp->read_name();
8190 imp->require_c_string(" ");
8192 if (imp->match_c_string("..."))
8194 imp->advance(3);
8195 is_varargs = true;
8198 Type* ptype = imp->read_type();
8199 if (is_varargs)
8200 ptype = Type::make_array_type(ptype, NULL);
8201 parameters->push_back(Typed_identifier(name, ptype,
8202 imp->location()));
8203 if (imp->peek_char() != ',')
8204 break;
8205 go_assert(!is_varargs);
8206 imp->require_c_string(", ");
8209 imp->require_c_string(")");
8211 Typed_identifier_list* results;
8212 if (imp->peek_char() != ' ')
8213 results = NULL;
8214 else
8216 results = new Typed_identifier_list;
8217 imp->advance(1);
8218 if (imp->peek_char() != '(')
8220 Type* rtype = imp->read_type();
8221 results->push_back(Typed_identifier("", rtype, imp->location()));
8223 else
8225 imp->advance(1);
8226 while (true)
8228 std::string name = imp->read_name();
8229 imp->require_c_string(" ");
8230 Type* rtype = imp->read_type();
8231 results->push_back(Typed_identifier(name, rtype,
8232 imp->location()));
8233 if (imp->peek_char() != ',')
8234 break;
8235 imp->require_c_string(", ");
8237 imp->require_c_string(")");
8241 Function_type* fntype = Type::make_function_type(NULL, parameters,
8242 results,
8243 imp->location());
8244 if (is_varargs)
8245 fntype->set_is_varargs();
8246 methods->push_back(Typed_identifier(name, fntype, imp->location()));
8248 imp->require_c_string("; ");
8251 imp->require_c_string("}");
8253 if (methods->empty())
8255 delete methods;
8256 methods = NULL;
8259 return Type::make_interface_type(methods, imp->location());
8262 // Make an interface type.
8264 Interface_type*
8265 Type::make_interface_type(Typed_identifier_list* methods,
8266 Location location)
8268 return new Interface_type(methods, location);
8271 // Make an empty interface type.
8273 Interface_type*
8274 Type::make_empty_interface_type(Location location)
8276 Interface_type* ret = new Interface_type(NULL, location);
8277 ret->finalize_methods();
8278 return ret;
8281 // Class Method.
8283 // Bind a method to an object.
8285 Expression*
8286 Method::bind_method(Expression* expr, Location location) const
8288 if (this->stub_ == NULL)
8290 // When there is no stub object, the binding is determined by
8291 // the child class.
8292 return this->do_bind_method(expr, location);
8294 return Expression::make_bound_method(expr, this, this->stub_, location);
8297 // Return the named object associated with a method. This may only be
8298 // called after methods are finalized.
8300 Named_object*
8301 Method::named_object() const
8303 if (this->stub_ != NULL)
8304 return this->stub_;
8305 return this->do_named_object();
8308 // Class Named_method.
8310 // The type of the method.
8312 Function_type*
8313 Named_method::do_type() const
8315 if (this->named_object_->is_function())
8316 return this->named_object_->func_value()->type();
8317 else if (this->named_object_->is_function_declaration())
8318 return this->named_object_->func_declaration_value()->type();
8319 else
8320 go_unreachable();
8323 // Return the location of the method receiver.
8325 Location
8326 Named_method::do_receiver_location() const
8328 return this->do_type()->receiver()->location();
8331 // Bind a method to an object.
8333 Expression*
8334 Named_method::do_bind_method(Expression* expr, Location location) const
8336 Named_object* no = this->named_object_;
8337 Bound_method_expression* bme = Expression::make_bound_method(expr, this,
8338 no, location);
8339 // If this is not a local method, and it does not use a stub, then
8340 // the real method expects a different type. We need to cast the
8341 // first argument.
8342 if (this->depth() > 0 && !this->needs_stub_method())
8344 Function_type* ftype = this->do_type();
8345 go_assert(ftype->is_method());
8346 Type* frtype = ftype->receiver()->type();
8347 bme->set_first_argument_type(frtype);
8349 return bme;
8352 // Return whether this method should not participate in interfaces.
8354 bool
8355 Named_method::do_nointerface() const
8357 Named_object* no = this->named_object_;
8358 return no->is_function() && no->func_value()->nointerface();
8361 // Class Interface_method.
8363 // Bind a method to an object.
8365 Expression*
8366 Interface_method::do_bind_method(Expression* expr,
8367 Location location) const
8369 return Expression::make_interface_field_reference(expr, this->name_,
8370 location);
8373 // Class Methods.
8375 // Insert a new method. Return true if it was inserted, false
8376 // otherwise.
8378 bool
8379 Methods::insert(const std::string& name, Method* m)
8381 std::pair<Method_map::iterator, bool> ins =
8382 this->methods_.insert(std::make_pair(name, m));
8383 if (ins.second)
8384 return true;
8385 else
8387 Method* old_method = ins.first->second;
8388 if (m->depth() < old_method->depth())
8390 delete old_method;
8391 ins.first->second = m;
8392 return true;
8394 else
8396 if (m->depth() == old_method->depth())
8397 old_method->set_is_ambiguous();
8398 return false;
8403 // Return the number of unambiguous methods.
8405 size_t
8406 Methods::count() const
8408 size_t ret = 0;
8409 for (Method_map::const_iterator p = this->methods_.begin();
8410 p != this->methods_.end();
8411 ++p)
8412 if (!p->second->is_ambiguous())
8413 ++ret;
8414 return ret;
8417 // Class Named_type.
8419 // Return the name of the type.
8421 const std::string&
8422 Named_type::name() const
8424 return this->named_object_->name();
8427 // Return the name of the type to use in an error message.
8429 std::string
8430 Named_type::message_name() const
8432 return this->named_object_->message_name();
8435 // Whether this is an alias. There are currently only two aliases so
8436 // we just recognize them by name.
8438 bool
8439 Named_type::is_alias() const
8441 if (!this->is_builtin())
8442 return false;
8443 const std::string& name(this->name());
8444 return name == "byte" || name == "rune";
8447 // Return the base type for this type. We have to be careful about
8448 // circular type definitions, which are invalid but may be seen here.
8450 Type*
8451 Named_type::named_base()
8453 if (this->seen_)
8454 return this;
8455 this->seen_ = true;
8456 Type* ret = this->type_->base();
8457 this->seen_ = false;
8458 return ret;
8461 const Type*
8462 Named_type::named_base() const
8464 if (this->seen_)
8465 return this;
8466 this->seen_ = true;
8467 const Type* ret = this->type_->base();
8468 this->seen_ = false;
8469 return ret;
8472 // Return whether this is an error type. We have to be careful about
8473 // circular type definitions, which are invalid but may be seen here.
8475 bool
8476 Named_type::is_named_error_type() const
8478 if (this->seen_)
8479 return false;
8480 this->seen_ = true;
8481 bool ret = this->type_->is_error_type();
8482 this->seen_ = false;
8483 return ret;
8486 // Whether this type is comparable. We have to be careful about
8487 // circular type definitions.
8489 bool
8490 Named_type::named_type_is_comparable(std::string* reason) const
8492 if (this->seen_)
8493 return false;
8494 this->seen_ = true;
8495 bool ret = Type::are_compatible_for_comparison(true, this->type_,
8496 this->type_, reason);
8497 this->seen_ = false;
8498 return ret;
8501 // Add a method to this type.
8503 Named_object*
8504 Named_type::add_method(const std::string& name, Function* function)
8506 if (this->local_methods_ == NULL)
8507 this->local_methods_ = new Bindings(NULL);
8508 return this->local_methods_->add_function(name, NULL, function);
8511 // Add a method declaration to this type.
8513 Named_object*
8514 Named_type::add_method_declaration(const std::string& name, Package* package,
8515 Function_type* type,
8516 Location location)
8518 if (this->local_methods_ == NULL)
8519 this->local_methods_ = new Bindings(NULL);
8520 return this->local_methods_->add_function_declaration(name, package, type,
8521 location);
8524 // Add an existing method to this type.
8526 void
8527 Named_type::add_existing_method(Named_object* no)
8529 if (this->local_methods_ == NULL)
8530 this->local_methods_ = new Bindings(NULL);
8531 this->local_methods_->add_named_object(no);
8534 // Look for a local method NAME, and returns its named object, or NULL
8535 // if not there.
8537 Named_object*
8538 Named_type::find_local_method(const std::string& name) const
8540 if (this->local_methods_ == NULL)
8541 return NULL;
8542 return this->local_methods_->lookup(name);
8545 // Return whether NAME is an unexported field or method, for better
8546 // error reporting.
8548 bool
8549 Named_type::is_unexported_local_method(Gogo* gogo,
8550 const std::string& name) const
8552 Bindings* methods = this->local_methods_;
8553 if (methods != NULL)
8555 for (Bindings::const_declarations_iterator p =
8556 methods->begin_declarations();
8557 p != methods->end_declarations();
8558 ++p)
8560 if (Gogo::is_hidden_name(p->first)
8561 && name == Gogo::unpack_hidden_name(p->first)
8562 && gogo->pack_hidden_name(name, false) != p->first)
8563 return true;
8566 return false;
8569 // Build the complete list of methods for this type, which means
8570 // recursively including all methods for anonymous fields. Create all
8571 // stub methods.
8573 void
8574 Named_type::finalize_methods(Gogo* gogo)
8576 if (this->all_methods_ != NULL)
8577 return;
8579 if (this->local_methods_ != NULL
8580 && (this->points_to() != NULL || this->interface_type() != NULL))
8582 const Bindings* lm = this->local_methods_;
8583 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
8584 p != lm->end_declarations();
8585 ++p)
8586 error_at(p->second->location(),
8587 "invalid pointer or interface receiver type");
8588 delete this->local_methods_;
8589 this->local_methods_ = NULL;
8590 return;
8593 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
8596 // Return the method NAME, or NULL if there isn't one or if it is
8597 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
8598 // ambiguous.
8600 Method*
8601 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
8603 return Type::method_function(this->all_methods_, name, is_ambiguous);
8606 // Return a pointer to the interface method table for this type for
8607 // the interface INTERFACE. IS_POINTER is true if this is for a
8608 // pointer to THIS.
8610 Expression*
8611 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
8613 return Type::interface_method_table(this, interface, is_pointer,
8614 &this->interface_method_tables_,
8615 &this->pointer_interface_method_tables_);
8618 // Return whether a named type has any hidden fields.
8620 bool
8621 Named_type::named_type_has_hidden_fields(std::string* reason) const
8623 if (this->seen_)
8624 return false;
8625 this->seen_ = true;
8626 bool ret = this->type_->has_hidden_fields(this, reason);
8627 this->seen_ = false;
8628 return ret;
8631 // Look for a use of a complete type within another type. This is
8632 // used to check that we don't try to use a type within itself.
8634 class Find_type_use : public Traverse
8636 public:
8637 Find_type_use(Named_type* find_type)
8638 : Traverse(traverse_types),
8639 find_type_(find_type), found_(false)
8642 // Whether we found the type.
8643 bool
8644 found() const
8645 { return this->found_; }
8647 protected:
8649 type(Type*);
8651 private:
8652 // The type we are looking for.
8653 Named_type* find_type_;
8654 // Whether we found the type.
8655 bool found_;
8658 // Check for FIND_TYPE in TYPE.
8661 Find_type_use::type(Type* type)
8663 if (type->named_type() != NULL && this->find_type_ == type->named_type())
8665 this->found_ = true;
8666 return TRAVERSE_EXIT;
8669 // It's OK if we see a reference to the type in any type which is
8670 // essentially a pointer: a pointer, a slice, a function, a map, or
8671 // a channel.
8672 if (type->points_to() != NULL
8673 || type->is_slice_type()
8674 || type->function_type() != NULL
8675 || type->map_type() != NULL
8676 || type->channel_type() != NULL)
8677 return TRAVERSE_SKIP_COMPONENTS;
8679 // For an interface, a reference to the type in a method type should
8680 // be ignored, but we have to consider direct inheritance. When
8681 // this is called, there may be cases of direct inheritance
8682 // represented as a method with no name.
8683 if (type->interface_type() != NULL)
8685 const Typed_identifier_list* methods = type->interface_type()->methods();
8686 if (methods != NULL)
8688 for (Typed_identifier_list::const_iterator p = methods->begin();
8689 p != methods->end();
8690 ++p)
8692 if (p->name().empty())
8694 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
8695 return TRAVERSE_EXIT;
8699 return TRAVERSE_SKIP_COMPONENTS;
8702 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
8703 // to convert TYPE to the backend representation before we convert
8704 // FIND_TYPE_.
8705 if (type->named_type() != NULL)
8707 switch (type->base()->classification())
8709 case Type::TYPE_ERROR:
8710 case Type::TYPE_BOOLEAN:
8711 case Type::TYPE_INTEGER:
8712 case Type::TYPE_FLOAT:
8713 case Type::TYPE_COMPLEX:
8714 case Type::TYPE_STRING:
8715 case Type::TYPE_NIL:
8716 break;
8718 case Type::TYPE_ARRAY:
8719 case Type::TYPE_STRUCT:
8720 this->find_type_->add_dependency(type->named_type());
8721 break;
8723 case Type::TYPE_NAMED:
8724 case Type::TYPE_FORWARD:
8725 go_assert(saw_errors());
8726 break;
8728 case Type::TYPE_VOID:
8729 case Type::TYPE_SINK:
8730 case Type::TYPE_FUNCTION:
8731 case Type::TYPE_POINTER:
8732 case Type::TYPE_CALL_MULTIPLE_RESULT:
8733 case Type::TYPE_MAP:
8734 case Type::TYPE_CHANNEL:
8735 case Type::TYPE_INTERFACE:
8736 default:
8737 go_unreachable();
8741 return TRAVERSE_CONTINUE;
8744 // Verify that a named type does not refer to itself.
8746 bool
8747 Named_type::do_verify()
8749 if (this->is_verified_)
8750 return true;
8751 this->is_verified_ = true;
8753 Find_type_use find(this);
8754 Type::traverse(this->type_, &find);
8755 if (find.found())
8757 error_at(this->location_, "invalid recursive type %qs",
8758 this->message_name().c_str());
8759 this->is_error_ = true;
8760 return false;
8763 // Check whether any of the local methods overloads an existing
8764 // struct field or interface method. We don't need to check the
8765 // list of methods against itself: that is handled by the Bindings
8766 // code.
8767 if (this->local_methods_ != NULL)
8769 Struct_type* st = this->type_->struct_type();
8770 if (st != NULL)
8772 for (Bindings::const_declarations_iterator p =
8773 this->local_methods_->begin_declarations();
8774 p != this->local_methods_->end_declarations();
8775 ++p)
8777 const std::string& name(p->first);
8778 if (st != NULL && st->find_local_field(name, NULL) != NULL)
8780 error_at(p->second->location(),
8781 "method %qs redeclares struct field name",
8782 Gogo::message_name(name).c_str());
8788 return true;
8791 // Return whether this type is or contains a pointer.
8793 bool
8794 Named_type::do_has_pointer() const
8796 if (this->seen_)
8797 return false;
8798 this->seen_ = true;
8799 bool ret = this->type_->has_pointer();
8800 this->seen_ = false;
8801 return ret;
8804 // Return whether comparisons for this type can use the identity
8805 // function.
8807 bool
8808 Named_type::do_compare_is_identity(Gogo* gogo)
8810 // We don't use this->seen_ here because compare_is_identity may
8811 // call base() later, and that will mess up if seen_ is set here.
8812 if (this->seen_in_compare_is_identity_)
8813 return false;
8814 this->seen_in_compare_is_identity_ = true;
8815 bool ret = this->type_->compare_is_identity(gogo);
8816 this->seen_in_compare_is_identity_ = false;
8817 return ret;
8820 // Return a hash code. This is used for method lookup. We simply
8821 // hash on the name itself.
8823 unsigned int
8824 Named_type::do_hash_for_method(Gogo* gogo) const
8826 if (this->is_alias())
8827 return this->type_->named_type()->do_hash_for_method(gogo);
8829 const std::string& name(this->named_object()->name());
8830 unsigned int ret = Type::hash_string(name, 0);
8832 // GOGO will be NULL here when called from Type_hash_identical.
8833 // That is OK because that is only used for internal hash tables
8834 // where we are going to be comparing named types for equality. In
8835 // other cases, which are cases where the runtime is going to
8836 // compare hash codes to see if the types are the same, we need to
8837 // include the pkgpath in the hash.
8838 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
8840 const Package* package = this->named_object()->package();
8841 if (package == NULL)
8842 ret = Type::hash_string(gogo->pkgpath(), ret);
8843 else
8844 ret = Type::hash_string(package->pkgpath(), ret);
8847 return ret;
8850 // Convert a named type to the backend representation. In order to
8851 // get dependencies right, we fill in a dummy structure for this type,
8852 // then convert all the dependencies, then complete this type. When
8853 // this function is complete, the size of the type is known.
8855 void
8856 Named_type::convert(Gogo* gogo)
8858 if (this->is_error_ || this->is_converted_)
8859 return;
8861 this->create_placeholder(gogo);
8863 // If we are called to turn unsafe.Sizeof into a constant, we may
8864 // not have verified the type yet. We have to make sure it is
8865 // verified, since that sets the list of dependencies.
8866 this->verify();
8868 // Convert all the dependencies. If they refer indirectly back to
8869 // this type, they will pick up the intermediate representation we just
8870 // created.
8871 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
8872 p != this->dependencies_.end();
8873 ++p)
8874 (*p)->convert(gogo);
8876 // Complete this type.
8877 Btype* bt = this->named_btype_;
8878 Type* base = this->type_->base();
8879 switch (base->classification())
8881 case TYPE_VOID:
8882 case TYPE_BOOLEAN:
8883 case TYPE_INTEGER:
8884 case TYPE_FLOAT:
8885 case TYPE_COMPLEX:
8886 case TYPE_STRING:
8887 case TYPE_NIL:
8888 break;
8890 case TYPE_MAP:
8891 case TYPE_CHANNEL:
8892 break;
8894 case TYPE_FUNCTION:
8895 case TYPE_POINTER:
8896 // The size of these types is already correct. We don't worry
8897 // about filling them in until later, when we also track
8898 // circular references.
8899 break;
8901 case TYPE_STRUCT:
8903 std::vector<Backend::Btyped_identifier> bfields;
8904 get_backend_struct_fields(gogo, base->struct_type()->fields(),
8905 true, &bfields);
8906 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8907 bt = gogo->backend()->error_type();
8909 break;
8911 case TYPE_ARRAY:
8912 // Slice types were completed in create_placeholder.
8913 if (!base->is_slice_type())
8915 Btype* bet = base->array_type()->get_backend_element(gogo, true);
8916 Bexpression* blen = base->array_type()->get_backend_length(gogo);
8917 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
8918 bt = gogo->backend()->error_type();
8920 break;
8922 case TYPE_INTERFACE:
8923 // Interface types were completed in create_placeholder.
8924 break;
8926 case TYPE_ERROR:
8927 return;
8929 default:
8930 case TYPE_SINK:
8931 case TYPE_CALL_MULTIPLE_RESULT:
8932 case TYPE_NAMED:
8933 case TYPE_FORWARD:
8934 go_unreachable();
8937 this->named_btype_ = bt;
8938 this->is_converted_ = true;
8939 this->is_placeholder_ = false;
8942 // Create the placeholder for a named type. This is the first step in
8943 // converting to the backend representation.
8945 void
8946 Named_type::create_placeholder(Gogo* gogo)
8948 if (this->is_error_)
8949 this->named_btype_ = gogo->backend()->error_type();
8951 if (this->named_btype_ != NULL)
8952 return;
8954 // Create the structure for this type. Note that because we call
8955 // base() here, we don't attempt to represent a named type defined
8956 // as another named type. Instead both named types will point to
8957 // different base representations.
8958 Type* base = this->type_->base();
8959 Btype* bt;
8960 bool set_name = true;
8961 switch (base->classification())
8963 case TYPE_ERROR:
8964 this->is_error_ = true;
8965 this->named_btype_ = gogo->backend()->error_type();
8966 return;
8968 case TYPE_VOID:
8969 case TYPE_BOOLEAN:
8970 case TYPE_INTEGER:
8971 case TYPE_FLOAT:
8972 case TYPE_COMPLEX:
8973 case TYPE_STRING:
8974 case TYPE_NIL:
8975 // These are simple basic types, we can just create them
8976 // directly.
8977 bt = Type::get_named_base_btype(gogo, base);
8978 break;
8980 case TYPE_MAP:
8981 case TYPE_CHANNEL:
8982 // All maps and channels have the same backend representation.
8983 bt = Type::get_named_base_btype(gogo, base);
8984 break;
8986 case TYPE_FUNCTION:
8987 case TYPE_POINTER:
8989 bool for_function = base->classification() == TYPE_FUNCTION;
8990 bt = gogo->backend()->placeholder_pointer_type(this->name(),
8991 this->location_,
8992 for_function);
8993 set_name = false;
8995 break;
8997 case TYPE_STRUCT:
8998 bt = gogo->backend()->placeholder_struct_type(this->name(),
8999 this->location_);
9000 this->is_placeholder_ = true;
9001 set_name = false;
9002 break;
9004 case TYPE_ARRAY:
9005 if (base->is_slice_type())
9006 bt = gogo->backend()->placeholder_struct_type(this->name(),
9007 this->location_);
9008 else
9010 bt = gogo->backend()->placeholder_array_type(this->name(),
9011 this->location_);
9012 this->is_placeholder_ = true;
9014 set_name = false;
9015 break;
9017 case TYPE_INTERFACE:
9018 if (base->interface_type()->is_empty())
9019 bt = Interface_type::get_backend_empty_interface_type(gogo);
9020 else
9022 bt = gogo->backend()->placeholder_struct_type(this->name(),
9023 this->location_);
9024 set_name = false;
9026 break;
9028 default:
9029 case TYPE_SINK:
9030 case TYPE_CALL_MULTIPLE_RESULT:
9031 case TYPE_NAMED:
9032 case TYPE_FORWARD:
9033 go_unreachable();
9036 if (set_name)
9037 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
9039 this->named_btype_ = bt;
9041 if (base->is_slice_type())
9043 // We do not record slices as dependencies of other types,
9044 // because we can fill them in completely here with the final
9045 // size.
9046 std::vector<Backend::Btyped_identifier> bfields;
9047 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
9048 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
9049 this->named_btype_ = gogo->backend()->error_type();
9051 else if (base->interface_type() != NULL
9052 && !base->interface_type()->is_empty())
9054 // We do not record interfaces as dependencies of other types,
9055 // because we can fill them in completely here with the final
9056 // size.
9057 std::vector<Backend::Btyped_identifier> bfields;
9058 get_backend_interface_fields(gogo, base->interface_type(), true,
9059 &bfields);
9060 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
9061 this->named_btype_ = gogo->backend()->error_type();
9065 // Get the backend representation for a named type.
9067 Btype*
9068 Named_type::do_get_backend(Gogo* gogo)
9070 if (this->is_error_)
9071 return gogo->backend()->error_type();
9073 Btype* bt = this->named_btype_;
9075 if (!gogo->named_types_are_converted())
9077 // We have not completed converting named types. NAMED_BTYPE_
9078 // is a placeholder and we shouldn't do anything further.
9079 if (bt != NULL)
9080 return bt;
9082 // We don't build dependencies for types whose sizes do not
9083 // change or are not relevant, so we may see them here while
9084 // converting types.
9085 this->create_placeholder(gogo);
9086 bt = this->named_btype_;
9087 go_assert(bt != NULL);
9088 return bt;
9091 // We are not converting types. This should only be called if the
9092 // type has already been converted.
9093 if (!this->is_converted_)
9095 go_assert(saw_errors());
9096 return gogo->backend()->error_type();
9099 go_assert(bt != NULL);
9101 // Complete the backend representation.
9102 Type* base = this->type_->base();
9103 Btype* bt1;
9104 switch (base->classification())
9106 case TYPE_ERROR:
9107 return gogo->backend()->error_type();
9109 case TYPE_VOID:
9110 case TYPE_BOOLEAN:
9111 case TYPE_INTEGER:
9112 case TYPE_FLOAT:
9113 case TYPE_COMPLEX:
9114 case TYPE_STRING:
9115 case TYPE_NIL:
9116 case TYPE_MAP:
9117 case TYPE_CHANNEL:
9118 return bt;
9120 case TYPE_STRUCT:
9121 if (!this->seen_in_get_backend_)
9123 this->seen_in_get_backend_ = true;
9124 base->struct_type()->finish_backend_fields(gogo);
9125 this->seen_in_get_backend_ = false;
9127 return bt;
9129 case TYPE_ARRAY:
9130 if (!this->seen_in_get_backend_)
9132 this->seen_in_get_backend_ = true;
9133 base->array_type()->finish_backend_element(gogo);
9134 this->seen_in_get_backend_ = false;
9136 return bt;
9138 case TYPE_INTERFACE:
9139 if (!this->seen_in_get_backend_)
9141 this->seen_in_get_backend_ = true;
9142 base->interface_type()->finish_backend_methods(gogo);
9143 this->seen_in_get_backend_ = false;
9145 return bt;
9147 case TYPE_FUNCTION:
9148 // Don't build a circular data structure. GENERIC can't handle
9149 // it.
9150 if (this->seen_in_get_backend_)
9152 this->is_circular_ = true;
9153 return gogo->backend()->circular_pointer_type(bt, false);
9155 this->seen_in_get_backend_ = true;
9156 bt1 = Type::get_named_base_btype(gogo, base);
9157 this->seen_in_get_backend_ = false;
9158 if (this->is_circular_)
9159 bt1 = gogo->backend()->circular_pointer_type(bt, false);
9160 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
9161 bt = gogo->backend()->error_type();
9162 return bt;
9164 case TYPE_POINTER:
9165 // Don't build a circular data structure. GENERIC can't handle
9166 // it.
9167 if (this->seen_in_get_backend_)
9169 this->is_circular_ = true;
9170 return gogo->backend()->circular_pointer_type(bt, false);
9172 this->seen_in_get_backend_ = true;
9173 bt1 = Type::get_named_base_btype(gogo, base);
9174 this->seen_in_get_backend_ = false;
9175 if (this->is_circular_)
9176 bt1 = gogo->backend()->circular_pointer_type(bt, false);
9177 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
9178 bt = gogo->backend()->error_type();
9179 return bt;
9181 default:
9182 case TYPE_SINK:
9183 case TYPE_CALL_MULTIPLE_RESULT:
9184 case TYPE_NAMED:
9185 case TYPE_FORWARD:
9186 go_unreachable();
9189 go_unreachable();
9192 // Build a type descriptor for a named type.
9194 Expression*
9195 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9197 if (name == NULL && this->is_alias())
9198 return this->type_->type_descriptor(gogo, this->type_);
9200 // If NAME is not NULL, then we don't really want the type
9201 // descriptor for this type; we want the descriptor for the
9202 // underlying type, giving it the name NAME.
9203 return this->named_type_descriptor(gogo, this->type_,
9204 name == NULL ? this : name);
9207 // Add to the reflection string. This is used mostly for the name of
9208 // the type used in a type descriptor, not for actual reflection
9209 // strings.
9211 void
9212 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
9214 if (this->is_alias())
9216 this->append_reflection(this->type_, gogo, ret);
9217 return;
9219 if (!this->is_builtin())
9221 // We handle -fgo-prefix and -fgo-pkgpath differently here for
9222 // compatibility with how the compiler worked before
9223 // -fgo-pkgpath was introduced. When -fgo-pkgpath is specified,
9224 // we use it to make a unique reflection string, so that the
9225 // type canonicalization in the reflect package will work. In
9226 // order to be compatible with the gc compiler, we put tabs into
9227 // the package path, so that the reflect methods can discard it.
9228 const Package* package = this->named_object_->package();
9229 if (gogo->pkgpath_from_option())
9231 ret->push_back('\t');
9232 ret->append(package != NULL
9233 ? package->pkgpath_symbol()
9234 : gogo->pkgpath_symbol());
9235 ret->push_back('\t');
9237 ret->append(package != NULL
9238 ? package->package_name()
9239 : gogo->package_name());
9240 ret->push_back('.');
9242 if (this->in_function_ != NULL)
9244 ret->push_back('\t');
9245 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
9246 ret->push_back('$');
9247 if (this->in_function_index_ > 0)
9249 char buf[30];
9250 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
9251 ret->append(buf);
9252 ret->push_back('$');
9254 ret->push_back('\t');
9256 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
9259 // Generate GC symbol for named types.
9261 void
9262 Named_type::do_gc_symbol(Gogo* gogo, Expression_list** vals,
9263 Expression** offset, int stack)
9265 if (!this->seen_)
9267 this->seen_ = true;
9268 Type::gc_symbol(gogo, this->real_type(), vals, offset, stack);
9269 this->seen_ = false;
9273 // Get the mangled name.
9275 void
9276 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
9278 if (this->is_alias())
9280 this->append_mangled_name(this->type_, gogo, ret);
9281 return;
9283 Named_object* no = this->named_object_;
9284 std::string name;
9285 if (this->is_builtin())
9286 go_assert(this->in_function_ == NULL);
9287 else
9289 const std::string& pkgpath(no->package() == NULL
9290 ? gogo->pkgpath_symbol()
9291 : no->package()->pkgpath_symbol());
9292 name = pkgpath;
9293 name.append(1, '.');
9294 if (this->in_function_ != NULL)
9296 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
9297 name.append(1, '$');
9298 if (this->in_function_index_ > 0)
9300 char buf[30];
9301 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
9302 name.append(buf);
9303 name.append(1, '$');
9307 name.append(Gogo::unpack_hidden_name(no->name()));
9308 char buf[20];
9309 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
9310 ret->append(buf);
9311 ret->append(name);
9314 // Export the type. This is called to export a global type.
9316 void
9317 Named_type::export_named_type(Export* exp, const std::string&) const
9319 // We don't need to write the name of the type here, because it will
9320 // be written by Export::write_type anyhow.
9321 exp->write_c_string("type ");
9322 exp->write_type(this);
9323 exp->write_c_string(";\n");
9326 // Import a named type.
9328 void
9329 Named_type::import_named_type(Import* imp, Named_type** ptype)
9331 imp->require_c_string("type ");
9332 Type *type = imp->read_type();
9333 *ptype = type->named_type();
9334 go_assert(*ptype != NULL);
9335 imp->require_c_string(";\n");
9338 // Export the type when it is referenced by another type. In this
9339 // case Export::export_type will already have issued the name.
9341 void
9342 Named_type::do_export(Export* exp) const
9344 exp->write_type(this->type_);
9346 // To save space, we only export the methods directly attached to
9347 // this type.
9348 Bindings* methods = this->local_methods_;
9349 if (methods == NULL)
9350 return;
9352 exp->write_c_string("\n");
9353 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
9354 p != methods->end_definitions();
9355 ++p)
9357 exp->write_c_string(" ");
9358 (*p)->export_named_object(exp);
9361 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
9362 p != methods->end_declarations();
9363 ++p)
9365 if (p->second->is_function_declaration())
9367 exp->write_c_string(" ");
9368 p->second->export_named_object(exp);
9373 // Make a named type.
9375 Named_type*
9376 Type::make_named_type(Named_object* named_object, Type* type,
9377 Location location)
9379 return new Named_type(named_object, type, location);
9382 // Finalize the methods for TYPE. It will be a named type or a struct
9383 // type. This sets *ALL_METHODS to the list of methods, and builds
9384 // all required stubs.
9386 void
9387 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
9388 Methods** all_methods)
9390 *all_methods = NULL;
9391 std::vector<const Named_type*> seen;
9392 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, all_methods);
9393 Type::build_stub_methods(gogo, type, *all_methods, location);
9396 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
9397 // build up the struct field indexes as we go. DEPTH is the depth of
9398 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
9399 // adding these methods for an anonymous field with pointer type.
9400 // NEEDS_STUB_METHOD is true if we need to use a stub method which
9401 // calls the real method. TYPES_SEEN is used to avoid infinite
9402 // recursion.
9404 void
9405 Type::add_methods_for_type(const Type* type,
9406 const Method::Field_indexes* field_indexes,
9407 unsigned int depth,
9408 bool is_embedded_pointer,
9409 bool needs_stub_method,
9410 std::vector<const Named_type*>* seen,
9411 Methods** methods)
9413 // Pointer types may not have methods.
9414 if (type->points_to() != NULL)
9415 return;
9417 const Named_type* nt = type->named_type();
9418 if (nt != NULL)
9420 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9421 p != seen->end();
9422 ++p)
9424 if (*p == nt)
9425 return;
9428 seen->push_back(nt);
9430 Type::add_local_methods_for_type(nt, field_indexes, depth,
9431 is_embedded_pointer, needs_stub_method,
9432 methods);
9435 Type::add_embedded_methods_for_type(type, field_indexes, depth,
9436 is_embedded_pointer, needs_stub_method,
9437 seen, methods);
9439 // If we are called with depth > 0, then we are looking at an
9440 // anonymous field of a struct. If such a field has interface type,
9441 // then we need to add the interface methods. We don't want to add
9442 // them when depth == 0, because we will already handle them
9443 // following the usual rules for an interface type.
9444 if (depth > 0)
9445 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
9447 if (nt != NULL)
9448 seen->pop_back();
9451 // Add the local methods for the named type NT to *METHODS. The
9452 // parameters are as for add_methods_to_type.
9454 void
9455 Type::add_local_methods_for_type(const Named_type* nt,
9456 const Method::Field_indexes* field_indexes,
9457 unsigned int depth,
9458 bool is_embedded_pointer,
9459 bool needs_stub_method,
9460 Methods** methods)
9462 const Bindings* local_methods = nt->local_methods();
9463 if (local_methods == NULL)
9464 return;
9466 if (*methods == NULL)
9467 *methods = new Methods();
9469 for (Bindings::const_declarations_iterator p =
9470 local_methods->begin_declarations();
9471 p != local_methods->end_declarations();
9472 ++p)
9474 Named_object* no = p->second;
9475 bool is_value_method = (is_embedded_pointer
9476 || !Type::method_expects_pointer(no));
9477 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
9478 (needs_stub_method || depth > 0));
9479 if (!(*methods)->insert(no->name(), m))
9480 delete m;
9484 // Add the embedded methods for TYPE to *METHODS. These are the
9485 // methods attached to anonymous fields. The parameters are as for
9486 // add_methods_to_type.
9488 void
9489 Type::add_embedded_methods_for_type(const Type* type,
9490 const Method::Field_indexes* field_indexes,
9491 unsigned int depth,
9492 bool is_embedded_pointer,
9493 bool needs_stub_method,
9494 std::vector<const Named_type*>* seen,
9495 Methods** methods)
9497 // Look for anonymous fields in TYPE. TYPE has fields if it is a
9498 // struct.
9499 const Struct_type* st = type->struct_type();
9500 if (st == NULL)
9501 return;
9503 const Struct_field_list* fields = st->fields();
9504 if (fields == NULL)
9505 return;
9507 unsigned int i = 0;
9508 for (Struct_field_list::const_iterator pf = fields->begin();
9509 pf != fields->end();
9510 ++pf, ++i)
9512 if (!pf->is_anonymous())
9513 continue;
9515 Type* ftype = pf->type();
9516 bool is_pointer = false;
9517 if (ftype->points_to() != NULL)
9519 ftype = ftype->points_to();
9520 is_pointer = true;
9522 Named_type* fnt = ftype->named_type();
9523 if (fnt == NULL)
9525 // This is an error, but it will be diagnosed elsewhere.
9526 continue;
9529 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
9530 sub_field_indexes->next = field_indexes;
9531 sub_field_indexes->field_index = i;
9533 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
9534 (is_embedded_pointer || is_pointer),
9535 (needs_stub_method
9536 || is_pointer
9537 || i > 0),
9538 seen,
9539 methods);
9543 // If TYPE is an interface type, then add its method to *METHODS.
9544 // This is for interface methods attached to an anonymous field. The
9545 // parameters are as for add_methods_for_type.
9547 void
9548 Type::add_interface_methods_for_type(const Type* type,
9549 const Method::Field_indexes* field_indexes,
9550 unsigned int depth,
9551 Methods** methods)
9553 const Interface_type* it = type->interface_type();
9554 if (it == NULL)
9555 return;
9557 const Typed_identifier_list* imethods = it->methods();
9558 if (imethods == NULL)
9559 return;
9561 if (*methods == NULL)
9562 *methods = new Methods();
9564 for (Typed_identifier_list::const_iterator pm = imethods->begin();
9565 pm != imethods->end();
9566 ++pm)
9568 Function_type* fntype = pm->type()->function_type();
9569 if (fntype == NULL)
9571 // This is an error, but it should be reported elsewhere
9572 // when we look at the methods for IT.
9573 continue;
9575 go_assert(!fntype->is_method());
9576 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
9577 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
9578 field_indexes, depth);
9579 if (!(*methods)->insert(pm->name(), m))
9580 delete m;
9584 // Build stub methods for TYPE as needed. METHODS is the set of
9585 // methods for the type. A stub method may be needed when a type
9586 // inherits a method from an anonymous field. When we need the
9587 // address of the method, as in a type descriptor, we need to build a
9588 // little stub which does the required field dereferences and jumps to
9589 // the real method. LOCATION is the location of the type definition.
9591 void
9592 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
9593 Location location)
9595 if (methods == NULL)
9596 return;
9597 for (Methods::const_iterator p = methods->begin();
9598 p != methods->end();
9599 ++p)
9601 Method* m = p->second;
9602 if (m->is_ambiguous() || !m->needs_stub_method())
9603 continue;
9605 const std::string& name(p->first);
9607 // Build a stub method.
9609 const Function_type* fntype = m->type();
9611 static unsigned int counter;
9612 char buf[100];
9613 snprintf(buf, sizeof buf, "$this%u", counter);
9614 ++counter;
9616 Type* receiver_type = const_cast<Type*>(type);
9617 if (!m->is_value_method())
9618 receiver_type = Type::make_pointer_type(receiver_type);
9619 Location receiver_location = m->receiver_location();
9620 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
9621 receiver_location);
9623 const Typed_identifier_list* fnparams = fntype->parameters();
9624 Typed_identifier_list* stub_params;
9625 if (fnparams == NULL || fnparams->empty())
9626 stub_params = NULL;
9627 else
9629 // We give each stub parameter a unique name.
9630 stub_params = new Typed_identifier_list();
9631 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
9632 pp != fnparams->end();
9633 ++pp)
9635 char pbuf[100];
9636 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
9637 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
9638 pp->location()));
9639 ++counter;
9643 const Typed_identifier_list* fnresults = fntype->results();
9644 Typed_identifier_list* stub_results;
9645 if (fnresults == NULL || fnresults->empty())
9646 stub_results = NULL;
9647 else
9649 // We create the result parameters without any names, since
9650 // we won't refer to them.
9651 stub_results = new Typed_identifier_list();
9652 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
9653 pr != fnresults->end();
9654 ++pr)
9655 stub_results->push_back(Typed_identifier("", pr->type(),
9656 pr->location()));
9659 Function_type* stub_type = Type::make_function_type(receiver,
9660 stub_params,
9661 stub_results,
9662 fntype->location());
9663 if (fntype->is_varargs())
9664 stub_type->set_is_varargs();
9666 // We only create the function in the package which creates the
9667 // type.
9668 const Package* package;
9669 if (type->named_type() == NULL)
9670 package = NULL;
9671 else
9672 package = type->named_type()->named_object()->package();
9673 Named_object* stub;
9674 if (package != NULL)
9675 stub = Named_object::make_function_declaration(name, package,
9676 stub_type, location);
9677 else
9679 stub = gogo->start_function(name, stub_type, false,
9680 fntype->location());
9681 Type::build_one_stub_method(gogo, m, buf, stub_params,
9682 fntype->is_varargs(), location);
9683 gogo->finish_function(fntype->location());
9685 if (type->named_type() == NULL && stub->is_function())
9686 stub->func_value()->set_is_unnamed_type_stub_method();
9687 if (m->nointerface() && stub->is_function())
9688 stub->func_value()->set_nointerface();
9691 m->set_stub_object(stub);
9695 // Build a stub method which adjusts the receiver as required to call
9696 // METHOD. RECEIVER_NAME is the name we used for the receiver.
9697 // PARAMS is the list of function parameters.
9699 void
9700 Type::build_one_stub_method(Gogo* gogo, Method* method,
9701 const char* receiver_name,
9702 const Typed_identifier_list* params,
9703 bool is_varargs,
9704 Location location)
9706 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
9707 go_assert(receiver_object != NULL);
9709 Expression* expr = Expression::make_var_reference(receiver_object, location);
9710 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
9711 if (expr->type()->points_to() == NULL)
9712 expr = Expression::make_unary(OPERATOR_AND, expr, location);
9714 Expression_list* arguments;
9715 if (params == NULL || params->empty())
9716 arguments = NULL;
9717 else
9719 arguments = new Expression_list();
9720 for (Typed_identifier_list::const_iterator p = params->begin();
9721 p != params->end();
9722 ++p)
9724 Named_object* param = gogo->lookup(p->name(), NULL);
9725 go_assert(param != NULL);
9726 Expression* param_ref = Expression::make_var_reference(param,
9727 location);
9728 arguments->push_back(param_ref);
9732 Expression* func = method->bind_method(expr, location);
9733 go_assert(func != NULL);
9734 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
9735 location);
9736 call->set_hidden_fields_are_ok();
9738 Statement* s = Statement::make_return_from_call(call, location);
9739 Return_statement* retstat = s->return_statement();
9740 if (retstat != NULL)
9742 // We can return values with hidden fields from a stub. This is
9743 // necessary if the method is itself hidden.
9744 retstat->set_hidden_fields_are_ok();
9746 gogo->add_statement(s);
9749 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
9750 // in reverse order.
9752 Expression*
9753 Type::apply_field_indexes(Expression* expr,
9754 const Method::Field_indexes* field_indexes,
9755 Location location)
9757 if (field_indexes == NULL)
9758 return expr;
9759 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
9760 Struct_type* stype = expr->type()->deref()->struct_type();
9761 go_assert(stype != NULL
9762 && field_indexes->field_index < stype->field_count());
9763 if (expr->type()->struct_type() == NULL)
9765 go_assert(expr->type()->points_to() != NULL);
9766 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
9767 go_assert(expr->type()->struct_type() == stype);
9769 return Expression::make_field_reference(expr, field_indexes->field_index,
9770 location);
9773 // Return whether NO is a method for which the receiver is a pointer.
9775 bool
9776 Type::method_expects_pointer(const Named_object* no)
9778 const Function_type *fntype;
9779 if (no->is_function())
9780 fntype = no->func_value()->type();
9781 else if (no->is_function_declaration())
9782 fntype = no->func_declaration_value()->type();
9783 else
9784 go_unreachable();
9785 return fntype->receiver()->type()->points_to() != NULL;
9788 // Given a set of methods for a type, METHODS, return the method NAME,
9789 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
9790 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
9791 // but is ambiguous (and return NULL).
9793 Method*
9794 Type::method_function(const Methods* methods, const std::string& name,
9795 bool* is_ambiguous)
9797 if (is_ambiguous != NULL)
9798 *is_ambiguous = false;
9799 if (methods == NULL)
9800 return NULL;
9801 Methods::const_iterator p = methods->find(name);
9802 if (p == methods->end())
9803 return NULL;
9804 Method* m = p->second;
9805 if (m->is_ambiguous())
9807 if (is_ambiguous != NULL)
9808 *is_ambiguous = true;
9809 return NULL;
9811 return m;
9814 // Return a pointer to the interface method table for TYPE for the
9815 // interface INTERFACE.
9817 Expression*
9818 Type::interface_method_table(Type* type,
9819 Interface_type *interface,
9820 bool is_pointer,
9821 Interface_method_tables** method_tables,
9822 Interface_method_tables** pointer_tables)
9824 go_assert(!interface->is_empty());
9826 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
9828 if (*pimt == NULL)
9829 *pimt = new Interface_method_tables(5);
9831 std::pair<Interface_type*, Expression*> val(interface, NULL);
9832 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
9834 Location loc = Linemap::predeclared_location();
9835 if (ins.second)
9837 // This is a new entry in the hash table.
9838 go_assert(ins.first->second == NULL);
9839 ins.first->second =
9840 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
9842 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
9845 // Look for field or method NAME for TYPE. Return an Expression for
9846 // the field or method bound to EXPR. If there is no such field or
9847 // method, give an appropriate error and return an error expression.
9849 Expression*
9850 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
9851 const std::string& name,
9852 Location location)
9854 if (type->deref()->is_error_type())
9855 return Expression::make_error(location);
9857 const Named_type* nt = type->deref()->named_type();
9858 const Struct_type* st = type->deref()->struct_type();
9859 const Interface_type* it = type->interface_type();
9861 // If this is a pointer to a pointer, then it is possible that the
9862 // pointed-to type has methods.
9863 bool dereferenced = false;
9864 if (nt == NULL
9865 && st == NULL
9866 && it == NULL
9867 && type->points_to() != NULL
9868 && type->points_to()->points_to() != NULL)
9870 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
9871 type = type->points_to();
9872 if (type->deref()->is_error_type())
9873 return Expression::make_error(location);
9874 nt = type->points_to()->named_type();
9875 st = type->points_to()->struct_type();
9876 dereferenced = true;
9879 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
9880 || expr->is_addressable());
9881 std::vector<const Named_type*> seen;
9882 bool is_method = false;
9883 bool found_pointer_method = false;
9884 std::string ambig1;
9885 std::string ambig2;
9886 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
9887 &seen, NULL, &is_method,
9888 &found_pointer_method, &ambig1, &ambig2))
9890 Expression* ret;
9891 if (!is_method)
9893 go_assert(st != NULL);
9894 if (type->struct_type() == NULL)
9896 go_assert(type->points_to() != NULL);
9897 expr = Expression::make_unary(OPERATOR_MULT, expr,
9898 location);
9899 go_assert(expr->type()->struct_type() == st);
9901 ret = st->field_reference(expr, name, location);
9903 else if (it != NULL && it->find_method(name) != NULL)
9904 ret = Expression::make_interface_field_reference(expr, name,
9905 location);
9906 else
9908 Method* m;
9909 if (nt != NULL)
9910 m = nt->method_function(name, NULL);
9911 else if (st != NULL)
9912 m = st->method_function(name, NULL);
9913 else
9914 go_unreachable();
9915 go_assert(m != NULL);
9916 if (dereferenced)
9918 error_at(location,
9919 "calling method %qs requires explicit dereference",
9920 Gogo::message_name(name).c_str());
9921 return Expression::make_error(location);
9923 if (!m->is_value_method() && expr->type()->points_to() == NULL)
9924 expr = Expression::make_unary(OPERATOR_AND, expr, location);
9925 ret = m->bind_method(expr, location);
9927 go_assert(ret != NULL);
9928 return ret;
9930 else
9932 if (Gogo::is_erroneous_name(name))
9934 // An error was already reported.
9936 else if (!ambig1.empty())
9937 error_at(location, "%qs is ambiguous via %qs and %qs",
9938 Gogo::message_name(name).c_str(), ambig1.c_str(),
9939 ambig2.c_str());
9940 else if (found_pointer_method)
9941 error_at(location, "method requires a pointer receiver");
9942 else if (nt == NULL && st == NULL && it == NULL)
9943 error_at(location,
9944 ("reference to field %qs in object which "
9945 "has no fields or methods"),
9946 Gogo::message_name(name).c_str());
9947 else
9949 bool is_unexported;
9950 // The test for 'a' and 'z' is to handle builtin names,
9951 // which are not hidden.
9952 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
9953 is_unexported = false;
9954 else
9956 std::string unpacked = Gogo::unpack_hidden_name(name);
9957 seen.clear();
9958 is_unexported = Type::is_unexported_field_or_method(gogo, type,
9959 unpacked,
9960 &seen);
9962 if (is_unexported)
9963 error_at(location, "reference to unexported field or method %qs",
9964 Gogo::message_name(name).c_str());
9965 else
9966 error_at(location, "reference to undefined field or method %qs",
9967 Gogo::message_name(name).c_str());
9969 return Expression::make_error(location);
9973 // Look in TYPE for a field or method named NAME, return true if one
9974 // is found. This looks through embedded anonymous fields and handles
9975 // ambiguity. If a method is found, sets *IS_METHOD to true;
9976 // otherwise, if a field is found, set it to false. If
9977 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
9978 // whose address can not be taken. SEEN is used to avoid infinite
9979 // recursion on invalid types.
9981 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
9982 // method we couldn't use because it requires a pointer. LEVEL is
9983 // used for recursive calls, and can be NULL for a non-recursive call.
9984 // When this function returns false because it finds that the name is
9985 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
9986 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
9987 // will be unchanged.
9989 // This function just returns whether or not there is a field or
9990 // method, and whether it is a field or method. It doesn't build an
9991 // expression to refer to it. If it is a method, we then look in the
9992 // list of all methods for the type. If it is a field, the search has
9993 // to be done again, looking only for fields, and building up the
9994 // expression as we go.
9996 bool
9997 Type::find_field_or_method(const Type* type,
9998 const std::string& name,
9999 bool receiver_can_be_pointer,
10000 std::vector<const Named_type*>* seen,
10001 int* level,
10002 bool* is_method,
10003 bool* found_pointer_method,
10004 std::string* ambig1,
10005 std::string* ambig2)
10007 // Named types can have locally defined methods.
10008 const Named_type* nt = type->named_type();
10009 if (nt == NULL && type->points_to() != NULL)
10010 nt = type->points_to()->named_type();
10011 if (nt != NULL)
10013 Named_object* no = nt->find_local_method(name);
10014 if (no != NULL)
10016 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
10018 *is_method = true;
10019 return true;
10022 // Record that we have found a pointer method in order to
10023 // give a better error message if we don't find anything
10024 // else.
10025 *found_pointer_method = true;
10028 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
10029 p != seen->end();
10030 ++p)
10032 if (*p == nt)
10034 // We've already seen this type when searching for methods.
10035 return false;
10040 // Interface types can have methods.
10041 const Interface_type* it = type->interface_type();
10042 if (it != NULL && it->find_method(name) != NULL)
10044 *is_method = true;
10045 return true;
10048 // Struct types can have fields. They can also inherit fields and
10049 // methods from anonymous fields.
10050 const Struct_type* st = type->deref()->struct_type();
10051 if (st == NULL)
10052 return false;
10053 const Struct_field_list* fields = st->fields();
10054 if (fields == NULL)
10055 return false;
10057 if (nt != NULL)
10058 seen->push_back(nt);
10060 int found_level = 0;
10061 bool found_is_method = false;
10062 std::string found_ambig1;
10063 std::string found_ambig2;
10064 const Struct_field* found_parent = NULL;
10065 for (Struct_field_list::const_iterator pf = fields->begin();
10066 pf != fields->end();
10067 ++pf)
10069 if (pf->is_field_name(name))
10071 *is_method = false;
10072 if (nt != NULL)
10073 seen->pop_back();
10074 return true;
10077 if (!pf->is_anonymous())
10078 continue;
10080 if (pf->type()->deref()->is_error_type()
10081 || pf->type()->deref()->is_undefined())
10082 continue;
10084 Named_type* fnt = pf->type()->named_type();
10085 if (fnt == NULL)
10086 fnt = pf->type()->deref()->named_type();
10087 go_assert(fnt != NULL);
10089 // Methods with pointer receivers on embedded field are
10090 // inherited by the pointer to struct, and also by the struct
10091 // type if the field itself is a pointer.
10092 bool can_be_pointer = (receiver_can_be_pointer
10093 || pf->type()->points_to() != NULL);
10094 int sublevel = level == NULL ? 1 : *level + 1;
10095 bool sub_is_method;
10096 std::string subambig1;
10097 std::string subambig2;
10098 bool subfound = Type::find_field_or_method(fnt,
10099 name,
10100 can_be_pointer,
10101 seen,
10102 &sublevel,
10103 &sub_is_method,
10104 found_pointer_method,
10105 &subambig1,
10106 &subambig2);
10107 if (!subfound)
10109 if (!subambig1.empty())
10111 // The name was found via this field, but is ambiguous.
10112 // if the ambiguity is lower or at the same level as
10113 // anything else we have already found, then we want to
10114 // pass the ambiguity back to the caller.
10115 if (found_level == 0 || sublevel <= found_level)
10117 found_ambig1 = (Gogo::message_name(pf->field_name())
10118 + '.' + subambig1);
10119 found_ambig2 = (Gogo::message_name(pf->field_name())
10120 + '.' + subambig2);
10121 found_level = sublevel;
10125 else
10127 // The name was found via this field. Use the level to see
10128 // if we want to use this one, or whether it introduces an
10129 // ambiguity.
10130 if (found_level == 0 || sublevel < found_level)
10132 found_level = sublevel;
10133 found_is_method = sub_is_method;
10134 found_ambig1.clear();
10135 found_ambig2.clear();
10136 found_parent = &*pf;
10138 else if (sublevel > found_level)
10140 else if (found_ambig1.empty())
10142 // We found an ambiguity.
10143 go_assert(found_parent != NULL);
10144 found_ambig1 = Gogo::message_name(found_parent->field_name());
10145 found_ambig2 = Gogo::message_name(pf->field_name());
10147 else
10149 // We found an ambiguity, but we already know of one.
10150 // Just report the earlier one.
10155 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
10156 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
10157 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
10158 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
10160 if (nt != NULL)
10161 seen->pop_back();
10163 if (found_level == 0)
10164 return false;
10165 else if (!found_ambig1.empty())
10167 go_assert(!found_ambig1.empty());
10168 ambig1->assign(found_ambig1);
10169 ambig2->assign(found_ambig2);
10170 if (level != NULL)
10171 *level = found_level;
10172 return false;
10174 else
10176 if (level != NULL)
10177 *level = found_level;
10178 *is_method = found_is_method;
10179 return true;
10183 // Return whether NAME is an unexported field or method for TYPE.
10185 bool
10186 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
10187 const std::string& name,
10188 std::vector<const Named_type*>* seen)
10190 const Named_type* nt = type->named_type();
10191 if (nt == NULL)
10192 nt = type->deref()->named_type();
10193 if (nt != NULL)
10195 if (nt->is_unexported_local_method(gogo, name))
10196 return true;
10198 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
10199 p != seen->end();
10200 ++p)
10202 if (*p == nt)
10204 // We've already seen this type.
10205 return false;
10210 const Interface_type* it = type->interface_type();
10211 if (it != NULL && it->is_unexported_method(gogo, name))
10212 return true;
10214 type = type->deref();
10216 const Struct_type* st = type->struct_type();
10217 if (st != NULL && st->is_unexported_local_field(gogo, name))
10218 return true;
10220 if (st == NULL)
10221 return false;
10223 const Struct_field_list* fields = st->fields();
10224 if (fields == NULL)
10225 return false;
10227 if (nt != NULL)
10228 seen->push_back(nt);
10230 for (Struct_field_list::const_iterator pf = fields->begin();
10231 pf != fields->end();
10232 ++pf)
10234 if (pf->is_anonymous()
10235 && !pf->type()->deref()->is_error_type()
10236 && !pf->type()->deref()->is_undefined())
10238 Named_type* subtype = pf->type()->named_type();
10239 if (subtype == NULL)
10240 subtype = pf->type()->deref()->named_type();
10241 if (subtype == NULL)
10243 // This is an error, but it will be diagnosed elsewhere.
10244 continue;
10246 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
10248 if (nt != NULL)
10249 seen->pop_back();
10250 return true;
10255 if (nt != NULL)
10256 seen->pop_back();
10258 return false;
10261 // Class Forward_declaration.
10263 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
10264 : Type(TYPE_FORWARD),
10265 named_object_(named_object->resolve()), warned_(false)
10267 go_assert(this->named_object_->is_unknown()
10268 || this->named_object_->is_type_declaration());
10271 // Return the named object.
10273 Named_object*
10274 Forward_declaration_type::named_object()
10276 return this->named_object_->resolve();
10279 const Named_object*
10280 Forward_declaration_type::named_object() const
10282 return this->named_object_->resolve();
10285 // Return the name of the forward declared type.
10287 const std::string&
10288 Forward_declaration_type::name() const
10290 return this->named_object()->name();
10293 // Warn about a use of a type which has been declared but not defined.
10295 void
10296 Forward_declaration_type::warn() const
10298 Named_object* no = this->named_object_->resolve();
10299 if (no->is_unknown())
10301 // The name was not defined anywhere.
10302 if (!this->warned_)
10304 error_at(this->named_object_->location(),
10305 "use of undefined type %qs",
10306 no->message_name().c_str());
10307 this->warned_ = true;
10310 else if (no->is_type_declaration())
10312 // The name was seen as a type, but the type was never defined.
10313 if (no->type_declaration_value()->using_type())
10315 error_at(this->named_object_->location(),
10316 "use of undefined type %qs",
10317 no->message_name().c_str());
10318 this->warned_ = true;
10321 else
10323 // The name was defined, but not as a type.
10324 if (!this->warned_)
10326 error_at(this->named_object_->location(), "expected type");
10327 this->warned_ = true;
10332 // Get the base type of a declaration. This gives an error if the
10333 // type has not yet been defined.
10335 Type*
10336 Forward_declaration_type::real_type()
10338 if (this->is_defined())
10339 return this->named_object()->type_value();
10340 else
10342 this->warn();
10343 return Type::make_error_type();
10347 const Type*
10348 Forward_declaration_type::real_type() const
10350 if (this->is_defined())
10351 return this->named_object()->type_value();
10352 else
10354 this->warn();
10355 return Type::make_error_type();
10359 // Return whether the base type is defined.
10361 bool
10362 Forward_declaration_type::is_defined() const
10364 return this->named_object()->is_type();
10367 // Add a method. This is used when methods are defined before the
10368 // type.
10370 Named_object*
10371 Forward_declaration_type::add_method(const std::string& name,
10372 Function* function)
10374 Named_object* no = this->named_object();
10375 if (no->is_unknown())
10376 no->declare_as_type();
10377 return no->type_declaration_value()->add_method(name, function);
10380 // Add a method declaration. This is used when methods are declared
10381 // before the type.
10383 Named_object*
10384 Forward_declaration_type::add_method_declaration(const std::string& name,
10385 Package* package,
10386 Function_type* type,
10387 Location location)
10389 Named_object* no = this->named_object();
10390 if (no->is_unknown())
10391 no->declare_as_type();
10392 Type_declaration* td = no->type_declaration_value();
10393 return td->add_method_declaration(name, package, type, location);
10396 // Traversal.
10399 Forward_declaration_type::do_traverse(Traverse* traverse)
10401 if (this->is_defined()
10402 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
10403 return TRAVERSE_EXIT;
10404 return TRAVERSE_CONTINUE;
10407 // Verify the type.
10409 bool
10410 Forward_declaration_type::do_verify()
10412 if (!this->is_defined() && !this->is_nil_constant_as_type())
10414 this->warn();
10415 return false;
10417 return true;
10420 // Get the backend representation for the type.
10422 Btype*
10423 Forward_declaration_type::do_get_backend(Gogo* gogo)
10425 if (this->is_defined())
10426 return Type::get_named_base_btype(gogo, this->real_type());
10428 if (this->warned_)
10429 return gogo->backend()->error_type();
10431 // We represent an undefined type as a struct with no fields. That
10432 // should work fine for the backend, since the same case can arise
10433 // in C.
10434 std::vector<Backend::Btyped_identifier> fields;
10435 Btype* bt = gogo->backend()->struct_type(fields);
10436 return gogo->backend()->named_type(this->name(), bt,
10437 this->named_object()->location());
10440 // Build a type descriptor for a forwarded type.
10442 Expression*
10443 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
10445 Location ploc = Linemap::predeclared_location();
10446 if (!this->is_defined())
10447 return Expression::make_error(ploc);
10448 else
10450 Type* t = this->real_type();
10451 if (name != NULL)
10452 return this->named_type_descriptor(gogo, t, name);
10453 else
10454 return Expression::make_type_descriptor(t, ploc);
10458 // The reflection string.
10460 void
10461 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
10463 this->append_reflection(this->real_type(), gogo, ret);
10466 // The mangled name.
10468 void
10469 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
10471 if (this->is_defined())
10472 this->append_mangled_name(this->real_type(), gogo, ret);
10473 else
10475 const Named_object* no = this->named_object();
10476 std::string name;
10477 if (no->package() == NULL)
10478 name = gogo->pkgpath_symbol();
10479 else
10480 name = no->package()->pkgpath_symbol();
10481 name += '.';
10482 name += Gogo::unpack_hidden_name(no->name());
10483 char buf[20];
10484 snprintf(buf, sizeof buf, "N%u_",
10485 static_cast<unsigned int>(name.length()));
10486 ret->append(buf);
10487 ret->append(name);
10491 // Export a forward declaration. This can happen when a defined type
10492 // refers to a type which is only declared (and is presumably defined
10493 // in some other file in the same package).
10495 void
10496 Forward_declaration_type::do_export(Export*) const
10498 // If there is a base type, that should be exported instead of this.
10499 go_assert(!this->is_defined());
10501 // We don't output anything.
10504 // Make a forward declaration.
10506 Type*
10507 Type::make_forward_declaration(Named_object* named_object)
10509 return new Forward_declaration_type(named_object);
10512 // Class Typed_identifier_list.
10514 // Sort the entries by name.
10516 struct Typed_identifier_list_sort
10518 public:
10519 bool
10520 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
10521 { return t1.name() < t2.name(); }
10524 void
10525 Typed_identifier_list::sort_by_name()
10527 std::sort(this->entries_.begin(), this->entries_.end(),
10528 Typed_identifier_list_sort());
10531 // Traverse types.
10534 Typed_identifier_list::traverse(Traverse* traverse)
10536 for (Typed_identifier_list::const_iterator p = this->begin();
10537 p != this->end();
10538 ++p)
10540 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
10541 return TRAVERSE_EXIT;
10543 return TRAVERSE_CONTINUE;
10546 // Copy the list.
10548 Typed_identifier_list*
10549 Typed_identifier_list::copy() const
10551 Typed_identifier_list* ret = new Typed_identifier_list();
10552 for (Typed_identifier_list::const_iterator p = this->begin();
10553 p != this->end();
10554 ++p)
10555 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
10556 return ret;