OSDN Git Service

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