OSDN Git Service

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