OSDN Git Service

compiler: Fix handling of invalid types within invalid types.
[pf3gnuchains/gcc-fork.git] / gcc / go / gofrontend / types.cc
1 // types.cc -- Go frontend types.
2
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.
6
7 #include "go-system.h"
8
9 #include <gmp.h>
10
11 #ifndef ENABLE_BUILD_WITH_CXX
12 extern "C"
13 {
14 #endif
15
16 #include "toplev.h"
17 #include "intl.h"
18 #include "tree.h"
19 #include "gimple.h"
20 #include "real.h"
21 #include "convert.h"
22
23 #ifndef ENABLE_BUILD_WITH_CXX
24 }
25 #endif
26
27 #include "go-c.h"
28 #include "gogo.h"
29 #include "operator.h"
30 #include "expressions.h"
31 #include "statements.h"
32 #include "export.h"
33 #include "import.h"
34 #include "backend.h"
35 #include "types.h"
36
37 // Forward declarations so that we don't have to make types.h #include
38 // backend.h.
39
40 static void
41 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
42                           bool use_placeholder,
43                           std::vector<Backend::Btyped_identifier>* bfields);
44
45 static void
46 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
47                          std::vector<Backend::Btyped_identifier>* bfields);
48
49 static void
50 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
51                              bool use_placeholder,
52                              std::vector<Backend::Btyped_identifier>* bfields);
53
54 // Class Type.
55
56 Type::Type(Type_classification classification)
57   : classification_(classification), btype_is_placeholder_(false),
58     btype_(NULL), type_descriptor_var_(NULL)
59 {
60 }
61
62 Type::~Type()
63 {
64 }
65
66 // Get the base type for a type--skip names and forward declarations.
67
68 Type*
69 Type::base()
70 {
71   switch (this->classification_)
72     {
73     case TYPE_NAMED:
74       return this->named_type()->named_base();
75     case TYPE_FORWARD:
76       return this->forward_declaration_type()->real_type()->base();
77     default:
78       return this;
79     }
80 }
81
82 const Type*
83 Type::base() const
84 {
85   switch (this->classification_)
86     {
87     case TYPE_NAMED:
88       return this->named_type()->named_base();
89     case TYPE_FORWARD:
90       return this->forward_declaration_type()->real_type()->base();
91     default:
92       return this;
93     }
94 }
95
96 // Skip defined forward declarations.
97
98 Type*
99 Type::forwarded()
100 {
101   Type* t = this;
102   Forward_declaration_type* ftype = t->forward_declaration_type();
103   while (ftype != NULL && ftype->is_defined())
104     {
105       t = ftype->real_type();
106       ftype = t->forward_declaration_type();
107     }
108   return t;
109 }
110
111 const Type*
112 Type::forwarded() const
113 {
114   const Type* t = this;
115   const Forward_declaration_type* ftype = t->forward_declaration_type();
116   while (ftype != NULL && ftype->is_defined())
117     {
118       t = ftype->real_type();
119       ftype = t->forward_declaration_type();
120     }
121   return t;
122 }
123
124 // If this is a named type, return it.  Otherwise, return NULL.
125
126 Named_type*
127 Type::named_type()
128 {
129   return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
130 }
131
132 const Named_type*
133 Type::named_type() const
134 {
135   return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
136 }
137
138 // Return true if this type is not defined.
139
140 bool
141 Type::is_undefined() const
142 {
143   return this->forwarded()->forward_declaration_type() != NULL;
144 }
145
146 // Return true if this is a basic type: a type which is not composed
147 // of other types, and is not void.
148
149 bool
150 Type::is_basic_type() const
151 {
152   switch (this->classification_)
153     {
154     case TYPE_INTEGER:
155     case TYPE_FLOAT:
156     case TYPE_COMPLEX:
157     case TYPE_BOOLEAN:
158     case TYPE_STRING:
159     case TYPE_NIL:
160       return true;
161
162     case TYPE_ERROR:
163     case TYPE_VOID:
164     case TYPE_FUNCTION:
165     case TYPE_POINTER:
166     case TYPE_STRUCT:
167     case TYPE_ARRAY:
168     case TYPE_MAP:
169     case TYPE_CHANNEL:
170     case TYPE_INTERFACE:
171       return false;
172
173     case TYPE_NAMED:
174     case TYPE_FORWARD:
175       return this->base()->is_basic_type();
176
177     default:
178       go_unreachable();
179     }
180 }
181
182 // Return true if this is an abstract type.
183
184 bool
185 Type::is_abstract() const
186 {
187   switch (this->classification())
188     {
189     case TYPE_INTEGER:
190       return this->integer_type()->is_abstract();
191     case TYPE_FLOAT:
192       return this->float_type()->is_abstract();
193     case TYPE_COMPLEX:
194       return this->complex_type()->is_abstract();
195     case TYPE_STRING:
196       return this->is_abstract_string_type();
197     case TYPE_BOOLEAN:
198       return this->is_abstract_boolean_type();
199     default:
200       return false;
201     }
202 }
203
204 // Return a non-abstract version of an abstract type.
205
206 Type*
207 Type::make_non_abstract_type()
208 {
209   go_assert(this->is_abstract());
210   switch (this->classification())
211     {
212     case TYPE_INTEGER:
213       if (this->integer_type()->is_rune())
214         return Type::lookup_integer_type("int32");
215       else
216         return Type::lookup_integer_type("int");
217     case TYPE_FLOAT:
218       return Type::lookup_float_type("float64");
219     case TYPE_COMPLEX:
220       return Type::lookup_complex_type("complex128");
221     case TYPE_STRING:
222       return Type::lookup_string_type();
223     case TYPE_BOOLEAN:
224       return Type::lookup_bool_type();
225     default:
226       go_unreachable();
227     }
228 }
229
230 // Return true if this is an error type.  Don't give an error if we
231 // try to dereference an undefined forwarding type, as this is called
232 // in the parser when the type may legitimately be undefined.
233
234 bool
235 Type::is_error_type() const
236 {
237   const Type* t = this->forwarded();
238   // Note that we return false for an undefined forward type.
239   switch (t->classification_)
240     {
241     case TYPE_ERROR:
242       return true;
243     case TYPE_NAMED:
244       return t->named_type()->is_named_error_type();
245     default:
246       return false;
247     }
248 }
249
250 // If this is a pointer type, return the type to which it points.
251 // Otherwise, return NULL.
252
253 Type*
254 Type::points_to() const
255 {
256   const Pointer_type* ptype = this->convert<const Pointer_type,
257                                             TYPE_POINTER>();
258   return ptype == NULL ? NULL : ptype->points_to();
259 }
260
261 // Return whether this is an open array type.
262
263 bool
264 Type::is_slice_type() const
265 {
266   return this->array_type() != NULL && this->array_type()->length() == NULL;
267 }
268
269 // Return whether this is the predeclared constant nil being used as a
270 // type.
271
272 bool
273 Type::is_nil_constant_as_type() const
274 {
275   const Type* t = this->forwarded();
276   if (t->forward_declaration_type() != NULL)
277     {
278       const Named_object* no = t->forward_declaration_type()->named_object();
279       if (no->is_unknown())
280         no = no->unknown_value()->real_named_object();
281       if (no != NULL
282           && no->is_const()
283           && no->const_value()->expr()->is_nil_expression())
284         return true;
285     }
286   return false;
287 }
288
289 // Traverse a type.
290
291 int
292 Type::traverse(Type* type, Traverse* traverse)
293 {
294   go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
295              || (traverse->traverse_mask()
296                  & Traverse::traverse_expressions) != 0);
297   if (traverse->remember_type(type))
298     {
299       // We have already traversed this type.
300       return TRAVERSE_CONTINUE;
301     }
302   if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
303     {
304       int t = traverse->type(type);
305       if (t == TRAVERSE_EXIT)
306         return TRAVERSE_EXIT;
307       else if (t == TRAVERSE_SKIP_COMPONENTS)
308         return TRAVERSE_CONTINUE;
309     }
310   // An array type has an expression which we need to traverse if
311   // traverse_expressions is set.
312   if (type->do_traverse(traverse) == TRAVERSE_EXIT)
313     return TRAVERSE_EXIT;
314   return TRAVERSE_CONTINUE;
315 }
316
317 // Default implementation for do_traverse for child class.
318
319 int
320 Type::do_traverse(Traverse*)
321 {
322   return TRAVERSE_CONTINUE;
323 }
324
325 // Return whether two types are identical.  If ERRORS_ARE_IDENTICAL,
326 // then return true for all erroneous types; this is used to avoid
327 // cascading errors.  If REASON is not NULL, optionally set *REASON to
328 // the reason the types are not identical.
329
330 bool
331 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
332                     std::string* reason)
333 {
334   if (t1 == NULL || t2 == NULL)
335     {
336       // Something is wrong.
337       return errors_are_identical ? true : t1 == t2;
338     }
339
340   // Skip defined forward declarations.
341   t1 = t1->forwarded();
342   t2 = t2->forwarded();
343
344   // Ignore aliases for purposes of type identity.
345   if (t1->named_type() != NULL && t1->named_type()->is_alias())
346     t1 = t1->named_type()->real_type();
347   if (t2->named_type() != NULL && t2->named_type()->is_alias())
348     t2 = t2->named_type()->real_type();
349
350   if (t1 == t2)
351     return true;
352
353   // An undefined forward declaration is an error.
354   if (t1->forward_declaration_type() != NULL
355       || t2->forward_declaration_type() != NULL)
356     return errors_are_identical;
357
358   // Avoid cascading errors with error types.
359   if (t1->is_error_type() || t2->is_error_type())
360     {
361       if (errors_are_identical)
362         return true;
363       return t1->is_error_type() && t2->is_error_type();
364     }
365
366   // Get a good reason for the sink type.  Note that the sink type on
367   // the left hand side of an assignment is handled in are_assignable.
368   if (t1->is_sink_type() || t2->is_sink_type())
369     {
370       if (reason != NULL)
371         *reason = "invalid use of _";
372       return false;
373     }
374
375   // A named type is only identical to itself.
376   if (t1->named_type() != NULL || t2->named_type() != NULL)
377     return false;
378
379   // Check type shapes.
380   if (t1->classification() != t2->classification())
381     return false;
382
383   switch (t1->classification())
384     {
385     case TYPE_VOID:
386     case TYPE_BOOLEAN:
387     case TYPE_STRING:
388     case TYPE_NIL:
389       // These types are always identical.
390       return true;
391
392     case TYPE_INTEGER:
393       return t1->integer_type()->is_identical(t2->integer_type());
394
395     case TYPE_FLOAT:
396       return t1->float_type()->is_identical(t2->float_type());
397
398     case TYPE_COMPLEX:
399       return t1->complex_type()->is_identical(t2->complex_type());
400
401     case TYPE_FUNCTION:
402       return t1->function_type()->is_identical(t2->function_type(),
403                                                false,
404                                                errors_are_identical,
405                                                reason);
406
407     case TYPE_POINTER:
408       return Type::are_identical(t1->points_to(), t2->points_to(),
409                                  errors_are_identical, reason);
410
411     case TYPE_STRUCT:
412       return t1->struct_type()->is_identical(t2->struct_type(),
413                                              errors_are_identical);
414
415     case TYPE_ARRAY:
416       return t1->array_type()->is_identical(t2->array_type(),
417                                             errors_are_identical);
418
419     case TYPE_MAP:
420       return t1->map_type()->is_identical(t2->map_type(),
421                                           errors_are_identical);
422
423     case TYPE_CHANNEL:
424       return t1->channel_type()->is_identical(t2->channel_type(),
425                                               errors_are_identical);
426
427     case TYPE_INTERFACE:
428       return t1->interface_type()->is_identical(t2->interface_type(),
429                                                 errors_are_identical);
430
431     case TYPE_CALL_MULTIPLE_RESULT:
432       if (reason != NULL)
433         *reason = "invalid use of multiple value function call";
434       return false;
435
436     default:
437       go_unreachable();
438     }
439 }
440
441 // Return true if it's OK to have a binary operation with types LHS
442 // and RHS.  This is not used for shifts or comparisons.
443
444 bool
445 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
446 {
447   if (Type::are_identical(lhs, rhs, true, NULL))
448     return true;
449
450   // A constant of abstract bool type may be mixed with any bool type.
451   if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
452       || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
453     return true;
454
455   // A constant of abstract string type may be mixed with any string
456   // type.
457   if ((rhs->is_abstract_string_type() && lhs->is_string_type())
458       || (lhs->is_abstract_string_type() && rhs->is_string_type()))
459     return true;
460
461   lhs = lhs->base();
462   rhs = rhs->base();
463
464   // A constant of abstract integer, float, or complex type may be
465   // mixed with an integer, float, or complex type.
466   if ((rhs->is_abstract()
467        && (rhs->integer_type() != NULL
468            || rhs->float_type() != NULL
469            || rhs->complex_type() != NULL)
470        && (lhs->integer_type() != NULL
471            || lhs->float_type() != NULL
472            || lhs->complex_type() != NULL))
473       || (lhs->is_abstract()
474           && (lhs->integer_type() != NULL
475               || lhs->float_type() != NULL
476               || lhs->complex_type() != NULL)
477           && (rhs->integer_type() != NULL
478               || rhs->float_type() != NULL
479               || rhs->complex_type() != NULL)))
480     return true;
481
482   // The nil type may be compared to a pointer, an interface type, a
483   // slice type, a channel type, a map type, or a function type.
484   if (lhs->is_nil_type()
485       && (rhs->points_to() != NULL
486           || rhs->interface_type() != NULL
487           || rhs->is_slice_type()
488           || rhs->map_type() != NULL
489           || rhs->channel_type() != NULL
490           || rhs->function_type() != NULL))
491     return true;
492   if (rhs->is_nil_type()
493       && (lhs->points_to() != NULL
494           || lhs->interface_type() != NULL
495           || lhs->is_slice_type()
496           || lhs->map_type() != NULL
497           || lhs->channel_type() != NULL
498           || lhs->function_type() != NULL))
499     return true;
500
501   return false;
502 }
503
504 // Return true if a value with type T1 may be compared with a value of
505 // type T2.  IS_EQUALITY_OP is true for == or !=, false for <, etc.
506
507 bool
508 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
509                                     const Type *t2, std::string *reason)
510 {
511   if (t1 != t2
512       && !Type::are_assignable(t1, t2, NULL)
513       && !Type::are_assignable(t2, t1, NULL))
514     {
515       if (reason != NULL)
516         *reason = "incompatible types in binary expression";
517       return false;
518     }
519
520   if (!is_equality_op)
521     {
522       if (t1->integer_type() == NULL
523           && t1->float_type() == NULL
524           && !t1->is_string_type())
525         {
526           if (reason != NULL)
527             *reason = _("invalid comparison of non-ordered type");
528           return false;
529         }
530     }
531   else if (t1->is_slice_type()
532            || t1->map_type() != NULL
533            || t1->function_type() != NULL
534            || t2->is_slice_type()
535            || t2->map_type() != NULL
536            || t2->function_type() != NULL)
537     {
538       if (!t1->is_nil_type() && !t2->is_nil_type())
539         {
540           if (reason != NULL)
541             {
542               if (t1->is_slice_type() || t2->is_slice_type())
543                 *reason = _("slice can only be compared to nil");
544               else if (t1->map_type() != NULL || t2->map_type() != NULL)
545                 *reason = _("map can only be compared to nil");
546               else
547                 *reason = _("func can only be compared to nil");
548
549               // Match 6g error messages.
550               if (t1->interface_type() != NULL || t2->interface_type() != NULL)
551                 {
552                   char buf[200];
553                   snprintf(buf, sizeof buf, _("invalid operation (%s)"),
554                            reason->c_str());
555                   *reason = buf;
556                 }
557             }
558           return false;
559         }
560     }
561   else
562     {
563       if (!t1->is_boolean_type()
564           && t1->integer_type() == NULL
565           && t1->float_type() == NULL
566           && t1->complex_type() == NULL
567           && !t1->is_string_type()
568           && t1->points_to() == NULL
569           && t1->channel_type() == NULL
570           && t1->interface_type() == NULL
571           && t1->struct_type() == NULL
572           && t1->array_type() == NULL
573           && !t1->is_nil_type())
574         {
575           if (reason != NULL)
576             *reason = _("invalid comparison of non-comparable type");
577           return false;
578         }
579
580       if (t1->named_type() != NULL)
581         return t1->named_type()->named_type_is_comparable(reason);
582       else if (t2->named_type() != NULL)
583         return t2->named_type()->named_type_is_comparable(reason);
584       else if (t1->struct_type() != NULL)
585         {
586           const Struct_field_list* fields = t1->struct_type()->fields();
587           for (Struct_field_list::const_iterator p = fields->begin();
588                p != fields->end();
589                ++p)
590             {
591               if (!p->type()->is_comparable())
592                 {
593                   if (reason != NULL)
594                     *reason = _("invalid comparison of non-comparable struct");
595                   return false;
596                 }
597             }
598         }
599       else if (t1->array_type() != NULL)
600         {
601           if (t1->array_type()->length()->is_nil_expression()
602               || !t1->array_type()->element_type()->is_comparable())
603             {
604               if (reason != NULL)
605                 *reason = _("invalid comparison of non-comparable array");
606               return false;
607             }
608         }
609     }
610
611   return true;
612 }
613
614 // Return true if a value with type RHS may be assigned to a variable
615 // with type LHS.  If CHECK_HIDDEN_FIELDS is true, check whether any
616 // hidden fields are modified.  If REASON is not NULL, set *REASON to
617 // the reason the types are not assignable.
618
619 bool
620 Type::are_assignable_check_hidden(const Type* lhs, const Type* rhs,
621                                   bool check_hidden_fields,
622                                   std::string* reason)
623 {
624   // Do some checks first.  Make sure the types are defined.
625   if (rhs != NULL
626       && rhs->forwarded()->forward_declaration_type() == NULL
627       && rhs->is_void_type())
628     {
629       if (reason != NULL)
630         *reason = "non-value used as value";
631       return false;
632     }
633
634   if (lhs != NULL && lhs->forwarded()->forward_declaration_type() == NULL)
635     {
636       // Any value may be assigned to the blank identifier.
637       if (lhs->is_sink_type())
638         return true;
639
640       // All fields of a struct must be exported, or the assignment
641       // must be in the same package.
642       if (check_hidden_fields
643           && rhs != NULL
644           && rhs->forwarded()->forward_declaration_type() == NULL)
645         {
646           if (lhs->has_hidden_fields(NULL, reason)
647               || rhs->has_hidden_fields(NULL, reason))
648             return false;
649         }
650     }
651
652   // Identical types are assignable.
653   if (Type::are_identical(lhs, rhs, true, reason))
654     return true;
655
656   // The types are assignable if they have identical underlying types
657   // and either LHS or RHS is not a named type.
658   if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
659        || (rhs->named_type() != NULL && lhs->named_type() == NULL))
660       && Type::are_identical(lhs->base(), rhs->base(), true, reason))
661     return true;
662
663   // The types are assignable if LHS is an interface type and RHS
664   // implements the required methods.
665   const Interface_type* lhs_interface_type = lhs->interface_type();
666   if (lhs_interface_type != NULL)
667     {
668       if (lhs_interface_type->implements_interface(rhs, reason))
669         return true;
670       const Interface_type* rhs_interface_type = rhs->interface_type();
671       if (rhs_interface_type != NULL
672           && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
673                                                           reason))
674         return true;
675     }
676
677   // The type are assignable if RHS is a bidirectional channel type,
678   // LHS is a channel type, they have identical element types, and
679   // either LHS or RHS is not a named type.
680   if (lhs->channel_type() != NULL
681       && rhs->channel_type() != NULL
682       && rhs->channel_type()->may_send()
683       && rhs->channel_type()->may_receive()
684       && (lhs->named_type() == NULL || rhs->named_type() == NULL)
685       && Type::are_identical(lhs->channel_type()->element_type(),
686                              rhs->channel_type()->element_type(),
687                              true,
688                              reason))
689     return true;
690
691   // The nil type may be assigned to a pointer, function, slice, map,
692   // channel, or interface type.
693   if (rhs->is_nil_type()
694       && (lhs->points_to() != NULL
695           || lhs->function_type() != NULL
696           || lhs->is_slice_type()
697           || lhs->map_type() != NULL
698           || lhs->channel_type() != NULL
699           || lhs->interface_type() != NULL))
700     return true;
701
702   // An untyped numeric constant may be assigned to a numeric type if
703   // it is representable in that type.
704   if ((rhs->is_abstract()
705        && (rhs->integer_type() != NULL
706            || rhs->float_type() != NULL
707            || rhs->complex_type() != NULL))
708       && (lhs->integer_type() != NULL
709           || lhs->float_type() != NULL
710           || lhs->complex_type() != NULL))
711     return true;
712
713   // Give some better error messages.
714   if (reason != NULL && reason->empty())
715     {
716       if (rhs->interface_type() != NULL)
717         reason->assign(_("need explicit conversion"));
718       else if (rhs->is_call_multiple_result_type())
719         reason->assign(_("multiple value function call in "
720                          "single value context"));
721       else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
722         {
723           size_t len = (lhs->named_type()->name().length()
724                         + rhs->named_type()->name().length()
725                         + 100);
726           char* buf = new char[len];
727           snprintf(buf, len, _("cannot use type %s as type %s"),
728                    rhs->named_type()->message_name().c_str(),
729                    lhs->named_type()->message_name().c_str());
730           reason->assign(buf);
731           delete[] buf;
732         }
733     }
734
735   return false;
736 }
737
738 // Return true if a value with type RHS may be assigned to a variable
739 // with type LHS.  If REASON is not NULL, set *REASON to the reason
740 // the types are not assignable.
741
742 bool
743 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
744 {
745   return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
746 }
747
748 // Like are_assignable but don't check for hidden fields.
749
750 bool
751 Type::are_assignable_hidden_ok(const Type* lhs, const Type* rhs,
752                                std::string* reason)
753 {
754   return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
755 }
756
757 // Return true if a value with type RHS may be converted to type LHS.
758 // If REASON is not NULL, set *REASON to the reason the types are not
759 // convertible.
760
761 bool
762 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
763 {
764   // The types are convertible if they are assignable.
765   if (Type::are_assignable(lhs, rhs, reason))
766     return true;
767
768   // The types are convertible if they have identical underlying
769   // types.
770   if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
771       && Type::are_identical(lhs->base(), rhs->base(), true, reason))
772     return true;
773
774   // The types are convertible if they are both unnamed pointer types
775   // and their pointer base types have identical underlying types.
776   if (lhs->named_type() == NULL
777       && rhs->named_type() == NULL
778       && lhs->points_to() != NULL
779       && rhs->points_to() != NULL
780       && (lhs->points_to()->named_type() != NULL
781           || rhs->points_to()->named_type() != NULL)
782       && Type::are_identical(lhs->points_to()->base(),
783                              rhs->points_to()->base(),
784                              true,
785                              reason))
786     return true;
787
788   // Integer and floating point types are convertible to each other.
789   if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
790       && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
791     return true;
792
793   // Complex types are convertible to each other.
794   if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
795     return true;
796
797   // An integer, or []byte, or []rune, may be converted to a string.
798   if (lhs->is_string_type())
799     {
800       if (rhs->integer_type() != NULL)
801         return true;
802       if (rhs->is_slice_type())
803         {
804           const Type* e = rhs->array_type()->element_type()->forwarded();
805           if (e->integer_type() != NULL
806               && (e->integer_type()->is_byte()
807                   || e->integer_type()->is_rune()))
808             return true;
809         }
810     }
811
812   // A string may be converted to []byte or []rune.
813   if (rhs->is_string_type() && lhs->is_slice_type())
814     {
815       const Type* e = lhs->array_type()->element_type()->forwarded();
816       if (e->integer_type() != NULL
817           && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
818         return true;
819     }
820
821   // An unsafe.Pointer type may be converted to any pointer type or to
822   // uintptr, and vice-versa.
823   if (lhs->is_unsafe_pointer_type()
824       && (rhs->points_to() != NULL
825           || (rhs->integer_type() != NULL
826               && rhs->forwarded() == Type::lookup_integer_type("uintptr"))))
827     return true;
828   if (rhs->is_unsafe_pointer_type()
829       && (lhs->points_to() != NULL
830           || (lhs->integer_type() != NULL
831               && lhs->forwarded() == Type::lookup_integer_type("uintptr"))))
832     return true;
833
834   // Give a better error message.
835   if (reason != NULL)
836     {
837       if (reason->empty())
838         *reason = "invalid type conversion";
839       else
840         {
841           std::string s = "invalid type conversion (";
842           s += *reason;
843           s += ')';
844           *reason = s;
845         }
846     }
847
848   return false;
849 }
850
851 // Return whether this type has any hidden fields.  This is only a
852 // possibility for a few types.
853
854 bool
855 Type::has_hidden_fields(const Named_type* within, std::string* reason) const
856 {
857   switch (this->forwarded()->classification_)
858     {
859     case TYPE_NAMED:
860       return this->named_type()->named_type_has_hidden_fields(reason);
861     case TYPE_STRUCT:
862       return this->struct_type()->struct_has_hidden_fields(within, reason);
863     case TYPE_ARRAY:
864       return this->array_type()->array_has_hidden_fields(within, reason);
865     default:
866       return false;
867     }
868 }
869
870 // Return a hash code for the type to be used for method lookup.
871
872 unsigned int
873 Type::hash_for_method(Gogo* gogo) const
874 {
875   unsigned int ret = 0;
876   if (this->classification_ != TYPE_FORWARD)
877     ret += this->classification_;
878   return ret + this->do_hash_for_method(gogo);
879 }
880
881 // Default implementation of do_hash_for_method.  This is appropriate
882 // for types with no subfields.
883
884 unsigned int
885 Type::do_hash_for_method(Gogo*) const
886 {
887   return 0;
888 }
889
890 // Return a hash code for a string, given a starting hash.
891
892 unsigned int
893 Type::hash_string(const std::string& s, unsigned int h)
894 {
895   const char* p = s.data();
896   size_t len = s.length();
897   for (; len > 0; --len)
898     {
899       h ^= *p++;
900       h*= 16777619;
901     }
902   return h;
903 }
904
905 // A hash table mapping unnamed types to the backend representation of
906 // those types.
907
908 Type::Type_btypes Type::type_btypes;
909
910 // Return a tree representing this type.
911
912 Btype*
913 Type::get_backend(Gogo* gogo)
914 {
915   if (this->btype_ != NULL)
916     {
917       if (this->btype_is_placeholder_ && gogo->named_types_are_converted())
918         this->finish_backend(gogo);
919       return this->btype_;
920     }
921
922   if (this->forward_declaration_type() != NULL
923       || this->named_type() != NULL)
924     return this->get_btype_without_hash(gogo);
925
926   if (this->is_error_type())
927     return gogo->backend()->error_type();
928
929   // To avoid confusing the backend, translate all identical Go types
930   // to the same backend representation.  We use a hash table to do
931   // that.  There is no need to use the hash table for named types, as
932   // named types are only identical to themselves.
933
934   std::pair<Type*, Btype*> val(this, NULL);
935   std::pair<Type_btypes::iterator, bool> ins =
936     Type::type_btypes.insert(val);
937   if (!ins.second && ins.first->second != NULL)
938     {
939       if (gogo != NULL && gogo->named_types_are_converted())
940         this->btype_ = ins.first->second;
941       return ins.first->second;
942     }
943
944   Btype* bt = this->get_btype_without_hash(gogo);
945
946   if (ins.first->second == NULL)
947     ins.first->second = bt;
948   else
949     {
950       // We have already created a backend representation for this
951       // type.  This can happen when an unnamed type is defined using
952       // a named type which in turns uses an identical unnamed type.
953       // Use the tree we created earlier and ignore the one we just
954       // built.
955       bt = ins.first->second;
956       if (gogo == NULL || !gogo->named_types_are_converted())
957         return bt;
958       this->btype_ = bt;
959     }
960
961   return bt;
962 }
963
964 // Return the backend representation for a type without looking in the
965 // hash table for identical types.  This is used for named types,
966 // since a named type is never identical to any other type.
967
968 Btype*
969 Type::get_btype_without_hash(Gogo* gogo)
970 {
971   if (this->btype_ == NULL)
972     {
973       Btype* bt = this->do_get_backend(gogo);
974
975       // For a recursive function or pointer type, we will temporarily
976       // return a circular pointer type during the recursion.  We
977       // don't want to record that for a forwarding type, as it may
978       // confuse us later.
979       if (this->forward_declaration_type() != NULL
980           && gogo->backend()->is_circular_pointer_type(bt))
981         return bt;
982
983       if (gogo == NULL || !gogo->named_types_are_converted())
984         return bt;
985
986       this->btype_ = bt;
987     }
988   return this->btype_;
989 }
990
991 // Get the backend representation of a type without forcing the
992 // creation of the backend representation of all supporting types.
993 // This will return a backend type that has the correct size but may
994 // be incomplete.  E.g., a pointer will just be a placeholder pointer,
995 // and will not contain the final representation of the type to which
996 // it points.  This is used while converting all named types to the
997 // backend representation, to avoid problems with indirect references
998 // to types which are not yet complete.  When this is called, the
999 // sizes of all direct references (e.g., a struct field) should be
1000 // known, but the sizes of indirect references (e.g., the type to
1001 // which a pointer points) may not.
1002
1003 Btype*
1004 Type::get_backend_placeholder(Gogo* gogo)
1005 {
1006   if (gogo->named_types_are_converted())
1007     return this->get_backend(gogo);
1008   if (this->btype_ != NULL)
1009     return this->btype_;
1010
1011   Btype* bt;
1012   switch (this->classification_)
1013     {
1014     case TYPE_ERROR:
1015     case TYPE_VOID:
1016     case TYPE_BOOLEAN:
1017     case TYPE_INTEGER:
1018     case TYPE_FLOAT:
1019     case TYPE_COMPLEX:
1020     case TYPE_STRING:
1021     case TYPE_NIL:
1022       // These are simple types that can just be created directly.
1023       return this->get_backend(gogo);
1024
1025     case TYPE_FUNCTION:
1026       {
1027         Location loc = this->function_type()->location();
1028         bt = gogo->backend()->placeholder_pointer_type("", loc, true);
1029       }
1030       break;
1031
1032     case TYPE_POINTER:
1033       {
1034         Location loc = Linemap::unknown_location();
1035         bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1036       }
1037       break;
1038
1039     case TYPE_STRUCT:
1040       // We don't have to make the struct itself be a placeholder.  We
1041       // are promised that we know the sizes of the struct fields.
1042       // But we may have to use a placeholder for any particular
1043       // struct field.
1044       {
1045         std::vector<Backend::Btyped_identifier> bfields;
1046         get_backend_struct_fields(gogo, this->struct_type()->fields(),
1047                                   true, &bfields);
1048         bt = gogo->backend()->struct_type(bfields);
1049       }
1050       break;
1051
1052     case TYPE_ARRAY:
1053       if (this->is_slice_type())
1054         {
1055           std::vector<Backend::Btyped_identifier> bfields;
1056           get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1057           bt = gogo->backend()->struct_type(bfields);
1058         }
1059       else
1060         {
1061           Btype* element = this->array_type()->get_backend_element(gogo, true);
1062           Bexpression* len = this->array_type()->get_backend_length(gogo);
1063           bt = gogo->backend()->array_type(element, len);
1064         }
1065       break;
1066         
1067     case TYPE_MAP:
1068     case TYPE_CHANNEL:
1069       // All maps and channels have the same backend representation.
1070       return this->get_backend(gogo);
1071
1072     case TYPE_INTERFACE:
1073       if (this->interface_type()->is_empty())
1074         return Interface_type::get_backend_empty_interface_type(gogo);
1075       else
1076         {
1077           std::vector<Backend::Btyped_identifier> bfields;
1078           get_backend_interface_fields(gogo, this->interface_type(), true,
1079                                        &bfields);
1080           bt = gogo->backend()->struct_type(bfields);
1081         }
1082       break;
1083
1084     case TYPE_NAMED:
1085     case TYPE_FORWARD:
1086       // Named types keep track of their own dependencies and manage
1087       // their own placeholders.
1088       return this->get_backend(gogo);
1089
1090     case TYPE_SINK:
1091     case TYPE_CALL_MULTIPLE_RESULT:
1092     default:
1093       go_unreachable();
1094     }
1095
1096   this->btype_ = bt;
1097   this->btype_is_placeholder_ = true;
1098   return bt;
1099 }
1100
1101 // Complete the backend representation.  This is called for a type
1102 // using a placeholder type.
1103
1104 void
1105 Type::finish_backend(Gogo* gogo)
1106 {
1107   go_assert(this->btype_ != NULL);
1108   if (!this->btype_is_placeholder_)
1109     return;
1110
1111   switch (this->classification_)
1112     {
1113     case TYPE_ERROR:
1114     case TYPE_VOID:
1115     case TYPE_BOOLEAN:
1116     case TYPE_INTEGER:
1117     case TYPE_FLOAT:
1118     case TYPE_COMPLEX:
1119     case TYPE_STRING:
1120     case TYPE_NIL:
1121       go_unreachable();
1122
1123     case TYPE_FUNCTION:
1124       {
1125         Btype* bt = this->do_get_backend(gogo);
1126         if (!gogo->backend()->set_placeholder_function_type(this->btype_, bt))
1127           go_assert(saw_errors());
1128       }
1129       break;
1130
1131     case TYPE_POINTER:
1132       {
1133         Btype* bt = this->do_get_backend(gogo);
1134         if (!gogo->backend()->set_placeholder_pointer_type(this->btype_, bt))
1135           go_assert(saw_errors());
1136       }
1137       break;
1138
1139     case TYPE_STRUCT:
1140       // The struct type itself is done, but we have to make sure that
1141       // all the field types are converted.
1142       this->struct_type()->finish_backend_fields(gogo);
1143       break;
1144
1145     case TYPE_ARRAY:
1146       // The array type itself is done, but make sure the element type
1147       // is converted.
1148       this->array_type()->finish_backend_element(gogo);
1149       break;
1150         
1151     case TYPE_MAP:
1152     case TYPE_CHANNEL:
1153       go_unreachable();
1154
1155     case TYPE_INTERFACE:
1156       // The interface type itself is done, but make sure the method
1157       // types are converted.
1158       this->interface_type()->finish_backend_methods(gogo);
1159       break;
1160
1161     case TYPE_NAMED:
1162     case TYPE_FORWARD:
1163       go_unreachable();
1164
1165     case TYPE_SINK:
1166     case TYPE_CALL_MULTIPLE_RESULT:
1167     default:
1168       go_unreachable();
1169     }
1170
1171   this->btype_is_placeholder_ = false;
1172 }
1173
1174 // Return a pointer to the type descriptor for this type.
1175
1176 tree
1177 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1178 {
1179   Type* t = this->forwarded();
1180   if (t->named_type() != NULL && t->named_type()->is_alias())
1181     t = t->named_type()->real_type();
1182   if (t->type_descriptor_var_ == NULL)
1183     {
1184       t->make_type_descriptor_var(gogo);
1185       go_assert(t->type_descriptor_var_ != NULL);
1186     }
1187   tree var_tree = var_to_tree(t->type_descriptor_var_);
1188   if (var_tree == error_mark_node)
1189     return error_mark_node;
1190   return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
1191 }
1192
1193 // A mapping from unnamed types to type descriptor variables.
1194
1195 Type::Type_descriptor_vars Type::type_descriptor_vars;
1196
1197 // Build the type descriptor for this type.
1198
1199 void
1200 Type::make_type_descriptor_var(Gogo* gogo)
1201 {
1202   go_assert(this->type_descriptor_var_ == NULL);
1203
1204   Named_type* nt = this->named_type();
1205
1206   // We can have multiple instances of unnamed types, but we only want
1207   // to emit the type descriptor once.  We use a hash table.  This is
1208   // not necessary for named types, as they are unique, and we store
1209   // the type descriptor in the type itself.
1210   Bvariable** phash = NULL;
1211   if (nt == NULL)
1212     {
1213       Bvariable* bvnull = NULL;
1214       std::pair<Type_descriptor_vars::iterator, bool> ins =
1215         Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1216       if (!ins.second)
1217         {
1218           // We've already build a type descriptor for this type.
1219           this->type_descriptor_var_ = ins.first->second;
1220           return;
1221         }
1222       phash = &ins.first->second;
1223     }
1224
1225   std::string var_name = this->type_descriptor_var_name(gogo, nt);
1226
1227   // Build the contents of the type descriptor.
1228   Expression* initializer = this->do_type_descriptor(gogo, NULL);
1229
1230   Btype* initializer_btype = initializer->type()->get_backend(gogo);
1231
1232   Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1233
1234   const Package* dummy;
1235   if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1236     {
1237       this->type_descriptor_var_ =
1238         gogo->backend()->immutable_struct_reference(var_name,
1239                                                     initializer_btype,
1240                                                     loc);
1241       if (phash != NULL)
1242         *phash = this->type_descriptor_var_;
1243       return;
1244     }
1245
1246   // See if this type descriptor can appear in multiple packages.
1247   bool is_common = false;
1248   if (nt != NULL)
1249     {
1250       // We create the descriptor for a builtin type whenever we need
1251       // it.
1252       is_common = nt->is_builtin();
1253     }
1254   else
1255     {
1256       // This is an unnamed type.  The descriptor could be defined in
1257       // any package where it is needed, and the linker will pick one
1258       // descriptor to keep.
1259       is_common = true;
1260     }
1261
1262   // We are going to build the type descriptor in this package.  We
1263   // must create the variable before we convert the initializer to the
1264   // backend representation, because the initializer may refer to the
1265   // type descriptor of this type.  By setting type_descriptor_var_ we
1266   // ensure that type_descriptor_pointer will work if called while
1267   // converting INITIALIZER.
1268
1269   this->type_descriptor_var_ =
1270     gogo->backend()->immutable_struct(var_name, is_common, initializer_btype,
1271                                       loc);
1272   if (phash != NULL)
1273     *phash = this->type_descriptor_var_;
1274
1275   Translate_context context(gogo, NULL, NULL, NULL);
1276   context.set_is_const();
1277   Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
1278
1279   gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1280                                              var_name, is_common,
1281                                              initializer_btype, loc,
1282                                              binitializer);
1283 }
1284
1285 // Return the name of the type descriptor variable.  If NT is not
1286 // NULL, use it to get the name.  Otherwise this is an unnamed type.
1287
1288 std::string
1289 Type::type_descriptor_var_name(Gogo* gogo, Named_type* nt)
1290 {
1291   if (nt == NULL)
1292     return "__go_td_" + this->mangled_name(gogo);
1293
1294   Named_object* no = nt->named_object();
1295   const Named_object* in_function = nt->in_function();
1296   std::string ret = "__go_tdn_";
1297   if (nt->is_builtin())
1298     go_assert(in_function == NULL);
1299   else
1300     {
1301       const std::string& unique_prefix(no->package() == NULL
1302                                        ? gogo->unique_prefix()
1303                                        : no->package()->unique_prefix());
1304       const std::string& package_name(no->package() == NULL
1305                                       ? gogo->package_name()
1306                                       : no->package()->name());
1307       ret.append(unique_prefix);
1308       ret.append(1, '.');
1309       ret.append(package_name);
1310       ret.append(1, '.');
1311       if (in_function != NULL)
1312         {
1313           ret.append(Gogo::unpack_hidden_name(in_function->name()));
1314           ret.append(1, '.');
1315         }
1316     }
1317   ret.append(no->name());
1318   return ret;
1319 }
1320
1321 // Return true if this type descriptor is defined in a different
1322 // package.  If this returns true it sets *PACKAGE to the package.
1323
1324 bool
1325 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1326                                         const Package** package)
1327 {
1328   if (nt != NULL)
1329     {
1330       if (nt->named_object()->package() != NULL)
1331         {
1332           // This is a named type defined in a different package.  The
1333           // type descriptor should be defined in that package.
1334           *package = nt->named_object()->package();
1335           return true;
1336         }
1337     }
1338   else
1339     {
1340       if (this->points_to() != NULL
1341           && this->points_to()->named_type() != NULL
1342           && this->points_to()->named_type()->named_object()->package() != NULL)
1343         {
1344           // This is an unnamed pointer to a named type defined in a
1345           // different package.  The descriptor should be defined in
1346           // that package.
1347           *package = this->points_to()->named_type()->named_object()->package();
1348           return true;
1349         }
1350     }
1351   return false;
1352 }
1353
1354 // Return a composite literal for a type descriptor.
1355
1356 Expression*
1357 Type::type_descriptor(Gogo* gogo, Type* type)
1358 {
1359   return type->do_type_descriptor(gogo, NULL);
1360 }
1361
1362 // Return a composite literal for a type descriptor with a name.
1363
1364 Expression*
1365 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1366 {
1367   go_assert(name != NULL && type->named_type() != name);
1368   return type->do_type_descriptor(gogo, name);
1369 }
1370
1371 // Make a builtin struct type from a list of fields.  The fields are
1372 // pairs of a name and a type.
1373
1374 Struct_type*
1375 Type::make_builtin_struct_type(int nfields, ...)
1376 {
1377   va_list ap;
1378   va_start(ap, nfields);
1379
1380   Location bloc = Linemap::predeclared_location();
1381   Struct_field_list* sfl = new Struct_field_list();
1382   for (int i = 0; i < nfields; i++)
1383     {
1384       const char* field_name = va_arg(ap, const char *);
1385       Type* type = va_arg(ap, Type*);
1386       sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1387     }
1388
1389   va_end(ap);
1390
1391   return Type::make_struct_type(sfl, bloc);
1392 }
1393
1394 // A list of builtin named types.
1395
1396 std::vector<Named_type*> Type::named_builtin_types;
1397
1398 // Make a builtin named type.
1399
1400 Named_type*
1401 Type::make_builtin_named_type(const char* name, Type* type)
1402 {
1403   Location bloc = Linemap::predeclared_location();
1404   Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1405   Named_type* ret = no->type_value();
1406   Type::named_builtin_types.push_back(ret);
1407   return ret;
1408 }
1409
1410 // Convert the named builtin types.
1411
1412 void
1413 Type::convert_builtin_named_types(Gogo* gogo)
1414 {
1415   for (std::vector<Named_type*>::const_iterator p =
1416          Type::named_builtin_types.begin();
1417        p != Type::named_builtin_types.end();
1418        ++p)
1419     {
1420       bool r = (*p)->verify();
1421       go_assert(r);
1422       (*p)->convert(gogo);
1423     }
1424 }
1425
1426 // Return the type of a type descriptor.  We should really tie this to
1427 // runtime.Type rather than copying it.  This must match commonType in
1428 // libgo/go/runtime/type.go.
1429
1430 Type*
1431 Type::make_type_descriptor_type()
1432 {
1433   static Type* ret;
1434   if (ret == NULL)
1435     {
1436       Location bloc = Linemap::predeclared_location();
1437
1438       Type* uint8_type = Type::lookup_integer_type("uint8");
1439       Type* uint32_type = Type::lookup_integer_type("uint32");
1440       Type* uintptr_type = Type::lookup_integer_type("uintptr");
1441       Type* string_type = Type::lookup_string_type();
1442       Type* pointer_string_type = Type::make_pointer_type(string_type);
1443
1444       // This is an unnamed version of unsafe.Pointer.  Perhaps we
1445       // should use the named version instead, although that would
1446       // require us to create the unsafe package if it has not been
1447       // imported.  It probably doesn't matter.
1448       Type* void_type = Type::make_void_type();
1449       Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1450
1451       // Forward declaration for the type descriptor type.
1452       Named_object* named_type_descriptor_type =
1453         Named_object::make_type_declaration("commonType", NULL, bloc);
1454       Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1455       Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1456
1457       // The type of a method on a concrete type.
1458       Struct_type* method_type =
1459         Type::make_builtin_struct_type(5,
1460                                        "name", pointer_string_type,
1461                                        "pkgPath", pointer_string_type,
1462                                        "mtyp", pointer_type_descriptor_type,
1463                                        "typ", pointer_type_descriptor_type,
1464                                        "tfn", unsafe_pointer_type);
1465       Named_type* named_method_type =
1466         Type::make_builtin_named_type("method", method_type);
1467
1468       // Information for types with a name or methods.
1469       Type* slice_named_method_type =
1470         Type::make_array_type(named_method_type, NULL);
1471       Struct_type* uncommon_type =
1472         Type::make_builtin_struct_type(3,
1473                                        "name", pointer_string_type,
1474                                        "pkgPath", pointer_string_type,
1475                                        "methods", slice_named_method_type);
1476       Named_type* named_uncommon_type =
1477         Type::make_builtin_named_type("uncommonType", uncommon_type);
1478
1479       Type* pointer_uncommon_type =
1480         Type::make_pointer_type(named_uncommon_type);
1481
1482       // The type descriptor type.
1483
1484       Typed_identifier_list* params = new Typed_identifier_list();
1485       params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1486       params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1487
1488       Typed_identifier_list* results = new Typed_identifier_list();
1489       results->push_back(Typed_identifier("", uintptr_type, bloc));
1490
1491       Type* hashfn_type = Type::make_function_type(NULL, params, results, bloc);
1492
1493       params = new Typed_identifier_list();
1494       params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1495       params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1496       params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1497
1498       results = new Typed_identifier_list();
1499       results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1500
1501       Type* equalfn_type = Type::make_function_type(NULL, params, results,
1502                                                     bloc);
1503
1504       Struct_type* type_descriptor_type =
1505         Type::make_builtin_struct_type(10,
1506                                        "Kind", uint8_type,
1507                                        "align", uint8_type,
1508                                        "fieldAlign", uint8_type,
1509                                        "size", uintptr_type,
1510                                        "hash", uint32_type,
1511                                        "hashfn", hashfn_type,
1512                                        "equalfn", equalfn_type,
1513                                        "string", pointer_string_type,
1514                                        "", pointer_uncommon_type,
1515                                        "ptrToThis",
1516                                        pointer_type_descriptor_type);
1517
1518       Named_type* named = Type::make_builtin_named_type("commonType",
1519                                                         type_descriptor_type);
1520
1521       named_type_descriptor_type->set_type_value(named);
1522
1523       ret = named;
1524     }
1525
1526   return ret;
1527 }
1528
1529 // Make the type of a pointer to a type descriptor as represented in
1530 // Go.
1531
1532 Type*
1533 Type::make_type_descriptor_ptr_type()
1534 {
1535   static Type* ret;
1536   if (ret == NULL)
1537     ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1538   return ret;
1539 }
1540
1541 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1542 // hash code for this type and which compare whether two values of
1543 // this type are equal.  If NAME is not NULL it is the name of this
1544 // type.  HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1545 // functions, for convenience; they may be NULL.
1546
1547 void
1548 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1549                      Function_type* equal_fntype, Named_object** hash_fn,
1550                      Named_object** equal_fn)
1551 {
1552   if (hash_fntype == NULL || equal_fntype == NULL)
1553     {
1554       Location bloc = Linemap::predeclared_location();
1555
1556       Type* uintptr_type = Type::lookup_integer_type("uintptr");
1557       Type* void_type = Type::make_void_type();
1558       Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1559
1560       if (hash_fntype == NULL)
1561         {
1562           Typed_identifier_list* params = new Typed_identifier_list();
1563           params->push_back(Typed_identifier("key", unsafe_pointer_type,
1564                                              bloc));
1565           params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1566
1567           Typed_identifier_list* results = new Typed_identifier_list();
1568           results->push_back(Typed_identifier("", uintptr_type, bloc));
1569
1570           hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1571         }
1572       if (equal_fntype == NULL)
1573         {
1574           Typed_identifier_list* params = new Typed_identifier_list();
1575           params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1576                                              bloc));
1577           params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1578                                              bloc));
1579           params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1580
1581           Typed_identifier_list* results = new Typed_identifier_list();
1582           results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1583                                               bloc));
1584
1585           equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1586         }
1587     }
1588
1589   const char* hash_fnname;
1590   const char* equal_fnname;
1591   if (this->compare_is_identity(gogo))
1592     {
1593       hash_fnname = "__go_type_hash_identity";
1594       equal_fnname = "__go_type_equal_identity";
1595     }
1596   else if (!this->is_comparable())
1597     {
1598       hash_fnname = "__go_type_hash_error";
1599       equal_fnname = "__go_type_equal_error";
1600     }
1601   else
1602     {
1603       switch (this->base()->classification())
1604         {
1605         case Type::TYPE_ERROR:
1606         case Type::TYPE_VOID:
1607         case Type::TYPE_NIL:
1608         case Type::TYPE_FUNCTION:
1609         case Type::TYPE_MAP:
1610           // For these types is_comparable should have returned false.
1611           go_unreachable();
1612
1613         case Type::TYPE_BOOLEAN:
1614         case Type::TYPE_INTEGER:
1615         case Type::TYPE_POINTER:
1616         case Type::TYPE_CHANNEL:
1617           // For these types compare_is_identity should have returned true.
1618           go_unreachable();
1619
1620         case Type::TYPE_FLOAT:
1621           hash_fnname = "__go_type_hash_float";
1622           equal_fnname = "__go_type_equal_float";
1623           break;
1624
1625         case Type::TYPE_COMPLEX:
1626           hash_fnname = "__go_type_hash_complex";
1627           equal_fnname = "__go_type_equal_complex";
1628           break;
1629
1630         case Type::TYPE_STRING:
1631           hash_fnname = "__go_type_hash_string";
1632           equal_fnname = "__go_type_equal_string";
1633           break;
1634
1635         case Type::TYPE_STRUCT:
1636           {
1637             // This is a struct which can not be compared using a
1638             // simple identity function.  We need to build a function
1639             // for comparison.
1640             this->specific_type_functions(gogo, name, hash_fntype,
1641                                           equal_fntype, hash_fn, equal_fn);
1642             return;
1643           }
1644
1645         case Type::TYPE_ARRAY:
1646           if (this->is_slice_type())
1647             {
1648               // Type::is_compatible_for_comparison should have
1649               // returned false.
1650               go_unreachable();
1651             }
1652           else
1653             {
1654               // This is an array which can not be compared using a
1655               // simple identity function.  We need to build a
1656               // function for comparison.
1657               this->specific_type_functions(gogo, name, hash_fntype,
1658                                             equal_fntype, hash_fn, equal_fn);
1659               return;
1660             }
1661           break;
1662
1663         case Type::TYPE_INTERFACE:
1664           if (this->interface_type()->is_empty())
1665             {
1666               hash_fnname = "__go_type_hash_empty_interface";
1667               equal_fnname = "__go_type_equal_empty_interface";
1668             }
1669           else
1670             {
1671               hash_fnname = "__go_type_hash_interface";
1672               equal_fnname = "__go_type_equal_interface";
1673             }
1674           break;
1675
1676         case Type::TYPE_NAMED:
1677         case Type::TYPE_FORWARD:
1678           go_unreachable();
1679
1680         default:
1681           go_unreachable();
1682         }
1683     }
1684
1685
1686   Location bloc = Linemap::predeclared_location();
1687   *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1688                                                      hash_fntype, bloc);
1689   (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1690   *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1691                                                       equal_fntype, bloc);
1692   (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1693 }
1694
1695 // A hash table mapping types to the specific hash functions.
1696
1697 Type::Type_functions Type::type_functions_table;
1698
1699 // Handle a type function which is specific to a type: a struct or
1700 // array which can not use an identity comparison.
1701
1702 void
1703 Type::specific_type_functions(Gogo* gogo, Named_type* name,
1704                               Function_type* hash_fntype,
1705                               Function_type* equal_fntype,
1706                               Named_object** hash_fn,
1707                               Named_object** equal_fn)
1708 {
1709   Hash_equal_fn fnull(NULL, NULL);
1710   std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1711   std::pair<Type_functions::iterator, bool> ins =
1712     Type::type_functions_table.insert(val);
1713   if (!ins.second)
1714     {
1715       // We already have functions for this type
1716       *hash_fn = ins.first->second.first;
1717       *equal_fn = ins.first->second.second;
1718       return;
1719     }
1720
1721   std::string base_name;
1722   if (name == NULL)
1723     {
1724       // Mangled names can have '.' if they happen to refer to named
1725       // types in some way.  That's fine if this is simply a named
1726       // type, but otherwise it will confuse the code that builds
1727       // function identifiers.  Remove '.' when necessary.
1728       base_name = this->mangled_name(gogo);
1729       size_t i;
1730       while ((i = base_name.find('.')) != std::string::npos)
1731         base_name[i] = '$';
1732       base_name = gogo->pack_hidden_name(base_name, false);
1733     }
1734   else
1735     {
1736       // This name is already hidden or not as appropriate.
1737       base_name = name->name();
1738       const Named_object* in_function = name->in_function();
1739       if (in_function != NULL)
1740         base_name += '$' + in_function->name();
1741     }
1742   std::string hash_name = base_name + "$hash";
1743   std::string equal_name = base_name + "$equal";
1744
1745   Location bloc = Linemap::predeclared_location();
1746
1747   const Package* package = NULL;
1748   bool is_defined_elsewhere =
1749     this->type_descriptor_defined_elsewhere(name, &package);
1750   if (is_defined_elsewhere)
1751     {
1752       *hash_fn = Named_object::make_function_declaration(hash_name, package,
1753                                                          hash_fntype, bloc);
1754       *equal_fn = Named_object::make_function_declaration(equal_name, package,
1755                                                           equal_fntype, bloc);
1756     }
1757   else
1758     {
1759       *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
1760       *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
1761                                                  bloc);
1762     }
1763
1764   ins.first->second.first = *hash_fn;
1765   ins.first->second.second = *equal_fn;
1766
1767   if (!is_defined_elsewhere)
1768     {
1769       if (gogo->in_global_scope())
1770         this->write_specific_type_functions(gogo, name, hash_name, hash_fntype,
1771                                             equal_name, equal_fntype);
1772       else
1773         gogo->queue_specific_type_function(this, name, hash_name, hash_fntype,
1774                                            equal_name, equal_fntype);
1775     }
1776 }
1777
1778 // Write the hash and equality functions for a type which needs to be
1779 // written specially.
1780
1781 void
1782 Type::write_specific_type_functions(Gogo* gogo, Named_type* name,
1783                                     const std::string& hash_name,
1784                                     Function_type* hash_fntype,
1785                                     const std::string& equal_name,
1786                                     Function_type* equal_fntype)
1787 {
1788   Location bloc = Linemap::predeclared_location();
1789
1790   Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
1791                                                bloc);
1792   gogo->start_block(bloc);
1793
1794   if (this->struct_type() != NULL)
1795     this->struct_type()->write_hash_function(gogo, name, hash_fntype,
1796                                              equal_fntype);
1797   else if (this->array_type() != NULL)
1798     this->array_type()->write_hash_function(gogo, name, hash_fntype,
1799                                             equal_fntype);
1800   else
1801     go_unreachable();
1802
1803   Block* b = gogo->finish_block(bloc);
1804   gogo->add_block(b, bloc);
1805   gogo->lower_block(hash_fn, b);
1806   gogo->finish_function(bloc);
1807
1808   Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
1809                                                 false, bloc);
1810   gogo->start_block(bloc);
1811
1812   if (this->struct_type() != NULL)
1813     this->struct_type()->write_equal_function(gogo, name);
1814   else if (this->array_type() != NULL)
1815     this->array_type()->write_equal_function(gogo, name);
1816   else
1817     go_unreachable();
1818
1819   b = gogo->finish_block(bloc);
1820   gogo->add_block(b, bloc);
1821   gogo->lower_block(equal_fn, b);
1822   gogo->finish_function(bloc);
1823 }
1824
1825 // Return a composite literal for the type descriptor for a plain type
1826 // of kind RUNTIME_TYPE_KIND named NAME.
1827
1828 Expression*
1829 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
1830                                   Named_type* name, const Methods* methods,
1831                                   bool only_value_methods)
1832 {
1833   Location bloc = Linemap::predeclared_location();
1834
1835   Type* td_type = Type::make_type_descriptor_type();
1836   const Struct_field_list* fields = td_type->struct_type()->fields();
1837
1838   Expression_list* vals = new Expression_list();
1839   vals->reserve(9);
1840
1841   if (!this->has_pointer())
1842     runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
1843   Struct_field_list::const_iterator p = fields->begin();
1844   go_assert(p->is_field_name("Kind"));
1845   mpz_t iv;
1846   mpz_init_set_ui(iv, runtime_type_kind);
1847   vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1848
1849   ++p;
1850   go_assert(p->is_field_name("align"));
1851   Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT;
1852   vals->push_back(Expression::make_type_info(this, type_info));
1853
1854   ++p;
1855   go_assert(p->is_field_name("fieldAlign"));
1856   type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
1857   vals->push_back(Expression::make_type_info(this, type_info));
1858
1859   ++p;
1860   go_assert(p->is_field_name("size"));
1861   type_info = Expression::TYPE_INFO_SIZE;
1862   vals->push_back(Expression::make_type_info(this, type_info));
1863
1864   ++p;
1865   go_assert(p->is_field_name("hash"));
1866   unsigned int h;
1867   if (name != NULL)
1868     h = name->hash_for_method(gogo);
1869   else
1870     h = this->hash_for_method(gogo);
1871   mpz_set_ui(iv, h);
1872   vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1873
1874   ++p;
1875   go_assert(p->is_field_name("hashfn"));
1876   Function_type* hash_fntype = p->type()->function_type();
1877
1878   ++p;
1879   go_assert(p->is_field_name("equalfn"));
1880   Function_type* equal_fntype = p->type()->function_type();
1881
1882   Named_object* hash_fn;
1883   Named_object* equal_fn;
1884   this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
1885                        &equal_fn);
1886   vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
1887   vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
1888
1889   ++p;
1890   go_assert(p->is_field_name("string"));
1891   Expression* s = Expression::make_string((name != NULL
1892                                            ? name->reflection(gogo)
1893                                            : this->reflection(gogo)),
1894                                           bloc);
1895   vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1896
1897   ++p;
1898   go_assert(p->is_field_name("uncommonType"));
1899   if (name == NULL && methods == NULL)
1900     vals->push_back(Expression::make_nil(bloc));
1901   else
1902     {
1903       if (methods == NULL)
1904         methods = name->methods();
1905       vals->push_back(this->uncommon_type_constructor(gogo,
1906                                                       p->type()->deref(),
1907                                                       name, methods,
1908                                                       only_value_methods));
1909     }
1910
1911   ++p;
1912   go_assert(p->is_field_name("ptrToThis"));
1913   if (name == NULL)
1914     vals->push_back(Expression::make_nil(bloc));
1915   else
1916     {
1917       Type* pt = Type::make_pointer_type(name);
1918       vals->push_back(Expression::make_type_descriptor(pt, bloc));
1919     }
1920
1921   ++p;
1922   go_assert(p == fields->end());
1923
1924   mpz_clear(iv);
1925
1926   return Expression::make_struct_composite_literal(td_type, vals, bloc);
1927 }
1928
1929 // Return a composite literal for the uncommon type information for
1930 // this type.  UNCOMMON_STRUCT_TYPE is the type of the uncommon type
1931 // struct.  If name is not NULL, it is the name of the type.  If
1932 // METHODS is not NULL, it is the list of methods.  ONLY_VALUE_METHODS
1933 // is true if only value methods should be included.  At least one of
1934 // NAME and METHODS must not be NULL.
1935
1936 Expression*
1937 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
1938                                 Named_type* name, const Methods* methods,
1939                                 bool only_value_methods) const
1940 {
1941   Location bloc = Linemap::predeclared_location();
1942
1943   const Struct_field_list* fields = uncommon_type->struct_type()->fields();
1944
1945   Expression_list* vals = new Expression_list();
1946   vals->reserve(3);
1947
1948   Struct_field_list::const_iterator p = fields->begin();
1949   go_assert(p->is_field_name("name"));
1950
1951   ++p;
1952   go_assert(p->is_field_name("pkgPath"));
1953
1954   if (name == NULL)
1955     {
1956       vals->push_back(Expression::make_nil(bloc));
1957       vals->push_back(Expression::make_nil(bloc));
1958     }
1959   else
1960     {
1961       Named_object* no = name->named_object();
1962       std::string n = Gogo::unpack_hidden_name(no->name());
1963       Expression* s = Expression::make_string(n, bloc);
1964       vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1965
1966       if (name->is_builtin())
1967         vals->push_back(Expression::make_nil(bloc));
1968       else
1969         {
1970           const Package* package = no->package();
1971           const std::string& unique_prefix(package == NULL
1972                                            ? gogo->unique_prefix()
1973                                            : package->unique_prefix());
1974           const std::string& package_name(package == NULL
1975                                           ? gogo->package_name()
1976                                           : package->name());
1977           n.assign(unique_prefix);
1978           n.append(1, '.');
1979           n.append(package_name);
1980           if (name->in_function() != NULL)
1981             {
1982               n.append(1, '.');
1983               n.append(Gogo::unpack_hidden_name(name->in_function()->name()));
1984             }
1985           s = Expression::make_string(n, bloc);
1986           vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1987         }
1988     }
1989
1990   ++p;
1991   go_assert(p->is_field_name("methods"));
1992   vals->push_back(this->methods_constructor(gogo, p->type(), methods,
1993                                             only_value_methods));
1994
1995   ++p;
1996   go_assert(p == fields->end());
1997
1998   Expression* r = Expression::make_struct_composite_literal(uncommon_type,
1999                                                             vals, bloc);
2000   return Expression::make_unary(OPERATOR_AND, r, bloc);
2001 }
2002
2003 // Sort methods by name.
2004
2005 class Sort_methods
2006 {
2007  public:
2008   bool
2009   operator()(const std::pair<std::string, const Method*>& m1,
2010              const std::pair<std::string, const Method*>& m2) const
2011   { return m1.first < m2.first; }
2012 };
2013
2014 // Return a composite literal for the type method table for this type.
2015 // METHODS_TYPE is the type of the table, and is a slice type.
2016 // METHODS is the list of methods.  If ONLY_VALUE_METHODS is true,
2017 // then only value methods are used.
2018
2019 Expression*
2020 Type::methods_constructor(Gogo* gogo, Type* methods_type,
2021                           const Methods* methods,
2022                           bool only_value_methods) const
2023 {
2024   Location bloc = Linemap::predeclared_location();
2025
2026   std::vector<std::pair<std::string, const Method*> > smethods;
2027   if (methods != NULL)
2028     {
2029       smethods.reserve(methods->count());
2030       for (Methods::const_iterator p = methods->begin();
2031            p != methods->end();
2032            ++p)
2033         {
2034           if (p->second->is_ambiguous())
2035             continue;
2036           if (only_value_methods && !p->second->is_value_method())
2037             continue;
2038           smethods.push_back(std::make_pair(p->first, p->second));
2039         }
2040     }
2041
2042   if (smethods.empty())
2043     return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
2044
2045   std::sort(smethods.begin(), smethods.end(), Sort_methods());
2046
2047   Type* method_type = methods_type->array_type()->element_type();
2048
2049   Expression_list* vals = new Expression_list();
2050   vals->reserve(smethods.size());
2051   for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
2052          = smethods.begin();
2053        p != smethods.end();
2054        ++p)
2055     vals->push_back(this->method_constructor(gogo, method_type, p->first,
2056                                              p->second, only_value_methods));
2057
2058   return Expression::make_slice_composite_literal(methods_type, vals, bloc);
2059 }
2060
2061 // Return a composite literal for a single method.  METHOD_TYPE is the
2062 // type of the entry.  METHOD_NAME is the name of the method and M is
2063 // the method information.
2064
2065 Expression*
2066 Type::method_constructor(Gogo*, Type* method_type,
2067                          const std::string& method_name,
2068                          const Method* m,
2069                          bool only_value_methods) const
2070 {
2071   Location bloc = Linemap::predeclared_location();
2072
2073   const Struct_field_list* fields = method_type->struct_type()->fields();
2074
2075   Expression_list* vals = new Expression_list();
2076   vals->reserve(5);
2077
2078   Struct_field_list::const_iterator p = fields->begin();
2079   go_assert(p->is_field_name("name"));
2080   const std::string n = Gogo::unpack_hidden_name(method_name);
2081   Expression* s = Expression::make_string(n, bloc);
2082   vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2083
2084   ++p;
2085   go_assert(p->is_field_name("pkgPath"));
2086   if (!Gogo::is_hidden_name(method_name))
2087     vals->push_back(Expression::make_nil(bloc));
2088   else
2089     {
2090       s = Expression::make_string(Gogo::hidden_name_prefix(method_name), bloc);
2091       vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2092     }
2093
2094   Named_object* no = (m->needs_stub_method()
2095                       ? m->stub_object()
2096                       : m->named_object());
2097
2098   Function_type* mtype;
2099   if (no->is_function())
2100     mtype = no->func_value()->type();
2101   else
2102     mtype = no->func_declaration_value()->type();
2103   go_assert(mtype->is_method());
2104   Type* nonmethod_type = mtype->copy_without_receiver();
2105
2106   ++p;
2107   go_assert(p->is_field_name("mtyp"));
2108   vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
2109
2110   ++p;
2111   go_assert(p->is_field_name("typ"));
2112   if (!only_value_methods && m->is_value_method())
2113     {
2114       // This is a value method on a pointer type.  Change the type of
2115       // the method to use a pointer receiver.  The implementation
2116       // always uses a pointer receiver anyhow.
2117       Type* rtype = mtype->receiver()->type();
2118       Type* prtype = Type::make_pointer_type(rtype);
2119       Typed_identifier* receiver =
2120         new Typed_identifier(mtype->receiver()->name(), prtype,
2121                              mtype->receiver()->location());
2122       mtype = Type::make_function_type(receiver,
2123                                        (mtype->parameters() == NULL
2124                                         ? NULL
2125                                         : mtype->parameters()->copy()),
2126                                        (mtype->results() == NULL
2127                                         ? NULL
2128                                         : mtype->results()->copy()),
2129                                        mtype->location());
2130     }
2131   vals->push_back(Expression::make_type_descriptor(mtype, bloc));
2132
2133   ++p;
2134   go_assert(p->is_field_name("tfn"));
2135   vals->push_back(Expression::make_func_reference(no, NULL, bloc));
2136
2137   ++p;
2138   go_assert(p == fields->end());
2139
2140   return Expression::make_struct_composite_literal(method_type, vals, bloc);
2141 }
2142
2143 // Return a composite literal for the type descriptor of a plain type.
2144 // RUNTIME_TYPE_KIND is the value of the kind field.  If NAME is not
2145 // NULL, it is the name to use as well as the list of methods.
2146
2147 Expression*
2148 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
2149                             Named_type* name)
2150 {
2151   return this->type_descriptor_constructor(gogo, runtime_type_kind,
2152                                            name, NULL, true);
2153 }
2154
2155 // Return the type reflection string for this type.
2156
2157 std::string
2158 Type::reflection(Gogo* gogo) const
2159 {
2160   std::string ret;
2161
2162   // The do_reflection virtual function should set RET to the
2163   // reflection string.
2164   this->do_reflection(gogo, &ret);
2165
2166   return ret;
2167 }
2168
2169 // Return a mangled name for the type.
2170
2171 std::string
2172 Type::mangled_name(Gogo* gogo) const
2173 {
2174   std::string ret;
2175
2176   // The do_mangled_name virtual function should set RET to the
2177   // mangled name.  For a composite type it should append a code for
2178   // the composition and then call do_mangled_name on the components.
2179   this->do_mangled_name(gogo, &ret);
2180
2181   return ret;
2182 }
2183
2184 // Return whether the backend size of the type is known.
2185
2186 bool
2187 Type::is_backend_type_size_known(Gogo* gogo)
2188 {
2189   switch (this->classification_)
2190     {
2191     case TYPE_ERROR:
2192     case TYPE_VOID:
2193     case TYPE_BOOLEAN:
2194     case TYPE_INTEGER:
2195     case TYPE_FLOAT:
2196     case TYPE_COMPLEX:
2197     case TYPE_STRING:
2198     case TYPE_FUNCTION:
2199     case TYPE_POINTER:
2200     case TYPE_NIL:
2201     case TYPE_MAP:
2202     case TYPE_CHANNEL:
2203     case TYPE_INTERFACE:
2204       return true;
2205
2206     case TYPE_STRUCT:
2207       {
2208         const Struct_field_list* fields = this->struct_type()->fields();
2209         for (Struct_field_list::const_iterator pf = fields->begin();
2210              pf != fields->end();
2211              ++pf)
2212           if (!pf->type()->is_backend_type_size_known(gogo))
2213             return false;
2214         return true;
2215       }
2216
2217     case TYPE_ARRAY:
2218       {
2219         const Array_type* at = this->array_type();
2220         if (at->length() == NULL)
2221           return true;
2222         else
2223           {
2224             mpz_t ival;
2225             mpz_init(ival);
2226             Type* dummy;
2227             bool length_known = at->length()->integer_constant_value(true,
2228                                                                      ival,
2229                                                                      &dummy);
2230             mpz_clear(ival);
2231             if (!length_known)
2232               return false;
2233             return at->element_type()->is_backend_type_size_known(gogo);
2234           }
2235       }
2236
2237     case TYPE_NAMED:
2238       // Begin converting this type to the backend representation.
2239       // This will create a placeholder if necessary.
2240       this->get_backend(gogo);
2241       return this->named_type()->is_named_backend_type_size_known();
2242
2243     case TYPE_FORWARD:
2244       {
2245         Forward_declaration_type* fdt = this->forward_declaration_type();
2246         return fdt->real_type()->is_backend_type_size_known(gogo);
2247       }
2248
2249     case TYPE_SINK:
2250     case TYPE_CALL_MULTIPLE_RESULT:
2251       go_unreachable();
2252
2253     default:
2254       go_unreachable();
2255     }
2256 }
2257
2258 // If the size of the type can be determined, set *PSIZE to the size
2259 // in bytes and return true.  Otherwise, return false.  This queries
2260 // the backend.
2261
2262 bool
2263 Type::backend_type_size(Gogo* gogo, unsigned int *psize)
2264 {
2265   if (!this->is_backend_type_size_known(gogo))
2266     return false;
2267   Btype* bt = this->get_backend_placeholder(gogo);
2268   size_t size = gogo->backend()->type_size(bt);
2269   *psize = static_cast<unsigned int>(size);
2270   if (*psize != size)
2271     return false;
2272   return true;
2273 }
2274
2275 // If the alignment of the type can be determined, set *PALIGN to
2276 // the alignment in bytes and return true.  Otherwise, return false.
2277
2278 bool
2279 Type::backend_type_align(Gogo* gogo, unsigned int *palign)
2280 {
2281   if (!this->is_backend_type_size_known(gogo))
2282     return false;
2283   Btype* bt = this->get_backend_placeholder(gogo);
2284   size_t align = gogo->backend()->type_alignment(bt);
2285   *palign = static_cast<unsigned int>(align);
2286   if (*palign != align)
2287     return false;
2288   return true;
2289 }
2290
2291 // Like backend_type_align, but return the alignment when used as a
2292 // field.
2293
2294 bool
2295 Type::backend_type_field_align(Gogo* gogo, unsigned int *palign)
2296 {
2297   if (!this->is_backend_type_size_known(gogo))
2298     return false;
2299   Btype* bt = this->get_backend_placeholder(gogo);
2300   size_t a = gogo->backend()->type_field_alignment(bt);
2301   *palign = static_cast<unsigned int>(a);
2302   if (*palign != a)
2303     return false;
2304   return true;
2305 }
2306
2307 // Default function to export a type.
2308
2309 void
2310 Type::do_export(Export*) const
2311 {
2312   go_unreachable();
2313 }
2314
2315 // Import a type.
2316
2317 Type*
2318 Type::import_type(Import* imp)
2319 {
2320   if (imp->match_c_string("("))
2321     return Function_type::do_import(imp);
2322   else if (imp->match_c_string("*"))
2323     return Pointer_type::do_import(imp);
2324   else if (imp->match_c_string("struct "))
2325     return Struct_type::do_import(imp);
2326   else if (imp->match_c_string("["))
2327     return Array_type::do_import(imp);
2328   else if (imp->match_c_string("map "))
2329     return Map_type::do_import(imp);
2330   else if (imp->match_c_string("chan "))
2331     return Channel_type::do_import(imp);
2332   else if (imp->match_c_string("interface"))
2333     return Interface_type::do_import(imp);
2334   else
2335     {
2336       error_at(imp->location(), "import error: expected type");
2337       return Type::make_error_type();
2338     }
2339 }
2340
2341 // A type used to indicate a parsing error.  This exists to simplify
2342 // later error detection.
2343
2344 class Error_type : public Type
2345 {
2346  public:
2347   Error_type()
2348     : Type(TYPE_ERROR)
2349   { }
2350
2351  protected:
2352   bool
2353   do_compare_is_identity(Gogo*) const
2354   { return false; }
2355
2356   Btype*
2357   do_get_backend(Gogo* gogo)
2358   { return gogo->backend()->error_type(); }
2359
2360   Expression*
2361   do_type_descriptor(Gogo*, Named_type*)
2362   { return Expression::make_error(Linemap::predeclared_location()); }
2363
2364   void
2365   do_reflection(Gogo*, std::string*) const
2366   { go_assert(saw_errors()); }
2367
2368   void
2369   do_mangled_name(Gogo*, std::string* ret) const
2370   { ret->push_back('E'); }
2371 };
2372
2373 Type*
2374 Type::make_error_type()
2375 {
2376   static Error_type singleton_error_type;
2377   return &singleton_error_type;
2378 }
2379
2380 // The void type.
2381
2382 class Void_type : public Type
2383 {
2384  public:
2385   Void_type()
2386     : Type(TYPE_VOID)
2387   { }
2388
2389  protected:
2390   bool
2391   do_compare_is_identity(Gogo*) const
2392   { return false; }
2393
2394   Btype*
2395   do_get_backend(Gogo* gogo)
2396   { return gogo->backend()->void_type(); }
2397
2398   Expression*
2399   do_type_descriptor(Gogo*, Named_type*)
2400   { go_unreachable(); }
2401
2402   void
2403   do_reflection(Gogo*, std::string*) const
2404   { }
2405
2406   void
2407   do_mangled_name(Gogo*, std::string* ret) const
2408   { ret->push_back('v'); }
2409 };
2410
2411 Type*
2412 Type::make_void_type()
2413 {
2414   static Void_type singleton_void_type;
2415   return &singleton_void_type;
2416 }
2417
2418 // The boolean type.
2419
2420 class Boolean_type : public Type
2421 {
2422  public:
2423   Boolean_type()
2424     : Type(TYPE_BOOLEAN)
2425   { }
2426
2427  protected:
2428   bool
2429   do_compare_is_identity(Gogo*) const
2430   { return true; }
2431
2432   Btype*
2433   do_get_backend(Gogo* gogo)
2434   { return gogo->backend()->bool_type(); }
2435
2436   Expression*
2437   do_type_descriptor(Gogo*, Named_type* name);
2438
2439   // We should not be asked for the reflection string of a basic type.
2440   void
2441   do_reflection(Gogo*, std::string* ret) const
2442   { ret->append("bool"); }
2443
2444   void
2445   do_mangled_name(Gogo*, std::string* ret) const
2446   { ret->push_back('b'); }
2447 };
2448
2449 // Make the type descriptor.
2450
2451 Expression*
2452 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2453 {
2454   if (name != NULL)
2455     return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
2456   else
2457     {
2458       Named_object* no = gogo->lookup_global("bool");
2459       go_assert(no != NULL);
2460       return Type::type_descriptor(gogo, no->type_value());
2461     }
2462 }
2463
2464 Type*
2465 Type::make_boolean_type()
2466 {
2467   static Boolean_type boolean_type;
2468   return &boolean_type;
2469 }
2470
2471 // The named type "bool".
2472
2473 static Named_type* named_bool_type;
2474
2475 // Get the named type "bool".
2476
2477 Named_type*
2478 Type::lookup_bool_type()
2479 {
2480   return named_bool_type;
2481 }
2482
2483 // Make the named type "bool".
2484
2485 Named_type*
2486 Type::make_named_bool_type()
2487 {
2488   Type* bool_type = Type::make_boolean_type();
2489   Named_object* named_object =
2490     Named_object::make_type("bool", NULL, bool_type,
2491                             Linemap::predeclared_location());
2492   Named_type* named_type = named_object->type_value();
2493   named_bool_type = named_type;
2494   return named_type;
2495 }
2496
2497 // Class Integer_type.
2498
2499 Integer_type::Named_integer_types Integer_type::named_integer_types;
2500
2501 // Create a new integer type.  Non-abstract integer types always have
2502 // names.
2503
2504 Named_type*
2505 Integer_type::create_integer_type(const char* name, bool is_unsigned,
2506                                   int bits, int runtime_type_kind)
2507 {
2508   Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
2509                                                 runtime_type_kind);
2510   std::string sname(name);
2511   Named_object* named_object =
2512     Named_object::make_type(sname, NULL, integer_type,
2513                             Linemap::predeclared_location());
2514   Named_type* named_type = named_object->type_value();
2515   std::pair<Named_integer_types::iterator, bool> ins =
2516     Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
2517   go_assert(ins.second);
2518   return named_type;
2519 }
2520
2521 // Look up an existing integer type.
2522
2523 Named_type*
2524 Integer_type::lookup_integer_type(const char* name)
2525 {
2526   Named_integer_types::const_iterator p =
2527     Integer_type::named_integer_types.find(name);
2528   go_assert(p != Integer_type::named_integer_types.end());
2529   return p->second;
2530 }
2531
2532 // Create a new abstract integer type.
2533
2534 Integer_type*
2535 Integer_type::create_abstract_integer_type()
2536 {
2537   static Integer_type* abstract_type;
2538   if (abstract_type == NULL)
2539     abstract_type = new Integer_type(true, false, INT_TYPE_SIZE,
2540                                      RUNTIME_TYPE_KIND_INT);
2541   return abstract_type;
2542 }
2543
2544 // Create a new abstract character type.
2545
2546 Integer_type*
2547 Integer_type::create_abstract_character_type()
2548 {
2549   static Integer_type* abstract_type;
2550   if (abstract_type == NULL)
2551     {
2552       abstract_type = new Integer_type(true, false, 32,
2553                                        RUNTIME_TYPE_KIND_INT32);
2554       abstract_type->set_is_rune();
2555     }
2556   return abstract_type;
2557 }
2558
2559 // Integer type compatibility.
2560
2561 bool
2562 Integer_type::is_identical(const Integer_type* t) const
2563 {
2564   if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
2565     return false;
2566   return this->is_abstract_ == t->is_abstract_;
2567 }
2568
2569 // Hash code.
2570
2571 unsigned int
2572 Integer_type::do_hash_for_method(Gogo*) const
2573 {
2574   return ((this->bits_ << 4)
2575           + ((this->is_unsigned_ ? 1 : 0) << 8)
2576           + ((this->is_abstract_ ? 1 : 0) << 9));
2577 }
2578
2579 // Convert an Integer_type to the backend representation.
2580
2581 Btype*
2582 Integer_type::do_get_backend(Gogo* gogo)
2583 {
2584   if (this->is_abstract_)
2585     {
2586       go_assert(saw_errors());
2587       return gogo->backend()->error_type();
2588     }
2589   return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
2590 }
2591
2592 // The type descriptor for an integer type.  Integer types are always
2593 // named.
2594
2595 Expression*
2596 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2597 {
2598   go_assert(name != NULL || saw_errors());
2599   return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2600 }
2601
2602 // We should not be asked for the reflection string of a basic type.
2603
2604 void
2605 Integer_type::do_reflection(Gogo*, std::string*) const
2606 {
2607   go_assert(saw_errors());
2608 }
2609
2610 // Mangled name.
2611
2612 void
2613 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
2614 {
2615   char buf[100];
2616   snprintf(buf, sizeof buf, "i%s%s%de",
2617            this->is_abstract_ ? "a" : "",
2618            this->is_unsigned_ ? "u" : "",
2619            this->bits_);
2620   ret->append(buf);
2621 }
2622
2623 // Make an integer type.
2624
2625 Named_type*
2626 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
2627                         int runtime_type_kind)
2628 {
2629   return Integer_type::create_integer_type(name, is_unsigned, bits,
2630                                            runtime_type_kind);
2631 }
2632
2633 // Make an abstract integer type.
2634
2635 Integer_type*
2636 Type::make_abstract_integer_type()
2637 {
2638   return Integer_type::create_abstract_integer_type();
2639 }
2640
2641 // Make an abstract character type.
2642
2643 Integer_type*
2644 Type::make_abstract_character_type()
2645 {
2646   return Integer_type::create_abstract_character_type();
2647 }
2648
2649 // Look up an integer type.
2650
2651 Named_type*
2652 Type::lookup_integer_type(const char* name)
2653 {
2654   return Integer_type::lookup_integer_type(name);
2655 }
2656
2657 // Class Float_type.
2658
2659 Float_type::Named_float_types Float_type::named_float_types;
2660
2661 // Create a new float type.  Non-abstract float types always have
2662 // names.
2663
2664 Named_type*
2665 Float_type::create_float_type(const char* name, int bits,
2666                               int runtime_type_kind)
2667 {
2668   Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
2669   std::string sname(name);
2670   Named_object* named_object =
2671     Named_object::make_type(sname, NULL, float_type,
2672                             Linemap::predeclared_location());
2673   Named_type* named_type = named_object->type_value();
2674   std::pair<Named_float_types::iterator, bool> ins =
2675     Float_type::named_float_types.insert(std::make_pair(sname, named_type));
2676   go_assert(ins.second);
2677   return named_type;
2678 }
2679
2680 // Look up an existing float type.
2681
2682 Named_type*
2683 Float_type::lookup_float_type(const char* name)
2684 {
2685   Named_float_types::const_iterator p =
2686     Float_type::named_float_types.find(name);
2687   go_assert(p != Float_type::named_float_types.end());
2688   return p->second;
2689 }
2690
2691 // Create a new abstract float type.
2692
2693 Float_type*
2694 Float_type::create_abstract_float_type()
2695 {
2696   static Float_type* abstract_type;
2697   if (abstract_type == NULL)
2698     abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
2699   return abstract_type;
2700 }
2701
2702 // Whether this type is identical with T.
2703
2704 bool
2705 Float_type::is_identical(const Float_type* t) const
2706 {
2707   if (this->bits_ != t->bits_)
2708     return false;
2709   return this->is_abstract_ == t->is_abstract_;
2710 }
2711
2712 // Hash code.
2713
2714 unsigned int
2715 Float_type::do_hash_for_method(Gogo*) const
2716 {
2717   return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2718 }
2719
2720 // Convert to the backend representation.
2721
2722 Btype*
2723 Float_type::do_get_backend(Gogo* gogo)
2724 {
2725   return gogo->backend()->float_type(this->bits_);
2726 }
2727
2728 // The type descriptor for a float type.  Float types are always named.
2729
2730 Expression*
2731 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2732 {
2733   go_assert(name != NULL || saw_errors());
2734   return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2735 }
2736
2737 // We should not be asked for the reflection string of a basic type.
2738
2739 void
2740 Float_type::do_reflection(Gogo*, std::string*) const
2741 {
2742   go_assert(saw_errors());
2743 }
2744
2745 // Mangled name.
2746
2747 void
2748 Float_type::do_mangled_name(Gogo*, std::string* ret) const
2749 {
2750   char buf[100];
2751   snprintf(buf, sizeof buf, "f%s%de",
2752            this->is_abstract_ ? "a" : "",
2753            this->bits_);
2754   ret->append(buf);
2755 }
2756
2757 // Make a floating point type.
2758
2759 Named_type*
2760 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
2761 {
2762   return Float_type::create_float_type(name, bits, runtime_type_kind);
2763 }
2764
2765 // Make an abstract float type.
2766
2767 Float_type*
2768 Type::make_abstract_float_type()
2769 {
2770   return Float_type::create_abstract_float_type();
2771 }
2772
2773 // Look up a float type.
2774
2775 Named_type*
2776 Type::lookup_float_type(const char* name)
2777 {
2778   return Float_type::lookup_float_type(name);
2779 }
2780
2781 // Class Complex_type.
2782
2783 Complex_type::Named_complex_types Complex_type::named_complex_types;
2784
2785 // Create a new complex type.  Non-abstract complex types always have
2786 // names.
2787
2788 Named_type*
2789 Complex_type::create_complex_type(const char* name, int bits,
2790                                   int runtime_type_kind)
2791 {
2792   Complex_type* complex_type = new Complex_type(false, bits,
2793                                                 runtime_type_kind);
2794   std::string sname(name);
2795   Named_object* named_object =
2796     Named_object::make_type(sname, NULL, complex_type,
2797                             Linemap::predeclared_location());
2798   Named_type* named_type = named_object->type_value();
2799   std::pair<Named_complex_types::iterator, bool> ins =
2800     Complex_type::named_complex_types.insert(std::make_pair(sname,
2801                                                             named_type));
2802   go_assert(ins.second);
2803   return named_type;
2804 }
2805
2806 // Look up an existing complex type.
2807
2808 Named_type*
2809 Complex_type::lookup_complex_type(const char* name)
2810 {
2811   Named_complex_types::const_iterator p =
2812     Complex_type::named_complex_types.find(name);
2813   go_assert(p != Complex_type::named_complex_types.end());
2814   return p->second;
2815 }
2816
2817 // Create a new abstract complex type.
2818
2819 Complex_type*
2820 Complex_type::create_abstract_complex_type()
2821 {
2822   static Complex_type* abstract_type;
2823   if (abstract_type == NULL)
2824     abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
2825   return abstract_type;
2826 }
2827
2828 // Whether this type is identical with T.
2829
2830 bool
2831 Complex_type::is_identical(const Complex_type *t) const
2832 {
2833   if (this->bits_ != t->bits_)
2834     return false;
2835   return this->is_abstract_ == t->is_abstract_;
2836 }
2837
2838 // Hash code.
2839
2840 unsigned int
2841 Complex_type::do_hash_for_method(Gogo*) const
2842 {
2843   return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2844 }
2845
2846 // Convert to the backend representation.
2847
2848 Btype*
2849 Complex_type::do_get_backend(Gogo* gogo)
2850 {
2851   return gogo->backend()->complex_type(this->bits_);
2852 }
2853
2854 // The type descriptor for a complex type.  Complex types are always
2855 // named.
2856
2857 Expression*
2858 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2859 {
2860   go_assert(name != NULL || saw_errors());
2861   return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2862 }
2863
2864 // We should not be asked for the reflection string of a basic type.
2865
2866 void
2867 Complex_type::do_reflection(Gogo*, std::string*) const
2868 {
2869   go_assert(saw_errors());
2870 }
2871
2872 // Mangled name.
2873
2874 void
2875 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
2876 {
2877   char buf[100];
2878   snprintf(buf, sizeof buf, "c%s%de",
2879            this->is_abstract_ ? "a" : "",
2880            this->bits_);
2881   ret->append(buf);
2882 }
2883
2884 // Make a complex type.
2885
2886 Named_type*
2887 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
2888 {
2889   return Complex_type::create_complex_type(name, bits, runtime_type_kind);
2890 }
2891
2892 // Make an abstract complex type.
2893
2894 Complex_type*
2895 Type::make_abstract_complex_type()
2896 {
2897   return Complex_type::create_abstract_complex_type();
2898 }
2899
2900 // Look up a complex type.
2901
2902 Named_type*
2903 Type::lookup_complex_type(const char* name)
2904 {
2905   return Complex_type::lookup_complex_type(name);
2906 }
2907
2908 // Class String_type.
2909
2910 // Convert String_type to the backend representation.  A string is a
2911 // struct with two fields: a pointer to the characters and a length.
2912
2913 Btype*
2914 String_type::do_get_backend(Gogo* gogo)
2915 {
2916   static Btype* backend_string_type;
2917   if (backend_string_type == NULL)
2918     {
2919       std::vector<Backend::Btyped_identifier> fields(2);
2920
2921       Type* b = gogo->lookup_global("byte")->type_value();
2922       Type* pb = Type::make_pointer_type(b);
2923
2924       // We aren't going to get back to this field to finish the
2925       // backend representation, so force it to be finished now.
2926       if (!gogo->named_types_are_converted())
2927         {
2928           pb->get_backend_placeholder(gogo);
2929           pb->finish_backend(gogo);
2930         }
2931
2932       fields[0].name = "__data";
2933       fields[0].btype = pb->get_backend(gogo);
2934       fields[0].location = Linemap::predeclared_location();
2935
2936       Type* int_type = Type::lookup_integer_type("int");
2937       fields[1].name = "__length";
2938       fields[1].btype = int_type->get_backend(gogo);
2939       fields[1].location = fields[0].location;
2940
2941       backend_string_type = gogo->backend()->struct_type(fields);
2942     }
2943   return backend_string_type;
2944 }
2945
2946 // Return a tree for the length of STRING.
2947
2948 tree
2949 String_type::length_tree(Gogo*, tree string)
2950 {
2951   tree string_type = TREE_TYPE(string);
2952   go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2953   tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type));
2954   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)),
2955                     "__length") == 0);
2956   return fold_build3(COMPONENT_REF, integer_type_node, string,
2957                      length_field, NULL_TREE);
2958 }
2959
2960 // Return a tree for a pointer to the bytes of STRING.
2961
2962 tree
2963 String_type::bytes_tree(Gogo*, tree string)
2964 {
2965   tree string_type = TREE_TYPE(string);
2966   go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2967   tree bytes_field = TYPE_FIELDS(string_type);
2968   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)),
2969                     "__data") == 0);
2970   return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string,
2971                      bytes_field, NULL_TREE);
2972 }
2973
2974 // The type descriptor for the string type.
2975
2976 Expression*
2977 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2978 {
2979   if (name != NULL)
2980     return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
2981   else
2982     {
2983       Named_object* no = gogo->lookup_global("string");
2984       go_assert(no != NULL);
2985       return Type::type_descriptor(gogo, no->type_value());
2986     }
2987 }
2988
2989 // We should not be asked for the reflection string of a basic type.
2990
2991 void
2992 String_type::do_reflection(Gogo*, std::string* ret) const
2993 {
2994   ret->append("string");
2995 }
2996
2997 // Mangled name of a string type.
2998
2999 void
3000 String_type::do_mangled_name(Gogo*, std::string* ret) const
3001 {
3002   ret->push_back('z');
3003 }
3004
3005 // Make a string type.
3006
3007 Type*
3008 Type::make_string_type()
3009 {
3010   static String_type string_type;
3011   return &string_type;
3012 }
3013
3014 // The named type "string".
3015
3016 static Named_type* named_string_type;
3017
3018 // Get the named type "string".
3019
3020 Named_type*
3021 Type::lookup_string_type()
3022 {
3023   return named_string_type;
3024 }
3025
3026 // Make the named type string.
3027
3028 Named_type*
3029 Type::make_named_string_type()
3030 {
3031   Type* string_type = Type::make_string_type();
3032   Named_object* named_object =
3033     Named_object::make_type("string", NULL, string_type,
3034                             Linemap::predeclared_location());
3035   Named_type* named_type = named_object->type_value();
3036   named_string_type = named_type;
3037   return named_type;
3038 }
3039
3040 // The sink type.  This is the type of the blank identifier _.  Any
3041 // type may be assigned to it.
3042
3043 class Sink_type : public Type
3044 {
3045  public:
3046   Sink_type()
3047     : Type(TYPE_SINK)
3048   { }
3049
3050  protected:
3051   bool
3052   do_compare_is_identity(Gogo*) const
3053   { return false; }
3054
3055   Btype*
3056   do_get_backend(Gogo*)
3057   { go_unreachable(); }
3058
3059   Expression*
3060   do_type_descriptor(Gogo*, Named_type*)
3061   { go_unreachable(); }
3062
3063   void
3064   do_reflection(Gogo*, std::string*) const
3065   { go_unreachable(); }
3066
3067   void
3068   do_mangled_name(Gogo*, std::string*) const
3069   { go_unreachable(); }
3070 };
3071
3072 // Make the sink type.
3073
3074 Type*
3075 Type::make_sink_type()
3076 {
3077   static Sink_type sink_type;
3078   return &sink_type;
3079 }
3080
3081 // Class Function_type.
3082
3083 // Traversal.
3084
3085 int
3086 Function_type::do_traverse(Traverse* traverse)
3087 {
3088   if (this->receiver_ != NULL
3089       && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
3090     return TRAVERSE_EXIT;
3091   if (this->parameters_ != NULL
3092       && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
3093     return TRAVERSE_EXIT;
3094   if (this->results_ != NULL
3095       && this->results_->traverse(traverse) == TRAVERSE_EXIT)
3096     return TRAVERSE_EXIT;
3097   return TRAVERSE_CONTINUE;
3098 }
3099
3100 // Returns whether T is a valid redeclaration of this type.  If this
3101 // returns false, and REASON is not NULL, *REASON may be set to a
3102 // brief explanation of why it returned false.
3103
3104 bool
3105 Function_type::is_valid_redeclaration(const Function_type* t,
3106                                       std::string* reason) const
3107 {
3108   if (!this->is_identical(t, false, true, reason))
3109     return false;
3110
3111   // A redeclaration of a function is required to use the same names
3112   // for the receiver and parameters.
3113   if (this->receiver() != NULL
3114       && this->receiver()->name() != t->receiver()->name())
3115     {
3116       if (reason != NULL)
3117         *reason = "receiver name changed";
3118       return false;
3119     }
3120
3121   const Typed_identifier_list* parms1 = this->parameters();
3122   const Typed_identifier_list* parms2 = t->parameters();
3123   if (parms1 != NULL)
3124     {
3125       Typed_identifier_list::const_iterator p1 = parms1->begin();
3126       for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3127            p2 != parms2->end();
3128            ++p2, ++p1)
3129         {
3130           if (p1->name() != p2->name())
3131             {
3132               if (reason != NULL)
3133                 *reason = "parameter name changed";
3134               return false;
3135             }
3136
3137           // This is called at parse time, so we may have unknown
3138           // types.
3139           Type* t1 = p1->type()->forwarded();
3140           Type* t2 = p2->type()->forwarded();
3141           if (t1 != t2
3142               && t1->forward_declaration_type() != NULL
3143               && (t2->forward_declaration_type() == NULL
3144                   || (t1->forward_declaration_type()->named_object()
3145                       != t2->forward_declaration_type()->named_object())))
3146             return false;
3147         }
3148     }
3149
3150   const Typed_identifier_list* results1 = this->results();
3151   const Typed_identifier_list* results2 = t->results();
3152   if (results1 != NULL)
3153     {
3154       Typed_identifier_list::const_iterator res1 = results1->begin();
3155       for (Typed_identifier_list::const_iterator res2 = results2->begin();
3156            res2 != results2->end();
3157            ++res2, ++res1)
3158         {
3159           if (res1->name() != res2->name())
3160             {
3161               if (reason != NULL)
3162                 *reason = "result name changed";
3163               return false;
3164             }
3165
3166           // This is called at parse time, so we may have unknown
3167           // types.
3168           Type* t1 = res1->type()->forwarded();
3169           Type* t2 = res2->type()->forwarded();
3170           if (t1 != t2
3171               && t1->forward_declaration_type() != NULL
3172               && (t2->forward_declaration_type() == NULL
3173                   || (t1->forward_declaration_type()->named_object()
3174                       != t2->forward_declaration_type()->named_object())))
3175             return false;
3176         }
3177     }
3178
3179   return true;
3180 }
3181
3182 // Check whether T is the same as this type.
3183
3184 bool
3185 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
3186                             bool errors_are_identical,
3187                             std::string* reason) const
3188 {
3189   if (!ignore_receiver)
3190     {
3191       const Typed_identifier* r1 = this->receiver();
3192       const Typed_identifier* r2 = t->receiver();
3193       if ((r1 != NULL) != (r2 != NULL))
3194         {
3195           if (reason != NULL)
3196             *reason = _("different receiver types");
3197           return false;
3198         }
3199       if (r1 != NULL)
3200         {
3201           if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
3202                                    reason))
3203             {
3204               if (reason != NULL && !reason->empty())
3205                 *reason = "receiver: " + *reason;
3206               return false;
3207             }
3208         }
3209     }
3210
3211   const Typed_identifier_list* parms1 = this->parameters();
3212   const Typed_identifier_list* parms2 = t->parameters();
3213   if ((parms1 != NULL) != (parms2 != NULL))
3214     {
3215       if (reason != NULL)
3216         *reason = _("different number of parameters");
3217       return false;
3218     }
3219   if (parms1 != NULL)
3220     {
3221       Typed_identifier_list::const_iterator p1 = parms1->begin();
3222       for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3223            p2 != parms2->end();
3224            ++p2, ++p1)
3225         {
3226           if (p1 == parms1->end())
3227             {
3228               if (reason != NULL)
3229                 *reason = _("different number of parameters");
3230               return false;
3231             }
3232
3233           if (!Type::are_identical(p1->type(), p2->type(),
3234                                    errors_are_identical, NULL))
3235             {
3236               if (reason != NULL)
3237                 *reason = _("different parameter types");
3238               return false;
3239             }
3240         }
3241       if (p1 != parms1->end())
3242         {
3243           if (reason != NULL)
3244             *reason = _("different number of parameters");
3245         return false;
3246         }
3247     }
3248
3249   if (this->is_varargs() != t->is_varargs())
3250     {
3251       if (reason != NULL)
3252         *reason = _("different varargs");
3253       return false;
3254     }
3255
3256   const Typed_identifier_list* results1 = this->results();
3257   const Typed_identifier_list* results2 = t->results();
3258   if ((results1 != NULL) != (results2 != NULL))
3259     {
3260       if (reason != NULL)
3261         *reason = _("different number of results");
3262       return false;
3263     }
3264   if (results1 != NULL)
3265     {
3266       Typed_identifier_list::const_iterator res1 = results1->begin();
3267       for (Typed_identifier_list::const_iterator res2 = results2->begin();
3268            res2 != results2->end();
3269            ++res2, ++res1)
3270         {
3271           if (res1 == results1->end())
3272             {
3273               if (reason != NULL)
3274                 *reason = _("different number of results");
3275               return false;
3276             }
3277
3278           if (!Type::are_identical(res1->type(), res2->type(),
3279                                    errors_are_identical, NULL))
3280             {
3281               if (reason != NULL)
3282                 *reason = _("different result types");
3283               return false;
3284             }
3285         }
3286       if (res1 != results1->end())
3287         {
3288           if (reason != NULL)
3289             *reason = _("different number of results");
3290           return false;
3291         }
3292     }
3293
3294   return true;
3295 }
3296
3297 // Hash code.
3298
3299 unsigned int
3300 Function_type::do_hash_for_method(Gogo* gogo) const
3301 {
3302   unsigned int ret = 0;
3303   // We ignore the receiver type for hash codes, because we need to
3304   // get the same hash code for a method in an interface and a method
3305   // declared for a type.  The former will not have a receiver.
3306   if (this->parameters_ != NULL)
3307     {
3308       int shift = 1;
3309       for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3310            p != this->parameters_->end();
3311            ++p, ++shift)
3312         ret += p->type()->hash_for_method(gogo) << shift;
3313     }
3314   if (this->results_ != NULL)
3315     {
3316       int shift = 2;
3317       for (Typed_identifier_list::const_iterator p = this->results_->begin();
3318            p != this->results_->end();
3319            ++p, ++shift)
3320         ret += p->type()->hash_for_method(gogo) << shift;
3321     }
3322   if (this->is_varargs_)
3323     ret += 1;
3324   ret <<= 4;
3325   return ret;
3326 }
3327
3328 // Get the backend representation for a function type.
3329
3330 Btype*
3331 Function_type::do_get_backend(Gogo* gogo)
3332 {
3333   Backend::Btyped_identifier breceiver;
3334   if (this->receiver_ != NULL)
3335     {
3336       breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
3337
3338       // We always pass the address of the receiver parameter, in
3339       // order to make interface calls work with unknown types.
3340       Type* rtype = this->receiver_->type();
3341       if (rtype->points_to() == NULL)
3342         rtype = Type::make_pointer_type(rtype);
3343       breceiver.btype = rtype->get_backend(gogo);
3344       breceiver.location = this->receiver_->location();
3345     }
3346
3347   std::vector<Backend::Btyped_identifier> bparameters;
3348   if (this->parameters_ != NULL)
3349     {
3350       bparameters.resize(this->parameters_->size());
3351       size_t i = 0;
3352       for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3353            p != this->parameters_->end();
3354            ++p, ++i)
3355         {
3356           bparameters[i].name = Gogo::unpack_hidden_name(p->name());
3357           bparameters[i].btype = p->type()->get_backend(gogo);
3358           bparameters[i].location = p->location();
3359         }
3360       go_assert(i == bparameters.size());
3361     }
3362
3363   std::vector<Backend::Btyped_identifier> bresults;
3364   if (this->results_ != NULL)
3365     {
3366       bresults.resize(this->results_->size());
3367       size_t i = 0;
3368       for (Typed_identifier_list::const_iterator p = this->results_->begin();
3369            p != this->results_->end();
3370            ++p, ++i)
3371         {
3372           bresults[i].name = Gogo::unpack_hidden_name(p->name());
3373           bresults[i].btype = p->type()->get_backend(gogo);
3374           bresults[i].location = p->location();
3375         }
3376       go_assert(i == bresults.size());
3377     }
3378
3379   return gogo->backend()->function_type(breceiver, bparameters, bresults,
3380                                         this->location());
3381 }
3382
3383 // The type of a function type descriptor.
3384
3385 Type*
3386 Function_type::make_function_type_descriptor_type()
3387 {
3388   static Type* ret;
3389   if (ret == NULL)
3390     {
3391       Type* tdt = Type::make_type_descriptor_type();
3392       Type* ptdt = Type::make_type_descriptor_ptr_type();
3393
3394       Type* bool_type = Type::lookup_bool_type();
3395
3396       Type* slice_type = Type::make_array_type(ptdt, NULL);
3397
3398       Struct_type* s = Type::make_builtin_struct_type(4,
3399                                                       "", tdt,
3400                                                       "dotdotdot", bool_type,
3401                                                       "in", slice_type,
3402                                                       "out", slice_type);
3403
3404       ret = Type::make_builtin_named_type("FuncType", s);
3405     }
3406
3407   return ret;
3408 }
3409
3410 // The type descriptor for a function type.
3411
3412 Expression*
3413 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3414 {
3415   Location bloc = Linemap::predeclared_location();
3416
3417   Type* ftdt = Function_type::make_function_type_descriptor_type();
3418
3419   const Struct_field_list* fields = ftdt->struct_type()->fields();
3420
3421   Expression_list* vals = new Expression_list();
3422   vals->reserve(4);
3423
3424   Struct_field_list::const_iterator p = fields->begin();
3425   go_assert(p->is_field_name("commonType"));
3426   vals->push_back(this->type_descriptor_constructor(gogo,
3427                                                     RUNTIME_TYPE_KIND_FUNC,
3428                                                     name, NULL, true));
3429
3430   ++p;
3431   go_assert(p->is_field_name("dotdotdot"));
3432   vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
3433
3434   ++p;
3435   go_assert(p->is_field_name("in"));
3436   vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
3437                                                this->parameters()));
3438
3439   ++p;
3440   go_assert(p->is_field_name("out"));
3441   vals->push_back(this->type_descriptor_params(p->type(), NULL,
3442                                                this->results()));
3443
3444   ++p;
3445   go_assert(p == fields->end());
3446
3447   return Expression::make_struct_composite_literal(ftdt, vals, bloc);
3448 }
3449
3450 // Return a composite literal for the parameters or results of a type
3451 // descriptor.
3452
3453 Expression*
3454 Function_type::type_descriptor_params(Type* params_type,
3455                                       const Typed_identifier* receiver,
3456                                       const Typed_identifier_list* params)
3457 {
3458   Location bloc = Linemap::predeclared_location();
3459
3460   if (receiver == NULL && params == NULL)
3461     return Expression::make_slice_composite_literal(params_type, NULL, bloc);
3462
3463   Expression_list* vals = new Expression_list();
3464   vals->reserve((params == NULL ? 0 : params->size())
3465                 + (receiver != NULL ? 1 : 0));
3466
3467   if (receiver != NULL)
3468     vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
3469
3470   if (params != NULL)
3471     {
3472       for (Typed_identifier_list::const_iterator p = params->begin();
3473            p != params->end();
3474            ++p)
3475         vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
3476     }
3477
3478   return Expression::make_slice_composite_literal(params_type, vals, bloc);
3479 }
3480
3481 // The reflection string.
3482
3483 void
3484 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
3485 {
3486   // FIXME: Turn this off until we straighten out the type of the
3487   // struct field used in a go statement which calls a method.
3488   // go_assert(this->receiver_ == NULL);
3489
3490   ret->append("func");
3491
3492   if (this->receiver_ != NULL)
3493     {
3494       ret->push_back('(');
3495       this->append_reflection(this->receiver_->type(), gogo, ret);
3496       ret->push_back(')');
3497     }
3498
3499   ret->push_back('(');
3500   const Typed_identifier_list* params = this->parameters();
3501   if (params != NULL)
3502     {
3503       bool is_varargs = this->is_varargs_;
3504       for (Typed_identifier_list::const_iterator p = params->begin();
3505            p != params->end();
3506            ++p)
3507         {
3508           if (p != params->begin())
3509             ret->append(", ");
3510           if (!is_varargs || p + 1 != params->end())
3511             this->append_reflection(p->type(), gogo, ret);
3512           else
3513             {
3514               ret->append("...");
3515               this->append_reflection(p->type()->array_type()->element_type(),
3516                                       gogo, ret);
3517             }
3518         }
3519     }
3520   ret->push_back(')');
3521
3522   const Typed_identifier_list* results = this->results();
3523   if (results != NULL && !results->empty())
3524     {
3525       if (results->size() == 1)
3526         ret->push_back(' ');
3527       else
3528         ret->append(" (");
3529       for (Typed_identifier_list::const_iterator p = results->begin();
3530            p != results->end();
3531            ++p)
3532         {
3533           if (p != results->begin())
3534             ret->append(", ");
3535           this->append_reflection(p->type(), gogo, ret);
3536         }
3537       if (results->size() > 1)
3538         ret->push_back(')');
3539     }
3540 }
3541
3542 // Mangled name.
3543
3544 void
3545 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3546 {
3547   ret->push_back('F');
3548
3549   if (this->receiver_ != NULL)
3550     {
3551       ret->push_back('m');
3552       this->append_mangled_name(this->receiver_->type(), gogo, ret);
3553     }
3554
3555   const Typed_identifier_list* params = this->parameters();
3556   if (params != NULL)
3557     {
3558       ret->push_back('p');
3559       for (Typed_identifier_list::const_iterator p = params->begin();
3560            p != params->end();
3561            ++p)
3562         this->append_mangled_name(p->type(), gogo, ret);
3563       if (this->is_varargs_)
3564         ret->push_back('V');
3565       ret->push_back('e');
3566     }
3567
3568   const Typed_identifier_list* results = this->results();
3569   if (results != NULL)
3570     {
3571       ret->push_back('r');
3572       for (Typed_identifier_list::const_iterator p = results->begin();
3573            p != results->end();
3574            ++p)
3575         this->append_mangled_name(p->type(), gogo, ret);
3576       ret->push_back('e');
3577     }
3578
3579   ret->push_back('e');
3580 }
3581
3582 // Export a function type.
3583
3584 void
3585 Function_type::do_export(Export* exp) const
3586 {
3587   // We don't write out the receiver.  The only function types which
3588   // should have a receiver are the ones associated with explicitly
3589   // defined methods.  For those the receiver type is written out by
3590   // Function::export_func.
3591
3592   exp->write_c_string("(");
3593   bool first = true;
3594   if (this->parameters_ != NULL)
3595     {
3596       bool is_varargs = this->is_varargs_;
3597       for (Typed_identifier_list::const_iterator p =
3598              this->parameters_->begin();
3599            p != this->parameters_->end();
3600            ++p)
3601         {
3602           if (first)
3603             first = false;
3604           else
3605             exp->write_c_string(", ");
3606           exp->write_name(p->name());
3607           exp->write_c_string(" ");
3608           if (!is_varargs || p + 1 != this->parameters_->end())
3609             exp->write_type(p->type());
3610           else
3611             {
3612               exp->write_c_string("...");
3613               exp->write_type(p->type()->array_type()->element_type());
3614             }
3615         }
3616     }
3617   exp->write_c_string(")");
3618
3619   const Typed_identifier_list* results = this->results_;
3620   if (results != NULL)
3621     {
3622       exp->write_c_string(" ");
3623       if (results->size() == 1 && results->begin()->name().empty())
3624         exp->write_type(results->begin()->type());
3625       else
3626         {
3627           first = true;
3628           exp->write_c_string("(");
3629           for (Typed_identifier_list::const_iterator p = results->begin();
3630                p != results->end();
3631                ++p)
3632             {
3633               if (first)
3634                 first = false;
3635               else
3636                 exp->write_c_string(", ");
3637               exp->write_name(p->name());
3638               exp->write_c_string(" ");
3639               exp->write_type(p->type());
3640             }
3641           exp->write_c_string(")");
3642         }
3643     }
3644 }
3645
3646 // Import a function type.
3647
3648 Function_type*
3649 Function_type::do_import(Import* imp)
3650 {
3651   imp->require_c_string("(");
3652   Typed_identifier_list* parameters;
3653   bool is_varargs = false;
3654   if (imp->peek_char() == ')')
3655     parameters = NULL;
3656   else
3657     {
3658       parameters = new Typed_identifier_list();
3659       while (true)
3660         {
3661           std::string name = imp->read_name();
3662           imp->require_c_string(" ");
3663
3664           if (imp->match_c_string("..."))
3665             {
3666               imp->advance(3);
3667               is_varargs = true;
3668             }
3669
3670           Type* ptype = imp->read_type();
3671           if (is_varargs)
3672             ptype = Type::make_array_type(ptype, NULL);
3673           parameters->push_back(Typed_identifier(name, ptype,
3674                                                  imp->location()));
3675           if (imp->peek_char() != ',')
3676             break;
3677           go_assert(!is_varargs);
3678           imp->require_c_string(", ");
3679         }
3680     }
3681   imp->require_c_string(")");
3682
3683   Typed_identifier_list* results;
3684   if (imp->peek_char() != ' ')
3685     results = NULL;
3686   else
3687     {
3688       imp->advance(1);
3689       results = new Typed_identifier_list;
3690       if (imp->peek_char() != '(')
3691         {
3692           Type* rtype = imp->read_type();
3693           results->push_back(Typed_identifier("", rtype, imp->location()));
3694         }
3695       else
3696         {
3697           imp->advance(1);
3698           while (true)
3699             {
3700               std::string name = imp->read_name();
3701               imp->require_c_string(" ");
3702               Type* rtype = imp->read_type();
3703               results->push_back(Typed_identifier(name, rtype,
3704                                                   imp->location()));
3705               if (imp->peek_char() != ',')
3706                 break;
3707               imp->require_c_string(", ");
3708             }
3709           imp->require_c_string(")");
3710         }
3711     }
3712
3713   Function_type* ret = Type::make_function_type(NULL, parameters, results,
3714                                                 imp->location());
3715   if (is_varargs)
3716     ret->set_is_varargs();
3717   return ret;
3718 }
3719
3720 // Make a copy of a function type without a receiver.
3721
3722 Function_type*
3723 Function_type::copy_without_receiver() const
3724 {
3725   go_assert(this->is_method());
3726   Function_type *ret = Type::make_function_type(NULL, this->parameters_,
3727                                                 this->results_,
3728                                                 this->location_);
3729   if (this->is_varargs())
3730     ret->set_is_varargs();
3731   if (this->is_builtin())
3732     ret->set_is_builtin();
3733   return ret;
3734 }
3735
3736 // Make a copy of a function type with a receiver.
3737
3738 Function_type*
3739 Function_type::copy_with_receiver(Type* receiver_type) const
3740 {
3741   go_assert(!this->is_method());
3742   Typed_identifier* receiver = new Typed_identifier("", receiver_type,
3743                                                     this->location_);
3744   return Type::make_function_type(receiver, this->parameters_,
3745                                   this->results_, this->location_);
3746 }
3747
3748 // Make a function type.
3749
3750 Function_type*
3751 Type::make_function_type(Typed_identifier* receiver,
3752                          Typed_identifier_list* parameters,
3753                          Typed_identifier_list* results,
3754                          Location location)
3755 {
3756   return new Function_type(receiver, parameters, results, location);
3757 }
3758
3759 // Class Pointer_type.
3760
3761 // Traversal.
3762
3763 int
3764 Pointer_type::do_traverse(Traverse* traverse)
3765 {
3766   return Type::traverse(this->to_type_, traverse);
3767 }
3768
3769 // Hash code.
3770
3771 unsigned int
3772 Pointer_type::do_hash_for_method(Gogo* gogo) const
3773 {
3774   return this->to_type_->hash_for_method(gogo) << 4;
3775 }
3776
3777 // Get the backend representation for a pointer type.
3778
3779 Btype*
3780 Pointer_type::do_get_backend(Gogo* gogo)
3781 {
3782   Btype* to_btype = this->to_type_->get_backend(gogo);
3783   return gogo->backend()->pointer_type(to_btype);
3784 }
3785
3786 // The type of a pointer type descriptor.
3787
3788 Type*
3789 Pointer_type::make_pointer_type_descriptor_type()
3790 {
3791   static Type* ret;
3792   if (ret == NULL)
3793     {
3794       Type* tdt = Type::make_type_descriptor_type();
3795       Type* ptdt = Type::make_type_descriptor_ptr_type();
3796
3797       Struct_type* s = Type::make_builtin_struct_type(2,
3798                                                       "", tdt,
3799                                                       "elem", ptdt);
3800
3801       ret = Type::make_builtin_named_type("PtrType", s);
3802     }
3803
3804   return ret;
3805 }
3806
3807 // The type descriptor for a pointer type.
3808
3809 Expression*
3810 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3811 {
3812   if (this->is_unsafe_pointer_type())
3813     {
3814       go_assert(name != NULL);
3815       return this->plain_type_descriptor(gogo,
3816                                          RUNTIME_TYPE_KIND_UNSAFE_POINTER,
3817                                          name);
3818     }
3819   else
3820     {
3821       Location bloc = Linemap::predeclared_location();
3822
3823       const Methods* methods;
3824       Type* deref = this->points_to();
3825       if (deref->named_type() != NULL)
3826         methods = deref->named_type()->methods();
3827       else if (deref->struct_type() != NULL)
3828         methods = deref->struct_type()->methods();
3829       else
3830         methods = NULL;
3831
3832       Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
3833
3834       const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
3835
3836       Expression_list* vals = new Expression_list();
3837       vals->reserve(2);
3838
3839       Struct_field_list::const_iterator p = fields->begin();
3840       go_assert(p->is_field_name("commonType"));
3841       vals->push_back(this->type_descriptor_constructor(gogo,
3842                                                         RUNTIME_TYPE_KIND_PTR,
3843                                                         name, methods, false));
3844
3845       ++p;
3846       go_assert(p->is_field_name("elem"));
3847       vals->push_back(Expression::make_type_descriptor(deref, bloc));
3848
3849       return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
3850     }
3851 }
3852
3853 // Reflection string.
3854
3855 void
3856 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
3857 {
3858   ret->push_back('*');
3859   this->append_reflection(this->to_type_, gogo, ret);
3860 }
3861
3862 // Mangled name.
3863
3864 void
3865 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3866 {
3867   ret->push_back('p');
3868   this->append_mangled_name(this->to_type_, gogo, ret);
3869 }
3870
3871 // Export.
3872
3873 void
3874 Pointer_type::do_export(Export* exp) const
3875 {
3876   exp->write_c_string("*");
3877   if (this->is_unsafe_pointer_type())
3878     exp->write_c_string("any");
3879   else
3880     exp->write_type(this->to_type_);
3881 }
3882
3883 // Import.
3884
3885 Pointer_type*
3886 Pointer_type::do_import(Import* imp)
3887 {
3888   imp->require_c_string("*");
3889   if (imp->match_c_string("any"))
3890     {
3891       imp->advance(3);
3892       return Type::make_pointer_type(Type::make_void_type());
3893     }
3894   Type* to = imp->read_type();
3895   return Type::make_pointer_type(to);
3896 }
3897
3898 // Make a pointer type.
3899
3900 Pointer_type*
3901 Type::make_pointer_type(Type* to_type)
3902 {
3903   typedef Unordered_map(Type*, Pointer_type*) Hashtable;
3904   static Hashtable pointer_types;
3905   Hashtable::const_iterator p = pointer_types.find(to_type);
3906   if (p != pointer_types.end())
3907     return p->second;
3908   Pointer_type* ret = new Pointer_type(to_type);
3909   pointer_types[to_type] = ret;
3910   return ret;
3911 }
3912
3913 // The nil type.  We use a special type for nil because it is not the
3914 // same as any other type.  In C term nil has type void*, but there is
3915 // no such type in Go.
3916
3917 class Nil_type : public Type
3918 {
3919  public:
3920   Nil_type()
3921     : Type(TYPE_NIL)
3922   { }
3923
3924  protected:
3925   bool
3926   do_compare_is_identity(Gogo*) const
3927   { return false; }
3928
3929   Btype*
3930   do_get_backend(Gogo* gogo)
3931   { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
3932
3933   Expression*
3934   do_type_descriptor(Gogo*, Named_type*)
3935   { go_unreachable(); }
3936
3937   void
3938   do_reflection(Gogo*, std::string*) const
3939   { go_unreachable(); }
3940
3941   void
3942   do_mangled_name(Gogo*, std::string* ret) const
3943   { ret->push_back('n'); }
3944 };
3945
3946 // Make the nil type.
3947
3948 Type*
3949 Type::make_nil_type()
3950 {
3951   static Nil_type singleton_nil_type;
3952   return &singleton_nil_type;
3953 }
3954
3955 // The type of a function call which returns multiple values.  This is
3956 // really a struct, but we don't want to confuse a function call which
3957 // returns a struct with a function call which returns multiple
3958 // values.
3959
3960 class Call_multiple_result_type : public Type
3961 {
3962  public:
3963   Call_multiple_result_type(Call_expression* call)
3964     : Type(TYPE_CALL_MULTIPLE_RESULT),
3965       call_(call)
3966   { }
3967
3968  protected:
3969   bool
3970   do_has_pointer() const
3971   {
3972     go_assert(saw_errors());
3973     return false;
3974   }
3975
3976   bool
3977   do_compare_is_identity(Gogo*) const
3978   { return false; }
3979
3980   Btype*
3981   do_get_backend(Gogo* gogo)
3982   {
3983     go_assert(saw_errors());
3984     return gogo->backend()->error_type();
3985   }
3986
3987   Expression*
3988   do_type_descriptor(Gogo*, Named_type*)
3989   {
3990     go_assert(saw_errors());
3991     return Expression::make_error(Linemap::unknown_location());
3992   }
3993
3994   void
3995   do_reflection(Gogo*, std::string*) const
3996   { go_assert(saw_errors()); }
3997
3998   void
3999   do_mangled_name(Gogo*, std::string*) const
4000   { go_assert(saw_errors()); }
4001
4002  private:
4003   // The expression being called.
4004   Call_expression* call_;
4005 };
4006
4007 // Make a call result type.
4008
4009 Type*
4010 Type::make_call_multiple_result_type(Call_expression* call)
4011 {
4012   return new Call_multiple_result_type(call);
4013 }
4014
4015 // Class Struct_field.
4016
4017 // Get the name of a field.
4018
4019 const std::string&
4020 Struct_field::field_name() const
4021 {
4022   const std::string& name(this->typed_identifier_.name());
4023   if (!name.empty())
4024     return name;
4025   else
4026     {
4027       // This is called during parsing, before anything is lowered, so
4028       // we have to be pretty careful to avoid dereferencing an
4029       // unknown type name.
4030       Type* t = this->typed_identifier_.type();
4031       Type* dt = t;
4032       if (t->classification() == Type::TYPE_POINTER)
4033         {
4034           // Very ugly.
4035           Pointer_type* ptype = static_cast<Pointer_type*>(t);
4036           dt = ptype->points_to();
4037         }
4038       if (dt->forward_declaration_type() != NULL)
4039         return dt->forward_declaration_type()->name();
4040       else if (dt->named_type() != NULL)
4041         return dt->named_type()->name();
4042       else if (t->is_error_type() || dt->is_error_type())
4043         {
4044           static const std::string error_string = "*error*";
4045           return error_string;
4046         }
4047       else
4048         {
4049           // Avoid crashing in the erroneous case where T is named but
4050           // DT is not.
4051           go_assert(t != dt);
4052           if (t->forward_declaration_type() != NULL)
4053             return t->forward_declaration_type()->name();
4054           else if (t->named_type() != NULL)
4055             return t->named_type()->name();
4056           else
4057             go_unreachable();
4058         }
4059     }
4060 }
4061
4062 // Return whether this field is named NAME.
4063
4064 bool
4065 Struct_field::is_field_name(const std::string& name) const
4066 {
4067   const std::string& me(this->typed_identifier_.name());
4068   if (!me.empty())
4069     return me == name;
4070   else
4071     {
4072       Type* t = this->typed_identifier_.type();
4073       if (t->points_to() != NULL)
4074         t = t->points_to();
4075       Named_type* nt = t->named_type();
4076       if (nt != NULL && nt->name() == name)
4077         return true;
4078
4079       // This is a horrible hack caused by the fact that we don't pack
4080       // the names of builtin types.  FIXME.
4081       if (nt != NULL
4082           && nt->is_builtin()
4083           && nt->name() == Gogo::unpack_hidden_name(name))
4084         return true;
4085
4086       return false;
4087     }
4088 }
4089
4090 // Class Struct_type.
4091
4092 // Traversal.
4093
4094 int
4095 Struct_type::do_traverse(Traverse* traverse)
4096 {
4097   Struct_field_list* fields = this->fields_;
4098   if (fields != NULL)
4099     {
4100       for (Struct_field_list::iterator p = fields->begin();
4101            p != fields->end();
4102            ++p)
4103         {
4104           if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
4105             return TRAVERSE_EXIT;
4106         }
4107     }
4108   return TRAVERSE_CONTINUE;
4109 }
4110
4111 // Verify that the struct type is complete and valid.
4112
4113 bool
4114 Struct_type::do_verify()
4115 {
4116   Struct_field_list* fields = this->fields_;
4117   if (fields == NULL)
4118     return true;
4119   for (Struct_field_list::iterator p = fields->begin();
4120        p != fields->end();
4121        ++p)
4122     {
4123       Type* t = p->type();
4124       if (t->is_undefined())
4125         {
4126           error_at(p->location(), "struct field type is incomplete");
4127           p->set_type(Type::make_error_type());
4128         }
4129       else if (p->is_anonymous())
4130         {
4131           if (t->named_type() != NULL && t->points_to() != NULL)
4132             {
4133               error_at(p->location(), "embedded type may not be a pointer");
4134               p->set_type(Type::make_error_type());
4135             }
4136           else if (t->points_to() != NULL
4137                    && t->points_to()->interface_type() != NULL)
4138             {
4139               error_at(p->location(),
4140                        "embedded type may not be pointer to interface");
4141               p->set_type(Type::make_error_type());
4142             }
4143         }
4144     }
4145   return true;
4146 }
4147
4148 // Whether this contains a pointer.
4149
4150 bool
4151 Struct_type::do_has_pointer() const
4152 {
4153   const Struct_field_list* fields = this->fields();
4154   if (fields == NULL)
4155     return false;
4156   for (Struct_field_list::const_iterator p = fields->begin();
4157        p != fields->end();
4158        ++p)
4159     {
4160       if (p->type()->has_pointer())
4161         return true;
4162     }
4163   return false;
4164 }
4165
4166 // Whether this type is identical to T.
4167
4168 bool
4169 Struct_type::is_identical(const Struct_type* t,
4170                           bool errors_are_identical) const
4171 {
4172   const Struct_field_list* fields1 = this->fields();
4173   const Struct_field_list* fields2 = t->fields();
4174   if (fields1 == NULL || fields2 == NULL)
4175     return fields1 == fields2;
4176   Struct_field_list::const_iterator pf2 = fields2->begin();
4177   for (Struct_field_list::const_iterator pf1 = fields1->begin();
4178        pf1 != fields1->end();
4179        ++pf1, ++pf2)
4180     {
4181       if (pf2 == fields2->end())
4182         return false;
4183       if (pf1->field_name() != pf2->field_name())
4184         return false;
4185       if (pf1->is_anonymous() != pf2->is_anonymous()
4186           || !Type::are_identical(pf1->type(), pf2->type(),
4187                                   errors_are_identical, NULL))
4188         return false;
4189       if (!pf1->has_tag())
4190         {
4191           if (pf2->has_tag())
4192             return false;
4193         }
4194       else
4195         {
4196           if (!pf2->has_tag())
4197             return false;
4198           if (pf1->tag() != pf2->tag())
4199             return false;
4200         }
4201     }
4202   if (pf2 != fields2->end())
4203     return false;
4204   return true;
4205 }
4206
4207 // Whether this struct type has any hidden fields.
4208
4209 bool
4210 Struct_type::struct_has_hidden_fields(const Named_type* within,
4211                                       std::string* reason) const
4212 {
4213   const Struct_field_list* fields = this->fields();
4214   if (fields == NULL)
4215     return false;
4216   const Package* within_package = (within == NULL
4217                                    ? NULL
4218                                    : within->named_object()->package());
4219   for (Struct_field_list::const_iterator pf = fields->begin();
4220        pf != fields->end();
4221        ++pf)
4222     {
4223       if (within_package != NULL
4224           && !pf->is_anonymous()
4225           && Gogo::is_hidden_name(pf->field_name()))
4226         {
4227           if (reason != NULL)
4228             {
4229               std::string within_name = within->named_object()->message_name();
4230               std::string name = Gogo::message_name(pf->field_name());
4231               size_t bufsize = 200 + within_name.length() + name.length();
4232               char* buf = new char[bufsize];
4233               snprintf(buf, bufsize,
4234                        _("implicit assignment of %s%s%s hidden field %s%s%s"),
4235                        open_quote, within_name.c_str(), close_quote,
4236                        open_quote, name.c_str(), close_quote);
4237               reason->assign(buf);
4238               delete[] buf;
4239             }
4240           return true;
4241         }
4242
4243       if (pf->type()->has_hidden_fields(within, reason))
4244         return true;
4245     }
4246
4247   return false;
4248 }
4249
4250 // Whether comparisons of this struct type are simple identity
4251 // comparisons.
4252
4253 bool
4254 Struct_type::do_compare_is_identity(Gogo* gogo) const
4255 {
4256   const Struct_field_list* fields = this->fields_;
4257   if (fields == NULL)
4258     return true;
4259   unsigned int offset = 0;
4260   for (Struct_field_list::const_iterator pf = fields->begin();
4261        pf != fields->end();
4262        ++pf)
4263     {
4264       if (!pf->type()->compare_is_identity(gogo))
4265         return false;
4266
4267       unsigned int field_align;
4268       if (!pf->type()->backend_type_align(gogo, &field_align))
4269         return false;
4270       if ((offset & (field_align - 1)) != 0)
4271         {
4272           // This struct has padding.  We don't guarantee that that
4273           // padding is zero-initialized for a stack variable, so we
4274           // can't use memcmp to compare struct values.
4275           return false;
4276         }
4277
4278       unsigned int field_size;
4279       if (!pf->type()->backend_type_size(gogo, &field_size))
4280         return false;
4281       offset += field_size;
4282     }
4283   return true;
4284 }
4285
4286 // Build identity and hash functions for this struct.
4287
4288 // Hash code.
4289
4290 unsigned int
4291 Struct_type::do_hash_for_method(Gogo* gogo) const
4292 {
4293   unsigned int ret = 0;
4294   if (this->fields() != NULL)
4295     {
4296       for (Struct_field_list::const_iterator pf = this->fields()->begin();
4297            pf != this->fields()->end();
4298            ++pf)
4299         ret = (ret << 1) + pf->type()->hash_for_method(gogo);
4300     }
4301   return ret <<= 2;
4302 }
4303
4304 // Find the local field NAME.
4305
4306 const Struct_field*
4307 Struct_type::find_local_field(const std::string& name,
4308                               unsigned int *pindex) const
4309 {
4310   const Struct_field_list* fields = this->fields_;
4311   if (fields == NULL)
4312     return NULL;
4313   unsigned int i = 0;
4314   for (Struct_field_list::const_iterator pf = fields->begin();
4315        pf != fields->end();
4316        ++pf, ++i)
4317     {
4318       if (pf->is_field_name(name))
4319         {
4320           if (pindex != NULL)
4321             *pindex = i;
4322           return &*pf;
4323         }
4324     }
4325   return NULL;
4326 }
4327
4328 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
4329
4330 Field_reference_expression*
4331 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
4332                              Location location) const
4333 {
4334   unsigned int depth;
4335   return this->field_reference_depth(struct_expr, name, location, NULL,
4336                                      &depth);
4337 }
4338
4339 // Return an expression for a field, along with the depth at which it
4340 // was found.
4341
4342 Field_reference_expression*
4343 Struct_type::field_reference_depth(Expression* struct_expr,
4344                                    const std::string& name,
4345                                    Location location,
4346                                    Saw_named_type* saw,
4347                                    unsigned int* depth) const
4348 {
4349   const Struct_field_list* fields = this->fields_;
4350   if (fields == NULL)
4351     return NULL;
4352
4353   // Look for a field with this name.
4354   unsigned int i = 0;
4355   for (Struct_field_list::const_iterator pf = fields->begin();
4356        pf != fields->end();
4357        ++pf, ++i)
4358     {
4359       if (pf->is_field_name(name))
4360         {
4361           *depth = 0;
4362           return Expression::make_field_reference(struct_expr, i, location);
4363         }
4364     }
4365
4366   // Look for an anonymous field which contains a field with this
4367   // name.
4368   unsigned int found_depth = 0;
4369   Field_reference_expression* ret = NULL;
4370   i = 0;
4371   for (Struct_field_list::const_iterator pf = fields->begin();
4372        pf != fields->end();
4373        ++pf, ++i)
4374     {
4375       if (!pf->is_anonymous())
4376         continue;
4377
4378       Struct_type* st = pf->type()->deref()->struct_type();
4379       if (st == NULL)
4380         continue;
4381
4382       Saw_named_type* hold_saw = saw;
4383       Saw_named_type saw_here;
4384       Named_type* nt = pf->type()->named_type();
4385       if (nt == NULL)
4386         nt = pf->type()->deref()->named_type();
4387       if (nt != NULL)
4388         {
4389           Saw_named_type* q;
4390           for (q = saw; q != NULL; q = q->next)
4391             {
4392               if (q->nt == nt)
4393                 {
4394                   // If this is an error, it will be reported
4395                   // elsewhere.
4396                   break;
4397                 }
4398             }
4399           if (q != NULL)
4400             continue;
4401           saw_here.next = saw;
4402           saw_here.nt = nt;
4403           saw = &saw_here;
4404         }
4405
4406       // Look for a reference using a NULL struct expression.  If we
4407       // find one, fill in the struct expression with a reference to
4408       // this field.
4409       unsigned int subdepth;
4410       Field_reference_expression* sub = st->field_reference_depth(NULL, name,
4411                                                                   location,
4412                                                                   saw,
4413                                                                   &subdepth);
4414
4415       saw = hold_saw;
4416
4417       if (sub == NULL)
4418         continue;
4419
4420       if (ret == NULL || subdepth < found_depth)
4421         {
4422           if (ret != NULL)
4423             delete ret;
4424           ret = sub;
4425           found_depth = subdepth;
4426           Expression* here = Expression::make_field_reference(struct_expr, i,
4427                                                               location);
4428           if (pf->type()->points_to() != NULL)
4429             here = Expression::make_unary(OPERATOR_MULT, here, location);
4430           while (sub->expr() != NULL)
4431             {
4432               sub = sub->expr()->deref()->field_reference_expression();
4433               go_assert(sub != NULL);
4434             }
4435           sub->set_struct_expression(here);
4436         }
4437       else if (subdepth > found_depth)
4438         delete sub;
4439       else
4440         {
4441           // We do not handle ambiguity here--it should be handled by
4442           // Type::bind_field_or_method.
4443           delete sub;
4444           found_depth = 0;
4445           ret = NULL;
4446         }
4447     }
4448
4449   if (ret != NULL)
4450     *depth = found_depth + 1;
4451
4452   return ret;
4453 }
4454
4455 // Return the total number of fields, including embedded fields.
4456
4457 unsigned int
4458 Struct_type::total_field_count() const
4459 {
4460   if (this->fields_ == NULL)
4461     return 0;
4462   unsigned int ret = 0;
4463   for (Struct_field_list::const_iterator pf = this->fields_->begin();
4464        pf != this->fields_->end();
4465        ++pf)
4466     {
4467       if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
4468         ++ret;
4469       else
4470         ret += pf->type()->struct_type()->total_field_count();
4471     }
4472   return ret;
4473 }
4474
4475 // Return whether NAME is an unexported field, for better error reporting.
4476
4477 bool
4478 Struct_type::is_unexported_local_field(Gogo* gogo,
4479                                        const std::string& name) const
4480 {
4481   const Struct_field_list* fields = this->fields_;
4482   if (fields != NULL)
4483     {
4484       for (Struct_field_list::const_iterator pf = fields->begin();
4485            pf != fields->end();
4486            ++pf)
4487         {
4488           const std::string& field_name(pf->field_name());
4489           if (Gogo::is_hidden_name(field_name)
4490               && name == Gogo::unpack_hidden_name(field_name)
4491               && gogo->pack_hidden_name(name, false) != field_name)
4492             return true;
4493         }
4494     }
4495   return false;
4496 }
4497
4498 // Finalize the methods of an unnamed struct.
4499
4500 void
4501 Struct_type::finalize_methods(Gogo* gogo)
4502 {
4503   if (this->all_methods_ != NULL)
4504     return;
4505   Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
4506 }
4507
4508 // Return the method NAME, or NULL if there isn't one or if it is
4509 // ambiguous.  Set *IS_AMBIGUOUS if the method exists but is
4510 // ambiguous.
4511
4512 Method*
4513 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
4514 {
4515   return Type::method_function(this->all_methods_, name, is_ambiguous);
4516 }
4517
4518 // Convert struct fields to the backend representation.  This is not
4519 // declared in types.h so that types.h doesn't have to #include
4520 // backend.h.
4521
4522 static void
4523 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
4524                           bool use_placeholder,
4525                           std::vector<Backend::Btyped_identifier>* bfields)
4526 {
4527   bfields->resize(fields->size());
4528   size_t i = 0;
4529   for (Struct_field_list::const_iterator p = fields->begin();
4530        p != fields->end();
4531        ++p, ++i)
4532     {
4533       (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
4534       (*bfields)[i].btype = (use_placeholder
4535                              ? p->type()->get_backend_placeholder(gogo)
4536                              : p->type()->get_backend(gogo));
4537       (*bfields)[i].location = p->location();
4538     }
4539   go_assert(i == fields->size());
4540 }
4541
4542 // Get the tree for a struct type.
4543
4544 Btype*
4545 Struct_type::do_get_backend(Gogo* gogo)
4546 {
4547   std::vector<Backend::Btyped_identifier> bfields;
4548   get_backend_struct_fields(gogo, this->fields_, false, &bfields);
4549   return gogo->backend()->struct_type(bfields);
4550 }
4551
4552 // Finish the backend representation of the fields of a struct.
4553
4554 void
4555 Struct_type::finish_backend_fields(Gogo* gogo)
4556 {
4557   const Struct_field_list* fields = this->fields_;
4558   if (fields != NULL)
4559     {
4560       for (Struct_field_list::const_iterator p = fields->begin();
4561            p != fields->end();
4562            ++p)
4563         p->type()->get_backend(gogo);
4564     }
4565 }
4566
4567 // The type of a struct type descriptor.
4568
4569 Type*
4570 Struct_type::make_struct_type_descriptor_type()
4571 {
4572   static Type* ret;
4573   if (ret == NULL)
4574     {
4575       Type* tdt = Type::make_type_descriptor_type();
4576       Type* ptdt = Type::make_type_descriptor_ptr_type();
4577
4578       Type* uintptr_type = Type::lookup_integer_type("uintptr");
4579       Type* string_type = Type::lookup_string_type();
4580       Type* pointer_string_type = Type::make_pointer_type(string_type);
4581
4582       Struct_type* sf =
4583         Type::make_builtin_struct_type(5,
4584                                        "name", pointer_string_type,
4585                                        "pkgPath", pointer_string_type,
4586                                        "typ", ptdt,
4587                                        "tag", pointer_string_type,
4588                                        "offset", uintptr_type);
4589       Type* nsf = Type::make_builtin_named_type("structField", sf);
4590
4591       Type* slice_type = Type::make_array_type(nsf, NULL);
4592
4593       Struct_type* s = Type::make_builtin_struct_type(2,
4594                                                       "", tdt,
4595                                                       "fields", slice_type);
4596
4597       ret = Type::make_builtin_named_type("StructType", s);
4598     }
4599
4600   return ret;
4601 }
4602
4603 // Build a type descriptor for a struct type.
4604
4605 Expression*
4606 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4607 {
4608   Location bloc = Linemap::predeclared_location();
4609
4610   Type* stdt = Struct_type::make_struct_type_descriptor_type();
4611
4612   const Struct_field_list* fields = stdt->struct_type()->fields();
4613
4614   Expression_list* vals = new Expression_list();
4615   vals->reserve(2);
4616
4617   const Methods* methods = this->methods();
4618   // A named struct should not have methods--the methods should attach
4619   // to the named type.
4620   go_assert(methods == NULL || name == NULL);
4621
4622   Struct_field_list::const_iterator ps = fields->begin();
4623   go_assert(ps->is_field_name("commonType"));
4624   vals->push_back(this->type_descriptor_constructor(gogo,
4625                                                     RUNTIME_TYPE_KIND_STRUCT,
4626                                                     name, methods, true));
4627
4628   ++ps;
4629   go_assert(ps->is_field_name("fields"));
4630
4631   Expression_list* elements = new Expression_list();
4632   elements->reserve(this->fields_->size());
4633   Type* element_type = ps->type()->array_type()->element_type();
4634   for (Struct_field_list::const_iterator pf = this->fields_->begin();
4635        pf != this->fields_->end();
4636        ++pf)
4637     {
4638       const Struct_field_list* f = element_type->struct_type()->fields();
4639
4640       Expression_list* fvals = new Expression_list();
4641       fvals->reserve(5);
4642
4643       Struct_field_list::const_iterator q = f->begin();
4644       go_assert(q->is_field_name("name"));
4645       if (pf->is_anonymous())
4646         fvals->push_back(Expression::make_nil(bloc));
4647       else
4648         {
4649           std::string n = Gogo::unpack_hidden_name(pf->field_name());
4650           Expression* s = Expression::make_string(n, bloc);
4651           fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4652         }
4653
4654       ++q;
4655       go_assert(q->is_field_name("pkgPath"));
4656       if (!Gogo::is_hidden_name(pf->field_name()))
4657         fvals->push_back(Expression::make_nil(bloc));
4658       else
4659         {
4660           std::string n = Gogo::hidden_name_prefix(pf->field_name());
4661           Expression* s = Expression::make_string(n, bloc);
4662           fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4663         }
4664
4665       ++q;
4666       go_assert(q->is_field_name("typ"));
4667       fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
4668
4669       ++q;
4670       go_assert(q->is_field_name("tag"));
4671       if (!pf->has_tag())
4672         fvals->push_back(Expression::make_nil(bloc));
4673       else
4674         {
4675           Expression* s = Expression::make_string(pf->tag(), bloc);
4676           fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4677         }
4678
4679       ++q;
4680       go_assert(q->is_field_name("offset"));
4681       fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
4682
4683       Expression* v = Expression::make_struct_composite_literal(element_type,
4684                                                                 fvals, bloc);
4685       elements->push_back(v);
4686     }
4687
4688   vals->push_back(Expression::make_slice_composite_literal(ps->type(),
4689                                                            elements, bloc));
4690
4691   return Expression::make_struct_composite_literal(stdt, vals, bloc);
4692 }
4693
4694 // Write the hash function for a struct which can not use the identity
4695 // function.
4696
4697 void
4698 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
4699                                  Function_type* hash_fntype,
4700                                  Function_type* equal_fntype)
4701 {
4702   Location bloc = Linemap::predeclared_location();
4703
4704   // The pointer to the struct that we are going to hash.  This is an
4705   // argument to the hash function we are implementing here.
4706   Named_object* key_arg = gogo->lookup("key", NULL);
4707   go_assert(key_arg != NULL);
4708   Type* key_arg_type = key_arg->var_value()->type();
4709
4710   Type* uintptr_type = Type::lookup_integer_type("uintptr");
4711
4712   // Get a 0.
4713   mpz_t ival;
4714   mpz_init_set_ui(ival, 0);
4715   Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
4716   mpz_clear(ival);
4717
4718   // Make a temporary to hold the return value, initialized to 0.
4719   Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
4720                                                           bloc);
4721   gogo->add_statement(retval);
4722
4723   // Make a temporary to hold the key as a uintptr.
4724   Expression* ref = Expression::make_var_reference(key_arg, bloc);
4725   ref = Expression::make_cast(uintptr_type, ref, bloc);
4726   Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
4727                                                        bloc);
4728   gogo->add_statement(key);
4729
4730   // Loop over the struct fields.
4731   bool first = true;
4732   const Struct_field_list* fields = this->fields_;
4733   for (Struct_field_list::const_iterator pf = fields->begin();
4734        pf != fields->end();
4735        ++pf)
4736     {
4737       if (first)
4738         first = false;
4739       else
4740         {
4741           // Multiply retval by 33.
4742           mpz_init_set_ui(ival, 33);
4743           Expression* i33 = Expression::make_integer(&ival, uintptr_type,
4744                                                      bloc);
4745           mpz_clear(ival);
4746
4747           ref = Expression::make_temporary_reference(retval, bloc);
4748           Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ,
4749                                                               ref, i33, bloc);
4750           gogo->add_statement(s);
4751         }
4752
4753       // Get a pointer to the value of this field.
4754       Expression* offset = Expression::make_struct_field_offset(this, &*pf);
4755       ref = Expression::make_temporary_reference(key, bloc);
4756       Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
4757                                                    bloc);
4758       subkey = Expression::make_cast(key_arg_type, subkey, bloc);
4759
4760       // Get the size of this field.
4761       Expression* size = Expression::make_type_info(pf->type(),
4762                                                     Expression::TYPE_INFO_SIZE);
4763
4764       // Get the hash function to use for the type of this field.
4765       Named_object* hash_fn;
4766       Named_object* equal_fn;
4767       pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
4768                                  equal_fntype, &hash_fn, &equal_fn);
4769
4770       // Call the hash function for the field.
4771       Expression_list* args = new Expression_list();
4772       args->push_back(subkey);
4773       args->push_back(size);
4774       Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
4775       Expression* call = Expression::make_call(func, args, false, bloc);
4776
4777       // Add the field's hash value to retval.
4778       Temporary_reference_expression* tref =
4779         Expression::make_temporary_reference(retval, bloc);
4780       tref->set_is_lvalue();
4781       Statement* s = Statement::make_assignment_operation(OPERATOR_PLUSEQ,
4782                                                           tref, call, bloc);
4783       gogo->add_statement(s);
4784     }
4785
4786   // Return retval to the caller of the hash function.
4787   Expression_list* vals = new Expression_list();
4788   ref = Expression::make_temporary_reference(retval, bloc);
4789   vals->push_back(ref);
4790   Statement* s = Statement::make_return_statement(vals, bloc);
4791   gogo->add_statement(s);
4792 }
4793
4794 // Write the equality function for a struct which can not use the
4795 // identity function.
4796
4797 void
4798 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
4799 {
4800   Location bloc = Linemap::predeclared_location();
4801
4802   // The pointers to the structs we are going to compare.
4803   Named_object* key1_arg = gogo->lookup("key1", NULL);
4804   Named_object* key2_arg = gogo->lookup("key2", NULL);
4805   go_assert(key1_arg != NULL && key2_arg != NULL);
4806
4807   // Build temporaries with the right types.
4808   Type* pt = Type::make_pointer_type(name != NULL
4809                                      ? static_cast<Type*>(name)
4810                                      : static_cast<Type*>(this));
4811
4812   Expression* ref = Expression::make_var_reference(key1_arg, bloc);
4813   ref = Expression::make_unsafe_cast(pt, ref, bloc);
4814   Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
4815   gogo->add_statement(p1);
4816
4817   ref = Expression::make_var_reference(key2_arg, bloc);
4818   ref = Expression::make_unsafe_cast(pt, ref, bloc);
4819   Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
4820   gogo->add_statement(p2);
4821
4822   const Struct_field_list* fields = this->fields_;
4823   unsigned int field_index = 0;
4824   for (Struct_field_list::const_iterator pf = fields->begin();
4825        pf != fields->end();
4826        ++pf, ++field_index)
4827     {
4828       // Compare one field in both P1 and P2.
4829       Expression* f1 = Expression::make_temporary_reference(p1, bloc);
4830       f1 = Expression::make_unary(OPERATOR_MULT, f1, bloc);
4831       f1 = Expression::make_field_reference(f1, field_index, bloc);
4832
4833       Expression* f2 = Expression::make_temporary_reference(p2, bloc);
4834       f2 = Expression::make_unary(OPERATOR_MULT, f2, bloc);
4835       f2 = Expression::make_field_reference(f2, field_index, bloc);
4836
4837       Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
4838
4839       // If the values are not equal, return false.
4840       gogo->start_block(bloc);
4841       Expression_list* vals = new Expression_list();
4842       vals->push_back(Expression::make_boolean(false, bloc));
4843       Statement* s = Statement::make_return_statement(vals, bloc);
4844       gogo->add_statement(s);
4845       Block* then_block = gogo->finish_block(bloc);
4846
4847       s = Statement::make_if_statement(cond, then_block, NULL, bloc);
4848       gogo->add_statement(s);
4849     }
4850
4851   // All the fields are equal, so return true.
4852   Expression_list* vals = new Expression_list();
4853   vals->push_back(Expression::make_boolean(true, bloc));
4854   Statement* s = Statement::make_return_statement(vals, bloc);
4855   gogo->add_statement(s);
4856 }
4857
4858 // Reflection string.
4859
4860 void
4861 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
4862 {
4863   ret->append("struct { ");
4864
4865   for (Struct_field_list::const_iterator p = this->fields_->begin();
4866        p != this->fields_->end();
4867        ++p)
4868     {
4869       if (p != this->fields_->begin())
4870         ret->append("; ");
4871       if (p->is_anonymous())
4872         ret->push_back('?');
4873       else
4874         ret->append(Gogo::unpack_hidden_name(p->field_name()));
4875       ret->push_back(' ');
4876       this->append_reflection(p->type(), gogo, ret);
4877
4878       if (p->has_tag())
4879         {
4880           const std::string& tag(p->tag());
4881           ret->append(" \"");
4882           for (std::string::const_iterator p = tag.begin();
4883                p != tag.end();
4884                ++p)
4885             {
4886               if (*p == '\0')
4887                 ret->append("\\x00");
4888               else if (*p == '\n')
4889                 ret->append("\\n");
4890               else if (*p == '\t')
4891                 ret->append("\\t");
4892               else if (*p == '"')
4893                 ret->append("\\\"");
4894               else if (*p == '\\')
4895                 ret->append("\\\\");
4896               else
4897                 ret->push_back(*p);
4898             }
4899           ret->push_back('"');
4900         }
4901     }
4902
4903   ret->append(" }");
4904 }
4905
4906 // Mangled name.
4907
4908 void
4909 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4910 {
4911   ret->push_back('S');
4912
4913   const Struct_field_list* fields = this->fields_;
4914   if (fields != NULL)
4915     {
4916       for (Struct_field_list::const_iterator p = fields->begin();
4917            p != fields->end();
4918            ++p)
4919         {
4920           if (p->is_anonymous())
4921             ret->append("0_");
4922           else
4923             {
4924               std::string n = Gogo::unpack_hidden_name(p->field_name());
4925               char buf[20];
4926               snprintf(buf, sizeof buf, "%u_",
4927                        static_cast<unsigned int>(n.length()));
4928               ret->append(buf);
4929               ret->append(n);
4930             }
4931           this->append_mangled_name(p->type(), gogo, ret);
4932           if (p->has_tag())
4933             {
4934               const std::string& tag(p->tag());
4935               std::string out;
4936               for (std::string::const_iterator p = tag.begin();
4937                    p != tag.end();
4938                    ++p)
4939                 {
4940                   if (ISALNUM(*p) || *p == '_')
4941                     out.push_back(*p);
4942                   else
4943                     {
4944                       char buf[20];
4945                       snprintf(buf, sizeof buf, ".%x.",
4946                                static_cast<unsigned int>(*p));
4947                       out.append(buf);
4948                     }
4949                 }
4950               char buf[20];
4951               snprintf(buf, sizeof buf, "T%u_",
4952                        static_cast<unsigned int>(out.length()));
4953               ret->append(buf);
4954               ret->append(out);
4955             }
4956         }
4957     }
4958
4959   ret->push_back('e');
4960 }
4961
4962 // If the offset of field INDEX in the backend implementation can be
4963 // determined, set *POFFSET to the offset in bytes and return true.
4964 // Otherwise, return false.
4965
4966 bool
4967 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
4968                                   unsigned int* poffset)
4969 {
4970   if (!this->is_backend_type_size_known(gogo))
4971     return false;
4972   Btype* bt = this->get_backend_placeholder(gogo);
4973   size_t offset = gogo->backend()->type_field_offset(bt, index);
4974   *poffset = static_cast<unsigned int>(offset);
4975   if (*poffset != offset)
4976     return false;
4977   return true;
4978 }
4979
4980 // Export.
4981
4982 void
4983 Struct_type::do_export(Export* exp) const
4984 {
4985   exp->write_c_string("struct { ");
4986   const Struct_field_list* fields = this->fields_;
4987   go_assert(fields != NULL);
4988   for (Struct_field_list::const_iterator p = fields->begin();
4989        p != fields->end();
4990        ++p)
4991     {
4992       if (p->is_anonymous())
4993         exp->write_string("? ");
4994       else
4995         {
4996           exp->write_string(p->field_name());
4997           exp->write_c_string(" ");
4998         }
4999       exp->write_type(p->type());
5000
5001       if (p->has_tag())
5002         {
5003           exp->write_c_string(" ");
5004           Expression* expr =
5005             Expression::make_string(p->tag(), Linemap::predeclared_location());
5006           expr->export_expression(exp);
5007           delete expr;
5008         }
5009
5010       exp->write_c_string("; ");
5011     }
5012   exp->write_c_string("}");
5013 }
5014
5015 // Import.
5016
5017 Struct_type*
5018 Struct_type::do_import(Import* imp)
5019 {
5020   imp->require_c_string("struct { ");
5021   Struct_field_list* fields = new Struct_field_list;
5022   if (imp->peek_char() != '}')
5023     {
5024       while (true)
5025         {
5026           std::string name;
5027           if (imp->match_c_string("? "))
5028             imp->advance(2);
5029           else
5030             {
5031               name = imp->read_identifier();
5032               imp->require_c_string(" ");
5033             }
5034           Type* ftype = imp->read_type();
5035
5036           Struct_field sf(Typed_identifier(name, ftype, imp->location()));
5037
5038           if (imp->peek_char() == ' ')
5039             {
5040               imp->advance(1);
5041               Expression* expr = Expression::import_expression(imp);
5042               String_expression* sexpr = expr->string_expression();
5043               go_assert(sexpr != NULL);
5044               sf.set_tag(sexpr->val());
5045               delete sexpr;
5046             }
5047
5048           imp->require_c_string("; ");
5049           fields->push_back(sf);
5050           if (imp->peek_char() == '}')
5051             break;
5052         }
5053     }
5054   imp->require_c_string("}");
5055
5056   return Type::make_struct_type(fields, imp->location());
5057 }
5058
5059 // Make a struct type.
5060
5061 Struct_type*
5062 Type::make_struct_type(Struct_field_list* fields,
5063                        Location location)
5064 {
5065   return new Struct_type(fields, location);
5066 }
5067
5068 // Class Array_type.
5069
5070 // Whether two array types are identical.
5071
5072 bool
5073 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
5074 {
5075   if (!Type::are_identical(this->element_type(), t->element_type(),
5076                            errors_are_identical, NULL))
5077     return false;
5078
5079   Expression* l1 = this->length();
5080   Expression* l2 = t->length();
5081
5082   // Slices of the same element type are identical.
5083   if (l1 == NULL && l2 == NULL)
5084     return true;
5085
5086   // Arrays of the same element type are identical if they have the
5087   // same length.
5088   if (l1 != NULL && l2 != NULL)
5089     {
5090       if (l1 == l2)
5091         return true;
5092
5093       // Try to determine the lengths.  If we can't, assume the arrays
5094       // are not identical.
5095       bool ret = false;
5096       mpz_t v1;
5097       mpz_init(v1);
5098       Type* type1;
5099       mpz_t v2;
5100       mpz_init(v2);
5101       Type* type2;
5102       if (l1->integer_constant_value(true, v1, &type1)
5103           && l2->integer_constant_value(true, v2, &type2))
5104         ret = mpz_cmp(v1, v2) == 0;
5105       mpz_clear(v1);
5106       mpz_clear(v2);
5107       return ret;
5108     }
5109
5110   // Otherwise the arrays are not identical.
5111   return false;
5112 }
5113
5114 // Traversal.
5115
5116 int
5117 Array_type::do_traverse(Traverse* traverse)
5118 {
5119   if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
5120     return TRAVERSE_EXIT;
5121   if (this->length_ != NULL
5122       && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
5123     return TRAVERSE_EXIT;
5124   return TRAVERSE_CONTINUE;
5125 }
5126
5127 // Check that the length is valid.
5128
5129 bool
5130 Array_type::verify_length()
5131 {
5132   if (this->length_ == NULL)
5133     return true;
5134
5135   Type_context context(Type::lookup_integer_type("int"), false);
5136   this->length_->determine_type(&context);
5137
5138   if (!this->length_->is_constant())
5139     {
5140       error_at(this->length_->location(), "array bound is not constant");
5141       return false;
5142     }
5143
5144   mpz_t val;
5145   mpz_init(val);
5146   Type* vt;
5147   if (!this->length_->integer_constant_value(true, val, &vt))
5148     {
5149       mpfr_t fval;
5150       mpfr_init(fval);
5151       if (!this->length_->float_constant_value(fval, &vt))
5152         {
5153           if (this->length_->type()->integer_type() != NULL
5154               || this->length_->type()->float_type() != NULL)
5155             error_at(this->length_->location(),
5156                      "array bound is not constant");
5157           else
5158             error_at(this->length_->location(),
5159                      "array bound is not numeric");
5160           mpfr_clear(fval);
5161           mpz_clear(val);
5162           return false;
5163         }
5164       if (!mpfr_integer_p(fval))
5165         {
5166           error_at(this->length_->location(),
5167                    "array bound truncated to integer");
5168           mpfr_clear(fval);
5169           mpz_clear(val);
5170           return false;
5171         }
5172       mpz_init(val);
5173       mpfr_get_z(val, fval, GMP_RNDN);
5174       mpfr_clear(fval);
5175     }
5176
5177   if (mpz_sgn(val) < 0)
5178     {
5179       error_at(this->length_->location(), "negative array bound");
5180       mpz_clear(val);
5181       return false;
5182     }
5183
5184   Type* int_type = Type::lookup_integer_type("int");
5185   int tbits = int_type->integer_type()->bits();
5186   int vbits = mpz_sizeinbase(val, 2);
5187   if (vbits + 1 > tbits)
5188     {
5189       error_at(this->length_->location(), "array bound overflows");
5190       mpz_clear(val);
5191       return false;
5192     }
5193
5194   mpz_clear(val);
5195
5196   return true;
5197 }
5198
5199 // Verify the type.
5200
5201 bool
5202 Array_type::do_verify()
5203 {
5204   if (!this->verify_length())
5205     this->length_ = Expression::make_error(this->length_->location());
5206   return true;
5207 }
5208
5209 // Whether we can use memcmp to compare this array.
5210
5211 bool
5212 Array_type::do_compare_is_identity(Gogo* gogo) const
5213 {
5214   if (this->length_ == NULL)
5215     return false;
5216
5217   // Check for [...], which indicates that this is not a real type.
5218   if (this->length_->is_nil_expression())
5219     return false;
5220
5221   if (!this->element_type_->compare_is_identity(gogo))
5222     return false;
5223
5224   // If there is any padding, then we can't use memcmp.
5225   unsigned int size;
5226   unsigned int align;
5227   if (!this->element_type_->backend_type_size(gogo, &size)
5228       || !this->element_type_->backend_type_align(gogo, &align))
5229     return false;
5230   if ((size & (align - 1)) != 0)
5231     return false;
5232
5233   return true;
5234 }
5235
5236 // Array type hash code.
5237
5238 unsigned int
5239 Array_type::do_hash_for_method(Gogo* gogo) const
5240 {
5241   // There is no very convenient way to get a hash code for the
5242   // length.
5243   return this->element_type_->hash_for_method(gogo) + 1;
5244 }
5245
5246 // Write the hash function for an array which can not use the identify
5247 // function.
5248
5249 void
5250 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
5251                                 Function_type* hash_fntype,
5252                                 Function_type* equal_fntype)
5253 {
5254   Location bloc = Linemap::predeclared_location();
5255
5256   // The pointer to the array that we are going to hash.  This is an
5257   // argument to the hash function we are implementing here.
5258   Named_object* key_arg = gogo->lookup("key", NULL);
5259   go_assert(key_arg != NULL);
5260   Type* key_arg_type = key_arg->var_value()->type();
5261
5262   Type* uintptr_type = Type::lookup_integer_type("uintptr");
5263
5264   // Get a 0.
5265   mpz_t ival;
5266   mpz_init_set_ui(ival, 0);
5267   Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
5268   mpz_clear(ival);
5269
5270   // Make a temporary to hold the return value, initialized to 0.
5271   Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
5272                                                           bloc);
5273   gogo->add_statement(retval);
5274
5275   // Make a temporary to hold the key as a uintptr.
5276   Expression* ref = Expression::make_var_reference(key_arg, bloc);
5277   ref = Expression::make_cast(uintptr_type, ref, bloc);
5278   Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
5279                                                        bloc);
5280   gogo->add_statement(key);
5281
5282   // Loop over the array elements.
5283   // for i = range a
5284   Type* int_type = Type::lookup_integer_type("int");
5285   Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
5286   gogo->add_statement(index);
5287
5288   Expression* iref = Expression::make_temporary_reference(index, bloc);
5289   Expression* aref = Expression::make_var_reference(key_arg, bloc);
5290   Type* pt = Type::make_pointer_type(name != NULL
5291                                      ? static_cast<Type*>(name)
5292                                      : static_cast<Type*>(this));
5293   aref = Expression::make_cast(pt, aref, bloc);
5294   For_range_statement* for_range = Statement::make_for_range_statement(iref,
5295                                                                        NULL,
5296                                                                        aref,
5297                                                                        bloc);
5298
5299   gogo->start_block(bloc);
5300
5301   // Multiply retval by 33.
5302   mpz_init_set_ui(ival, 33);
5303   Expression* i33 = Expression::make_integer(&ival, uintptr_type, bloc);
5304   mpz_clear(ival);
5305
5306   ref = Expression::make_temporary_reference(retval, bloc);
5307   Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ, ref,
5308                                                       i33, bloc);
5309   gogo->add_statement(s);
5310
5311   // Get the hash function for the element type.
5312   Named_object* hash_fn;
5313   Named_object* equal_fn;
5314   this->element_type_->type_functions(gogo, this->element_type_->named_type(),
5315                                       hash_fntype, equal_fntype, &hash_fn,
5316                                       &equal_fn);
5317
5318   // Get a pointer to this element in the loop.
5319   Expression* subkey = Expression::make_temporary_reference(key, bloc);
5320   subkey = Expression::make_cast(key_arg_type, subkey, bloc);
5321
5322   // Get the size of each element.
5323   Expression* ele_size = Expression::make_type_info(this->element_type_,
5324                                                     Expression::TYPE_INFO_SIZE);
5325
5326   // Get the hash of this element.
5327   Expression_list* args = new Expression_list();
5328   args->push_back(subkey);
5329   args->push_back(ele_size);
5330   Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
5331   Expression* call = Expression::make_call(func, args, false, bloc);
5332
5333   // Add the element's hash value to retval.
5334   Temporary_reference_expression* tref =
5335     Expression::make_temporary_reference(retval, bloc);
5336   tref->set_is_lvalue();
5337   s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, call, bloc);
5338   gogo->add_statement(s);
5339
5340   // Increase the element pointer.
5341   tref = Expression::make_temporary_reference(key, bloc);
5342   tref->set_is_lvalue();
5343   s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
5344                                            bloc);
5345
5346   Block* statements = gogo->finish_block(bloc);
5347
5348   for_range->add_statements(statements);
5349   gogo->add_statement(for_range);
5350
5351   // Return retval to the caller of the hash function.
5352   Expression_list* vals = new Expression_list();
5353   ref = Expression::make_temporary_reference(retval, bloc);
5354   vals->push_back(ref);
5355   s = Statement::make_return_statement(vals, bloc);
5356   gogo->add_statement(s);
5357 }
5358
5359 // Write the equality function for an array which can not use the
5360 // identity function.
5361
5362 void
5363 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
5364 {
5365   Location bloc = Linemap::predeclared_location();
5366
5367   // The pointers to the arrays we are going to compare.
5368   Named_object* key1_arg = gogo->lookup("key1", NULL);
5369   Named_object* key2_arg = gogo->lookup("key2", NULL);
5370   go_assert(key1_arg != NULL && key2_arg != NULL);
5371
5372   // Build temporaries for the keys with the right types.
5373   Type* pt = Type::make_pointer_type(name != NULL
5374                                      ? static_cast<Type*>(name)
5375                                      : static_cast<Type*>(this));
5376
5377   Expression* ref = Expression::make_var_reference(key1_arg, bloc);
5378   ref = Expression::make_unsafe_cast(pt, ref, bloc);
5379   Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
5380   gogo->add_statement(p1);
5381
5382   ref = Expression::make_var_reference(key2_arg, bloc);
5383   ref = Expression::make_unsafe_cast(pt, ref, bloc);
5384   Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
5385   gogo->add_statement(p2);
5386
5387   // Loop over the array elements.
5388   // for i = range a
5389   Type* int_type = Type::lookup_integer_type("int");
5390   Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
5391   gogo->add_statement(index);
5392
5393   Expression* iref = Expression::make_temporary_reference(index, bloc);
5394   Expression* aref = Expression::make_temporary_reference(p1, bloc);
5395   For_range_statement* for_range = Statement::make_for_range_statement(iref,
5396                                                                        NULL,
5397                                                                        aref,
5398                                                                        bloc);
5399
5400   gogo->start_block(bloc);
5401
5402   // Compare element in P1 and P2.
5403   Expression* e1 = Expression::make_temporary_reference(p1, bloc);
5404   e1 = Expression::make_unary(OPERATOR_MULT, e1, bloc);
5405   ref = Expression::make_temporary_reference(index, bloc);
5406   e1 = Expression::make_array_index(e1, ref, NULL, bloc);
5407
5408   Expression* e2 = Expression::make_temporary_reference(p2, bloc);
5409   e2 = Expression::make_unary(OPERATOR_MULT, e2, bloc);
5410   ref = Expression::make_temporary_reference(index, bloc);
5411   e2 = Expression::make_array_index(e2, ref, NULL, bloc);
5412
5413   Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
5414
5415   // If the elements are not equal, return false.
5416   gogo->start_block(bloc);
5417   Expression_list* vals = new Expression_list();
5418   vals->push_back(Expression::make_boolean(false, bloc));
5419   Statement* s = Statement::make_return_statement(vals, bloc);
5420   gogo->add_statement(s);
5421   Block* then_block = gogo->finish_block(bloc);
5422
5423   s = Statement::make_if_statement(cond, then_block, NULL, bloc);
5424   gogo->add_statement(s);
5425
5426   Block* statements = gogo->finish_block(bloc);
5427
5428   for_range->add_statements(statements);
5429   gogo->add_statement(for_range);
5430
5431   // All the elements are equal, so return true.
5432   vals = new Expression_list();
5433   vals->push_back(Expression::make_boolean(true, bloc));
5434   s = Statement::make_return_statement(vals, bloc);
5435   gogo->add_statement(s);
5436 }
5437
5438 // Get a tree for the length of a fixed array.  The length may be
5439 // computed using a function call, so we must only evaluate it once.
5440
5441 tree
5442 Array_type::get_length_tree(Gogo* gogo)
5443 {
5444   go_assert(this->length_ != NULL);
5445   if (this->length_tree_ == NULL_TREE)
5446     {
5447       mpz_t val;
5448       mpz_init(val);
5449       Type* t;
5450       if (this->length_->integer_constant_value(true, val, &t))
5451         {
5452           if (t == NULL)
5453             t = Type::lookup_integer_type("int");
5454           else if (t->is_abstract())
5455             t = t->make_non_abstract_type();
5456           tree tt = type_to_tree(t->get_backend(gogo));
5457           this->length_tree_ = Expression::integer_constant_tree(val, tt);
5458           mpz_clear(val);
5459         }
5460       else
5461         {
5462           mpz_clear(val);
5463
5464           // Make up a translation context for the array length
5465           // expression.  FIXME: This won't work in general.
5466           Translate_context context(gogo, NULL, NULL, NULL);
5467           tree len = this->length_->get_tree(&context);
5468           if (len != error_mark_node)
5469             {
5470               len = convert_to_integer(integer_type_node, len);
5471               len = save_expr(len);
5472             }
5473           this->length_tree_ = len;
5474         }
5475     }
5476   return this->length_tree_;
5477 }
5478
5479 // Get the backend representation of the fields of a slice.  This is
5480 // not declared in types.h so that types.h doesn't have to #include
5481 // backend.h.
5482 //
5483 // We use int for the count and capacity fields.  This matches 6g.
5484 // The language more or less assumes that we can't allocate space of a
5485 // size which does not fit in int.
5486
5487 static void
5488 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
5489                          std::vector<Backend::Btyped_identifier>* bfields)
5490 {
5491   bfields->resize(3);
5492
5493   Type* pet = Type::make_pointer_type(type->element_type());
5494   Btype* pbet = (use_placeholder
5495                  ? pet->get_backend_placeholder(gogo)
5496                  : pet->get_backend(gogo));
5497   Location ploc = Linemap::predeclared_location();
5498
5499   Backend::Btyped_identifier* p = &(*bfields)[0];
5500   p->name = "__values";
5501   p->btype = pbet;
5502   p->location = ploc;
5503
5504   Type* int_type = Type::lookup_integer_type("int");
5505
5506   p = &(*bfields)[1];
5507   p->name = "__count";
5508   p->btype = int_type->get_backend(gogo);
5509   p->location = ploc;
5510
5511   p = &(*bfields)[2];
5512   p->name = "__capacity";
5513   p->btype = int_type->get_backend(gogo);
5514   p->location = ploc;
5515 }
5516
5517 // Get a tree for the type of this array.  A fixed array is simply
5518 // represented as ARRAY_TYPE with the appropriate index--i.e., it is
5519 // just like an array in C.  An open array is a struct with three
5520 // fields: a data pointer, the length, and the capacity.
5521
5522 Btype*
5523 Array_type::do_get_backend(Gogo* gogo)
5524 {
5525   if (this->length_ == NULL)
5526     {
5527       std::vector<Backend::Btyped_identifier> bfields;
5528       get_backend_slice_fields(gogo, this, false, &bfields);
5529       return gogo->backend()->struct_type(bfields);
5530     }
5531   else
5532     {
5533       Btype* element = this->get_backend_element(gogo, false);
5534       Bexpression* len = this->get_backend_length(gogo);
5535       return gogo->backend()->array_type(element, len);
5536     }
5537 }
5538
5539 // Return the backend representation of the element type.
5540
5541 Btype*
5542 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
5543 {
5544   if (use_placeholder)
5545     return this->element_type_->get_backend_placeholder(gogo);
5546   else
5547     return this->element_type_->get_backend(gogo);
5548 }
5549
5550 // Return the backend representation of the length.
5551
5552 Bexpression*
5553 Array_type::get_backend_length(Gogo* gogo)
5554 {
5555   return tree_to_expr(this->get_length_tree(gogo));
5556 }
5557
5558 // Finish backend representation of the array.
5559
5560 void
5561 Array_type::finish_backend_element(Gogo* gogo)
5562 {
5563   Type* et = this->array_type()->element_type();
5564   et->get_backend(gogo);
5565   if (this->is_slice_type())
5566     {
5567       // This relies on the fact that we always use the same
5568       // structure for a pointer to any given type.
5569       Type* pet = Type::make_pointer_type(et);
5570       pet->get_backend(gogo);
5571     }
5572 }
5573
5574 // Return a tree for a pointer to the values in ARRAY.
5575
5576 tree
5577 Array_type::value_pointer_tree(Gogo*, tree array) const
5578 {
5579   tree ret;
5580   if (this->length() != NULL)
5581     {
5582       // Fixed array.
5583       ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))),
5584                          build_fold_addr_expr(array));
5585     }
5586   else
5587     {
5588       // Open array.
5589       tree field = TYPE_FIELDS(TREE_TYPE(array));
5590       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
5591                         "__values") == 0);
5592       ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field,
5593                         NULL_TREE);
5594     }
5595   if (TREE_CONSTANT(array))
5596     TREE_CONSTANT(ret) = 1;
5597   return ret;
5598 }
5599
5600 // Return a tree for the length of the array ARRAY which has this
5601 // type.
5602
5603 tree
5604 Array_type::length_tree(Gogo* gogo, tree array)
5605 {
5606   if (this->length_ != NULL)
5607     {
5608       if (TREE_CODE(array) == SAVE_EXPR)
5609         return fold_convert(integer_type_node, this->get_length_tree(gogo));
5610       else
5611         return omit_one_operand(integer_type_node,
5612                                 this->get_length_tree(gogo), array);
5613     }
5614
5615   // This is an open array.  We need to read the length field.
5616
5617   tree type = TREE_TYPE(array);
5618   go_assert(TREE_CODE(type) == RECORD_TYPE);
5619
5620   tree field = DECL_CHAIN(TYPE_FIELDS(type));
5621   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
5622
5623   tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
5624   if (TREE_CONSTANT(array))
5625     TREE_CONSTANT(ret) = 1;
5626   return ret;
5627 }
5628
5629 // Return a tree for the capacity of the array ARRAY which has this
5630 // type.
5631
5632 tree
5633 Array_type::capacity_tree(Gogo* gogo, tree array)
5634 {
5635   if (this->length_ != NULL)
5636     return omit_one_operand(integer_type_node, this->get_length_tree(gogo),
5637                             array);
5638
5639   // This is an open array.  We need to read the capacity field.
5640
5641   tree type = TREE_TYPE(array);
5642   go_assert(TREE_CODE(type) == RECORD_TYPE);
5643
5644   tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type)));
5645   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
5646
5647   return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
5648 }
5649
5650 // Export.
5651
5652 void
5653 Array_type::do_export(Export* exp) const
5654 {
5655   exp->write_c_string("[");
5656   if (this->length_ != NULL)
5657     this->length_->export_expression(exp);
5658   exp->write_c_string("] ");
5659   exp->write_type(this->element_type_);
5660 }
5661
5662 // Import.
5663
5664 Array_type*
5665 Array_type::do_import(Import* imp)
5666 {
5667   imp->require_c_string("[");
5668   Expression* length;
5669   if (imp->peek_char() == ']')
5670     length = NULL;
5671   else
5672     length = Expression::import_expression(imp);
5673   imp->require_c_string("] ");
5674   Type* element_type = imp->read_type();
5675   return Type::make_array_type(element_type, length);
5676 }
5677
5678 // The type of an array type descriptor.
5679
5680 Type*
5681 Array_type::make_array_type_descriptor_type()
5682 {
5683   static Type* ret;
5684   if (ret == NULL)
5685     {
5686       Type* tdt = Type::make_type_descriptor_type();
5687       Type* ptdt = Type::make_type_descriptor_ptr_type();
5688
5689       Type* uintptr_type = Type::lookup_integer_type("uintptr");
5690
5691       Struct_type* sf =
5692         Type::make_builtin_struct_type(4,
5693                                        "", tdt,
5694                                        "elem", ptdt,
5695                                        "slice", ptdt,
5696                                        "len", uintptr_type);
5697
5698       ret = Type::make_builtin_named_type("ArrayType", sf);
5699     }
5700
5701   return ret;
5702 }
5703
5704 // The type of an slice type descriptor.
5705
5706 Type*
5707 Array_type::make_slice_type_descriptor_type()
5708 {
5709   static Type* ret;
5710   if (ret == NULL)
5711     {
5712       Type* tdt = Type::make_type_descriptor_type();
5713       Type* ptdt = Type::make_type_descriptor_ptr_type();
5714
5715       Struct_type* sf =
5716         Type::make_builtin_struct_type(2,
5717                                        "", tdt,
5718                                        "elem", ptdt);
5719
5720       ret = Type::make_builtin_named_type("SliceType", sf);
5721     }
5722
5723   return ret;
5724 }
5725
5726 // Build a type descriptor for an array/slice type.
5727
5728 Expression*
5729 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5730 {
5731   if (this->length_ != NULL)
5732     return this->array_type_descriptor(gogo, name);
5733   else
5734     return this->slice_type_descriptor(gogo, name);
5735 }
5736
5737 // Build a type descriptor for an array type.
5738
5739 Expression*
5740 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
5741 {
5742   Location bloc = Linemap::predeclared_location();
5743
5744   Type* atdt = Array_type::make_array_type_descriptor_type();
5745
5746   const Struct_field_list* fields = atdt->struct_type()->fields();
5747
5748   Expression_list* vals = new Expression_list();
5749   vals->reserve(3);
5750
5751   Struct_field_list::const_iterator p = fields->begin();
5752   go_assert(p->is_field_name("commonType"));
5753   vals->push_back(this->type_descriptor_constructor(gogo,
5754                                                     RUNTIME_TYPE_KIND_ARRAY,
5755                                                     name, NULL, true));
5756
5757   ++p;
5758   go_assert(p->is_field_name("elem"));
5759   vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5760
5761   ++p;
5762   go_assert(p->is_field_name("slice"));
5763   Type* slice_type = Type::make_array_type(this->element_type_, NULL);
5764   vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
5765
5766   ++p;
5767   go_assert(p->is_field_name("len"));
5768   vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
5769
5770   ++p;
5771   go_assert(p == fields->end());
5772
5773   return Expression::make_struct_composite_literal(atdt, vals, bloc);
5774 }
5775
5776 // Build a type descriptor for a slice type.
5777
5778 Expression*
5779 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
5780 {
5781   Location bloc = Linemap::predeclared_location();
5782
5783   Type* stdt = Array_type::make_slice_type_descriptor_type();
5784
5785   const Struct_field_list* fields = stdt->struct_type()->fields();
5786
5787   Expression_list* vals = new Expression_list();
5788   vals->reserve(2);
5789
5790   Struct_field_list::const_iterator p = fields->begin();
5791   go_assert(p->is_field_name("commonType"));
5792   vals->push_back(this->type_descriptor_constructor(gogo,
5793                                                     RUNTIME_TYPE_KIND_SLICE,
5794                                                     name, NULL, true));
5795
5796   ++p;
5797   go_assert(p->is_field_name("elem"));
5798   vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5799
5800   ++p;
5801   go_assert(p == fields->end());
5802
5803   return Expression::make_struct_composite_literal(stdt, vals, bloc);
5804 }
5805
5806 // Reflection string.
5807
5808 void
5809 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
5810 {
5811   ret->push_back('[');
5812   if (this->length_ != NULL)
5813     {
5814       mpz_t val;
5815       mpz_init(val);
5816       Type* type;
5817       if (!this->length_->integer_constant_value(true, val, &type))
5818         error_at(this->length_->location(),
5819                  "array length must be integer constant expression");
5820       else if (mpz_cmp_si(val, 0) < 0)
5821         error_at(this->length_->location(), "array length is negative");
5822       else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
5823         error_at(this->length_->location(), "array length is too large");
5824       else
5825         {
5826           char buf[50];
5827           snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
5828           ret->append(buf);
5829         }
5830       mpz_clear(val);
5831     }
5832   ret->push_back(']');
5833
5834   this->append_reflection(this->element_type_, gogo, ret);
5835 }
5836
5837 // Mangled name.
5838
5839 void
5840 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5841 {
5842   ret->push_back('A');
5843   this->append_mangled_name(this->element_type_, gogo, ret);
5844   if (this->length_ != NULL)
5845     {
5846       mpz_t val;
5847       mpz_init(val);
5848       Type* type;
5849       if (!this->length_->integer_constant_value(true, val, &type))
5850         error_at(this->length_->location(),
5851                  "array length must be integer constant expression");
5852       else if (mpz_cmp_si(val, 0) < 0)
5853         error_at(this->length_->location(), "array length is negative");
5854       else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
5855         error_at(this->length_->location(), "array size is too large");
5856       else
5857         {
5858           char buf[50];
5859           snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
5860           ret->append(buf);
5861         }
5862       mpz_clear(val);
5863     }
5864   ret->push_back('e');
5865 }
5866
5867 // Make an array type.
5868
5869 Array_type*
5870 Type::make_array_type(Type* element_type, Expression* length)
5871 {
5872   return new Array_type(element_type, length);
5873 }
5874
5875 // Class Map_type.
5876
5877 // Traversal.
5878
5879 int
5880 Map_type::do_traverse(Traverse* traverse)
5881 {
5882   if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
5883       || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
5884     return TRAVERSE_EXIT;
5885   return TRAVERSE_CONTINUE;
5886 }
5887
5888 // Check that the map type is OK.
5889
5890 bool
5891 Map_type::do_verify()
5892 {
5893   // The runtime support uses "map[void]void".
5894   if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
5895     error_at(this->location_, "invalid map key type");
5896   return true;
5897 }
5898
5899 // Whether two map types are identical.
5900
5901 bool
5902 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
5903 {
5904   return (Type::are_identical(this->key_type(), t->key_type(),
5905                               errors_are_identical, NULL)
5906           && Type::are_identical(this->val_type(), t->val_type(),
5907                                  errors_are_identical, NULL));
5908 }
5909
5910 // Hash code.
5911
5912 unsigned int
5913 Map_type::do_hash_for_method(Gogo* gogo) const
5914 {
5915   return (this->key_type_->hash_for_method(gogo)
5916           + this->val_type_->hash_for_method(gogo)
5917           + 2);
5918 }
5919
5920 // Get the backend representation for a map type.  A map type is
5921 // represented as a pointer to a struct.  The struct is __go_map in
5922 // libgo/map.h.
5923
5924 Btype*
5925 Map_type::do_get_backend(Gogo* gogo)
5926 {
5927   static Btype* backend_map_type;
5928   if (backend_map_type == NULL)
5929     {
5930       std::vector<Backend::Btyped_identifier> bfields(4);
5931
5932       Location bloc = Linemap::predeclared_location();
5933
5934       Type* pdt = Type::make_type_descriptor_ptr_type();
5935       bfields[0].name = "__descriptor";
5936       bfields[0].btype = pdt->get_backend(gogo);
5937       bfields[0].location = bloc;
5938
5939       Type* uintptr_type = Type::lookup_integer_type("uintptr");
5940       bfields[1].name = "__element_count";
5941       bfields[1].btype = uintptr_type->get_backend(gogo);
5942       bfields[1].location = bloc;
5943
5944       bfields[2].name = "__bucket_count";
5945       bfields[2].btype = bfields[1].btype;
5946       bfields[2].location = bloc;
5947
5948       Btype* bvt = gogo->backend()->void_type();
5949       Btype* bpvt = gogo->backend()->pointer_type(bvt);
5950       Btype* bppvt = gogo->backend()->pointer_type(bpvt);
5951       bfields[3].name = "__buckets";
5952       bfields[3].btype = bppvt;
5953       bfields[3].location = bloc;
5954
5955       Btype *bt = gogo->backend()->struct_type(bfields);
5956       bt = gogo->backend()->named_type("__go_map", bt, bloc);
5957       backend_map_type = gogo->backend()->pointer_type(bt);
5958     }
5959   return backend_map_type;
5960 }
5961
5962 // The type of a map type descriptor.
5963
5964 Type*
5965 Map_type::make_map_type_descriptor_type()
5966 {
5967   static Type* ret;
5968   if (ret == NULL)
5969     {
5970       Type* tdt = Type::make_type_descriptor_type();
5971       Type* ptdt = Type::make_type_descriptor_ptr_type();
5972
5973       Struct_type* sf =
5974         Type::make_builtin_struct_type(3,
5975                                        "", tdt,
5976                                        "key", ptdt,
5977                                        "elem", ptdt);
5978
5979       ret = Type::make_builtin_named_type("MapType", sf);
5980     }
5981
5982   return ret;
5983 }
5984
5985 // Build a type descriptor for a map type.
5986
5987 Expression*
5988 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5989 {
5990   Location bloc = Linemap::predeclared_location();
5991
5992   Type* mtdt = Map_type::make_map_type_descriptor_type();
5993
5994   const Struct_field_list* fields = mtdt->struct_type()->fields();
5995
5996   Expression_list* vals = new Expression_list();
5997   vals->reserve(3);
5998
5999   Struct_field_list::const_iterator p = fields->begin();
6000   go_assert(p->is_field_name("commonType"));
6001   vals->push_back(this->type_descriptor_constructor(gogo,
6002                                                     RUNTIME_TYPE_KIND_MAP,
6003                                                     name, NULL, true));
6004
6005   ++p;
6006   go_assert(p->is_field_name("key"));
6007   vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
6008
6009   ++p;
6010   go_assert(p->is_field_name("elem"));
6011   vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
6012
6013   ++p;
6014   go_assert(p == fields->end());
6015
6016   return Expression::make_struct_composite_literal(mtdt, vals, bloc);
6017 }
6018
6019 // A mapping from map types to map descriptors.
6020
6021 Map_type::Map_descriptors Map_type::map_descriptors;
6022
6023 // Build a map descriptor for this type.  Return a pointer to it.
6024
6025 tree
6026 Map_type::map_descriptor_pointer(Gogo* gogo, Location location)
6027 {
6028   Bvariable* bvar = this->map_descriptor(gogo);
6029   tree var_tree = var_to_tree(bvar);
6030   if (var_tree == error_mark_node)
6031     return error_mark_node;
6032   return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
6033 }
6034
6035 // Build a map descriptor for this type.
6036
6037 Bvariable*
6038 Map_type::map_descriptor(Gogo* gogo)
6039 {
6040   std::pair<Map_type*, Bvariable*> val(this, NULL);
6041   std::pair<Map_type::Map_descriptors::iterator, bool> ins =
6042     Map_type::map_descriptors.insert(val);
6043   if (!ins.second)
6044     return ins.first->second;
6045
6046   Type* key_type = this->key_type_;
6047   Type* val_type = this->val_type_;
6048
6049   // The map entry type is a struct with three fields.  Build that
6050   // struct so that we can get the offsets of the key and value within
6051   // a map entry.  The first field should technically be a pointer to
6052   // this type itself, but since we only care about field offsets we
6053   // just use pointer to bool.
6054   Type* pbool = Type::make_pointer_type(Type::make_boolean_type());
6055   Struct_type* map_entry_type =
6056     Type::make_builtin_struct_type(3,
6057                                    "__next", pbool,
6058                                    "__key", key_type,
6059                                    "__val", val_type);
6060
6061   Type* map_descriptor_type = Map_type::make_map_descriptor_type();
6062
6063   const Struct_field_list* fields =
6064     map_descriptor_type->struct_type()->fields();
6065
6066   Expression_list* vals = new Expression_list();
6067   vals->reserve(4);
6068
6069   Location bloc = Linemap::predeclared_location();
6070
6071   Struct_field_list::const_iterator p = fields->begin();
6072
6073   go_assert(p->is_field_name("__map_descriptor"));
6074   vals->push_back(Expression::make_type_descriptor(this, bloc));
6075
6076   ++p;
6077   go_assert(p->is_field_name("__entry_size"));
6078   Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
6079   vals->push_back(Expression::make_type_info(map_entry_type, type_info));
6080
6081   Struct_field_list::const_iterator pf = map_entry_type->fields()->begin();
6082   ++pf;
6083   go_assert(pf->is_field_name("__key"));
6084
6085   ++p;
6086   go_assert(p->is_field_name("__key_offset"));
6087   vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6088
6089   ++pf;
6090   go_assert(pf->is_field_name("__val"));
6091
6092   ++p;
6093   go_assert(p->is_field_name("__val_offset"));
6094   vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6095
6096   ++p;
6097   go_assert(p == fields->end());
6098
6099   Expression* initializer =
6100     Expression::make_struct_composite_literal(map_descriptor_type, vals, bloc);
6101
6102   std::string mangled_name = "__go_map_" + this->mangled_name(gogo);
6103   Btype* map_descriptor_btype = map_descriptor_type->get_backend(gogo);
6104   Bvariable* bvar = gogo->backend()->immutable_struct(mangled_name, true,
6105                                                       map_descriptor_btype,
6106                                                       bloc);
6107
6108   Translate_context context(gogo, NULL, NULL, NULL);
6109   context.set_is_const();
6110   Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
6111
6112   gogo->backend()->immutable_struct_set_init(bvar, mangled_name, true,
6113                                              map_descriptor_btype, bloc,
6114                                              binitializer);
6115
6116   ins.first->second = bvar;
6117   return bvar;
6118 }
6119
6120 // Build the type of a map descriptor.  This must match the struct
6121 // __go_map_descriptor in libgo/runtime/map.h.
6122
6123 Type*
6124 Map_type::make_map_descriptor_type()
6125 {
6126   static Type* ret;
6127   if (ret == NULL)
6128     {
6129       Type* ptdt = Type::make_type_descriptor_ptr_type();
6130       Type* uintptr_type = Type::lookup_integer_type("uintptr");
6131       Struct_type* sf =
6132         Type::make_builtin_struct_type(4,
6133                                        "__map_descriptor", ptdt,
6134                                        "__entry_size", uintptr_type,
6135                                        "__key_offset", uintptr_type,
6136                                        "__val_offset", uintptr_type);
6137       ret = Type::make_builtin_named_type("__go_map_descriptor", sf);
6138     }
6139   return ret;
6140 }
6141
6142 // Reflection string for a map.
6143
6144 void
6145 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
6146 {
6147   ret->append("map[");
6148   this->append_reflection(this->key_type_, gogo, ret);
6149   ret->append("]");
6150   this->append_reflection(this->val_type_, gogo, ret);
6151 }
6152
6153 // Mangled name for a map.
6154
6155 void
6156 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6157 {
6158   ret->push_back('M');
6159   this->append_mangled_name(this->key_type_, gogo, ret);
6160   ret->append("__");
6161   this->append_mangled_name(this->val_type_, gogo, ret);
6162 }
6163
6164 // Export a map type.
6165
6166 void
6167 Map_type::do_export(Export* exp) const
6168 {
6169   exp->write_c_string("map [");
6170   exp->write_type(this->key_type_);
6171   exp->write_c_string("] ");
6172   exp->write_type(this->val_type_);
6173 }
6174
6175 // Import a map type.
6176
6177 Map_type*
6178 Map_type::do_import(Import* imp)
6179 {
6180   imp->require_c_string("map [");
6181   Type* key_type = imp->read_type();
6182   imp->require_c_string("] ");
6183   Type* val_type = imp->read_type();
6184   return Type::make_map_type(key_type, val_type, imp->location());
6185 }
6186
6187 // Make a map type.
6188
6189 Map_type*
6190 Type::make_map_type(Type* key_type, Type* val_type, Location location)
6191 {
6192   return new Map_type(key_type, val_type, location);
6193 }
6194
6195 // Class Channel_type.
6196
6197 // Hash code.
6198
6199 unsigned int
6200 Channel_type::do_hash_for_method(Gogo* gogo) const
6201 {
6202   unsigned int ret = 0;
6203   if (this->may_send_)
6204     ret += 1;
6205   if (this->may_receive_)
6206     ret += 2;
6207   if (this->element_type_ != NULL)
6208     ret += this->element_type_->hash_for_method(gogo) << 2;
6209   return ret << 3;
6210 }
6211
6212 // Whether this type is the same as T.
6213
6214 bool
6215 Channel_type::is_identical(const Channel_type* t,
6216                            bool errors_are_identical) const
6217 {
6218   if (!Type::are_identical(this->element_type(), t->element_type(),
6219                            errors_are_identical, NULL))
6220     return false;
6221   return (this->may_send_ == t->may_send_
6222           && this->may_receive_ == t->may_receive_);
6223 }
6224
6225 // Return the tree for a channel type.  A channel is a pointer to a
6226 // __go_channel struct.  The __go_channel struct is defined in
6227 // libgo/runtime/channel.h.
6228
6229 Btype*
6230 Channel_type::do_get_backend(Gogo* gogo)
6231 {
6232   static Btype* backend_channel_type;
6233   if (backend_channel_type == NULL)
6234     {
6235       std::vector<Backend::Btyped_identifier> bfields;
6236       Btype* bt = gogo->backend()->struct_type(bfields);
6237       bt = gogo->backend()->named_type("__go_channel", bt,
6238                                        Linemap::predeclared_location());
6239       backend_channel_type = gogo->backend()->pointer_type(bt);
6240     }
6241   return backend_channel_type;
6242 }
6243
6244 // Build a type descriptor for a channel type.
6245
6246 Type*
6247 Channel_type::make_chan_type_descriptor_type()
6248 {
6249   static Type* ret;
6250   if (ret == NULL)
6251     {
6252       Type* tdt = Type::make_type_descriptor_type();
6253       Type* ptdt = Type::make_type_descriptor_ptr_type();
6254
6255       Type* uintptr_type = Type::lookup_integer_type("uintptr");
6256
6257       Struct_type* sf =
6258         Type::make_builtin_struct_type(3,
6259                                        "", tdt,
6260                                        "elem", ptdt,
6261                                        "dir", uintptr_type);
6262
6263       ret = Type::make_builtin_named_type("ChanType", sf);
6264     }
6265
6266   return ret;
6267 }
6268
6269 // Build a type descriptor for a map type.
6270
6271 Expression*
6272 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6273 {
6274   Location bloc = Linemap::predeclared_location();
6275
6276   Type* ctdt = Channel_type::make_chan_type_descriptor_type();
6277
6278   const Struct_field_list* fields = ctdt->struct_type()->fields();
6279
6280   Expression_list* vals = new Expression_list();
6281   vals->reserve(3);
6282
6283   Struct_field_list::const_iterator p = fields->begin();
6284   go_assert(p->is_field_name("commonType"));
6285   vals->push_back(this->type_descriptor_constructor(gogo,
6286                                                     RUNTIME_TYPE_KIND_CHAN,
6287                                                     name, NULL, true));
6288
6289   ++p;
6290   go_assert(p->is_field_name("elem"));
6291   vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
6292
6293   ++p;
6294   go_assert(p->is_field_name("dir"));
6295   // These bits must match the ones in libgo/runtime/go-type.h.
6296   int val = 0;
6297   if (this->may_receive_)
6298     val |= 1;
6299   if (this->may_send_)
6300     val |= 2;
6301   mpz_t iv;
6302   mpz_init_set_ui(iv, val);
6303   vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
6304   mpz_clear(iv);
6305
6306   ++p;
6307   go_assert(p == fields->end());
6308
6309   return Expression::make_struct_composite_literal(ctdt, vals, bloc);
6310 }
6311
6312 // Reflection string.
6313
6314 void
6315 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
6316 {
6317   if (!this->may_send_)
6318     ret->append("<-");
6319   ret->append("chan");
6320   if (!this->may_receive_)
6321     ret->append("<-");
6322   ret->push_back(' ');
6323   this->append_reflection(this->element_type_, gogo, ret);
6324 }
6325
6326 // Mangled name.
6327
6328 void
6329 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6330 {
6331   ret->push_back('C');
6332   this->append_mangled_name(this->element_type_, gogo, ret);
6333   if (this->may_send_)
6334     ret->push_back('s');
6335   if (this->may_receive_)
6336     ret->push_back('r');
6337   ret->push_back('e');
6338 }
6339
6340 // Export.
6341
6342 void
6343 Channel_type::do_export(Export* exp) const
6344 {
6345   exp->write_c_string("chan ");
6346   if (this->may_send_ && !this->may_receive_)
6347     exp->write_c_string("-< ");
6348   else if (this->may_receive_ && !this->may_send_)
6349     exp->write_c_string("<- ");
6350   exp->write_type(this->element_type_);
6351 }
6352
6353 // Import.
6354
6355 Channel_type*
6356 Channel_type::do_import(Import* imp)
6357 {
6358   imp->require_c_string("chan ");
6359
6360   bool may_send;
6361   bool may_receive;
6362   if (imp->match_c_string("-< "))
6363     {
6364       imp->advance(3);
6365       may_send = true;
6366       may_receive = false;
6367     }
6368   else if (imp->match_c_string("<- "))
6369     {
6370       imp->advance(3);
6371       may_receive = true;
6372       may_send = false;
6373     }
6374   else
6375     {
6376       may_send = true;
6377       may_receive = true;
6378     }
6379
6380   Type* element_type = imp->read_type();
6381
6382   return Type::make_channel_type(may_send, may_receive, element_type);
6383 }
6384
6385 // Make a new channel type.
6386
6387 Channel_type*
6388 Type::make_channel_type(bool send, bool receive, Type* element_type)
6389 {
6390   return new Channel_type(send, receive, element_type);
6391 }
6392
6393 // Class Interface_type.
6394
6395 // Traversal.
6396
6397 int
6398 Interface_type::do_traverse(Traverse* traverse)
6399 {
6400   Typed_identifier_list* methods = (this->methods_are_finalized_
6401                                     ? this->all_methods_
6402                                     : this->parse_methods_);
6403   if (methods == NULL)
6404     return TRAVERSE_CONTINUE;
6405   return methods->traverse(traverse);
6406 }
6407
6408 // Finalize the methods.  This handles interface inheritance.
6409
6410 void
6411 Interface_type::finalize_methods()
6412 {
6413   if (this->methods_are_finalized_)
6414     return;
6415   this->methods_are_finalized_ = true;
6416   if (this->parse_methods_ == NULL)
6417     return;
6418
6419   this->all_methods_ = new Typed_identifier_list();
6420   this->all_methods_->reserve(this->parse_methods_->size());
6421   Typed_identifier_list inherit;
6422   for (Typed_identifier_list::const_iterator pm =
6423          this->parse_methods_->begin();
6424        pm != this->parse_methods_->end();
6425        ++pm)
6426     {
6427       const Typed_identifier* p = &*pm;
6428       if (p->name().empty())
6429         inherit.push_back(*p);
6430       else if (this->find_method(p->name()) == NULL)
6431         this->all_methods_->push_back(*p);
6432       else
6433         error_at(p->location(), "duplicate method %qs",
6434                  Gogo::message_name(p->name()).c_str());
6435     }
6436
6437   std::vector<Named_type*> seen;
6438   seen.reserve(inherit.size());
6439   bool issued_recursive_error = false;
6440   while (!inherit.empty())
6441     {
6442       Type* t = inherit.back().type();
6443       Location tl = inherit.back().location();
6444       inherit.pop_back();
6445
6446       Interface_type* it = t->interface_type();
6447       if (it == NULL)
6448         {
6449           if (!t->is_error())
6450             error_at(tl, "interface contains embedded non-interface");
6451           continue;
6452         }
6453       if (it == this)
6454         {
6455           if (!issued_recursive_error)
6456             {
6457               error_at(tl, "invalid recursive interface");
6458               issued_recursive_error = true;
6459             }
6460           continue;
6461         }
6462
6463       Named_type* nt = t->named_type();
6464       if (nt != NULL && it->parse_methods_ != NULL)
6465         {
6466           std::vector<Named_type*>::const_iterator q;
6467           for (q = seen.begin(); q != seen.end(); ++q)
6468             {
6469               if (*q == nt)
6470                 {
6471                   error_at(tl, "inherited interface loop");
6472                   break;
6473                 }
6474             }
6475           if (q != seen.end())
6476             continue;
6477           seen.push_back(nt);
6478         }
6479
6480       const Typed_identifier_list* imethods = it->parse_methods_;
6481       if (imethods == NULL)
6482         continue;
6483       for (Typed_identifier_list::const_iterator q = imethods->begin();
6484            q != imethods->end();
6485            ++q)
6486         {
6487           if (q->name().empty())
6488             inherit.push_back(*q);
6489           else if (this->find_method(q->name()) == NULL)
6490             this->all_methods_->push_back(Typed_identifier(q->name(),
6491                                                            q->type(), tl));
6492           else
6493             error_at(tl, "inherited method %qs is ambiguous",
6494                      Gogo::message_name(q->name()).c_str());
6495         }
6496     }
6497
6498   if (!this->all_methods_->empty())
6499     this->all_methods_->sort_by_name();
6500   else
6501     {
6502       delete this->all_methods_;
6503       this->all_methods_ = NULL;
6504     }
6505 }
6506
6507 // Return the method NAME, or NULL.
6508
6509 const Typed_identifier*
6510 Interface_type::find_method(const std::string& name) const
6511 {
6512   go_assert(this->methods_are_finalized_);
6513   if (this->all_methods_ == NULL)
6514     return NULL;
6515   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6516        p != this->all_methods_->end();
6517        ++p)
6518     if (p->name() == name)
6519       return &*p;
6520   return NULL;
6521 }
6522
6523 // Return the method index.
6524
6525 size_t
6526 Interface_type::method_index(const std::string& name) const
6527 {
6528   go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
6529   size_t ret = 0;
6530   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6531        p != this->all_methods_->end();
6532        ++p, ++ret)
6533     if (p->name() == name)
6534       return ret;
6535   go_unreachable();
6536 }
6537
6538 // Return whether NAME is an unexported method, for better error
6539 // reporting.
6540
6541 bool
6542 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
6543 {
6544   go_assert(this->methods_are_finalized_);
6545   if (this->all_methods_ == NULL)
6546     return false;
6547   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6548        p != this->all_methods_->end();
6549        ++p)
6550     {
6551       const std::string& method_name(p->name());
6552       if (Gogo::is_hidden_name(method_name)
6553           && name == Gogo::unpack_hidden_name(method_name)
6554           && gogo->pack_hidden_name(name, false) != method_name)
6555         return true;
6556     }
6557   return false;
6558 }
6559
6560 // Whether this type is identical with T.
6561
6562 bool
6563 Interface_type::is_identical(const Interface_type* t,
6564                              bool errors_are_identical) const
6565 {
6566   go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
6567
6568   // We require the same methods with the same types.  The methods
6569   // have already been sorted.
6570   if (this->all_methods_ == NULL || t->all_methods_ == NULL)
6571     return this->all_methods_ == t->all_methods_;
6572
6573   if (this->assume_identical(this, t) || t->assume_identical(t, this))
6574     return true;
6575
6576   Assume_identical* hold_ai = this->assume_identical_;
6577   Assume_identical ai;
6578   ai.t1 = this;
6579   ai.t2 = t;
6580   ai.next = hold_ai;
6581   this->assume_identical_ = &ai;
6582
6583   Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
6584   Typed_identifier_list::const_iterator p2;
6585   for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
6586     {
6587       if (p1 == this->all_methods_->end())
6588         break;
6589       if (p1->name() != p2->name()
6590           || !Type::are_identical(p1->type(), p2->type(),
6591                                   errors_are_identical, NULL))
6592         break;
6593     }
6594
6595   this->assume_identical_ = hold_ai;
6596
6597   return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
6598 }
6599
6600 // Return true if T1 and T2 are assumed to be identical during a type
6601 // comparison.
6602
6603 bool
6604 Interface_type::assume_identical(const Interface_type* t1,
6605                                  const Interface_type* t2) const
6606 {
6607   for (Assume_identical* p = this->assume_identical_;
6608        p != NULL;
6609        p = p->next)
6610     if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
6611       return true;
6612   return false;
6613 }
6614
6615 // Whether we can assign the interface type T to this type.  The types
6616 // are known to not be identical.  An interface assignment is only
6617 // permitted if T is known to implement all methods in THIS.
6618 // Otherwise a type guard is required.
6619
6620 bool
6621 Interface_type::is_compatible_for_assign(const Interface_type* t,
6622                                          std::string* reason) const
6623 {
6624   go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
6625   if (this->all_methods_ == NULL)
6626     return true;
6627   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6628        p != this->all_methods_->end();
6629        ++p)
6630     {
6631       const Typed_identifier* m = t->find_method(p->name());
6632       if (m == NULL)
6633         {
6634           if (reason != NULL)
6635             {
6636               char buf[200];
6637               snprintf(buf, sizeof buf,
6638                        _("need explicit conversion; missing method %s%s%s"),
6639                        open_quote, Gogo::message_name(p->name()).c_str(),
6640                        close_quote);
6641               reason->assign(buf);
6642             }
6643           return false;
6644         }
6645
6646       std::string subreason;
6647       if (!Type::are_identical(p->type(), m->type(), true, &subreason))
6648         {
6649           if (reason != NULL)
6650             {
6651               std::string n = Gogo::message_name(p->name());
6652               size_t len = 100 + n.length() + subreason.length();
6653               char* buf = new char[len];
6654               if (subreason.empty())
6655                 snprintf(buf, len, _("incompatible type for method %s%s%s"),
6656                          open_quote, n.c_str(), close_quote);
6657               else
6658                 snprintf(buf, len,
6659                          _("incompatible type for method %s%s%s (%s)"),
6660                          open_quote, n.c_str(), close_quote,
6661                          subreason.c_str());
6662               reason->assign(buf);
6663               delete[] buf;
6664             }
6665           return false;
6666         }
6667     }
6668
6669   return true;
6670 }
6671
6672 // Hash code.
6673
6674 unsigned int
6675 Interface_type::do_hash_for_method(Gogo*) const
6676 {
6677   go_assert(this->methods_are_finalized_);
6678   unsigned int ret = 0;
6679   if (this->all_methods_ != NULL)
6680     {
6681       for (Typed_identifier_list::const_iterator p =
6682              this->all_methods_->begin();
6683            p != this->all_methods_->end();
6684            ++p)
6685         {
6686           ret = Type::hash_string(p->name(), ret);
6687           // We don't use the method type in the hash, to avoid
6688           // infinite recursion if an interface method uses a type
6689           // which is an interface which inherits from the interface
6690           // itself.
6691           // type T interface { F() interface {T}}
6692           ret <<= 1;
6693         }
6694     }
6695   return ret;
6696 }
6697
6698 // Return true if T implements the interface.  If it does not, and
6699 // REASON is not NULL, set *REASON to a useful error message.
6700
6701 bool
6702 Interface_type::implements_interface(const Type* t, std::string* reason) const
6703 {
6704   go_assert(this->methods_are_finalized_);
6705   if (this->all_methods_ == NULL)
6706     return true;
6707
6708   bool is_pointer = false;
6709   const Named_type* nt = t->named_type();
6710   const Struct_type* st = t->struct_type();
6711   // If we start with a named type, we don't dereference it to find
6712   // methods.
6713   if (nt == NULL)
6714     {
6715       const Type* pt = t->points_to();
6716       if (pt != NULL)
6717         {
6718           // If T is a pointer to a named type, then we need to look at
6719           // the type to which it points.
6720           is_pointer = true;
6721           nt = pt->named_type();
6722           st = pt->struct_type();
6723         }
6724     }
6725
6726   // If we have a named type, get the methods from it rather than from
6727   // any struct type.
6728   if (nt != NULL)
6729     st = NULL;
6730
6731   // Only named and struct types have methods.
6732   if (nt == NULL && st == NULL)
6733     {
6734       if (reason != NULL)
6735         {
6736           if (t->points_to() != NULL
6737               && t->points_to()->interface_type() != NULL)
6738             reason->assign(_("pointer to interface type has no methods"));
6739           else
6740             reason->assign(_("type has no methods"));
6741         }
6742       return false;
6743     }
6744
6745   if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
6746     {
6747       if (reason != NULL)
6748         {
6749           if (t->points_to() != NULL
6750               && t->points_to()->interface_type() != NULL)
6751             reason->assign(_("pointer to interface type has no methods"));
6752           else
6753             reason->assign(_("type has no methods"));
6754         }
6755       return false;
6756     }
6757
6758   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6759        p != this->all_methods_->end();
6760        ++p)
6761     {
6762       bool is_ambiguous = false;
6763       Method* m = (nt != NULL
6764                    ? nt->method_function(p->name(), &is_ambiguous)
6765                    : st->method_function(p->name(), &is_ambiguous));
6766       if (m == NULL)
6767         {
6768           if (reason != NULL)
6769             {
6770               std::string n = Gogo::message_name(p->name());
6771               size_t len = n.length() + 100;
6772               char* buf = new char[len];
6773               if (is_ambiguous)
6774                 snprintf(buf, len, _("ambiguous method %s%s%s"),
6775                          open_quote, n.c_str(), close_quote);
6776               else
6777                 snprintf(buf, len, _("missing method %s%s%s"),
6778                          open_quote, n.c_str(), close_quote);
6779               reason->assign(buf);
6780               delete[] buf;
6781             }
6782           return false;
6783         }
6784
6785       Function_type *p_fn_type = p->type()->function_type();
6786       Function_type* m_fn_type = m->type()->function_type();
6787       go_assert(p_fn_type != NULL && m_fn_type != NULL);
6788       std::string subreason;
6789       if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
6790         {
6791           if (reason != NULL)
6792             {
6793               std::string n = Gogo::message_name(p->name());
6794               size_t len = 100 + n.length() + subreason.length();
6795               char* buf = new char[len];
6796               if (subreason.empty())
6797                 snprintf(buf, len, _("incompatible type for method %s%s%s"),
6798                          open_quote, n.c_str(), close_quote);
6799               else
6800                 snprintf(buf, len,
6801                          _("incompatible type for method %s%s%s (%s)"),
6802                          open_quote, n.c_str(), close_quote,
6803                          subreason.c_str());
6804               reason->assign(buf);
6805               delete[] buf;
6806             }
6807           return false;
6808         }
6809
6810       if (!is_pointer && !m->is_value_method())
6811         {
6812           if (reason != NULL)
6813             {
6814               std::string n = Gogo::message_name(p->name());
6815               size_t len = 100 + n.length();
6816               char* buf = new char[len];
6817               snprintf(buf, len, _("method %s%s%s requires a pointer"),
6818                        open_quote, n.c_str(), close_quote);
6819               reason->assign(buf);
6820               delete[] buf;
6821             }
6822           return false;
6823         }
6824     }
6825
6826   return true;
6827 }
6828
6829 // Return the backend representation of the empty interface type.  We
6830 // use the same struct for all empty interfaces.
6831
6832 Btype*
6833 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
6834 {
6835   static Btype* empty_interface_type;
6836   if (empty_interface_type == NULL)
6837     {
6838       std::vector<Backend::Btyped_identifier> bfields(2);
6839
6840       Location bloc = Linemap::predeclared_location();
6841
6842       Type* pdt = Type::make_type_descriptor_ptr_type();
6843       bfields[0].name = "__type_descriptor";
6844       bfields[0].btype = pdt->get_backend(gogo);
6845       bfields[0].location = bloc;
6846
6847       Type* vt = Type::make_pointer_type(Type::make_void_type());
6848       bfields[1].name = "__object";
6849       bfields[1].btype = vt->get_backend(gogo);
6850       bfields[1].location = bloc;
6851
6852       empty_interface_type = gogo->backend()->struct_type(bfields);
6853     }
6854   return empty_interface_type;
6855 }
6856
6857 // Return the fields of a non-empty interface type.  This is not
6858 // declared in types.h so that types.h doesn't have to #include
6859 // backend.h.
6860
6861 static void
6862 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
6863                              bool use_placeholder,
6864                              std::vector<Backend::Btyped_identifier>* bfields)
6865 {
6866   Location loc = type->location();
6867
6868   std::vector<Backend::Btyped_identifier> mfields(type->methods()->size() + 1);
6869
6870   Type* pdt = Type::make_type_descriptor_ptr_type();
6871   mfields[0].name = "__type_descriptor";
6872   mfields[0].btype = pdt->get_backend(gogo);
6873   mfields[0].location = loc;
6874
6875   std::string last_name = "";
6876   size_t i = 1;
6877   for (Typed_identifier_list::const_iterator p = type->methods()->begin();
6878        p != type->methods()->end();
6879        ++p, ++i)
6880     {
6881       // The type of the method in Go only includes the parameters.
6882       // The actual method also has a receiver, which is always a
6883       // pointer.  We need to add that pointer type here in order to
6884       // generate the correct type for the backend.
6885       Function_type* ft = p->type()->function_type();
6886       go_assert(ft->receiver() == NULL);
6887
6888       const Typed_identifier_list* params = ft->parameters();
6889       Typed_identifier_list* mparams = new Typed_identifier_list();
6890       if (params != NULL)
6891         mparams->reserve(params->size() + 1);
6892       Type* vt = Type::make_pointer_type(Type::make_void_type());
6893       mparams->push_back(Typed_identifier("", vt, ft->location()));
6894       if (params != NULL)
6895         {
6896           for (Typed_identifier_list::const_iterator pp = params->begin();
6897                pp != params->end();
6898                ++pp)
6899             mparams->push_back(*pp);
6900         }
6901
6902       Typed_identifier_list* mresults = (ft->results() == NULL
6903                                          ? NULL
6904                                          : ft->results()->copy());
6905       Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
6906                                                     ft->location());
6907
6908       mfields[i].name = Gogo::unpack_hidden_name(p->name());
6909       mfields[i].btype = (use_placeholder
6910                           ? mft->get_backend_placeholder(gogo)
6911                           : mft->get_backend(gogo));
6912       mfields[i].location = loc;
6913       // Sanity check: the names should be sorted.
6914       go_assert(p->name() > last_name);
6915       last_name = p->name();
6916     }
6917
6918   Btype* methods = gogo->backend()->struct_type(mfields);
6919
6920   bfields->resize(2);
6921
6922   (*bfields)[0].name = "__methods";
6923   (*bfields)[0].btype = gogo->backend()->pointer_type(methods);
6924   (*bfields)[0].location = loc;
6925
6926   Type* vt = Type::make_pointer_type(Type::make_void_type());
6927   (*bfields)[1].name = "__object";
6928   (*bfields)[1].btype = vt->get_backend(gogo);
6929   (*bfields)[1].location = Linemap::predeclared_location();
6930 }
6931
6932 // Return a tree for an interface type.  An interface is a pointer to
6933 // a struct.  The struct has three fields.  The first field is a
6934 // pointer to the type descriptor for the dynamic type of the object.
6935 // The second field is a pointer to a table of methods for the
6936 // interface to be used with the object.  The third field is the value
6937 // of the object itself.
6938
6939 Btype*
6940 Interface_type::do_get_backend(Gogo* gogo)
6941 {
6942   if (this->is_empty())
6943     return Interface_type::get_backend_empty_interface_type(gogo);
6944   else
6945     {
6946       if (this->interface_btype_ != NULL)
6947         return this->interface_btype_;
6948       this->interface_btype_ =
6949         gogo->backend()->placeholder_struct_type("", this->location_);
6950       std::vector<Backend::Btyped_identifier> bfields;
6951       get_backend_interface_fields(gogo, this, false, &bfields);
6952       if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
6953                                                         bfields))
6954         this->interface_btype_ = gogo->backend()->error_type();
6955       return this->interface_btype_;
6956     }
6957 }
6958
6959 // Finish the backend representation of the methods.
6960
6961 void
6962 Interface_type::finish_backend_methods(Gogo* gogo)
6963 {
6964   if (!this->interface_type()->is_empty())
6965     {
6966       const Typed_identifier_list* methods = this->methods();
6967       if (methods != NULL)
6968         {
6969           for (Typed_identifier_list::const_iterator p = methods->begin();
6970                p != methods->end();
6971                ++p)
6972             p->type()->get_backend(gogo);
6973         }
6974     }
6975 }
6976
6977 // The type of an interface type descriptor.
6978
6979 Type*
6980 Interface_type::make_interface_type_descriptor_type()
6981 {
6982   static Type* ret;
6983   if (ret == NULL)
6984     {
6985       Type* tdt = Type::make_type_descriptor_type();
6986       Type* ptdt = Type::make_type_descriptor_ptr_type();
6987
6988       Type* string_type = Type::lookup_string_type();
6989       Type* pointer_string_type = Type::make_pointer_type(string_type);
6990
6991       Struct_type* sm =
6992         Type::make_builtin_struct_type(3,
6993                                        "name", pointer_string_type,
6994                                        "pkgPath", pointer_string_type,
6995                                        "typ", ptdt);
6996
6997       Type* nsm = Type::make_builtin_named_type("imethod", sm);
6998
6999       Type* slice_nsm = Type::make_array_type(nsm, NULL);
7000
7001       Struct_type* s = Type::make_builtin_struct_type(2,
7002                                                       "", tdt,
7003                                                       "methods", slice_nsm);
7004
7005       ret = Type::make_builtin_named_type("InterfaceType", s);
7006     }
7007
7008   return ret;
7009 }
7010
7011 // Build a type descriptor for an interface type.
7012
7013 Expression*
7014 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7015 {
7016   Location bloc = Linemap::predeclared_location();
7017
7018   Type* itdt = Interface_type::make_interface_type_descriptor_type();
7019
7020   const Struct_field_list* ifields = itdt->struct_type()->fields();
7021
7022   Expression_list* ivals = new Expression_list();
7023   ivals->reserve(2);
7024
7025   Struct_field_list::const_iterator pif = ifields->begin();
7026   go_assert(pif->is_field_name("commonType"));
7027   const int rt = RUNTIME_TYPE_KIND_INTERFACE;
7028   ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
7029                                                      true));
7030
7031   ++pif;
7032   go_assert(pif->is_field_name("methods"));
7033
7034   Expression_list* methods = new Expression_list();
7035   if (this->all_methods_ != NULL)
7036     {
7037       Type* elemtype = pif->type()->array_type()->element_type();
7038
7039       methods->reserve(this->all_methods_->size());
7040       for (Typed_identifier_list::const_iterator pm =
7041              this->all_methods_->begin();
7042            pm != this->all_methods_->end();
7043            ++pm)
7044         {
7045           const Struct_field_list* mfields = elemtype->struct_type()->fields();
7046
7047           Expression_list* mvals = new Expression_list();
7048           mvals->reserve(3);
7049
7050           Struct_field_list::const_iterator pmf = mfields->begin();
7051           go_assert(pmf->is_field_name("name"));
7052           std::string s = Gogo::unpack_hidden_name(pm->name());
7053           Expression* e = Expression::make_string(s, bloc);
7054           mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7055
7056           ++pmf;
7057           go_assert(pmf->is_field_name("pkgPath"));
7058           if (!Gogo::is_hidden_name(pm->name()))
7059             mvals->push_back(Expression::make_nil(bloc));
7060           else
7061             {
7062               s = Gogo::hidden_name_prefix(pm->name());
7063               e = Expression::make_string(s, bloc);
7064               mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7065             }
7066
7067           ++pmf;
7068           go_assert(pmf->is_field_name("typ"));
7069           mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
7070
7071           ++pmf;
7072           go_assert(pmf == mfields->end());
7073
7074           e = Expression::make_struct_composite_literal(elemtype, mvals,
7075                                                         bloc);
7076           methods->push_back(e);
7077         }
7078     }
7079
7080   ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
7081                                                             methods, bloc));
7082
7083   ++pif;
7084   go_assert(pif == ifields->end());
7085
7086   return Expression::make_struct_composite_literal(itdt, ivals, bloc);
7087 }
7088
7089 // Reflection string.
7090
7091 void
7092 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
7093 {
7094   ret->append("interface {");
7095   const Typed_identifier_list* methods = this->parse_methods_;
7096   if (methods != NULL)
7097     {
7098       ret->push_back(' ');
7099       for (Typed_identifier_list::const_iterator p = methods->begin();
7100            p != methods->end();
7101            ++p)
7102         {
7103           if (p != methods->begin())
7104             ret->append("; ");
7105           if (p->name().empty())
7106             this->append_reflection(p->type(), gogo, ret);
7107           else
7108             {
7109               if (!Gogo::is_hidden_name(p->name()))
7110                 ret->append(p->name());
7111               else
7112                 {
7113                   // This matches what the gc compiler does.
7114                   std::string prefix = Gogo::hidden_name_prefix(p->name());
7115                   ret->append(prefix.substr(prefix.find('.') + 1));
7116                   ret->push_back('.');
7117                   ret->append(Gogo::unpack_hidden_name(p->name()));
7118                 }
7119               std::string sub = p->type()->reflection(gogo);
7120               go_assert(sub.compare(0, 4, "func") == 0);
7121               sub = sub.substr(4);
7122               ret->append(sub);
7123             }
7124         }
7125       ret->push_back(' ');
7126     }
7127   ret->append("}");
7128 }
7129
7130 // Mangled name.
7131
7132 void
7133 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7134 {
7135   go_assert(this->methods_are_finalized_);
7136
7137   ret->push_back('I');
7138
7139   const Typed_identifier_list* methods = this->all_methods_;
7140   if (methods != NULL && !this->seen_)
7141     {
7142       this->seen_ = true;
7143       for (Typed_identifier_list::const_iterator p = methods->begin();
7144            p != methods->end();
7145            ++p)
7146         {
7147           if (!p->name().empty())
7148             {
7149               std::string n = Gogo::unpack_hidden_name(p->name());
7150               char buf[20];
7151               snprintf(buf, sizeof buf, "%u_",
7152                        static_cast<unsigned int>(n.length()));
7153               ret->append(buf);
7154               ret->append(n);
7155             }
7156           this->append_mangled_name(p->type(), gogo, ret);
7157         }
7158       this->seen_ = false;
7159     }
7160
7161   ret->push_back('e');
7162 }
7163
7164 // Export.
7165
7166 void
7167 Interface_type::do_export(Export* exp) const
7168 {
7169   exp->write_c_string("interface { ");
7170
7171   const Typed_identifier_list* methods = this->parse_methods_;
7172   if (methods != NULL)
7173     {
7174       for (Typed_identifier_list::const_iterator pm = methods->begin();
7175            pm != methods->end();
7176            ++pm)
7177         {
7178           if (pm->name().empty())
7179             {
7180               exp->write_c_string("? ");
7181               exp->write_type(pm->type());
7182             }
7183           else
7184             {
7185               exp->write_string(pm->name());
7186               exp->write_c_string(" (");
7187
7188               const Function_type* fntype = pm->type()->function_type();
7189
7190               bool first = true;
7191               const Typed_identifier_list* parameters = fntype->parameters();
7192               if (parameters != NULL)
7193                 {
7194                   bool is_varargs = fntype->is_varargs();
7195                   for (Typed_identifier_list::const_iterator pp =
7196                          parameters->begin();
7197                        pp != parameters->end();
7198                        ++pp)
7199                     {
7200                       if (first)
7201                         first = false;
7202                       else
7203                         exp->write_c_string(", ");
7204                       exp->write_name(pp->name());
7205                       exp->write_c_string(" ");
7206                       if (!is_varargs || pp + 1 != parameters->end())
7207                         exp->write_type(pp->type());
7208                       else
7209                         {
7210                           exp->write_c_string("...");
7211                           Type *pptype = pp->type();
7212                           exp->write_type(pptype->array_type()->element_type());
7213                         }
7214                     }
7215                 }
7216
7217               exp->write_c_string(")");
7218
7219               const Typed_identifier_list* results = fntype->results();
7220               if (results != NULL)
7221                 {
7222                   exp->write_c_string(" ");
7223                   if (results->size() == 1 && results->begin()->name().empty())
7224                     exp->write_type(results->begin()->type());
7225                   else
7226                     {
7227                       first = true;
7228                       exp->write_c_string("(");
7229                       for (Typed_identifier_list::const_iterator p =
7230                              results->begin();
7231                            p != results->end();
7232                            ++p)
7233                         {
7234                           if (first)
7235                             first = false;
7236                           else
7237                             exp->write_c_string(", ");
7238                           exp->write_name(p->name());
7239                           exp->write_c_string(" ");
7240                           exp->write_type(p->type());
7241                         }
7242                       exp->write_c_string(")");
7243                     }
7244                 }
7245             }
7246
7247           exp->write_c_string("; ");
7248         }
7249     }
7250
7251   exp->write_c_string("}");
7252 }
7253
7254 // Import an interface type.
7255
7256 Interface_type*
7257 Interface_type::do_import(Import* imp)
7258 {
7259   imp->require_c_string("interface { ");
7260
7261   Typed_identifier_list* methods = new Typed_identifier_list;
7262   while (imp->peek_char() != '}')
7263     {
7264       std::string name = imp->read_identifier();
7265
7266       if (name == "?")
7267         {
7268           imp->require_c_string(" ");
7269           Type* t = imp->read_type();
7270           methods->push_back(Typed_identifier("", t, imp->location()));
7271           imp->require_c_string("; ");
7272           continue;
7273         }
7274
7275       imp->require_c_string(" (");
7276
7277       Typed_identifier_list* parameters;
7278       bool is_varargs = false;
7279       if (imp->peek_char() == ')')
7280         parameters = NULL;
7281       else
7282         {
7283           parameters = new Typed_identifier_list;
7284           while (true)
7285             {
7286               std::string name = imp->read_name();
7287               imp->require_c_string(" ");
7288
7289               if (imp->match_c_string("..."))
7290                 {
7291                   imp->advance(3);
7292                   is_varargs = true;
7293                 }
7294
7295               Type* ptype = imp->read_type();
7296               if (is_varargs)
7297                 ptype = Type::make_array_type(ptype, NULL);
7298               parameters->push_back(Typed_identifier(name, ptype,
7299                                                      imp->location()));
7300               if (imp->peek_char() != ',')
7301                 break;
7302               go_assert(!is_varargs);
7303               imp->require_c_string(", ");
7304             }
7305         }
7306       imp->require_c_string(")");
7307
7308       Typed_identifier_list* results;
7309       if (imp->peek_char() != ' ')
7310         results = NULL;
7311       else
7312         {
7313           results = new Typed_identifier_list;
7314           imp->advance(1);
7315           if (imp->peek_char() != '(')
7316             {
7317               Type* rtype = imp->read_type();
7318               results->push_back(Typed_identifier("", rtype, imp->location()));
7319             }
7320           else
7321             {
7322               imp->advance(1);
7323               while (true)
7324                 {
7325                   std::string name = imp->read_name();
7326                   imp->require_c_string(" ");
7327                   Type* rtype = imp->read_type();
7328                   results->push_back(Typed_identifier(name, rtype,
7329                                                       imp->location()));
7330                   if (imp->peek_char() != ',')
7331                     break;
7332                   imp->require_c_string(", ");
7333                 }
7334               imp->require_c_string(")");
7335             }
7336         }
7337
7338       Function_type* fntype = Type::make_function_type(NULL, parameters,
7339                                                        results,
7340                                                        imp->location());
7341       if (is_varargs)
7342         fntype->set_is_varargs();
7343       methods->push_back(Typed_identifier(name, fntype, imp->location()));
7344
7345       imp->require_c_string("; ");
7346     }
7347
7348   imp->require_c_string("}");
7349
7350   if (methods->empty())
7351     {
7352       delete methods;
7353       methods = NULL;
7354     }
7355
7356   return Type::make_interface_type(methods, imp->location());
7357 }
7358
7359 // Make an interface type.
7360
7361 Interface_type*
7362 Type::make_interface_type(Typed_identifier_list* methods,
7363                           Location location)
7364 {
7365   return new Interface_type(methods, location);
7366 }
7367
7368 // Make an empty interface type.
7369
7370 Interface_type*
7371 Type::make_empty_interface_type(Location location)
7372 {
7373   Interface_type* ret = new Interface_type(NULL, location);
7374   ret->finalize_methods();
7375   return ret;
7376 }
7377
7378 // Class Method.
7379
7380 // Bind a method to an object.
7381
7382 Expression*
7383 Method::bind_method(Expression* expr, Location location) const
7384 {
7385   if (this->stub_ == NULL)
7386     {
7387       // When there is no stub object, the binding is determined by
7388       // the child class.
7389       return this->do_bind_method(expr, location);
7390     }
7391   return Expression::make_bound_method(expr, this->stub_, location);
7392 }
7393
7394 // Return the named object associated with a method.  This may only be
7395 // called after methods are finalized.
7396
7397 Named_object*
7398 Method::named_object() const
7399 {
7400   if (this->stub_ != NULL)
7401     return this->stub_;
7402   return this->do_named_object();
7403 }
7404
7405 // Class Named_method.
7406
7407 // The type of the method.
7408
7409 Function_type*
7410 Named_method::do_type() const
7411 {
7412   if (this->named_object_->is_function())
7413     return this->named_object_->func_value()->type();
7414   else if (this->named_object_->is_function_declaration())
7415     return this->named_object_->func_declaration_value()->type();
7416   else
7417     go_unreachable();
7418 }
7419
7420 // Return the location of the method receiver.
7421
7422 Location
7423 Named_method::do_receiver_location() const
7424 {
7425   return this->do_type()->receiver()->location();
7426 }
7427
7428 // Bind a method to an object.
7429
7430 Expression*
7431 Named_method::do_bind_method(Expression* expr, Location location) const
7432 {
7433   Named_object* no = this->named_object_;
7434   Bound_method_expression* bme = Expression::make_bound_method(expr, no,
7435                                                                location);
7436   // If this is not a local method, and it does not use a stub, then
7437   // the real method expects a different type.  We need to cast the
7438   // first argument.
7439   if (this->depth() > 0 && !this->needs_stub_method())
7440     {
7441       Function_type* ftype = this->do_type();
7442       go_assert(ftype->is_method());
7443       Type* frtype = ftype->receiver()->type();
7444       bme->set_first_argument_type(frtype);
7445     }
7446   return bme;
7447 }
7448
7449 // Class Interface_method.
7450
7451 // Bind a method to an object.
7452
7453 Expression*
7454 Interface_method::do_bind_method(Expression* expr,
7455                                  Location location) const
7456 {
7457   return Expression::make_interface_field_reference(expr, this->name_,
7458                                                     location);
7459 }
7460
7461 // Class Methods.
7462
7463 // Insert a new method.  Return true if it was inserted, false
7464 // otherwise.
7465
7466 bool
7467 Methods::insert(const std::string& name, Method* m)
7468 {
7469   std::pair<Method_map::iterator, bool> ins =
7470     this->methods_.insert(std::make_pair(name, m));
7471   if (ins.second)
7472     return true;
7473   else
7474     {
7475       Method* old_method = ins.first->second;
7476       if (m->depth() < old_method->depth())
7477         {
7478           delete old_method;
7479           ins.first->second = m;
7480           return true;
7481         }
7482       else
7483         {
7484           if (m->depth() == old_method->depth())
7485             old_method->set_is_ambiguous();
7486           return false;
7487         }
7488     }
7489 }
7490
7491 // Return the number of unambiguous methods.
7492
7493 size_t
7494 Methods::count() const
7495 {
7496   size_t ret = 0;
7497   for (Method_map::const_iterator p = this->methods_.begin();
7498        p != this->methods_.end();
7499        ++p)
7500     if (!p->second->is_ambiguous())
7501       ++ret;
7502   return ret;
7503 }
7504
7505 // Class Named_type.
7506
7507 // Return the name of the type.
7508
7509 const std::string&
7510 Named_type::name() const
7511 {
7512   return this->named_object_->name();
7513 }
7514
7515 // Return the name of the type to use in an error message.
7516
7517 std::string
7518 Named_type::message_name() const
7519 {
7520   return this->named_object_->message_name();
7521 }
7522
7523 // Whether this is an alias.  There are currently only two aliases so
7524 // we just recognize them by name.
7525
7526 bool
7527 Named_type::is_alias() const
7528 {
7529   if (!this->is_builtin())
7530     return false;
7531   const std::string& name(this->name());
7532   return name == "byte" || name == "rune";
7533 }
7534
7535 // Return the base type for this type.  We have to be careful about
7536 // circular type definitions, which are invalid but may be seen here.
7537
7538 Type*
7539 Named_type::named_base()
7540 {
7541   if (this->seen_)
7542     return this;
7543   this->seen_ = true;
7544   Type* ret = this->type_->base();
7545   this->seen_ = false;
7546   return ret;
7547 }
7548
7549 const Type*
7550 Named_type::named_base() const
7551 {
7552   if (this->seen_)
7553     return this;
7554   this->seen_ = true;
7555   const Type* ret = this->type_->base();
7556   this->seen_ = false;
7557   return ret;
7558 }
7559
7560 // Return whether this is an error type.  We have to be careful about
7561 // circular type definitions, which are invalid but may be seen here.
7562
7563 bool
7564 Named_type::is_named_error_type() const
7565 {
7566   if (this->seen_)
7567     return false;
7568   this->seen_ = true;
7569   bool ret = this->type_->is_error_type();
7570   this->seen_ = false;
7571   return ret;
7572 }
7573
7574 // Whether this type is comparable.  We have to be careful about
7575 // circular type definitions.
7576
7577 bool
7578 Named_type::named_type_is_comparable(std::string* reason) const
7579 {
7580   if (this->seen_)
7581     return false;
7582   this->seen_ = true;
7583   bool ret = Type::are_compatible_for_comparison(true, this->type_,
7584                                                  this->type_, reason);
7585   this->seen_ = false;
7586   return ret;
7587 }
7588
7589 // Add a method to this type.
7590
7591 Named_object*
7592 Named_type::add_method(const std::string& name, Function* function)
7593 {
7594   if (this->local_methods_ == NULL)
7595     this->local_methods_ = new Bindings(NULL);
7596   return this->local_methods_->add_function(name, NULL, function);
7597 }
7598
7599 // Add a method declaration to this type.
7600
7601 Named_object*
7602 Named_type::add_method_declaration(const std::string& name, Package* package,
7603                                    Function_type* type,
7604                                    Location location)
7605 {
7606   if (this->local_methods_ == NULL)
7607     this->local_methods_ = new Bindings(NULL);
7608   return this->local_methods_->add_function_declaration(name, package, type,
7609                                                         location);
7610 }
7611
7612 // Add an existing method to this type.
7613
7614 void
7615 Named_type::add_existing_method(Named_object* no)
7616 {
7617   if (this->local_methods_ == NULL)
7618     this->local_methods_ = new Bindings(NULL);
7619   this->local_methods_->add_named_object(no);
7620 }
7621
7622 // Look for a local method NAME, and returns its named object, or NULL
7623 // if not there.
7624
7625 Named_object*
7626 Named_type::find_local_method(const std::string& name) const
7627 {
7628   if (this->local_methods_ == NULL)
7629     return NULL;
7630   return this->local_methods_->lookup(name);
7631 }
7632
7633 // Return whether NAME is an unexported field or method, for better
7634 // error reporting.
7635
7636 bool
7637 Named_type::is_unexported_local_method(Gogo* gogo,
7638                                        const std::string& name) const
7639 {
7640   Bindings* methods = this->local_methods_;
7641   if (methods != NULL)
7642     {
7643       for (Bindings::const_declarations_iterator p =
7644              methods->begin_declarations();
7645            p != methods->end_declarations();
7646            ++p)
7647         {
7648           if (Gogo::is_hidden_name(p->first)
7649               && name == Gogo::unpack_hidden_name(p->first)
7650               && gogo->pack_hidden_name(name, false) != p->first)
7651             return true;
7652         }
7653     }
7654   return false;
7655 }
7656
7657 // Build the complete list of methods for this type, which means
7658 // recursively including all methods for anonymous fields.  Create all
7659 // stub methods.
7660
7661 void
7662 Named_type::finalize_methods(Gogo* gogo)
7663 {
7664   if (this->all_methods_ != NULL)
7665     return;
7666
7667   if (this->local_methods_ != NULL
7668       && (this->points_to() != NULL || this->interface_type() != NULL))
7669     {
7670       const Bindings* lm = this->local_methods_;
7671       for (Bindings::const_declarations_iterator p = lm->begin_declarations();
7672            p != lm->end_declarations();
7673            ++p)
7674         error_at(p->second->location(),
7675                  "invalid pointer or interface receiver type");
7676       delete this->local_methods_;
7677       this->local_methods_ = NULL;
7678       return;
7679     }
7680
7681   Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
7682 }
7683
7684 // Return the method NAME, or NULL if there isn't one or if it is
7685 // ambiguous.  Set *IS_AMBIGUOUS if the method exists but is
7686 // ambiguous.
7687
7688 Method*
7689 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
7690 {
7691   return Type::method_function(this->all_methods_, name, is_ambiguous);
7692 }
7693
7694 // Return a pointer to the interface method table for this type for
7695 // the interface INTERFACE.  IS_POINTER is true if this is for a
7696 // pointer to THIS.
7697
7698 tree
7699 Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface,
7700                                    bool is_pointer)
7701 {
7702   go_assert(!interface->is_empty());
7703
7704   Interface_method_tables** pimt = (is_pointer
7705                                     ? &this->interface_method_tables_
7706                                     : &this->pointer_interface_method_tables_);
7707
7708   if (*pimt == NULL)
7709     *pimt = new Interface_method_tables(5);
7710
7711   std::pair<const Interface_type*, tree> val(interface, NULL_TREE);
7712   std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
7713
7714   if (ins.second)
7715     {
7716       // This is a new entry in the hash table.
7717       go_assert(ins.first->second == NULL_TREE);
7718       ins.first->second = gogo->interface_method_table_for_type(interface,
7719                                                                 this,
7720                                                                 is_pointer);
7721     }
7722
7723   tree decl = ins.first->second;
7724   if (decl == error_mark_node)
7725     return error_mark_node;
7726   go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL);
7727   return build_fold_addr_expr(decl);
7728 }
7729
7730 // Return whether a named type has any hidden fields.
7731
7732 bool
7733 Named_type::named_type_has_hidden_fields(std::string* reason) const
7734 {
7735   if (this->seen_)
7736     return false;
7737   this->seen_ = true;
7738   bool ret = this->type_->has_hidden_fields(this, reason);
7739   this->seen_ = false;
7740   return ret;
7741 }
7742
7743 // Look for a use of a complete type within another type.  This is
7744 // used to check that we don't try to use a type within itself.
7745
7746 class Find_type_use : public Traverse
7747 {
7748  public:
7749   Find_type_use(Named_type* find_type)
7750     : Traverse(traverse_types),
7751       find_type_(find_type), found_(false)
7752   { }
7753
7754   // Whether we found the type.
7755   bool
7756   found() const
7757   { return this->found_; }
7758
7759  protected:
7760   int
7761   type(Type*);
7762
7763  private:
7764   // The type we are looking for.
7765   Named_type* find_type_;
7766   // Whether we found the type.
7767   bool found_;
7768 };
7769
7770 // Check for FIND_TYPE in TYPE.
7771
7772 int
7773 Find_type_use::type(Type* type)
7774 {
7775   if (type->named_type() != NULL && this->find_type_ == type->named_type())
7776     {
7777       this->found_ = true;
7778       return TRAVERSE_EXIT;
7779     }
7780
7781   // It's OK if we see a reference to the type in any type which is
7782   // essentially a pointer: a pointer, a slice, a function, a map, or
7783   // a channel.
7784   if (type->points_to() != NULL
7785       || type->is_slice_type()
7786       || type->function_type() != NULL
7787       || type->map_type() != NULL
7788       || type->channel_type() != NULL)
7789     return TRAVERSE_SKIP_COMPONENTS;
7790
7791   // For an interface, a reference to the type in a method type should
7792   // be ignored, but we have to consider direct inheritance.  When
7793   // this is called, there may be cases of direct inheritance
7794   // represented as a method with no name.
7795   if (type->interface_type() != NULL)
7796     {
7797       const Typed_identifier_list* methods = type->interface_type()->methods();
7798       if (methods != NULL)
7799         {
7800           for (Typed_identifier_list::const_iterator p = methods->begin();
7801                p != methods->end();
7802                ++p)
7803             {
7804               if (p->name().empty())
7805                 {
7806                   if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
7807                     return TRAVERSE_EXIT;
7808                 }
7809             }
7810         }
7811       return TRAVERSE_SKIP_COMPONENTS;
7812     }
7813
7814   // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
7815   // to convert TYPE to the backend representation before we convert
7816   // FIND_TYPE_.
7817   if (type->named_type() != NULL)
7818     {
7819       switch (type->base()->classification())
7820         {
7821         case Type::TYPE_ERROR:
7822         case Type::TYPE_BOOLEAN:
7823         case Type::TYPE_INTEGER:
7824         case Type::TYPE_FLOAT:
7825         case Type::TYPE_COMPLEX:
7826         case Type::TYPE_STRING:
7827         case Type::TYPE_NIL:
7828           break;
7829
7830         case Type::TYPE_ARRAY:
7831         case Type::TYPE_STRUCT:
7832           this->find_type_->add_dependency(type->named_type());
7833           break;
7834
7835         case Type::TYPE_NAMED:
7836         case Type::TYPE_FORWARD:
7837           go_assert(saw_errors());
7838           break;
7839
7840         case Type::TYPE_VOID:
7841         case Type::TYPE_SINK:
7842         case Type::TYPE_FUNCTION:
7843         case Type::TYPE_POINTER:
7844         case Type::TYPE_CALL_MULTIPLE_RESULT:
7845         case Type::TYPE_MAP:
7846         case Type::TYPE_CHANNEL:
7847         case Type::TYPE_INTERFACE:
7848         default:
7849           go_unreachable();
7850         }
7851     }
7852
7853   return TRAVERSE_CONTINUE;
7854 }
7855
7856 // Verify that a named type does not refer to itself.
7857
7858 bool
7859 Named_type::do_verify()
7860 {
7861   Find_type_use find(this);
7862   Type::traverse(this->type_, &find);
7863   if (find.found())
7864     {
7865       error_at(this->location_, "invalid recursive type %qs",
7866                this->message_name().c_str());
7867       this->is_error_ = true;
7868       return false;
7869     }
7870
7871   // Check whether any of the local methods overloads an existing
7872   // struct field or interface method.  We don't need to check the
7873   // list of methods against itself: that is handled by the Bindings
7874   // code.
7875   if (this->local_methods_ != NULL)
7876     {
7877       Struct_type* st = this->type_->struct_type();
7878       if (st != NULL)
7879         {
7880           for (Bindings::const_declarations_iterator p =
7881                  this->local_methods_->begin_declarations();
7882                p != this->local_methods_->end_declarations();
7883                ++p)
7884             {
7885               const std::string& name(p->first);
7886               if (st != NULL && st->find_local_field(name, NULL) != NULL)
7887                 {
7888                   error_at(p->second->location(),
7889                            "method %qs redeclares struct field name",
7890                            Gogo::message_name(name).c_str());
7891                 }
7892             }
7893         }
7894     }
7895
7896   return true;
7897 }
7898
7899 // Return whether this type is or contains a pointer.
7900
7901 bool
7902 Named_type::do_has_pointer() const
7903 {
7904   if (this->seen_)
7905     return false;
7906   this->seen_ = true;
7907   bool ret = this->type_->has_pointer();
7908   this->seen_ = false;
7909   return ret;
7910 }
7911
7912 // Return whether comparisons for this type can use the identity
7913 // function.
7914
7915 bool
7916 Named_type::do_compare_is_identity(Gogo* gogo) const
7917 {
7918   // We don't use this->seen_ here because compare_is_identity may
7919   // call base() later, and that will mess up if seen_ is set here.
7920   if (this->seen_in_compare_is_identity_)
7921     return false;
7922   this->seen_in_compare_is_identity_ = true;
7923   bool ret = this->type_->compare_is_identity(gogo);
7924   this->seen_in_compare_is_identity_ = false;
7925   return ret;
7926 }
7927
7928 // Return a hash code.  This is used for method lookup.  We simply
7929 // hash on the name itself.
7930
7931 unsigned int
7932 Named_type::do_hash_for_method(Gogo* gogo) const
7933 {
7934   if (this->is_alias())
7935     return this->type_->named_type()->do_hash_for_method(gogo);
7936
7937   const std::string& name(this->named_object()->name());
7938   unsigned int ret = Type::hash_string(name, 0);
7939
7940   // GOGO will be NULL here when called from Type_hash_identical.
7941   // That is OK because that is only used for internal hash tables
7942   // where we are going to be comparing named types for equality.  In
7943   // other cases, which are cases where the runtime is going to
7944   // compare hash codes to see if the types are the same, we need to
7945   // include the package prefix and name in the hash.
7946   if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
7947     {
7948       const Package* package = this->named_object()->package();
7949       if (package == NULL)
7950         {
7951           ret = Type::hash_string(gogo->unique_prefix(), ret);
7952           ret = Type::hash_string(gogo->package_name(), ret);
7953         }
7954       else
7955         {
7956           ret = Type::hash_string(package->unique_prefix(), ret);
7957           ret = Type::hash_string(package->name(), ret);
7958         }
7959     }
7960
7961   return ret;
7962 }
7963
7964 // Convert a named type to the backend representation.  In order to
7965 // get dependencies right, we fill in a dummy structure for this type,
7966 // then convert all the dependencies, then complete this type.  When
7967 // this function is complete, the size of the type is known.
7968
7969 void
7970 Named_type::convert(Gogo* gogo)
7971 {
7972   if (this->is_error_ || this->is_converted_)
7973     return;
7974
7975   this->create_placeholder(gogo);
7976
7977   // Convert all the dependencies.  If they refer indirectly back to
7978   // this type, they will pick up the intermediate tree we just
7979   // created.
7980   for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
7981        p != this->dependencies_.end();
7982        ++p)
7983     (*p)->convert(gogo);
7984
7985   // Complete this type.
7986   Btype* bt = this->named_btype_;
7987   Type* base = this->type_->base();
7988   switch (base->classification())
7989     {
7990     case TYPE_VOID:
7991     case TYPE_BOOLEAN:
7992     case TYPE_INTEGER:
7993     case TYPE_FLOAT:
7994     case TYPE_COMPLEX:
7995     case TYPE_STRING:
7996     case TYPE_NIL:
7997       break;
7998
7999     case TYPE_MAP:
8000     case TYPE_CHANNEL:
8001       break;
8002
8003     case TYPE_FUNCTION:
8004     case TYPE_POINTER:
8005       // The size of these types is already correct.  We don't worry
8006       // about filling them in until later, when we also track
8007       // circular references.
8008       break;
8009
8010     case TYPE_STRUCT:
8011       {
8012         std::vector<Backend::Btyped_identifier> bfields;
8013         get_backend_struct_fields(gogo, base->struct_type()->fields(),
8014                                   true, &bfields);
8015         if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8016           bt = gogo->backend()->error_type();
8017       }
8018       break;
8019
8020     case TYPE_ARRAY:
8021       // Slice types were completed in create_placeholder.
8022       if (!base->is_slice_type())
8023         {
8024           Btype* bet = base->array_type()->get_backend_element(gogo, true);
8025           Bexpression* blen = base->array_type()->get_backend_length(gogo);
8026           if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
8027             bt = gogo->backend()->error_type();
8028         }
8029       break;
8030
8031     case TYPE_INTERFACE:
8032       // Interface types were completed in create_placeholder.
8033       break;
8034
8035     case TYPE_ERROR:
8036       return;
8037
8038     default:
8039     case TYPE_SINK:
8040     case TYPE_CALL_MULTIPLE_RESULT:
8041     case TYPE_NAMED:
8042     case TYPE_FORWARD:
8043       go_unreachable();
8044     }
8045
8046   this->named_btype_ = bt;
8047   this->is_converted_ = true;
8048   this->is_placeholder_ = false;
8049 }
8050
8051 // Create the placeholder for a named type.  This is the first step in
8052 // converting to the backend representation.
8053
8054 void
8055 Named_type::create_placeholder(Gogo* gogo)
8056 {
8057   if (this->is_error_)
8058     this->named_btype_ = gogo->backend()->error_type();
8059
8060   if (this->named_btype_ != NULL)
8061     return;
8062
8063   // Create the structure for this type.  Note that because we call
8064   // base() here, we don't attempt to represent a named type defined
8065   // as another named type.  Instead both named types will point to
8066   // different base representations.
8067   Type* base = this->type_->base();
8068   Btype* bt;
8069   bool set_name = true;
8070   switch (base->classification())
8071     {
8072     case TYPE_ERROR:
8073       this->is_error_ = true;
8074       this->named_btype_ = gogo->backend()->error_type();
8075       return;
8076
8077     case TYPE_VOID:
8078     case TYPE_BOOLEAN:
8079     case TYPE_INTEGER:
8080     case TYPE_FLOAT:
8081     case TYPE_COMPLEX:
8082     case TYPE_STRING:
8083     case TYPE_NIL:
8084       // These are simple basic types, we can just create them
8085       // directly.
8086       bt = Type::get_named_base_btype(gogo, base);
8087       break;
8088
8089     case TYPE_MAP:
8090     case TYPE_CHANNEL:
8091       // All maps and channels have the same backend representation.
8092       bt = Type::get_named_base_btype(gogo, base);
8093       break;
8094
8095     case TYPE_FUNCTION:
8096     case TYPE_POINTER:
8097       {
8098         bool for_function = base->classification() == TYPE_FUNCTION;
8099         bt = gogo->backend()->placeholder_pointer_type(this->name(),
8100                                                        this->location_,
8101                                                        for_function);
8102         set_name = false;
8103       }
8104       break;
8105
8106     case TYPE_STRUCT:
8107       bt = gogo->backend()->placeholder_struct_type(this->name(),
8108                                                     this->location_);
8109       this->is_placeholder_ = true;
8110       set_name = false;
8111       break;
8112
8113     case TYPE_ARRAY:
8114       if (base->is_slice_type())
8115         bt = gogo->backend()->placeholder_struct_type(this->name(),
8116                                                       this->location_);
8117       else
8118         {
8119           bt = gogo->backend()->placeholder_array_type(this->name(),
8120                                                        this->location_);
8121           this->is_placeholder_ = true;
8122         }
8123       set_name = false;
8124       break;
8125
8126     case TYPE_INTERFACE:
8127       if (base->interface_type()->is_empty())
8128         bt = Interface_type::get_backend_empty_interface_type(gogo);
8129       else
8130         {
8131           bt = gogo->backend()->placeholder_struct_type(this->name(),
8132                                                         this->location_);
8133           set_name = false;
8134         }
8135       break;
8136
8137     default:
8138     case TYPE_SINK:
8139     case TYPE_CALL_MULTIPLE_RESULT:
8140     case TYPE_NAMED:
8141     case TYPE_FORWARD:
8142       go_unreachable();
8143     }
8144
8145   if (set_name)
8146     bt = gogo->backend()->named_type(this->name(), bt, this->location_);
8147
8148   this->named_btype_ = bt;
8149
8150   if (base->is_slice_type())
8151     {
8152       // We do not record slices as dependencies of other types,
8153       // because we can fill them in completely here with the final
8154       // size.
8155       std::vector<Backend::Btyped_identifier> bfields;
8156       get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
8157       if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8158         this->named_btype_ = gogo->backend()->error_type();
8159     }
8160   else if (base->interface_type() != NULL
8161            && !base->interface_type()->is_empty())
8162     {
8163       // We do not record interfaces as dependencies of other types,
8164       // because we can fill them in completely here with the final
8165       // size.
8166       std::vector<Backend::Btyped_identifier> bfields;
8167       get_backend_interface_fields(gogo, base->interface_type(), true,
8168                                    &bfields);
8169       if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8170         this->named_btype_ = gogo->backend()->error_type();
8171     }
8172 }
8173
8174 // Get a tree for a named type.
8175
8176 Btype*
8177 Named_type::do_get_backend(Gogo* gogo)
8178 {
8179   if (this->is_error_)
8180     return gogo->backend()->error_type();
8181
8182   Btype* bt = this->named_btype_;
8183
8184   if (!gogo->named_types_are_converted())
8185     {
8186       // We have not completed converting named types.  NAMED_BTYPE_
8187       // is a placeholder and we shouldn't do anything further.
8188       if (bt != NULL)
8189         return bt;
8190
8191       // We don't build dependencies for types whose sizes do not
8192       // change or are not relevant, so we may see them here while
8193       // converting types.
8194       this->create_placeholder(gogo);
8195       bt = this->named_btype_;
8196       go_assert(bt != NULL);
8197       return bt;
8198     }
8199
8200   // We are not converting types.  This should only be called if the
8201   // type has already been converted.
8202   if (!this->is_converted_)
8203     {
8204       go_assert(saw_errors());
8205       return gogo->backend()->error_type();
8206     }
8207
8208   go_assert(bt != NULL);
8209
8210   // Complete the tree.
8211   Type* base = this->type_->base();
8212   Btype* bt1;
8213   switch (base->classification())
8214     {
8215     case TYPE_ERROR:
8216       return gogo->backend()->error_type();
8217
8218     case TYPE_VOID:
8219     case TYPE_BOOLEAN:
8220     case TYPE_INTEGER:
8221     case TYPE_FLOAT:
8222     case TYPE_COMPLEX:
8223     case TYPE_STRING:
8224     case TYPE_NIL:
8225     case TYPE_MAP:
8226     case TYPE_CHANNEL:
8227       return bt;
8228
8229     case TYPE_STRUCT:
8230       if (!this->seen_in_get_backend_)
8231         {
8232           this->seen_in_get_backend_ = true;
8233           base->struct_type()->finish_backend_fields(gogo);
8234           this->seen_in_get_backend_ = false;
8235         }
8236       return bt;
8237
8238     case TYPE_ARRAY:
8239       if (!this->seen_in_get_backend_)
8240         {
8241           this->seen_in_get_backend_ = true;
8242           base->array_type()->finish_backend_element(gogo);
8243           this->seen_in_get_backend_ = false;
8244         }
8245       return bt;
8246
8247     case TYPE_INTERFACE:
8248       if (!this->seen_in_get_backend_)
8249         {
8250           this->seen_in_get_backend_ = true;
8251           base->interface_type()->finish_backend_methods(gogo);
8252           this->seen_in_get_backend_ = false;
8253         }
8254       return bt;
8255
8256     case TYPE_FUNCTION:
8257       // Don't build a circular data structure.  GENERIC can't handle
8258       // it.
8259       if (this->seen_in_get_backend_)
8260         {
8261           this->is_circular_ = true;
8262           return gogo->backend()->circular_pointer_type(bt, true);
8263         }
8264       this->seen_in_get_backend_ = true;
8265       bt1 = Type::get_named_base_btype(gogo, base);
8266       this->seen_in_get_backend_ = false;
8267       if (this->is_circular_)
8268         bt1 = gogo->backend()->circular_pointer_type(bt, true);
8269       if (!gogo->backend()->set_placeholder_function_type(bt, bt1))
8270         bt = gogo->backend()->error_type();
8271       return bt;
8272
8273     case TYPE_POINTER:
8274       // Don't build a circular data structure. GENERIC can't handle
8275       // it.
8276       if (this->seen_in_get_backend_)
8277         {
8278           this->is_circular_ = true;
8279           return gogo->backend()->circular_pointer_type(bt, false);
8280         }
8281       this->seen_in_get_backend_ = true;
8282       bt1 = Type::get_named_base_btype(gogo, base);
8283       this->seen_in_get_backend_ = false;
8284       if (this->is_circular_)
8285         bt1 = gogo->backend()->circular_pointer_type(bt, false);
8286       if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
8287         bt = gogo->backend()->error_type();
8288       return bt;
8289
8290     default:
8291     case TYPE_SINK:
8292     case TYPE_CALL_MULTIPLE_RESULT:
8293     case TYPE_NAMED:
8294     case TYPE_FORWARD:
8295       go_unreachable();
8296     }
8297
8298   go_unreachable();
8299 }
8300
8301 // Build a type descriptor for a named type.
8302
8303 Expression*
8304 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8305 {
8306   if (name == NULL && this->is_alias())
8307     return this->type_->type_descriptor(gogo, this->type_);
8308
8309   // If NAME is not NULL, then we don't really want the type
8310   // descriptor for this type; we want the descriptor for the
8311   // underlying type, giving it the name NAME.
8312   return this->named_type_descriptor(gogo, this->type_,
8313                                      name == NULL ? this : name);
8314 }
8315
8316 // Add to the reflection string.  This is used mostly for the name of
8317 // the type used in a type descriptor, not for actual reflection
8318 // strings.
8319
8320 void
8321 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
8322 {
8323   if (this->is_alias())
8324     {
8325       this->append_reflection(this->type_, gogo, ret);
8326       return;
8327     }
8328   if (!this->is_builtin())
8329     {
8330       const Package* package = this->named_object_->package();
8331       if (package != NULL)
8332         ret->append(package->name());
8333       else
8334         ret->append(gogo->package_name());
8335       ret->push_back('.');
8336     }
8337   if (this->in_function_ != NULL)
8338     {
8339       ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
8340       ret->push_back('$');
8341     }
8342   ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
8343 }
8344
8345 // Get the mangled name.
8346
8347 void
8348 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8349 {
8350   if (this->is_alias())
8351     {
8352       this->append_mangled_name(this->type_, gogo, ret);
8353       return;
8354     }
8355   Named_object* no = this->named_object_;
8356   std::string name;
8357   if (this->is_builtin())
8358     go_assert(this->in_function_ == NULL);
8359   else
8360     {
8361       const std::string& unique_prefix(no->package() == NULL
8362                                        ? gogo->unique_prefix()
8363                                        : no->package()->unique_prefix());
8364       const std::string& package_name(no->package() == NULL
8365                                       ? gogo->package_name()
8366                                       : no->package()->name());
8367       name = unique_prefix;
8368       name.append(1, '.');
8369       name.append(package_name);
8370       name.append(1, '.');
8371       if (this->in_function_ != NULL)
8372         {
8373           name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
8374           name.append(1, '$');
8375         }
8376     }
8377   name.append(Gogo::unpack_hidden_name(no->name()));
8378   char buf[20];
8379   snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
8380   ret->append(buf);
8381   ret->append(name);
8382 }
8383
8384 // Export the type.  This is called to export a global type.
8385
8386 void
8387 Named_type::export_named_type(Export* exp, const std::string&) const
8388 {
8389   // We don't need to write the name of the type here, because it will
8390   // be written by Export::write_type anyhow.
8391   exp->write_c_string("type ");
8392   exp->write_type(this);
8393   exp->write_c_string(";\n");
8394 }
8395
8396 // Import a named type.
8397
8398 void
8399 Named_type::import_named_type(Import* imp, Named_type** ptype)
8400 {
8401   imp->require_c_string("type ");
8402   Type *type = imp->read_type();
8403   *ptype = type->named_type();
8404   go_assert(*ptype != NULL);
8405   imp->require_c_string(";\n");
8406 }
8407
8408 // Export the type when it is referenced by another type.  In this
8409 // case Export::export_type will already have issued the name.
8410
8411 void
8412 Named_type::do_export(Export* exp) const
8413 {
8414   exp->write_type(this->type_);
8415
8416   // To save space, we only export the methods directly attached to
8417   // this type.
8418   Bindings* methods = this->local_methods_;
8419   if (methods == NULL)
8420     return;
8421
8422   exp->write_c_string("\n");
8423   for (Bindings::const_definitions_iterator p = methods->begin_definitions();
8424        p != methods->end_definitions();
8425        ++p)
8426     {
8427       exp->write_c_string(" ");
8428       (*p)->export_named_object(exp);
8429     }
8430
8431   for (Bindings::const_declarations_iterator p = methods->begin_declarations();
8432        p != methods->end_declarations();
8433        ++p)
8434     {
8435       if (p->second->is_function_declaration())
8436         {
8437           exp->write_c_string(" ");
8438           p->second->export_named_object(exp);
8439         }
8440     }
8441 }
8442
8443 // Make a named type.
8444
8445 Named_type*
8446 Type::make_named_type(Named_object* named_object, Type* type,
8447                       Location location)
8448 {
8449   return new Named_type(named_object, type, location);
8450 }
8451
8452 // Finalize the methods for TYPE.  It will be a named type or a struct
8453 // type.  This sets *ALL_METHODS to the list of methods, and builds
8454 // all required stubs.
8455
8456 void
8457 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
8458                        Methods** all_methods)
8459 {
8460   *all_methods = NULL;
8461   Types_seen types_seen;
8462   Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen,
8463                              all_methods);
8464   Type::build_stub_methods(gogo, type, *all_methods, location);
8465 }
8466
8467 // Add the methods for TYPE to *METHODS.  FIELD_INDEXES is used to
8468 // build up the struct field indexes as we go.  DEPTH is the depth of
8469 // the field within TYPE.  IS_EMBEDDED_POINTER is true if we are
8470 // adding these methods for an anonymous field with pointer type.
8471 // NEEDS_STUB_METHOD is true if we need to use a stub method which
8472 // calls the real method.  TYPES_SEEN is used to avoid infinite
8473 // recursion.
8474
8475 void
8476 Type::add_methods_for_type(const Type* type,
8477                            const Method::Field_indexes* field_indexes,
8478                            unsigned int depth,
8479                            bool is_embedded_pointer,
8480                            bool needs_stub_method,
8481                            Types_seen* types_seen,
8482                            Methods** methods)
8483 {
8484   // Pointer types may not have methods.
8485   if (type->points_to() != NULL)
8486     return;
8487
8488   const Named_type* nt = type->named_type();
8489   if (nt != NULL)
8490     {
8491       std::pair<Types_seen::iterator, bool> ins = types_seen->insert(nt);
8492       if (!ins.second)
8493         return;
8494     }
8495
8496   if (nt != NULL)
8497     Type::add_local_methods_for_type(nt, field_indexes, depth,
8498                                      is_embedded_pointer, needs_stub_method,
8499                                      methods);
8500
8501   Type::add_embedded_methods_for_type(type, field_indexes, depth,
8502                                       is_embedded_pointer, needs_stub_method,
8503                                       types_seen, methods);
8504
8505   // If we are called with depth > 0, then we are looking at an
8506   // anonymous field of a struct.  If such a field has interface type,
8507   // then we need to add the interface methods.  We don't want to add
8508   // them when depth == 0, because we will already handle them
8509   // following the usual rules for an interface type.
8510   if (depth > 0)
8511     Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
8512 }
8513
8514 // Add the local methods for the named type NT to *METHODS.  The
8515 // parameters are as for add_methods_to_type.
8516
8517 void
8518 Type::add_local_methods_for_type(const Named_type* nt,
8519                                  const Method::Field_indexes* field_indexes,
8520                                  unsigned int depth,
8521                                  bool is_embedded_pointer,
8522                                  bool needs_stub_method,
8523                                  Methods** methods)
8524 {
8525   const Bindings* local_methods = nt->local_methods();
8526   if (local_methods == NULL)
8527     return;
8528
8529   if (*methods == NULL)
8530     *methods = new Methods();
8531
8532   for (Bindings::const_declarations_iterator p =
8533          local_methods->begin_declarations();
8534        p != local_methods->end_declarations();
8535        ++p)
8536     {
8537       Named_object* no = p->second;
8538       bool is_value_method = (is_embedded_pointer
8539                               || !Type::method_expects_pointer(no));
8540       Method* m = new Named_method(no, field_indexes, depth, is_value_method,
8541                                    (needs_stub_method
8542                                     || (depth > 0 && is_value_method)));
8543       if (!(*methods)->insert(no->name(), m))
8544         delete m;
8545     }
8546 }
8547
8548 // Add the embedded methods for TYPE to *METHODS.  These are the
8549 // methods attached to anonymous fields.  The parameters are as for
8550 // add_methods_to_type.
8551
8552 void
8553 Type::add_embedded_methods_for_type(const Type* type,
8554                                     const Method::Field_indexes* field_indexes,
8555                                     unsigned int depth,
8556                                     bool is_embedded_pointer,
8557                                     bool needs_stub_method,
8558                                     Types_seen* types_seen,
8559                                     Methods** methods)
8560 {
8561   // Look for anonymous fields in TYPE.  TYPE has fields if it is a
8562   // struct.
8563   const Struct_type* st = type->struct_type();
8564   if (st == NULL)
8565     return;
8566
8567   const Struct_field_list* fields = st->fields();
8568   if (fields == NULL)
8569     return;
8570
8571   unsigned int i = 0;
8572   for (Struct_field_list::const_iterator pf = fields->begin();
8573        pf != fields->end();
8574        ++pf, ++i)
8575     {
8576       if (!pf->is_anonymous())
8577         continue;
8578
8579       Type* ftype = pf->type();
8580       bool is_pointer = false;
8581       if (ftype->points_to() != NULL)
8582         {
8583           ftype = ftype->points_to();
8584           is_pointer = true;
8585         }
8586       Named_type* fnt = ftype->named_type();
8587       if (fnt == NULL)
8588         {
8589           // This is an error, but it will be diagnosed elsewhere.
8590           continue;
8591         }
8592
8593       Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
8594       sub_field_indexes->next = field_indexes;
8595       sub_field_indexes->field_index = i;
8596
8597       Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
8598                                  (is_embedded_pointer || is_pointer),
8599                                  (needs_stub_method
8600                                   || is_pointer
8601                                   || i > 0),
8602                                  types_seen,
8603                                  methods);
8604     }
8605 }
8606
8607 // If TYPE is an interface type, then add its method to *METHODS.
8608 // This is for interface methods attached to an anonymous field.  The
8609 // parameters are as for add_methods_for_type.
8610
8611 void
8612 Type::add_interface_methods_for_type(const Type* type,
8613                                      const Method::Field_indexes* field_indexes,
8614                                      unsigned int depth,
8615                                      Methods** methods)
8616 {
8617   const Interface_type* it = type->interface_type();
8618   if (it == NULL)
8619     return;
8620
8621   const Typed_identifier_list* imethods = it->methods();
8622   if (imethods == NULL)
8623     return;
8624
8625   if (*methods == NULL)
8626     *methods = new Methods();
8627
8628   for (Typed_identifier_list::const_iterator pm = imethods->begin();
8629        pm != imethods->end();
8630        ++pm)
8631     {
8632       Function_type* fntype = pm->type()->function_type();
8633       if (fntype == NULL)
8634         {
8635           // This is an error, but it should be reported elsewhere
8636           // when we look at the methods for IT.
8637           continue;
8638         }
8639       go_assert(!fntype->is_method());
8640       fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
8641       Method* m = new Interface_method(pm->name(), pm->location(), fntype,
8642                                        field_indexes, depth);
8643       if (!(*methods)->insert(pm->name(), m))
8644         delete m;
8645     }
8646 }
8647
8648 // Build stub methods for TYPE as needed.  METHODS is the set of
8649 // methods for the type.  A stub method may be needed when a type
8650 // inherits a method from an anonymous field.  When we need the
8651 // address of the method, as in a type descriptor, we need to build a
8652 // little stub which does the required field dereferences and jumps to
8653 // the real method.  LOCATION is the location of the type definition.
8654
8655 void
8656 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
8657                          Location location)
8658 {
8659   if (methods == NULL)
8660     return;
8661   for (Methods::const_iterator p = methods->begin();
8662        p != methods->end();
8663        ++p)
8664     {
8665       Method* m = p->second;
8666       if (m->is_ambiguous() || !m->needs_stub_method())
8667         continue;
8668
8669       const std::string& name(p->first);
8670
8671       // Build a stub method.
8672
8673       const Function_type* fntype = m->type();
8674
8675       static unsigned int counter;
8676       char buf[100];
8677       snprintf(buf, sizeof buf, "$this%u", counter);
8678       ++counter;
8679
8680       Type* receiver_type = const_cast<Type*>(type);
8681       if (!m->is_value_method())
8682         receiver_type = Type::make_pointer_type(receiver_type);
8683       Location receiver_location = m->receiver_location();
8684       Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
8685                                                         receiver_location);
8686
8687       const Typed_identifier_list* fnparams = fntype->parameters();
8688       Typed_identifier_list* stub_params;
8689       if (fnparams == NULL || fnparams->empty())
8690         stub_params = NULL;
8691       else
8692         {
8693           // We give each stub parameter a unique name.
8694           stub_params = new Typed_identifier_list();
8695           for (Typed_identifier_list::const_iterator pp = fnparams->begin();
8696                pp != fnparams->end();
8697                ++pp)
8698             {
8699               char pbuf[100];
8700               snprintf(pbuf, sizeof pbuf, "$p%u", counter);
8701               stub_params->push_back(Typed_identifier(pbuf, pp->type(),
8702                                                       pp->location()));
8703               ++counter;
8704             }
8705         }
8706
8707       const Typed_identifier_list* fnresults = fntype->results();
8708       Typed_identifier_list* stub_results;
8709       if (fnresults == NULL || fnresults->empty())
8710         stub_results = NULL;
8711       else
8712         {
8713           // We create the result parameters without any names, since
8714           // we won't refer to them.
8715           stub_results = new Typed_identifier_list();
8716           for (Typed_identifier_list::const_iterator pr = fnresults->begin();
8717                pr != fnresults->end();
8718                ++pr)
8719             stub_results->push_back(Typed_identifier("", pr->type(),
8720                                                      pr->location()));
8721         }
8722
8723       Function_type* stub_type = Type::make_function_type(receiver,
8724                                                           stub_params,
8725                                                           stub_results,
8726                                                           fntype->location());
8727       if (fntype->is_varargs())
8728         stub_type->set_is_varargs();
8729
8730       // We only create the function in the package which creates the
8731       // type.
8732       const Package* package;
8733       if (type->named_type() == NULL)
8734         package = NULL;
8735       else
8736         package = type->named_type()->named_object()->package();
8737       Named_object* stub;
8738       if (package != NULL)
8739         stub = Named_object::make_function_declaration(name, package,
8740                                                        stub_type, location);
8741       else
8742         {
8743           stub = gogo->start_function(name, stub_type, false,
8744                                       fntype->location());
8745           Type::build_one_stub_method(gogo, m, buf, stub_params,
8746                                       fntype->is_varargs(), location);
8747           gogo->finish_function(fntype->location());
8748         }
8749
8750       m->set_stub_object(stub);
8751     }
8752 }
8753
8754 // Build a stub method which adjusts the receiver as required to call
8755 // METHOD.  RECEIVER_NAME is the name we used for the receiver.
8756 // PARAMS is the list of function parameters.
8757
8758 void
8759 Type::build_one_stub_method(Gogo* gogo, Method* method,
8760                             const char* receiver_name,
8761                             const Typed_identifier_list* params,
8762                             bool is_varargs,
8763                             Location location)
8764 {
8765   Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
8766   go_assert(receiver_object != NULL);
8767
8768   Expression* expr = Expression::make_var_reference(receiver_object, location);
8769   expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
8770   if (expr->type()->points_to() == NULL)
8771     expr = Expression::make_unary(OPERATOR_AND, expr, location);
8772
8773   Expression_list* arguments;
8774   if (params == NULL || params->empty())
8775     arguments = NULL;
8776   else
8777     {
8778       arguments = new Expression_list();
8779       for (Typed_identifier_list::const_iterator p = params->begin();
8780            p != params->end();
8781            ++p)
8782         {
8783           Named_object* param = gogo->lookup(p->name(), NULL);
8784           go_assert(param != NULL);
8785           Expression* param_ref = Expression::make_var_reference(param,
8786                                                                  location);
8787           arguments->push_back(param_ref);
8788         }
8789     }
8790
8791   Expression* func = method->bind_method(expr, location);
8792   go_assert(func != NULL);
8793   Call_expression* call = Expression::make_call(func, arguments, is_varargs,
8794                                                 location);
8795   call->set_hidden_fields_are_ok();
8796   size_t count = call->result_count();
8797   if (count == 0)
8798     gogo->add_statement(Statement::make_statement(call, true));
8799   else
8800     {
8801       Expression_list* retvals = new Expression_list();
8802       if (count <= 1)
8803         retvals->push_back(call);
8804       else
8805         {
8806           for (size_t i = 0; i < count; ++i)
8807             retvals->push_back(Expression::make_call_result(call, i));
8808         }
8809       Return_statement* retstat = Statement::make_return_statement(retvals,
8810                                                                    location);
8811
8812       // We can return values with hidden fields from a stub.  This is
8813       // necessary if the method is itself hidden.
8814       retstat->set_hidden_fields_are_ok();
8815
8816       gogo->add_statement(retstat);
8817     }
8818 }
8819
8820 // Apply FIELD_INDEXES to EXPR.  The field indexes have to be applied
8821 // in reverse order.
8822
8823 Expression*
8824 Type::apply_field_indexes(Expression* expr,
8825                           const Method::Field_indexes* field_indexes,
8826                           Location location)
8827 {
8828   if (field_indexes == NULL)
8829     return expr;
8830   expr = Type::apply_field_indexes(expr, field_indexes->next, location);
8831   Struct_type* stype = expr->type()->deref()->struct_type();
8832   go_assert(stype != NULL
8833              && field_indexes->field_index < stype->field_count());
8834   if (expr->type()->struct_type() == NULL)
8835     {
8836       go_assert(expr->type()->points_to() != NULL);
8837       expr = Expression::make_unary(OPERATOR_MULT, expr, location);
8838       go_assert(expr->type()->struct_type() == stype);
8839     }
8840   return Expression::make_field_reference(expr, field_indexes->field_index,
8841                                           location);
8842 }
8843
8844 // Return whether NO is a method for which the receiver is a pointer.
8845
8846 bool
8847 Type::method_expects_pointer(const Named_object* no)
8848 {
8849   const Function_type *fntype;
8850   if (no->is_function())
8851     fntype = no->func_value()->type();
8852   else if (no->is_function_declaration())
8853     fntype = no->func_declaration_value()->type();
8854   else
8855     go_unreachable();
8856   return fntype->receiver()->type()->points_to() != NULL;
8857 }
8858
8859 // Given a set of methods for a type, METHODS, return the method NAME,
8860 // or NULL if there isn't one or if it is ambiguous.  If IS_AMBIGUOUS
8861 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
8862 // but is ambiguous (and return NULL).
8863
8864 Method*
8865 Type::method_function(const Methods* methods, const std::string& name,
8866                       bool* is_ambiguous)
8867 {
8868   if (is_ambiguous != NULL)
8869     *is_ambiguous = false;
8870   if (methods == NULL)
8871     return NULL;
8872   Methods::const_iterator p = methods->find(name);
8873   if (p == methods->end())
8874     return NULL;
8875   Method* m = p->second;
8876   if (m->is_ambiguous())
8877     {
8878       if (is_ambiguous != NULL)
8879         *is_ambiguous = true;
8880       return NULL;
8881     }
8882   return m;
8883 }
8884
8885 // Look for field or method NAME for TYPE.  Return an Expression for
8886 // the field or method bound to EXPR.  If there is no such field or
8887 // method, give an appropriate error and return an error expression.
8888
8889 Expression*
8890 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
8891                            const std::string& name,
8892                            Location location)
8893 {
8894   if (type->deref()->is_error_type())
8895     return Expression::make_error(location);
8896
8897   const Named_type* nt = type->deref()->named_type();
8898   const Struct_type* st = type->deref()->struct_type();
8899   const Interface_type* it = type->interface_type();
8900
8901   // If this is a pointer to a pointer, then it is possible that the
8902   // pointed-to type has methods.
8903   bool dereferenced = false;
8904   if (nt == NULL
8905       && st == NULL
8906       && it == NULL
8907       && type->points_to() != NULL
8908       && type->points_to()->points_to() != NULL)
8909     {
8910       expr = Expression::make_unary(OPERATOR_MULT, expr, location);
8911       type = type->points_to();
8912       if (type->deref()->is_error_type())
8913         return Expression::make_error(location);
8914       nt = type->points_to()->named_type();
8915       st = type->points_to()->struct_type();
8916       dereferenced = true;
8917     }
8918
8919   bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
8920                                   || expr->is_addressable());
8921   std::vector<const Named_type*> seen;
8922   bool is_method = false;
8923   bool found_pointer_method = false;
8924   std::string ambig1;
8925   std::string ambig2;
8926   if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
8927                                  &seen, NULL, &is_method,
8928                                  &found_pointer_method, &ambig1, &ambig2))
8929     {
8930       Expression* ret;
8931       if (!is_method)
8932         {
8933           go_assert(st != NULL);
8934           if (type->struct_type() == NULL)
8935             {
8936               go_assert(type->points_to() != NULL);
8937               expr = Expression::make_unary(OPERATOR_MULT, expr,
8938                                             location);
8939               go_assert(expr->type()->struct_type() == st);
8940             }
8941           ret = st->field_reference(expr, name, location);
8942         }
8943       else if (it != NULL && it->find_method(name) != NULL)
8944         ret = Expression::make_interface_field_reference(expr, name,
8945                                                          location);
8946       else
8947         {
8948           Method* m;
8949           if (nt != NULL)
8950             m = nt->method_function(name, NULL);
8951           else if (st != NULL)
8952             m = st->method_function(name, NULL);
8953           else
8954             go_unreachable();
8955           go_assert(m != NULL);
8956           if (dereferenced && m->is_value_method())
8957             {
8958               error_at(location,
8959                        "calling value method requires explicit dereference");
8960               return Expression::make_error(location);
8961             }
8962           if (!m->is_value_method() && expr->type()->points_to() == NULL)
8963             expr = Expression::make_unary(OPERATOR_AND, expr, location);
8964           ret = m->bind_method(expr, location);
8965         }
8966       go_assert(ret != NULL);
8967       return ret;
8968     }
8969   else
8970     {
8971       if (!ambig1.empty())
8972         error_at(location, "%qs is ambiguous via %qs and %qs",
8973                  Gogo::message_name(name).c_str(), ambig1.c_str(),
8974                  ambig2.c_str());
8975       else if (found_pointer_method)
8976         error_at(location, "method requires a pointer");
8977       else if (nt == NULL && st == NULL && it == NULL)
8978         error_at(location,
8979                  ("reference to field %qs in object which "
8980                   "has no fields or methods"),
8981                  Gogo::message_name(name).c_str());
8982       else
8983         {
8984           bool is_unexported;
8985           if (!Gogo::is_hidden_name(name))
8986             is_unexported = false;
8987           else
8988             {
8989               std::string unpacked = Gogo::unpack_hidden_name(name);
8990               seen.clear();
8991               is_unexported = Type::is_unexported_field_or_method(gogo, type,
8992                                                                   unpacked,
8993                                                                   &seen);
8994             }
8995           if (is_unexported)
8996             error_at(location, "reference to unexported field or method %qs",
8997                      Gogo::message_name(name).c_str());
8998           else
8999             error_at(location, "reference to undefined field or method %qs",
9000                      Gogo::message_name(name).c_str());
9001         }
9002       return Expression::make_error(location);
9003     }
9004 }
9005
9006 // Look in TYPE for a field or method named NAME, return true if one
9007 // is found.  This looks through embedded anonymous fields and handles
9008 // ambiguity.  If a method is found, sets *IS_METHOD to true;
9009 // otherwise, if a field is found, set it to false.  If
9010 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
9011 // whose address can not be taken.  SEEN is used to avoid infinite
9012 // recursion on invalid types.
9013
9014 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
9015 // method we couldn't use because it requires a pointer.  LEVEL is
9016 // used for recursive calls, and can be NULL for a non-recursive call.
9017 // When this function returns false because it finds that the name is
9018 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
9019 // and *AMBIG2.  If the name is not found at all, *AMBIG1 and *AMBIG2
9020 // will be unchanged.
9021
9022 // This function just returns whether or not there is a field or
9023 // method, and whether it is a field or method.  It doesn't build an
9024 // expression to refer to it.  If it is a method, we then look in the
9025 // list of all methods for the type.  If it is a field, the search has
9026 // to be done again, looking only for fields, and building up the
9027 // expression as we go.
9028
9029 bool
9030 Type::find_field_or_method(const Type* type,
9031                            const std::string& name,
9032                            bool receiver_can_be_pointer,
9033                            std::vector<const Named_type*>* seen,
9034                            int* level,
9035                            bool* is_method,
9036                            bool* found_pointer_method,
9037                            std::string* ambig1,
9038                            std::string* ambig2)
9039 {
9040   // Named types can have locally defined methods.
9041   const Named_type* nt = type->named_type();
9042   if (nt == NULL && type->points_to() != NULL)
9043     nt = type->points_to()->named_type();
9044   if (nt != NULL)
9045     {
9046       Named_object* no = nt->find_local_method(name);
9047       if (no != NULL)
9048         {
9049           if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
9050             {
9051               *is_method = true;
9052               return true;
9053             }
9054
9055           // Record that we have found a pointer method in order to
9056           // give a better error message if we don't find anything
9057           // else.
9058           *found_pointer_method = true;
9059         }
9060
9061       for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9062            p != seen->end();
9063            ++p)
9064         {
9065           if (*p == nt)
9066             {
9067               // We've already seen this type when searching for methods.
9068               return false;
9069             }
9070         }
9071     }
9072
9073   // Interface types can have methods.
9074   const Interface_type* it = type->interface_type();
9075   if (it != NULL && it->find_method(name) != NULL)
9076     {
9077       *is_method = true;
9078       return true;
9079     }
9080
9081   // Struct types can have fields.  They can also inherit fields and
9082   // methods from anonymous fields.
9083   const Struct_type* st = type->deref()->struct_type();
9084   if (st == NULL)
9085     return false;
9086   const Struct_field_list* fields = st->fields();
9087   if (fields == NULL)
9088     return false;
9089
9090   if (nt != NULL)
9091     seen->push_back(nt);
9092
9093   int found_level = 0;
9094   bool found_is_method = false;
9095   std::string found_ambig1;
9096   std::string found_ambig2;
9097   const Struct_field* found_parent = NULL;
9098   for (Struct_field_list::const_iterator pf = fields->begin();
9099        pf != fields->end();
9100        ++pf)
9101     {
9102       if (pf->is_field_name(name))
9103         {
9104           *is_method = false;
9105           if (nt != NULL)
9106             seen->pop_back();
9107           return true;
9108         }
9109
9110       if (!pf->is_anonymous())
9111         continue;
9112
9113       if (pf->type()->deref()->is_error_type()
9114           || pf->type()->deref()->is_undefined())
9115         continue;
9116
9117       Named_type* fnt = pf->type()->named_type();
9118       if (fnt == NULL)
9119         fnt = pf->type()->deref()->named_type();
9120       go_assert(fnt != NULL);
9121
9122       int sublevel = level == NULL ? 1 : *level + 1;
9123       bool sub_is_method;
9124       std::string subambig1;
9125       std::string subambig2;
9126       bool subfound = Type::find_field_or_method(fnt,
9127                                                  name,
9128                                                  receiver_can_be_pointer,
9129                                                  seen,
9130                                                  &sublevel,
9131                                                  &sub_is_method,
9132                                                  found_pointer_method,
9133                                                  &subambig1,
9134                                                  &subambig2);
9135       if (!subfound)
9136         {
9137           if (!subambig1.empty())
9138             {
9139               // The name was found via this field, but is ambiguous.
9140               // if the ambiguity is lower or at the same level as
9141               // anything else we have already found, then we want to
9142               // pass the ambiguity back to the caller.
9143               if (found_level == 0 || sublevel <= found_level)
9144                 {
9145                   found_ambig1 = (Gogo::message_name(pf->field_name())
9146                                   + '.' + subambig1);
9147                   found_ambig2 = (Gogo::message_name(pf->field_name())
9148                                   + '.' + subambig2);
9149                   found_level = sublevel;
9150                 }
9151             }
9152         }
9153       else
9154         {
9155           // The name was found via this field.  Use the level to see
9156           // if we want to use this one, or whether it introduces an
9157           // ambiguity.
9158           if (found_level == 0 || sublevel < found_level)
9159             {
9160               found_level = sublevel;
9161               found_is_method = sub_is_method;
9162               found_ambig1.clear();
9163               found_ambig2.clear();
9164               found_parent = &*pf;
9165             }
9166           else if (sublevel > found_level)
9167             ;
9168           else if (found_ambig1.empty())
9169             {
9170               // We found an ambiguity.
9171               go_assert(found_parent != NULL);
9172               found_ambig1 = Gogo::message_name(found_parent->field_name());
9173               found_ambig2 = Gogo::message_name(pf->field_name());
9174             }
9175           else
9176             {
9177               // We found an ambiguity, but we already know of one.
9178               // Just report the earlier one.
9179             }
9180         }
9181     }
9182
9183   // Here if we didn't find anything FOUND_LEVEL is 0.  If we found
9184   // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
9185   // FOUND_AMBIG2 are not empty.  If we found the field, FOUND_LEVEL
9186   // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
9187
9188   if (nt != NULL)
9189     seen->pop_back();
9190
9191   if (found_level == 0)
9192     return false;
9193   else if (!found_ambig1.empty())
9194     {
9195       go_assert(!found_ambig1.empty());
9196       ambig1->assign(found_ambig1);
9197       ambig2->assign(found_ambig2);
9198       if (level != NULL)
9199         *level = found_level;
9200       return false;
9201     }
9202   else
9203     {
9204       if (level != NULL)
9205         *level = found_level;
9206       *is_method = found_is_method;
9207       return true;
9208     }
9209 }
9210
9211 // Return whether NAME is an unexported field or method for TYPE.
9212
9213 bool
9214 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
9215                                     const std::string& name,
9216                                     std::vector<const Named_type*>* seen)
9217 {
9218   const Named_type* nt = type->named_type();
9219   if (nt == NULL)
9220     nt = type->deref()->named_type();
9221   if (nt != NULL)
9222     {
9223       if (nt->is_unexported_local_method(gogo, name))
9224         return true;
9225
9226       for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9227            p != seen->end();
9228            ++p)
9229         {
9230           if (*p == nt)
9231             {
9232               // We've already seen this type.
9233               return false;
9234             }
9235         }
9236     }
9237
9238   const Interface_type* it = type->interface_type();
9239   if (it != NULL && it->is_unexported_method(gogo, name))
9240     return true;
9241
9242   type = type->deref();
9243
9244   const Struct_type* st = type->struct_type();
9245   if (st != NULL && st->is_unexported_local_field(gogo, name))
9246     return true;
9247
9248   if (st == NULL)
9249     return false;
9250
9251   const Struct_field_list* fields = st->fields();
9252   if (fields == NULL)
9253     return false;
9254
9255   if (nt != NULL)
9256     seen->push_back(nt);
9257
9258   for (Struct_field_list::const_iterator pf = fields->begin();
9259        pf != fields->end();
9260        ++pf)
9261     {
9262       if (pf->is_anonymous()
9263           && !pf->type()->deref()->is_error_type()
9264           && !pf->type()->deref()->is_undefined())
9265         {
9266           Named_type* subtype = pf->type()->named_type();
9267           if (subtype == NULL)
9268             subtype = pf->type()->deref()->named_type();
9269           if (subtype == NULL)
9270             {
9271               // This is an error, but it will be diagnosed elsewhere.
9272               continue;
9273             }
9274           if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
9275             {
9276               if (nt != NULL)
9277                 seen->pop_back();
9278               return true;
9279             }
9280         }
9281     }
9282
9283   if (nt != NULL)
9284     seen->pop_back();
9285
9286   return false;
9287 }
9288
9289 // Class Forward_declaration.
9290
9291 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
9292   : Type(TYPE_FORWARD),
9293     named_object_(named_object->resolve()), warned_(false)
9294 {
9295   go_assert(this->named_object_->is_unknown()
9296              || this->named_object_->is_type_declaration());
9297 }
9298
9299 // Return the named object.
9300
9301 Named_object*
9302 Forward_declaration_type::named_object()
9303 {
9304   return this->named_object_->resolve();
9305 }
9306
9307 const Named_object*
9308 Forward_declaration_type::named_object() const
9309 {
9310   return this->named_object_->resolve();
9311 }
9312
9313 // Return the name of the forward declared type.
9314
9315 const std::string&
9316 Forward_declaration_type::name() const
9317 {
9318   return this->named_object()->name();
9319 }
9320
9321 // Warn about a use of a type which has been declared but not defined.
9322
9323 void
9324 Forward_declaration_type::warn() const
9325 {
9326   Named_object* no = this->named_object_->resolve();
9327   if (no->is_unknown())
9328     {
9329       // The name was not defined anywhere.
9330       if (!this->warned_)
9331         {
9332           error_at(this->named_object_->location(),
9333                    "use of undefined type %qs",
9334                    no->message_name().c_str());
9335           this->warned_ = true;
9336         }
9337     }
9338   else if (no->is_type_declaration())
9339     {
9340       // The name was seen as a type, but the type was never defined.
9341       if (no->type_declaration_value()->using_type())
9342         {
9343           error_at(this->named_object_->location(),
9344                    "use of undefined type %qs",
9345                    no->message_name().c_str());
9346           this->warned_ = true;
9347         }
9348     }
9349   else
9350     {
9351       // The name was defined, but not as a type.
9352       if (!this->warned_)
9353         {
9354           error_at(this->named_object_->location(), "expected type");
9355           this->warned_ = true;
9356         }
9357     }
9358 }
9359
9360 // Get the base type of a declaration.  This gives an error if the
9361 // type has not yet been defined.
9362
9363 Type*
9364 Forward_declaration_type::real_type()
9365 {
9366   if (this->is_defined())
9367     return this->named_object()->type_value();
9368   else
9369     {
9370       this->warn();
9371       return Type::make_error_type();
9372     }
9373 }
9374
9375 const Type*
9376 Forward_declaration_type::real_type() const
9377 {
9378   if (this->is_defined())
9379     return this->named_object()->type_value();
9380   else
9381     {
9382       this->warn();
9383       return Type::make_error_type();
9384     }
9385 }
9386
9387 // Return whether the base type is defined.
9388
9389 bool
9390 Forward_declaration_type::is_defined() const
9391 {
9392   return this->named_object()->is_type();
9393 }
9394
9395 // Add a method.  This is used when methods are defined before the
9396 // type.
9397
9398 Named_object*
9399 Forward_declaration_type::add_method(const std::string& name,
9400                                      Function* function)
9401 {
9402   Named_object* no = this->named_object();
9403   if (no->is_unknown())
9404     no->declare_as_type();
9405   return no->type_declaration_value()->add_method(name, function);
9406 }
9407
9408 // Add a method declaration.  This is used when methods are declared
9409 // before the type.
9410
9411 Named_object*
9412 Forward_declaration_type::add_method_declaration(const std::string& name,
9413                                                  Package* package,
9414                                                  Function_type* type,
9415                                                  Location location)
9416 {
9417   Named_object* no = this->named_object();
9418   if (no->is_unknown())
9419     no->declare_as_type();
9420   Type_declaration* td = no->type_declaration_value();
9421   return td->add_method_declaration(name, package, type, location);
9422 }
9423
9424 // Traversal.
9425
9426 int
9427 Forward_declaration_type::do_traverse(Traverse* traverse)
9428 {
9429   if (this->is_defined()
9430       && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
9431     return TRAVERSE_EXIT;
9432   return TRAVERSE_CONTINUE;
9433 }
9434
9435 // Get the backend representation for the type.
9436
9437 Btype*
9438 Forward_declaration_type::do_get_backend(Gogo* gogo)
9439 {
9440   if (this->is_defined())
9441     return Type::get_named_base_btype(gogo, this->real_type());
9442
9443   if (this->warned_)
9444     return gogo->backend()->error_type();
9445
9446   // We represent an undefined type as a struct with no fields.  That
9447   // should work fine for the backend, since the same case can arise
9448   // in C.
9449   std::vector<Backend::Btyped_identifier> fields;
9450   Btype* bt = gogo->backend()->struct_type(fields);
9451   return gogo->backend()->named_type(this->name(), bt,
9452                                      this->named_object()->location());
9453 }
9454
9455 // Build a type descriptor for a forwarded type.
9456
9457 Expression*
9458 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9459 {
9460   Location ploc = Linemap::predeclared_location();
9461   if (!this->is_defined())
9462     return Expression::make_error(ploc);
9463   else
9464     {
9465       Type* t = this->real_type();
9466       if (name != NULL)
9467         return this->named_type_descriptor(gogo, t, name);
9468       else
9469         return Expression::make_type_descriptor(t, ploc);
9470     }
9471 }
9472
9473 // The reflection string.
9474
9475 void
9476 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
9477 {
9478   this->append_reflection(this->real_type(), gogo, ret);
9479 }
9480
9481 // The mangled name.
9482
9483 void
9484 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
9485 {
9486   if (this->is_defined())
9487     this->append_mangled_name(this->real_type(), gogo, ret);
9488   else
9489     {
9490       const Named_object* no = this->named_object();
9491       std::string name;
9492       if (no->package() == NULL)
9493         name = gogo->package_name();
9494       else
9495         name = no->package()->name();
9496       name += '.';
9497       name += Gogo::unpack_hidden_name(no->name());
9498       char buf[20];
9499       snprintf(buf, sizeof buf, "N%u_",
9500                static_cast<unsigned int>(name.length()));
9501       ret->append(buf);
9502       ret->append(name);
9503     }
9504 }
9505
9506 // Export a forward declaration.  This can happen when a defined type
9507 // refers to a type which is only declared (and is presumably defined
9508 // in some other file in the same package).
9509
9510 void
9511 Forward_declaration_type::do_export(Export*) const
9512 {
9513   // If there is a base type, that should be exported instead of this.
9514   go_assert(!this->is_defined());
9515
9516   // We don't output anything.
9517 }
9518
9519 // Make a forward declaration.
9520
9521 Type*
9522 Type::make_forward_declaration(Named_object* named_object)
9523 {
9524   return new Forward_declaration_type(named_object);
9525 }
9526
9527 // Class Typed_identifier_list.
9528
9529 // Sort the entries by name.
9530
9531 struct Typed_identifier_list_sort
9532 {
9533  public:
9534   bool
9535   operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
9536   { return t1.name() < t2.name(); }
9537 };
9538
9539 void
9540 Typed_identifier_list::sort_by_name()
9541 {
9542   std::sort(this->entries_.begin(), this->entries_.end(),
9543             Typed_identifier_list_sort());
9544 }
9545
9546 // Traverse types.
9547
9548 int
9549 Typed_identifier_list::traverse(Traverse* traverse)
9550 {
9551   for (Typed_identifier_list::const_iterator p = this->begin();
9552        p != this->end();
9553        ++p)
9554     {
9555       if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
9556         return TRAVERSE_EXIT;
9557     }
9558   return TRAVERSE_CONTINUE;
9559 }
9560
9561 // Copy the list.
9562
9563 Typed_identifier_list*
9564 Typed_identifier_list::copy() const
9565 {
9566   Typed_identifier_list* ret = new Typed_identifier_list();
9567   for (Typed_identifier_list::const_iterator p = this->begin();
9568        p != this->end();
9569        ++p)
9570     ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
9571   return ret;
9572 }