OSDN Git Service

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