OSDN Git Service

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