OSDN Git Service

Use backend interface for map 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   Gogo* gogo = context->gogo();
5053   tree map_type = type_to_tree(this->get_backend(gogo));
5054
5055   static tree new_map_fndecl;
5056   tree ret = Gogo::call_builtin(&new_map_fndecl,
5057                                 location,
5058                                 "__go_new_map",
5059                                 2,
5060                                 map_type,
5061                                 TREE_TYPE(TYPE_FIELDS(TREE_TYPE(map_type))),
5062                                 this->map_descriptor_pointer(gogo, location),
5063                                 sizetype,
5064                                 expr_tree);
5065   if (ret == error_mark_node)
5066     return error_mark_node;
5067   // This can panic if the capacity is out of range.
5068   TREE_NOTHROW(new_map_fndecl) = 0;
5069
5070   if (bad_index == NULL_TREE)
5071     return ret;
5072   else
5073     {
5074       tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_MAP_OUT_OF_BOUNDS,
5075                                        location);
5076       return build2(COMPOUND_EXPR, TREE_TYPE(ret),
5077                     build3(COND_EXPR, void_type_node,
5078                            bad_index, crash, NULL_TREE),
5079                     ret);
5080     }
5081 }
5082
5083 // The type of a map type descriptor.
5084
5085 Type*
5086 Map_type::make_map_type_descriptor_type()
5087 {
5088   static Type* ret;
5089   if (ret == NULL)
5090     {
5091       Type* tdt = Type::make_type_descriptor_type();
5092       Type* ptdt = Type::make_type_descriptor_ptr_type();
5093
5094       Struct_type* sf =
5095         Type::make_builtin_struct_type(3,
5096                                        "", tdt,
5097                                        "key", ptdt,
5098                                        "elem", ptdt);
5099
5100       ret = Type::make_builtin_named_type("MapType", sf);
5101     }
5102
5103   return ret;
5104 }
5105
5106 // Build a type descriptor for a map type.
5107
5108 Expression*
5109 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5110 {
5111   source_location bloc = BUILTINS_LOCATION;
5112
5113   Type* mtdt = Map_type::make_map_type_descriptor_type();
5114
5115   const Struct_field_list* fields = mtdt->struct_type()->fields();
5116
5117   Expression_list* vals = new Expression_list();
5118   vals->reserve(3);
5119
5120   Struct_field_list::const_iterator p = fields->begin();
5121   go_assert(p->field_name() == "commonType");
5122   vals->push_back(this->type_descriptor_constructor(gogo,
5123                                                     RUNTIME_TYPE_KIND_MAP,
5124                                                     name, NULL, true));
5125
5126   ++p;
5127   go_assert(p->field_name() == "key");
5128   vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
5129
5130   ++p;
5131   go_assert(p->field_name() == "elem");
5132   vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
5133
5134   ++p;
5135   go_assert(p == fields->end());
5136
5137   return Expression::make_struct_composite_literal(mtdt, vals, bloc);
5138 }
5139
5140 // A mapping from map types to map descriptors.
5141
5142 Map_type::Map_descriptors Map_type::map_descriptors;
5143
5144 // Build a map descriptor for this type.  Return a pointer to it.
5145
5146 tree
5147 Map_type::map_descriptor_pointer(Gogo* gogo, source_location location)
5148 {
5149   Bvariable* bvar = this->map_descriptor(gogo);
5150   tree var_tree = var_to_tree(bvar);
5151   if (var_tree == error_mark_node)
5152     return error_mark_node;
5153   return build_fold_addr_expr_loc(location, var_tree);
5154 }
5155
5156 // Build a map descriptor for this type.
5157
5158 Bvariable*
5159 Map_type::map_descriptor(Gogo* gogo)
5160 {
5161   std::pair<Map_type*, Bvariable*> val(this, NULL);
5162   std::pair<Map_type::Map_descriptors::iterator, bool> ins =
5163     Map_type::map_descriptors.insert(val);
5164   if (!ins.second)
5165     return ins.first->second;
5166
5167   Type* key_type = this->key_type_;
5168   Type* val_type = this->val_type_;
5169
5170   // The map entry type is a struct with three fields.  Build that
5171   // struct so that we can get the offsets of the key and value within
5172   // a map entry.  The first field should technically be a pointer to
5173   // this type itself, but since we only care about field offsets we
5174   // just use pointer to bool.
5175   Type* pbool = Type::make_pointer_type(Type::make_boolean_type());
5176   Struct_type* map_entry_type =
5177     Type::make_builtin_struct_type(3,
5178                                    "__next", pbool,
5179                                    "__key", key_type,
5180                                    "__val", val_type);
5181
5182   Type* map_descriptor_type = Map_type::make_map_descriptor_type();
5183
5184   const Struct_field_list* fields =
5185     map_descriptor_type->struct_type()->fields();
5186
5187   Expression_list* vals = new Expression_list();
5188   vals->reserve(4);
5189
5190   source_location bloc = BUILTINS_LOCATION;
5191
5192   Struct_field_list::const_iterator p = fields->begin();
5193
5194   go_assert(p->field_name() == "__map_descriptor");
5195   vals->push_back(Expression::make_type_descriptor(this, bloc));
5196
5197   ++p;
5198   go_assert(p->field_name() == "__entry_size");
5199   Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
5200   vals->push_back(Expression::make_type_info(map_entry_type, type_info));
5201
5202   Struct_field_list::const_iterator pf = map_entry_type->fields()->begin();
5203   ++pf;
5204   go_assert(pf->field_name() == "__key");
5205
5206   ++p;
5207   go_assert(p->field_name() == "__key_offset");
5208   vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
5209
5210   ++pf;
5211   go_assert(pf->field_name() == "__val");
5212
5213   ++p;
5214   go_assert(p->field_name() == "__val_offset");
5215   vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
5216
5217   ++p;
5218   go_assert(p == fields->end());
5219
5220   Expression* initializer =
5221     Expression::make_struct_composite_literal(map_descriptor_type, vals, bloc);
5222
5223   std::string mangled_name = "__go_map_" + this->mangled_name(gogo);
5224   Btype* map_descriptor_btype = map_descriptor_type->get_backend(gogo);
5225   Bvariable* bvar = gogo->backend()->immutable_struct(mangled_name, true,
5226                                                       map_descriptor_btype,
5227                                                       bloc);
5228
5229   Translate_context context(gogo, NULL, NULL, NULL);
5230   context.set_is_const();
5231   Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
5232
5233   gogo->backend()->immutable_struct_set_init(bvar, mangled_name, true,
5234                                              map_descriptor_btype, bloc,
5235                                              binitializer);
5236
5237   ins.first->second = bvar;
5238   return bvar;
5239 }
5240
5241 // Build the type of a map descriptor.  This must match the struct
5242 // __go_map_descriptor in libgo/runtime/map.h.
5243
5244 Type*
5245 Map_type::make_map_descriptor_type()
5246 {
5247   static Type* ret;
5248   if (ret == NULL)
5249     {
5250       Type* ptdt = Type::make_type_descriptor_ptr_type();
5251       Type* uintptr_type = Type::lookup_integer_type("uintptr");
5252       Struct_type* sf =
5253         Type::make_builtin_struct_type(4,
5254                                        "__map_descriptor", ptdt,
5255                                        "__entry_size", uintptr_type,
5256                                        "__key_offset", uintptr_type,
5257                                        "__val_offset", uintptr_type);
5258       ret = Type::make_builtin_named_type("__go_map_descriptor", sf);
5259     }
5260   return ret;
5261 }
5262
5263 // Reflection string for a map.
5264
5265 void
5266 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
5267 {
5268   ret->append("map[");
5269   this->append_reflection(this->key_type_, gogo, ret);
5270   ret->append("] ");
5271   this->append_reflection(this->val_type_, gogo, ret);
5272 }
5273
5274 // Mangled name for a map.
5275
5276 void
5277 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5278 {
5279   ret->push_back('M');
5280   this->append_mangled_name(this->key_type_, gogo, ret);
5281   ret->append("__");
5282   this->append_mangled_name(this->val_type_, gogo, ret);
5283 }
5284
5285 // Export a map type.
5286
5287 void
5288 Map_type::do_export(Export* exp) const
5289 {
5290   exp->write_c_string("map [");
5291   exp->write_type(this->key_type_);
5292   exp->write_c_string("] ");
5293   exp->write_type(this->val_type_);
5294 }
5295
5296 // Import a map type.
5297
5298 Map_type*
5299 Map_type::do_import(Import* imp)
5300 {
5301   imp->require_c_string("map [");
5302   Type* key_type = imp->read_type();
5303   imp->require_c_string("] ");
5304   Type* val_type = imp->read_type();
5305   return Type::make_map_type(key_type, val_type, imp->location());
5306 }
5307
5308 // Make a map type.
5309
5310 Map_type*
5311 Type::make_map_type(Type* key_type, Type* val_type, source_location location)
5312 {
5313   return new Map_type(key_type, val_type, location);
5314 }
5315
5316 // Class Channel_type.
5317
5318 // Hash code.
5319
5320 unsigned int
5321 Channel_type::do_hash_for_method(Gogo* gogo) const
5322 {
5323   unsigned int ret = 0;
5324   if (this->may_send_)
5325     ret += 1;
5326   if (this->may_receive_)
5327     ret += 2;
5328   if (this->element_type_ != NULL)
5329     ret += this->element_type_->hash_for_method(gogo) << 2;
5330   return ret << 3;
5331 }
5332
5333 // Whether this type is the same as T.
5334
5335 bool
5336 Channel_type::is_identical(const Channel_type* t,
5337                            bool errors_are_identical) const
5338 {
5339   if (!Type::are_identical(this->element_type(), t->element_type(),
5340                            errors_are_identical, NULL))
5341     return false;
5342   return (this->may_send_ == t->may_send_
5343           && this->may_receive_ == t->may_receive_);
5344 }
5345
5346 // Check whether the parameters for a call to the builtin function
5347 // make are OK for a channel.  A channel can take an optional single
5348 // parameter which is the buffer size.
5349
5350 bool
5351 Channel_type::do_check_make_expression(Expression_list* args,
5352                                       source_location location)
5353 {
5354   if (args != NULL && !args->empty())
5355     {
5356       if (!Type::check_int_value(args->front(),
5357                                  _("bad buffer size when making channel"),
5358                                  location))
5359         return false;
5360       else if (args->size() > 1)
5361         {
5362           error_at(location, "too many arguments when making channel");
5363           return false;
5364         }
5365     }
5366   return true;
5367 }
5368
5369 // Return the tree for a channel type.  A channel is a pointer to a
5370 // __go_channel struct.  The __go_channel struct is defined in
5371 // libgo/runtime/channel.h.
5372
5373 Btype*
5374 Channel_type::do_get_backend(Gogo* gogo)
5375 {
5376   static Btype* backend_channel_type;
5377   if (backend_channel_type == NULL)
5378     {
5379       std::vector<Backend::Btyped_identifier> bfields;
5380       Btype* bt = gogo->backend()->struct_type(bfields);
5381       bt = gogo->backend()->named_type("__go_channel", bt, BUILTINS_LOCATION);
5382       backend_channel_type = gogo->backend()->pointer_type(bt);
5383     }
5384   return backend_channel_type;
5385 }
5386
5387 // Handle the builtin function make for a channel.
5388
5389 tree
5390 Channel_type::do_make_expression_tree(Translate_context* context,
5391                                       Expression_list* args,
5392                                       source_location location)
5393 {
5394   Gogo* gogo = context->gogo();
5395   tree channel_type = type_to_tree(this->get_backend(gogo));
5396
5397   Type* ptdt = Type::make_type_descriptor_ptr_type();
5398   tree element_type_descriptor =
5399     this->element_type_->type_descriptor_pointer(gogo, location);
5400
5401   tree bad_index = NULL_TREE;
5402
5403   tree expr_tree;
5404   if (args == NULL || args->empty())
5405     expr_tree = size_zero_node;
5406   else
5407     {
5408       expr_tree = args->front()->get_tree(context);
5409       if (expr_tree == error_mark_node)
5410         return error_mark_node;
5411       if (!DECL_P(expr_tree))
5412         expr_tree = save_expr(expr_tree);
5413       if (!INTEGRAL_TYPE_P(TREE_TYPE(expr_tree)))
5414         expr_tree = convert_to_integer(sizetype, expr_tree);
5415       bad_index = Expression::check_bounds(expr_tree, sizetype, bad_index,
5416                                            location);
5417     }
5418
5419   static tree new_channel_fndecl;
5420   tree ret = Gogo::call_builtin(&new_channel_fndecl,
5421                                 location,
5422                                 "__go_new_channel",
5423                                 2,
5424                                 channel_type,
5425                                 type_to_tree(ptdt->get_backend(gogo)),
5426                                 element_type_descriptor,
5427                                 sizetype,
5428                                 expr_tree);
5429   if (ret == error_mark_node)
5430     return error_mark_node;
5431   // This can panic if the capacity is out of range.
5432   TREE_NOTHROW(new_channel_fndecl) = 0;
5433
5434   if (bad_index == NULL_TREE)
5435     return ret;
5436   else
5437     {
5438       tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_CHAN_OUT_OF_BOUNDS,
5439                                        location);
5440       return build2(COMPOUND_EXPR, TREE_TYPE(ret),
5441                     build3(COND_EXPR, void_type_node,
5442                            bad_index, crash, NULL_TREE),
5443                     ret);
5444     }
5445 }
5446
5447 // Build a type descriptor for a channel type.
5448
5449 Type*
5450 Channel_type::make_chan_type_descriptor_type()
5451 {
5452   static Type* ret;
5453   if (ret == NULL)
5454     {
5455       Type* tdt = Type::make_type_descriptor_type();
5456       Type* ptdt = Type::make_type_descriptor_ptr_type();
5457
5458       Type* uintptr_type = Type::lookup_integer_type("uintptr");
5459
5460       Struct_type* sf =
5461         Type::make_builtin_struct_type(3,
5462                                        "", tdt,
5463                                        "elem", ptdt,
5464                                        "dir", uintptr_type);
5465
5466       ret = Type::make_builtin_named_type("ChanType", sf);
5467     }
5468
5469   return ret;
5470 }
5471
5472 // Build a type descriptor for a map type.
5473
5474 Expression*
5475 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5476 {
5477   source_location bloc = BUILTINS_LOCATION;
5478
5479   Type* ctdt = Channel_type::make_chan_type_descriptor_type();
5480
5481   const Struct_field_list* fields = ctdt->struct_type()->fields();
5482
5483   Expression_list* vals = new Expression_list();
5484   vals->reserve(3);
5485
5486   Struct_field_list::const_iterator p = fields->begin();
5487   go_assert(p->field_name() == "commonType");
5488   vals->push_back(this->type_descriptor_constructor(gogo,
5489                                                     RUNTIME_TYPE_KIND_CHAN,
5490                                                     name, NULL, true));
5491
5492   ++p;
5493   go_assert(p->field_name() == "elem");
5494   vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5495
5496   ++p;
5497   go_assert(p->field_name() == "dir");
5498   // These bits must match the ones in libgo/runtime/go-type.h.
5499   int val = 0;
5500   if (this->may_receive_)
5501     val |= 1;
5502   if (this->may_send_)
5503     val |= 2;
5504   mpz_t iv;
5505   mpz_init_set_ui(iv, val);
5506   vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
5507   mpz_clear(iv);
5508
5509   ++p;
5510   go_assert(p == fields->end());
5511
5512   return Expression::make_struct_composite_literal(ctdt, vals, bloc);
5513 }
5514
5515 // Reflection string.
5516
5517 void
5518 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
5519 {
5520   if (!this->may_send_)
5521     ret->append("<-");
5522   ret->append("chan");
5523   if (!this->may_receive_)
5524     ret->append("<-");
5525   ret->push_back(' ');
5526   this->append_reflection(this->element_type_, gogo, ret);
5527 }
5528
5529 // Mangled name.
5530
5531 void
5532 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5533 {
5534   ret->push_back('C');
5535   this->append_mangled_name(this->element_type_, gogo, ret);
5536   if (this->may_send_)
5537     ret->push_back('s');
5538   if (this->may_receive_)
5539     ret->push_back('r');
5540   ret->push_back('e');
5541 }
5542
5543 // Export.
5544
5545 void
5546 Channel_type::do_export(Export* exp) const
5547 {
5548   exp->write_c_string("chan ");
5549   if (this->may_send_ && !this->may_receive_)
5550     exp->write_c_string("-< ");
5551   else if (this->may_receive_ && !this->may_send_)
5552     exp->write_c_string("<- ");
5553   exp->write_type(this->element_type_);
5554 }
5555
5556 // Import.
5557
5558 Channel_type*
5559 Channel_type::do_import(Import* imp)
5560 {
5561   imp->require_c_string("chan ");
5562
5563   bool may_send;
5564   bool may_receive;
5565   if (imp->match_c_string("-< "))
5566     {
5567       imp->advance(3);
5568       may_send = true;
5569       may_receive = false;
5570     }
5571   else if (imp->match_c_string("<- "))
5572     {
5573       imp->advance(3);
5574       may_receive = true;
5575       may_send = false;
5576     }
5577   else
5578     {
5579       may_send = true;
5580       may_receive = true;
5581     }
5582
5583   Type* element_type = imp->read_type();
5584
5585   return Type::make_channel_type(may_send, may_receive, element_type);
5586 }
5587
5588 // Make a new channel type.
5589
5590 Channel_type*
5591 Type::make_channel_type(bool send, bool receive, Type* element_type)
5592 {
5593   return new Channel_type(send, receive, element_type);
5594 }
5595
5596 // Class Interface_type.
5597
5598 // Traversal.
5599
5600 int
5601 Interface_type::do_traverse(Traverse* traverse)
5602 {
5603   if (this->methods_ == NULL)
5604     return TRAVERSE_CONTINUE;
5605   return this->methods_->traverse(traverse);
5606 }
5607
5608 // Finalize the methods.  This handles interface inheritance.
5609
5610 void
5611 Interface_type::finalize_methods()
5612 {
5613   if (this->methods_ == NULL)
5614     return;
5615   std::vector<Named_type*> seen;
5616   bool is_recursive = false;
5617   size_t from = 0;
5618   size_t to = 0;
5619   while (from < this->methods_->size())
5620     {
5621       const Typed_identifier* p = &this->methods_->at(from);
5622       if (!p->name().empty())
5623         {
5624           size_t i;
5625           for (i = 0; i < to; ++i)
5626             {
5627               if (this->methods_->at(i).name() == p->name())
5628                 {
5629                   error_at(p->location(), "duplicate method %qs",
5630                            Gogo::message_name(p->name()).c_str());
5631                   break;
5632                 }
5633             }
5634           if (i == to)
5635             {
5636               if (from != to)
5637                 this->methods_->set(to, *p);
5638               ++to;
5639             }
5640           ++from;
5641           continue;
5642         }
5643
5644       Interface_type* it = p->type()->interface_type();
5645       if (it == NULL)
5646         {
5647           error_at(p->location(), "interface contains embedded non-interface");
5648           ++from;
5649           continue;
5650         }
5651       if (it == this)
5652         {
5653           if (!is_recursive)
5654             {
5655               error_at(p->location(), "invalid recursive interface");
5656               is_recursive = true;
5657             }
5658           ++from;
5659           continue;
5660         }
5661
5662       Named_type* nt = p->type()->named_type();
5663       if (nt != NULL)
5664         {
5665           std::vector<Named_type*>::const_iterator q;
5666           for (q = seen.begin(); q != seen.end(); ++q)
5667             {
5668               if (*q == nt)
5669                 {
5670                   error_at(p->location(), "inherited interface loop");
5671                   break;
5672                 }
5673             }
5674           if (q != seen.end())
5675             {
5676               ++from;
5677               continue;
5678             }
5679           seen.push_back(nt);
5680         }
5681
5682       const Typed_identifier_list* methods = it->methods();
5683       if (methods == NULL)
5684         {
5685           ++from;
5686           continue;
5687         }
5688       for (Typed_identifier_list::const_iterator q = methods->begin();
5689            q != methods->end();
5690            ++q)
5691         {
5692           if (q->name().empty())
5693             {
5694               if (q->type()->forwarded() == p->type()->forwarded())
5695                 error_at(p->location(), "interface inheritance loop");
5696               else
5697                 {
5698                   size_t i;
5699                   for (i = from + 1; i < this->methods_->size(); ++i)
5700                     {
5701                       const Typed_identifier* r = &this->methods_->at(i);
5702                       if (r->name().empty()
5703                           && r->type()->forwarded() == q->type()->forwarded())
5704                         {
5705                           error_at(p->location(),
5706                                    "inherited interface listed twice");
5707                           break;
5708                         }
5709                     }
5710                   if (i == this->methods_->size())
5711                     this->methods_->push_back(Typed_identifier(q->name(),
5712                                                                q->type(),
5713                                                                p->location()));
5714                 }
5715             }
5716           else if (this->find_method(q->name()) == NULL)
5717             this->methods_->push_back(Typed_identifier(q->name(), q->type(),
5718                                                        p->location()));
5719           else
5720             {
5721               if (!is_recursive)
5722                 error_at(p->location(), "inherited method %qs is ambiguous",
5723                          Gogo::message_name(q->name()).c_str());
5724             }
5725         }
5726       ++from;
5727     }
5728   if (to == 0)
5729     {
5730       delete this->methods_;
5731       this->methods_ = NULL;
5732     }
5733   else
5734     {
5735       this->methods_->resize(to);
5736       this->methods_->sort_by_name();
5737     }
5738 }
5739
5740 // Return the method NAME, or NULL.
5741
5742 const Typed_identifier*
5743 Interface_type::find_method(const std::string& name) const
5744 {
5745   if (this->methods_ == NULL)
5746     return NULL;
5747   for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5748        p != this->methods_->end();
5749        ++p)
5750     if (p->name() == name)
5751       return &*p;
5752   return NULL;
5753 }
5754
5755 // Return the method index.
5756
5757 size_t
5758 Interface_type::method_index(const std::string& name) const
5759 {
5760   go_assert(this->methods_ != NULL);
5761   size_t ret = 0;
5762   for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5763        p != this->methods_->end();
5764        ++p, ++ret)
5765     if (p->name() == name)
5766       return ret;
5767   go_unreachable();
5768 }
5769
5770 // Return whether NAME is an unexported method, for better error
5771 // reporting.
5772
5773 bool
5774 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
5775 {
5776   if (this->methods_ == NULL)
5777     return false;
5778   for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5779        p != this->methods_->end();
5780        ++p)
5781     {
5782       const std::string& method_name(p->name());
5783       if (Gogo::is_hidden_name(method_name)
5784           && name == Gogo::unpack_hidden_name(method_name)
5785           && gogo->pack_hidden_name(name, false) != method_name)
5786         return true;
5787     }
5788   return false;
5789 }
5790
5791 // Whether this type is identical with T.
5792
5793 bool
5794 Interface_type::is_identical(const Interface_type* t,
5795                              bool errors_are_identical) const
5796 {
5797   // We require the same methods with the same types.  The methods
5798   // have already been sorted.
5799   if (this->methods() == NULL || t->methods() == NULL)
5800     return this->methods() == t->methods();
5801
5802   Typed_identifier_list::const_iterator p1 = this->methods()->begin();
5803   for (Typed_identifier_list::const_iterator p2 = t->methods()->begin();
5804        p2 != t->methods()->end();
5805        ++p1, ++p2)
5806     {
5807       if (p1 == this->methods()->end())
5808         return false;
5809       if (p1->name() != p2->name()
5810           || !Type::are_identical(p1->type(), p2->type(),
5811                                   errors_are_identical, NULL))
5812         return false;
5813     }
5814   if (p1 != this->methods()->end())
5815     return false;
5816   return true;
5817 }
5818
5819 // Whether we can assign the interface type T to this type.  The types
5820 // are known to not be identical.  An interface assignment is only
5821 // permitted if T is known to implement all methods in THIS.
5822 // Otherwise a type guard is required.
5823
5824 bool
5825 Interface_type::is_compatible_for_assign(const Interface_type* t,
5826                                          std::string* reason) const
5827 {
5828   if (this->methods() == NULL)
5829     return true;
5830   for (Typed_identifier_list::const_iterator p = this->methods()->begin();
5831        p != this->methods()->end();
5832        ++p)
5833     {
5834       const Typed_identifier* m = t->find_method(p->name());
5835       if (m == NULL)
5836         {
5837           if (reason != NULL)
5838             {
5839               char buf[200];
5840               snprintf(buf, sizeof buf,
5841                        _("need explicit conversion; missing method %s%s%s"),
5842                        open_quote, Gogo::message_name(p->name()).c_str(),
5843                        close_quote);
5844               reason->assign(buf);
5845             }
5846           return false;
5847         }
5848
5849       std::string subreason;
5850       if (!Type::are_identical(p->type(), m->type(), true, &subreason))
5851         {
5852           if (reason != NULL)
5853             {
5854               std::string n = Gogo::message_name(p->name());
5855               size_t len = 100 + n.length() + subreason.length();
5856               char* buf = new char[len];
5857               if (subreason.empty())
5858                 snprintf(buf, len, _("incompatible type for method %s%s%s"),
5859                          open_quote, n.c_str(), close_quote);
5860               else
5861                 snprintf(buf, len,
5862                          _("incompatible type for method %s%s%s (%s)"),
5863                          open_quote, n.c_str(), close_quote,
5864                          subreason.c_str());
5865               reason->assign(buf);
5866               delete[] buf;
5867             }
5868           return false;
5869         }
5870     }
5871
5872   return true;
5873 }
5874
5875 // Hash code.
5876
5877 unsigned int
5878 Interface_type::do_hash_for_method(Gogo* gogo) const
5879 {
5880   unsigned int ret = 0;
5881   if (this->methods_ != NULL)
5882     {
5883       for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5884            p != this->methods_->end();
5885            ++p)
5886         {
5887           ret = Type::hash_string(p->name(), ret);
5888           ret += p->type()->hash_for_method(gogo);
5889           ret <<= 1;
5890         }
5891     }
5892   return ret;
5893 }
5894
5895 // Return true if T implements the interface.  If it does not, and
5896 // REASON is not NULL, set *REASON to a useful error message.
5897
5898 bool
5899 Interface_type::implements_interface(const Type* t, std::string* reason) const
5900 {
5901   if (this->methods_ == NULL)
5902     return true;
5903
5904   bool is_pointer = false;
5905   const Named_type* nt = t->named_type();
5906   const Struct_type* st = t->struct_type();
5907   // If we start with a named type, we don't dereference it to find
5908   // methods.
5909   if (nt == NULL)
5910     {
5911       const Type* pt = t->points_to();
5912       if (pt != NULL)
5913         {
5914           // If T is a pointer to a named type, then we need to look at
5915           // the type to which it points.
5916           is_pointer = true;
5917           nt = pt->named_type();
5918           st = pt->struct_type();
5919         }
5920     }
5921
5922   // If we have a named type, get the methods from it rather than from
5923   // any struct type.
5924   if (nt != NULL)
5925     st = NULL;
5926
5927   // Only named and struct types have methods.
5928   if (nt == NULL && st == NULL)
5929     {
5930       if (reason != NULL)
5931         {
5932           if (t->points_to() != NULL
5933               && t->points_to()->interface_type() != NULL)
5934             reason->assign(_("pointer to interface type has no methods"));
5935           else
5936             reason->assign(_("type has no methods"));
5937         }
5938       return false;
5939     }
5940
5941   if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
5942     {
5943       if (reason != NULL)
5944         {
5945           if (t->points_to() != NULL
5946               && t->points_to()->interface_type() != NULL)
5947             reason->assign(_("pointer to interface type has no methods"));
5948           else
5949             reason->assign(_("type has no methods"));
5950         }
5951       return false;
5952     }
5953
5954   for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5955        p != this->methods_->end();
5956        ++p)
5957     {
5958       bool is_ambiguous = false;
5959       Method* m = (nt != NULL
5960                    ? nt->method_function(p->name(), &is_ambiguous)
5961                    : st->method_function(p->name(), &is_ambiguous));
5962       if (m == NULL)
5963         {
5964           if (reason != NULL)
5965             {
5966               std::string n = Gogo::message_name(p->name());
5967               size_t len = n.length() + 100;
5968               char* buf = new char[len];
5969               if (is_ambiguous)
5970                 snprintf(buf, len, _("ambiguous method %s%s%s"),
5971                          open_quote, n.c_str(), close_quote);
5972               else
5973                 snprintf(buf, len, _("missing method %s%s%s"),
5974                          open_quote, n.c_str(), close_quote);
5975               reason->assign(buf);
5976               delete[] buf;
5977             }
5978           return false;
5979         }
5980
5981       Function_type *p_fn_type = p->type()->function_type();
5982       Function_type* m_fn_type = m->type()->function_type();
5983       go_assert(p_fn_type != NULL && m_fn_type != NULL);
5984       std::string subreason;
5985       if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
5986         {
5987           if (reason != NULL)
5988             {
5989               std::string n = Gogo::message_name(p->name());
5990               size_t len = 100 + n.length() + subreason.length();
5991               char* buf = new char[len];
5992               if (subreason.empty())
5993                 snprintf(buf, len, _("incompatible type for method %s%s%s"),
5994                          open_quote, n.c_str(), close_quote);
5995               else
5996                 snprintf(buf, len,
5997                          _("incompatible type for method %s%s%s (%s)"),
5998                          open_quote, n.c_str(), close_quote,
5999                          subreason.c_str());
6000               reason->assign(buf);
6001               delete[] buf;
6002             }
6003           return false;
6004         }
6005
6006       if (!is_pointer && !m->is_value_method())
6007         {
6008           if (reason != NULL)
6009             {
6010               std::string n = Gogo::message_name(p->name());
6011               size_t len = 100 + n.length();
6012               char* buf = new char[len];
6013               snprintf(buf, len, _("method %s%s%s requires a pointer"),
6014                        open_quote, n.c_str(), close_quote);
6015               reason->assign(buf);
6016               delete[] buf;
6017             }
6018           return false;
6019         }
6020     }
6021
6022   return true;
6023 }
6024
6025 // Return the backend representation of the empty interface type.  We
6026 // use the same struct for all empty interfaces.
6027
6028 Btype*
6029 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
6030 {
6031   static Btype* empty_interface_type;
6032   if (empty_interface_type == NULL)
6033     {
6034       std::vector<Backend::Btyped_identifier> bfields(2);
6035
6036       Type* pdt = Type::make_type_descriptor_ptr_type();
6037       bfields[0].name = "__type_descriptor";
6038       bfields[0].btype = pdt->get_backend(gogo);
6039       bfields[0].location = UNKNOWN_LOCATION;
6040
6041       Type* vt = Type::make_pointer_type(Type::make_void_type());
6042       bfields[1].name = "__object";
6043       bfields[1].btype = vt->get_backend(gogo);
6044       bfields[1].location = UNKNOWN_LOCATION;
6045
6046       empty_interface_type = gogo->backend()->struct_type(bfields);
6047     }
6048   return empty_interface_type;
6049 }
6050
6051 // Return the fields of a non-empty interface type.  This is not
6052 // declared in types.h so that types.h doesn't have to #include
6053 // backend.h.
6054
6055 static void
6056 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
6057                              std::vector<Backend::Btyped_identifier>* bfields)
6058 {
6059   source_location loc = type->location();
6060
6061   std::vector<Backend::Btyped_identifier> mfields(type->methods()->size() + 1);
6062
6063   Type* pdt = Type::make_type_descriptor_ptr_type();
6064   mfields[0].name = "__type_descriptor";
6065   mfields[0].btype = pdt->get_backend(gogo);
6066   mfields[0].location = loc;
6067
6068   std::string last_name = "";
6069   size_t i = 1;
6070   for (Typed_identifier_list::const_iterator p = type->methods()->begin();
6071        p != type->methods()->end();
6072        ++p, ++i)
6073     {
6074       mfields[i].name = Gogo::unpack_hidden_name(p->name());
6075       mfields[i].btype = p->type()->get_backend(gogo);
6076       mfields[i].location = loc;
6077       // Sanity check: the names should be sorted.
6078       go_assert(p->name() > last_name);
6079       last_name = p->name();
6080     }
6081
6082   Btype* methods = gogo->backend()->struct_type(mfields);
6083
6084   bfields->resize(2);
6085
6086   (*bfields)[0].name = "__methods";
6087   (*bfields)[0].btype = gogo->backend()->pointer_type(methods);
6088   (*bfields)[0].location = loc;
6089
6090   Type* vt = Type::make_pointer_type(Type::make_void_type());
6091   (*bfields)[1].name = "__object";
6092   (*bfields)[1].btype = vt->get_backend(gogo);
6093   (*bfields)[1].location = UNKNOWN_LOCATION;
6094 }
6095
6096 // Return a tree for an interface type.  An interface is a pointer to
6097 // a struct.  The struct has three fields.  The first field is a
6098 // pointer to the type descriptor for the dynamic type of the object.
6099 // The second field is a pointer to a table of methods for the
6100 // interface to be used with the object.  The third field is the value
6101 // of the object itself.
6102
6103 Btype*
6104 Interface_type::do_get_backend(Gogo* gogo)
6105 {
6106   if (this->methods_ == NULL)
6107     return Interface_type::get_backend_empty_interface_type(gogo);
6108   else
6109     {
6110       std::vector<Backend::Btyped_identifier> bfields;
6111       get_backend_interface_fields(gogo, this, &bfields);
6112       return gogo->backend()->struct_type(bfields);
6113     }
6114 }
6115
6116 // The type of an interface type descriptor.
6117
6118 Type*
6119 Interface_type::make_interface_type_descriptor_type()
6120 {
6121   static Type* ret;
6122   if (ret == NULL)
6123     {
6124       Type* tdt = Type::make_type_descriptor_type();
6125       Type* ptdt = Type::make_type_descriptor_ptr_type();
6126
6127       Type* string_type = Type::lookup_string_type();
6128       Type* pointer_string_type = Type::make_pointer_type(string_type);
6129
6130       Struct_type* sm =
6131         Type::make_builtin_struct_type(3,
6132                                        "name", pointer_string_type,
6133                                        "pkgPath", pointer_string_type,
6134                                        "typ", ptdt);
6135
6136       Type* nsm = Type::make_builtin_named_type("imethod", sm);
6137
6138       Type* slice_nsm = Type::make_array_type(nsm, NULL);
6139
6140       Struct_type* s = Type::make_builtin_struct_type(2,
6141                                                       "", tdt,
6142                                                       "methods", slice_nsm);
6143
6144       ret = Type::make_builtin_named_type("InterfaceType", s);
6145     }
6146
6147   return ret;
6148 }
6149
6150 // Build a type descriptor for an interface type.
6151
6152 Expression*
6153 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6154 {
6155   source_location bloc = BUILTINS_LOCATION;
6156
6157   Type* itdt = Interface_type::make_interface_type_descriptor_type();
6158
6159   const Struct_field_list* ifields = itdt->struct_type()->fields();
6160
6161   Expression_list* ivals = new Expression_list();
6162   ivals->reserve(2);
6163
6164   Struct_field_list::const_iterator pif = ifields->begin();
6165   go_assert(pif->field_name() == "commonType");
6166   ivals->push_back(this->type_descriptor_constructor(gogo,
6167                                                      RUNTIME_TYPE_KIND_INTERFACE,
6168                                                      name, NULL, true));
6169
6170   ++pif;
6171   go_assert(pif->field_name() == "methods");
6172
6173   Expression_list* methods = new Expression_list();
6174   if (this->methods_ != NULL && !this->methods_->empty())
6175     {
6176       Type* elemtype = pif->type()->array_type()->element_type();
6177
6178       methods->reserve(this->methods_->size());
6179       for (Typed_identifier_list::const_iterator pm = this->methods_->begin();
6180            pm != this->methods_->end();
6181            ++pm)
6182         {
6183           const Struct_field_list* mfields = elemtype->struct_type()->fields();
6184
6185           Expression_list* mvals = new Expression_list();
6186           mvals->reserve(3);
6187
6188           Struct_field_list::const_iterator pmf = mfields->begin();
6189           go_assert(pmf->field_name() == "name");
6190           std::string s = Gogo::unpack_hidden_name(pm->name());
6191           Expression* e = Expression::make_string(s, bloc);
6192           mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
6193
6194           ++pmf;
6195           go_assert(pmf->field_name() == "pkgPath");
6196           if (!Gogo::is_hidden_name(pm->name()))
6197             mvals->push_back(Expression::make_nil(bloc));
6198           else
6199             {
6200               s = Gogo::hidden_name_prefix(pm->name());
6201               e = Expression::make_string(s, bloc);
6202               mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
6203             }
6204
6205           ++pmf;
6206           go_assert(pmf->field_name() == "typ");
6207           mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
6208
6209           ++pmf;
6210           go_assert(pmf == mfields->end());
6211
6212           e = Expression::make_struct_composite_literal(elemtype, mvals,
6213                                                         bloc);
6214           methods->push_back(e);
6215         }
6216     }
6217
6218   ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
6219                                                             methods, bloc));
6220
6221   ++pif;
6222   go_assert(pif == ifields->end());
6223
6224   return Expression::make_struct_composite_literal(itdt, ivals, bloc);
6225 }
6226
6227 // Reflection string.
6228
6229 void
6230 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
6231 {
6232   ret->append("interface {");
6233   if (this->methods_ != NULL)
6234     {
6235       for (Typed_identifier_list::const_iterator p = this->methods_->begin();
6236            p != this->methods_->end();
6237            ++p)
6238         {
6239           if (p != this->methods_->begin())
6240             ret->append(";");
6241           ret->push_back(' ');
6242           if (!Gogo::is_hidden_name(p->name()))
6243             ret->append(p->name());
6244           else
6245             {
6246               // This matches what the gc compiler does.
6247               std::string prefix = Gogo::hidden_name_prefix(p->name());
6248               ret->append(prefix.substr(prefix.find('.') + 1));
6249               ret->push_back('.');
6250               ret->append(Gogo::unpack_hidden_name(p->name()));
6251             }
6252           std::string sub = p->type()->reflection(gogo);
6253           go_assert(sub.compare(0, 4, "func") == 0);
6254           sub = sub.substr(4);
6255           ret->append(sub);
6256         }
6257     }
6258   ret->append(" }");
6259 }
6260
6261 // Mangled name.
6262
6263 void
6264 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6265 {
6266   ret->push_back('I');
6267
6268   const Typed_identifier_list* methods = this->methods_;
6269   if (methods != NULL)
6270     {
6271       for (Typed_identifier_list::const_iterator p = methods->begin();
6272            p != methods->end();
6273            ++p)
6274         {
6275           std::string n = Gogo::unpack_hidden_name(p->name());
6276           char buf[20];
6277           snprintf(buf, sizeof buf, "%u_",
6278                    static_cast<unsigned int>(n.length()));
6279           ret->append(buf);
6280           ret->append(n);
6281           this->append_mangled_name(p->type(), gogo, ret);
6282         }
6283     }
6284
6285   ret->push_back('e');
6286 }
6287
6288 // Export.
6289
6290 void
6291 Interface_type::do_export(Export* exp) const
6292 {
6293   exp->write_c_string("interface { ");
6294
6295   const Typed_identifier_list* methods = this->methods_;
6296   if (methods != NULL)
6297     {
6298       for (Typed_identifier_list::const_iterator pm = methods->begin();
6299            pm != methods->end();
6300            ++pm)
6301         {
6302           exp->write_string(pm->name());
6303           exp->write_c_string(" (");
6304
6305           const Function_type* fntype = pm->type()->function_type();
6306
6307           bool first = true;
6308           const Typed_identifier_list* parameters = fntype->parameters();
6309           if (parameters != NULL)
6310             {
6311               bool is_varargs = fntype->is_varargs();
6312               for (Typed_identifier_list::const_iterator pp =
6313                      parameters->begin();
6314                    pp != parameters->end();
6315                    ++pp)
6316                 {
6317                   if (first)
6318                     first = false;
6319                   else
6320                     exp->write_c_string(", ");
6321                   if (!is_varargs || pp + 1 != parameters->end())
6322                     exp->write_type(pp->type());
6323                   else
6324                     {
6325                       exp->write_c_string("...");
6326                       Type *pptype = pp->type();
6327                       exp->write_type(pptype->array_type()->element_type());
6328                     }
6329                 }
6330             }
6331
6332           exp->write_c_string(")");
6333
6334           const Typed_identifier_list* results = fntype->results();
6335           if (results != NULL)
6336             {
6337               exp->write_c_string(" ");
6338               if (results->size() == 1)
6339                 exp->write_type(results->begin()->type());
6340               else
6341                 {
6342                   first = true;
6343                   exp->write_c_string("(");
6344                   for (Typed_identifier_list::const_iterator p =
6345                          results->begin();
6346                        p != results->end();
6347                        ++p)
6348                     {
6349                       if (first)
6350                         first = false;
6351                       else
6352                         exp->write_c_string(", ");
6353                       exp->write_type(p->type());
6354                     }
6355                   exp->write_c_string(")");
6356                 }
6357             }
6358
6359           exp->write_c_string("; ");
6360         }
6361     }
6362
6363   exp->write_c_string("}");
6364 }
6365
6366 // Import an interface type.
6367
6368 Interface_type*
6369 Interface_type::do_import(Import* imp)
6370 {
6371   imp->require_c_string("interface { ");
6372
6373   Typed_identifier_list* methods = new Typed_identifier_list;
6374   while (imp->peek_char() != '}')
6375     {
6376       std::string name = imp->read_identifier();
6377       imp->require_c_string(" (");
6378
6379       Typed_identifier_list* parameters;
6380       bool is_varargs = false;
6381       if (imp->peek_char() == ')')
6382         parameters = NULL;
6383       else
6384         {
6385           parameters = new Typed_identifier_list;
6386           while (true)
6387             {
6388               if (imp->match_c_string("..."))
6389                 {
6390                   imp->advance(3);
6391                   is_varargs = true;
6392                 }
6393
6394               Type* ptype = imp->read_type();
6395               if (is_varargs)
6396                 ptype = Type::make_array_type(ptype, NULL);
6397               parameters->push_back(Typed_identifier(Import::import_marker,
6398                                                      ptype, imp->location()));
6399               if (imp->peek_char() != ',')
6400                 break;
6401               go_assert(!is_varargs);
6402               imp->require_c_string(", ");
6403             }
6404         }
6405       imp->require_c_string(")");
6406
6407       Typed_identifier_list* results;
6408       if (imp->peek_char() != ' ')
6409         results = NULL;
6410       else
6411         {
6412           results = new Typed_identifier_list;
6413           imp->advance(1);
6414           if (imp->peek_char() != '(')
6415             {
6416               Type* rtype = imp->read_type();
6417               results->push_back(Typed_identifier(Import::import_marker,
6418                                                   rtype, imp->location()));
6419             }
6420           else
6421             {
6422               imp->advance(1);
6423               while (true)
6424                 {
6425                   Type* rtype = imp->read_type();
6426                   results->push_back(Typed_identifier(Import::import_marker,
6427                                                       rtype, imp->location()));
6428                   if (imp->peek_char() != ',')
6429                     break;
6430                   imp->require_c_string(", ");
6431                 }
6432               imp->require_c_string(")");
6433             }
6434         }
6435
6436       Function_type* fntype = Type::make_function_type(NULL, parameters,
6437                                                        results,
6438                                                        imp->location());
6439       if (is_varargs)
6440         fntype->set_is_varargs();
6441       methods->push_back(Typed_identifier(name, fntype, imp->location()));
6442
6443       imp->require_c_string("; ");
6444     }
6445
6446   imp->require_c_string("}");
6447
6448   if (methods->empty())
6449     {
6450       delete methods;
6451       methods = NULL;
6452     }
6453
6454   return Type::make_interface_type(methods, imp->location());
6455 }
6456
6457 // Make an interface type.
6458
6459 Interface_type*
6460 Type::make_interface_type(Typed_identifier_list* methods,
6461                           source_location location)
6462 {
6463   return new Interface_type(methods, location);
6464 }
6465
6466 // Class Method.
6467
6468 // Bind a method to an object.
6469
6470 Expression*
6471 Method::bind_method(Expression* expr, source_location location) const
6472 {
6473   if (this->stub_ == NULL)
6474     {
6475       // When there is no stub object, the binding is determined by
6476       // the child class.
6477       return this->do_bind_method(expr, location);
6478     }
6479
6480   Expression* func = Expression::make_func_reference(this->stub_, NULL,
6481                                                      location);
6482   return Expression::make_bound_method(expr, func, location);
6483 }
6484
6485 // Return the named object associated with a method.  This may only be
6486 // called after methods are finalized.
6487
6488 Named_object*
6489 Method::named_object() const
6490 {
6491   if (this->stub_ != NULL)
6492     return this->stub_;
6493   return this->do_named_object();
6494 }
6495
6496 // Class Named_method.
6497
6498 // The type of the method.
6499
6500 Function_type*
6501 Named_method::do_type() const
6502 {
6503   if (this->named_object_->is_function())
6504     return this->named_object_->func_value()->type();
6505   else if (this->named_object_->is_function_declaration())
6506     return this->named_object_->func_declaration_value()->type();
6507   else
6508     go_unreachable();
6509 }
6510
6511 // Return the location of the method receiver.
6512
6513 source_location
6514 Named_method::do_receiver_location() const
6515 {
6516   return this->do_type()->receiver()->location();
6517 }
6518
6519 // Bind a method to an object.
6520
6521 Expression*
6522 Named_method::do_bind_method(Expression* expr, source_location location) const
6523 {
6524   Expression* func = Expression::make_func_reference(this->named_object_, NULL,
6525                                                      location);
6526   Bound_method_expression* bme = Expression::make_bound_method(expr, func,
6527                                                                location);
6528   // If this is not a local method, and it does not use a stub, then
6529   // the real method expects a different type.  We need to cast the
6530   // first argument.
6531   if (this->depth() > 0 && !this->needs_stub_method())
6532     {
6533       Function_type* ftype = this->do_type();
6534       go_assert(ftype->is_method());
6535       Type* frtype = ftype->receiver()->type();
6536       bme->set_first_argument_type(frtype);
6537     }
6538   return bme;
6539 }
6540
6541 // Class Interface_method.
6542
6543 // Bind a method to an object.
6544
6545 Expression*
6546 Interface_method::do_bind_method(Expression* expr,
6547                                  source_location location) const
6548 {
6549   return Expression::make_interface_field_reference(expr, this->name_,
6550                                                     location);
6551 }
6552
6553 // Class Methods.
6554
6555 // Insert a new method.  Return true if it was inserted, false
6556 // otherwise.
6557
6558 bool
6559 Methods::insert(const std::string& name, Method* m)
6560 {
6561   std::pair<Method_map::iterator, bool> ins =
6562     this->methods_.insert(std::make_pair(name, m));
6563   if (ins.second)
6564     return true;
6565   else
6566     {
6567       Method* old_method = ins.first->second;
6568       if (m->depth() < old_method->depth())
6569         {
6570           delete old_method;
6571           ins.first->second = m;
6572           return true;
6573         }
6574       else
6575         {
6576           if (m->depth() == old_method->depth())
6577             old_method->set_is_ambiguous();
6578           return false;
6579         }
6580     }
6581 }
6582
6583 // Return the number of unambiguous methods.
6584
6585 size_t
6586 Methods::count() const
6587 {
6588   size_t ret = 0;
6589   for (Method_map::const_iterator p = this->methods_.begin();
6590        p != this->methods_.end();
6591        ++p)
6592     if (!p->second->is_ambiguous())
6593       ++ret;
6594   return ret;
6595 }
6596
6597 // Class Named_type.
6598
6599 // Return the name of the type.
6600
6601 const std::string&
6602 Named_type::name() const
6603 {
6604   return this->named_object_->name();
6605 }
6606
6607 // Return the name of the type to use in an error message.
6608
6609 std::string
6610 Named_type::message_name() const
6611 {
6612   return this->named_object_->message_name();
6613 }
6614
6615 // Return the base type for this type.  We have to be careful about
6616 // circular type definitions, which are invalid but may be seen here.
6617
6618 Type*
6619 Named_type::named_base()
6620 {
6621   if (this->seen_ > 0)
6622     return this;
6623   ++this->seen_;
6624   Type* ret = this->type_->base();
6625   --this->seen_;
6626   return ret;
6627 }
6628
6629 const Type*
6630 Named_type::named_base() const
6631 {
6632   if (this->seen_ > 0)
6633     return this;
6634   ++this->seen_;
6635   const Type* ret = this->type_->base();
6636   --this->seen_;
6637   return ret;
6638 }
6639
6640 // Return whether this is an error type.  We have to be careful about
6641 // circular type definitions, which are invalid but may be seen here.
6642
6643 bool
6644 Named_type::is_named_error_type() const
6645 {
6646   if (this->seen_ > 0)
6647     return false;
6648   ++this->seen_;
6649   bool ret = this->type_->is_error_type();
6650   --this->seen_;
6651   return ret;
6652 }
6653
6654 // Add a method to this type.
6655
6656 Named_object*
6657 Named_type::add_method(const std::string& name, Function* function)
6658 {
6659   if (this->local_methods_ == NULL)
6660     this->local_methods_ = new Bindings(NULL);
6661   return this->local_methods_->add_function(name, NULL, function);
6662 }
6663
6664 // Add a method declaration to this type.
6665
6666 Named_object*
6667 Named_type::add_method_declaration(const std::string& name, Package* package,
6668                                    Function_type* type,
6669                                    source_location location)
6670 {
6671   if (this->local_methods_ == NULL)
6672     this->local_methods_ = new Bindings(NULL);
6673   return this->local_methods_->add_function_declaration(name, package, type,
6674                                                         location);
6675 }
6676
6677 // Add an existing method to this type.
6678
6679 void
6680 Named_type::add_existing_method(Named_object* no)
6681 {
6682   if (this->local_methods_ == NULL)
6683     this->local_methods_ = new Bindings(NULL);
6684   this->local_methods_->add_named_object(no);
6685 }
6686
6687 // Look for a local method NAME, and returns its named object, or NULL
6688 // if not there.
6689
6690 Named_object*
6691 Named_type::find_local_method(const std::string& name) const
6692 {
6693   if (this->local_methods_ == NULL)
6694     return NULL;
6695   return this->local_methods_->lookup(name);
6696 }
6697
6698 // Return whether NAME is an unexported field or method, for better
6699 // error reporting.
6700
6701 bool
6702 Named_type::is_unexported_local_method(Gogo* gogo,
6703                                        const std::string& name) const
6704 {
6705   Bindings* methods = this->local_methods_;
6706   if (methods != NULL)
6707     {
6708       for (Bindings::const_declarations_iterator p =
6709              methods->begin_declarations();
6710            p != methods->end_declarations();
6711            ++p)
6712         {
6713           if (Gogo::is_hidden_name(p->first)
6714               && name == Gogo::unpack_hidden_name(p->first)
6715               && gogo->pack_hidden_name(name, false) != p->first)
6716             return true;
6717         }
6718     }
6719   return false;
6720 }
6721
6722 // Build the complete list of methods for this type, which means
6723 // recursively including all methods for anonymous fields.  Create all
6724 // stub methods.
6725
6726 void
6727 Named_type::finalize_methods(Gogo* gogo)
6728 {
6729   if (this->all_methods_ != NULL)
6730     return;
6731
6732   if (this->local_methods_ != NULL
6733       && (this->points_to() != NULL || this->interface_type() != NULL))
6734     {
6735       const Bindings* lm = this->local_methods_;
6736       for (Bindings::const_declarations_iterator p = lm->begin_declarations();
6737            p != lm->end_declarations();
6738            ++p)
6739         error_at(p->second->location(),
6740                  "invalid pointer or interface receiver type");
6741       delete this->local_methods_;
6742       this->local_methods_ = NULL;
6743       return;
6744     }
6745
6746   Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6747 }
6748
6749 // Return the method NAME, or NULL if there isn't one or if it is
6750 // ambiguous.  Set *IS_AMBIGUOUS if the method exists but is
6751 // ambiguous.
6752
6753 Method*
6754 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
6755 {
6756   return Type::method_function(this->all_methods_, name, is_ambiguous);
6757 }
6758
6759 // Return a pointer to the interface method table for this type for
6760 // the interface INTERFACE.  IS_POINTER is true if this is for a
6761 // pointer to THIS.
6762
6763 tree
6764 Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface,
6765                                    bool is_pointer)
6766 {
6767   go_assert(!interface->is_empty());
6768
6769   Interface_method_tables** pimt = (is_pointer
6770                                     ? &this->interface_method_tables_
6771                                     : &this->pointer_interface_method_tables_);
6772
6773   if (*pimt == NULL)
6774     *pimt = new Interface_method_tables(5);
6775
6776   std::pair<const Interface_type*, tree> val(interface, NULL_TREE);
6777   std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
6778
6779   if (ins.second)
6780     {
6781       // This is a new entry in the hash table.
6782       go_assert(ins.first->second == NULL_TREE);
6783       ins.first->second = gogo->interface_method_table_for_type(interface,
6784                                                                 this,
6785                                                                 is_pointer);
6786     }
6787
6788   tree decl = ins.first->second;
6789   if (decl == error_mark_node)
6790     return error_mark_node;
6791   go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL);
6792   return build_fold_addr_expr(decl);
6793 }
6794
6795 // Return whether a named type has any hidden fields.
6796
6797 bool
6798 Named_type::named_type_has_hidden_fields(std::string* reason) const
6799 {
6800   if (this->seen_ > 0)
6801     return false;
6802   ++this->seen_;
6803   bool ret = this->type_->has_hidden_fields(this, reason);
6804   --this->seen_;
6805   return ret;
6806 }
6807
6808 // Look for a use of a complete type within another type.  This is
6809 // used to check that we don't try to use a type within itself.
6810
6811 class Find_type_use : public Traverse
6812 {
6813  public:
6814   Find_type_use(Named_type* find_type)
6815     : Traverse(traverse_types),
6816       find_type_(find_type), found_(false)
6817   { }
6818
6819   // Whether we found the type.
6820   bool
6821   found() const
6822   { return this->found_; }
6823
6824  protected:
6825   int
6826   type(Type*);
6827
6828  private:
6829   // The type we are looking for.
6830   Named_type* find_type_;
6831   // Whether we found the type.
6832   bool found_;
6833 };
6834
6835 // Check for FIND_TYPE in TYPE.
6836
6837 int
6838 Find_type_use::type(Type* type)
6839 {
6840   if (type->named_type() != NULL && this->find_type_ == type->named_type())
6841     {
6842       this->found_ = true;
6843       return TRAVERSE_EXIT;
6844     }
6845
6846   // It's OK if we see a reference to the type in any type which is
6847   // essentially a pointer: a pointer, a slice, a function, a map, or
6848   // a channel.
6849   if (type->points_to() != NULL
6850       || type->is_open_array_type()
6851       || type->function_type() != NULL
6852       || type->map_type() != NULL
6853       || type->channel_type() != NULL)
6854     return TRAVERSE_SKIP_COMPONENTS;
6855
6856   // For an interface, a reference to the type in a method type should
6857   // be ignored, but we have to consider direct inheritance.  When
6858   // this is called, there may be cases of direct inheritance
6859   // represented as a method with no name.
6860   if (type->interface_type() != NULL)
6861     {
6862       const Typed_identifier_list* methods = type->interface_type()->methods();
6863       if (methods != NULL)
6864         {
6865           for (Typed_identifier_list::const_iterator p = methods->begin();
6866                p != methods->end();
6867                ++p)
6868             {
6869               if (p->name().empty())
6870                 {
6871                   if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
6872                     return TRAVERSE_EXIT;
6873                 }
6874             }
6875         }
6876       return TRAVERSE_SKIP_COMPONENTS;
6877     }
6878
6879   // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
6880   // to convert TYPE to the backend representation before we convert
6881   // FIND_TYPE_.
6882   if (type->named_type() != NULL)
6883     {
6884       switch (type->base()->classification())
6885         {
6886         case Type::TYPE_ERROR:
6887         case Type::TYPE_BOOLEAN:
6888         case Type::TYPE_INTEGER:
6889         case Type::TYPE_FLOAT:
6890         case Type::TYPE_COMPLEX:
6891         case Type::TYPE_STRING:
6892         case Type::TYPE_NIL:
6893           break;
6894
6895         case Type::TYPE_ARRAY:
6896         case Type::TYPE_STRUCT:
6897           this->find_type_->add_dependency(type->named_type());
6898           break;
6899
6900         case Type::TYPE_VOID:
6901         case Type::TYPE_SINK:
6902         case Type::TYPE_FUNCTION:
6903         case Type::TYPE_POINTER:
6904         case Type::TYPE_CALL_MULTIPLE_RESULT:
6905         case Type::TYPE_MAP:
6906         case Type::TYPE_CHANNEL:
6907         case Type::TYPE_INTERFACE:
6908         case Type::TYPE_NAMED:
6909         case Type::TYPE_FORWARD:
6910         default:
6911           go_unreachable();
6912         }
6913     }
6914
6915   return TRAVERSE_CONTINUE;
6916 }
6917
6918 // Verify that a named type does not refer to itself.
6919
6920 bool
6921 Named_type::do_verify()
6922 {
6923   Find_type_use find(this);
6924   Type::traverse(this->type_, &find);
6925   if (find.found())
6926     {
6927       error_at(this->location_, "invalid recursive type %qs",
6928                this->message_name().c_str());
6929       this->is_error_ = true;
6930       return false;
6931     }
6932
6933   // Check whether any of the local methods overloads an existing
6934   // struct field or interface method.  We don't need to check the
6935   // list of methods against itself: that is handled by the Bindings
6936   // code.
6937   if (this->local_methods_ != NULL)
6938     {
6939       Struct_type* st = this->type_->struct_type();
6940       bool found_dup = false;
6941       if (st != NULL)
6942         {
6943           for (Bindings::const_declarations_iterator p =
6944                  this->local_methods_->begin_declarations();
6945                p != this->local_methods_->end_declarations();
6946                ++p)
6947             {
6948               const std::string& name(p->first);
6949               if (st != NULL && st->find_local_field(name, NULL) != NULL)
6950                 {
6951                   error_at(p->second->location(),
6952                            "method %qs redeclares struct field name",
6953                            Gogo::message_name(name).c_str());
6954                   found_dup = true;
6955                 }
6956             }
6957         }
6958       if (found_dup)
6959         return false;
6960     }
6961
6962   return true;
6963 }
6964
6965 // Return whether this type is or contains a pointer.
6966
6967 bool
6968 Named_type::do_has_pointer() const
6969 {
6970   if (this->seen_ > 0)
6971     return false;
6972   ++this->seen_;
6973   bool ret = this->type_->has_pointer();
6974   --this->seen_;
6975   return ret;
6976 }
6977
6978 // Return a hash code.  This is used for method lookup.  We simply
6979 // hash on the name itself.
6980
6981 unsigned int
6982 Named_type::do_hash_for_method(Gogo* gogo) const
6983 {
6984   const std::string& name(this->named_object()->name());
6985   unsigned int ret = Type::hash_string(name, 0);
6986
6987   // GOGO will be NULL here when called from Type_hash_identical.
6988   // That is OK because that is only used for internal hash tables
6989   // where we are going to be comparing named types for equality.  In
6990   // other cases, which are cases where the runtime is going to
6991   // compare hash codes to see if the types are the same, we need to
6992   // include the package prefix and name in the hash.
6993   if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
6994     {
6995       const Package* package = this->named_object()->package();
6996       if (package == NULL)
6997         {
6998           ret = Type::hash_string(gogo->unique_prefix(), ret);
6999           ret = Type::hash_string(gogo->package_name(), ret);
7000         }
7001       else
7002         {
7003           ret = Type::hash_string(package->unique_prefix(), ret);
7004           ret = Type::hash_string(package->name(), ret);
7005         }
7006     }
7007
7008   return ret;
7009 }
7010
7011 // Convert a named type to the backend representation.  In order to
7012 // get dependencies right, we fill in a dummy structure for this type,
7013 // then convert all the dependencies, then complete this type.  When
7014 // this function is complete, the size of the type is known.
7015
7016 void
7017 Named_type::convert(Gogo* gogo)
7018 {
7019   if (this->is_error_ || this->is_converted_)
7020     return;
7021
7022   this->create_placeholder(gogo);
7023
7024   // Convert all the dependencies.  If they refer indirectly back to
7025   // this type, they will pick up the intermediate tree we just
7026   // created.
7027   for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
7028        p != this->dependencies_.end();
7029        ++p)
7030     (*p)->convert(gogo);
7031
7032   // Complete this type.
7033   Btype* bt = this->named_btype_;
7034   Type* base = this->type_->base();
7035   switch (base->classification())
7036     {
7037     case TYPE_VOID:
7038     case TYPE_BOOLEAN:
7039     case TYPE_INTEGER:
7040     case TYPE_FLOAT:
7041     case TYPE_COMPLEX:
7042     case TYPE_STRING:
7043     case TYPE_NIL:
7044       break;
7045
7046     case TYPE_MAP:
7047     case TYPE_CHANNEL:
7048       break;
7049
7050     case TYPE_FUNCTION:
7051     case TYPE_POINTER:
7052       // The size of these types is already correct.  We don't worry
7053       // about filling them in until later, when we also track
7054       // circular references.
7055       break;
7056
7057     case TYPE_STRUCT:
7058       {
7059         std::vector<Backend::Btyped_identifier> bfields;
7060         get_backend_struct_fields(gogo, base->struct_type()->fields(),
7061                                   &bfields);
7062         if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
7063           bt = gogo->backend()->error_type();
7064       }
7065       break;
7066
7067     case TYPE_ARRAY:
7068       // Slice types were completed in create_placeholder.
7069       if (!base->is_open_array_type())
7070         {
7071           Btype* bet = base->array_type()->get_backend_element(gogo);
7072           Bexpression* blen = base->array_type()->get_backend_length(gogo);
7073           if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
7074             bt = gogo->backend()->error_type();
7075         }
7076       break;
7077
7078     case TYPE_INTERFACE:
7079       // Interface types were completed in create_placeholder.
7080       break;
7081
7082     case TYPE_ERROR:
7083       return;
7084
7085     default:
7086     case TYPE_SINK:
7087     case TYPE_CALL_MULTIPLE_RESULT:
7088     case TYPE_NAMED:
7089     case TYPE_FORWARD:
7090       go_unreachable();
7091     }
7092
7093   this->named_btype_ = bt;
7094   this->is_converted_ = true;
7095 }
7096
7097 // Create the placeholder for a named type.  This is the first step in
7098 // converting to the backend representation.
7099
7100 void
7101 Named_type::create_placeholder(Gogo* gogo)
7102 {
7103   if (this->is_error_)
7104     this->named_btype_ = gogo->backend()->error_type();
7105
7106   if (this->named_btype_ != NULL)
7107     return;
7108
7109   // Create the structure for this type.  Note that because we call
7110   // base() here, we don't attempt to represent a named type defined
7111   // as another named type.  Instead both named types will point to
7112   // different base representations.
7113   Type* base = this->type_->base();
7114   Btype* bt;
7115   bool set_name = true;
7116   switch (base->classification())
7117     {
7118     case TYPE_ERROR:
7119       this->is_error_ = true;
7120       this->named_btype_ = gogo->backend()->error_type();
7121       return;
7122
7123     case TYPE_VOID:
7124     case TYPE_BOOLEAN:
7125     case TYPE_INTEGER:
7126     case TYPE_FLOAT:
7127     case TYPE_COMPLEX:
7128     case TYPE_STRING:
7129     case TYPE_NIL:
7130       // These are simple basic types, we can just create them
7131       // directly.
7132       bt = Type::get_named_base_btype(gogo, base);
7133       break;
7134
7135     case TYPE_MAP:
7136     case TYPE_CHANNEL:
7137       // All maps and channels have the same backend representation.
7138       bt = Type::get_named_base_btype(gogo, base);
7139       break;
7140
7141     case TYPE_FUNCTION:
7142     case TYPE_POINTER:
7143       {
7144         bool for_function = base->classification() == TYPE_FUNCTION;
7145         bt = gogo->backend()->placeholder_pointer_type(this->name(),
7146                                                        this->location_,
7147                                                        for_function);
7148         set_name = false;
7149       }
7150       break;
7151
7152     case TYPE_STRUCT:
7153       bt = gogo->backend()->placeholder_struct_type(this->name(),
7154                                                     this->location_);
7155       set_name = false;
7156       break;
7157
7158     case TYPE_ARRAY:
7159       if (base->is_open_array_type())
7160         bt = gogo->backend()->placeholder_struct_type(this->name(),
7161                                                       this->location_);
7162       else
7163         bt = gogo->backend()->placeholder_array_type(this->name(),
7164                                                      this->location_);
7165       set_name = false;
7166       break;
7167
7168     case TYPE_INTERFACE:
7169       if (base->interface_type()->is_empty())
7170         bt = Interface_type::get_backend_empty_interface_type(gogo);
7171       else
7172         {
7173           bt = gogo->backend()->placeholder_struct_type(this->name(),
7174                                                         this->location_);
7175           set_name = false;
7176         }
7177       break;
7178
7179     default:
7180     case TYPE_SINK:
7181     case TYPE_CALL_MULTIPLE_RESULT:
7182     case TYPE_NAMED:
7183     case TYPE_FORWARD:
7184       go_unreachable();
7185     }
7186
7187   if (set_name)
7188     bt = gogo->backend()->named_type(this->name(), bt, this->location_);
7189
7190   this->named_btype_ = bt;
7191
7192   if (base->is_open_array_type())
7193     {
7194       // We do not record slices as dependencies of other types,
7195       // because we can fill them in completely here with the final
7196       // size.
7197       std::vector<Backend::Btyped_identifier> bfields;
7198       get_backend_slice_fields(gogo, base->array_type(), &bfields);
7199       if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
7200         this->named_btype_ = gogo->backend()->error_type();
7201     }
7202   else if (base->interface_type() != NULL
7203            && !base->interface_type()->is_empty())
7204     {
7205       // We do not record interfaces as dependencies of other types,
7206       // because we can fill them in completely here with the final
7207       // size.
7208       std::vector<Backend::Btyped_identifier> bfields;
7209       get_backend_interface_fields(gogo, base->interface_type(), &bfields);
7210       if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
7211         this->named_btype_ = gogo->backend()->error_type();
7212     }
7213 }
7214
7215 // Get a tree for a named type.
7216
7217 Btype*
7218 Named_type::do_get_backend(Gogo* gogo)
7219 {
7220   if (this->is_error_)
7221     return gogo->backend()->error_type();
7222
7223   Btype* bt = this->named_btype_;
7224
7225   if (!gogo->named_types_are_converted())
7226     {
7227       // We have not completed converting named types.  NAMED_BTYPE_
7228       // is a placeholder and we shouldn't do anything further.
7229       if (bt != NULL)
7230         return bt;
7231
7232       // We don't build dependencies for types whose sizes do not
7233       // change or are not relevant, so we may see them here while
7234       // converting types.
7235       this->create_placeholder(gogo);
7236       bt = this->named_btype_;
7237       go_assert(bt != NULL);
7238       return bt;
7239     }
7240
7241   // We are not converting types.  This should only be called if the
7242   // type has already been converted.
7243   if (!this->is_converted_)
7244     {
7245       go_assert(saw_errors());
7246       return gogo->backend()->error_type();
7247     }
7248
7249   go_assert(bt != NULL);
7250
7251   // Complete the tree.
7252   Type* base = this->type_->base();
7253   Btype* bt1;
7254   switch (base->classification())
7255     {
7256     case TYPE_ERROR:
7257       return gogo->backend()->error_type();
7258
7259     case TYPE_VOID:
7260     case TYPE_BOOLEAN:
7261     case TYPE_INTEGER:
7262     case TYPE_FLOAT:
7263     case TYPE_COMPLEX:
7264     case TYPE_STRING:
7265     case TYPE_NIL:
7266     case TYPE_MAP:
7267     case TYPE_CHANNEL:
7268     case TYPE_STRUCT:
7269     case TYPE_ARRAY:
7270     case TYPE_INTERFACE:
7271       return bt;
7272
7273     case TYPE_FUNCTION:
7274       // Don't build a circular data structure.  GENERIC can't handle
7275       // it.
7276       if (this->seen_ > 0)
7277         {
7278           this->is_circular_ = true;
7279           return gogo->backend()->circular_pointer_type(bt, true);
7280         }
7281       ++this->seen_;
7282       bt1 = Type::get_named_base_btype(gogo, base);
7283       --this->seen_;
7284       if (this->is_circular_)
7285         bt1 = gogo->backend()->circular_pointer_type(bt, true);
7286       if (!gogo->backend()->set_placeholder_function_type(bt, bt1))
7287         bt = gogo->backend()->error_type();
7288       return bt;
7289
7290     case TYPE_POINTER:
7291       // Don't build a circular data structure. GENERIC can't handle
7292       // it.
7293       if (this->seen_ > 0)
7294         {
7295           this->is_circular_ = true;
7296           return gogo->backend()->circular_pointer_type(bt, false);
7297         }
7298       ++this->seen_;
7299       bt1 = Type::get_named_base_btype(gogo, base);
7300       --this->seen_;
7301       if (this->is_circular_)
7302         bt1 = gogo->backend()->circular_pointer_type(bt, false);
7303       if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
7304         bt = gogo->backend()->error_type();
7305       return bt;
7306
7307     default:
7308     case TYPE_SINK:
7309     case TYPE_CALL_MULTIPLE_RESULT:
7310     case TYPE_NAMED:
7311     case TYPE_FORWARD:
7312       go_unreachable();
7313     }
7314
7315   go_unreachable();
7316 }
7317
7318 // Build a type descriptor for a named type.
7319
7320 Expression*
7321 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7322 {
7323   // If NAME is not NULL, then we don't really want the type
7324   // descriptor for this type; we want the descriptor for the
7325   // underlying type, giving it the name NAME.
7326   return this->named_type_descriptor(gogo, this->type_,
7327                                      name == NULL ? this : name);
7328 }
7329
7330 // Add to the reflection string.  This is used mostly for the name of
7331 // the type used in a type descriptor, not for actual reflection
7332 // strings.
7333
7334 void
7335 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
7336 {
7337   if (this->location() != BUILTINS_LOCATION)
7338     {
7339       const Package* package = this->named_object_->package();
7340       if (package != NULL)
7341         ret->append(package->name());
7342       else
7343         ret->append(gogo->package_name());
7344       ret->push_back('.');
7345     }
7346   if (this->in_function_ != NULL)
7347     {
7348       ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
7349       ret->push_back('$');
7350     }
7351   ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
7352 }
7353
7354 // Get the mangled name.
7355
7356 void
7357 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7358 {
7359   Named_object* no = this->named_object_;
7360   std::string name;
7361   if (this->location() == BUILTINS_LOCATION)
7362     go_assert(this->in_function_ == NULL);
7363   else
7364     {
7365       const std::string& unique_prefix(no->package() == NULL
7366                                        ? gogo->unique_prefix()
7367                                        : no->package()->unique_prefix());
7368       const std::string& package_name(no->package() == NULL
7369                                       ? gogo->package_name()
7370                                       : no->package()->name());
7371       name = unique_prefix;
7372       name.append(1, '.');
7373       name.append(package_name);
7374       name.append(1, '.');
7375       if (this->in_function_ != NULL)
7376         {
7377           name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
7378           name.append(1, '$');
7379         }
7380     }
7381   name.append(Gogo::unpack_hidden_name(no->name()));
7382   char buf[20];
7383   snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
7384   ret->append(buf);
7385   ret->append(name);
7386 }
7387
7388 // Export the type.  This is called to export a global type.
7389
7390 void
7391 Named_type::export_named_type(Export* exp, const std::string&) const
7392 {
7393   // We don't need to write the name of the type here, because it will
7394   // be written by Export::write_type anyhow.
7395   exp->write_c_string("type ");
7396   exp->write_type(this);
7397   exp->write_c_string(";\n");
7398 }
7399
7400 // Import a named type.
7401
7402 void
7403 Named_type::import_named_type(Import* imp, Named_type** ptype)
7404 {
7405   imp->require_c_string("type ");
7406   Type *type = imp->read_type();
7407   *ptype = type->named_type();
7408   go_assert(*ptype != NULL);
7409   imp->require_c_string(";\n");
7410 }
7411
7412 // Export the type when it is referenced by another type.  In this
7413 // case Export::export_type will already have issued the name.
7414
7415 void
7416 Named_type::do_export(Export* exp) const
7417 {
7418   exp->write_type(this->type_);
7419
7420   // To save space, we only export the methods directly attached to
7421   // this type.
7422   Bindings* methods = this->local_methods_;
7423   if (methods == NULL)
7424     return;
7425
7426   exp->write_c_string("\n");
7427   for (Bindings::const_definitions_iterator p = methods->begin_definitions();
7428        p != methods->end_definitions();
7429        ++p)
7430     {
7431       exp->write_c_string(" ");
7432       (*p)->export_named_object(exp);
7433     }
7434
7435   for (Bindings::const_declarations_iterator p = methods->begin_declarations();
7436        p != methods->end_declarations();
7437        ++p)
7438     {
7439       if (p->second->is_function_declaration())
7440         {
7441           exp->write_c_string(" ");
7442           p->second->export_named_object(exp);
7443         }
7444     }
7445 }
7446
7447 // Make a named type.
7448
7449 Named_type*
7450 Type::make_named_type(Named_object* named_object, Type* type,
7451                       source_location location)
7452 {
7453   return new Named_type(named_object, type, location);
7454 }
7455
7456 // Finalize the methods for TYPE.  It will be a named type or a struct
7457 // type.  This sets *ALL_METHODS to the list of methods, and builds
7458 // all required stubs.
7459
7460 void
7461 Type::finalize_methods(Gogo* gogo, const Type* type, source_location location,
7462                        Methods** all_methods)
7463 {
7464   *all_methods = NULL;
7465   Types_seen types_seen;
7466   Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen,
7467                              all_methods);
7468   Type::build_stub_methods(gogo, type, *all_methods, location);
7469 }
7470
7471 // Add the methods for TYPE to *METHODS.  FIELD_INDEXES is used to
7472 // build up the struct field indexes as we go.  DEPTH is the depth of
7473 // the field within TYPE.  IS_EMBEDDED_POINTER is true if we are
7474 // adding these methods for an anonymous field with pointer type.
7475 // NEEDS_STUB_METHOD is true if we need to use a stub method which
7476 // calls the real method.  TYPES_SEEN is used to avoid infinite
7477 // recursion.
7478
7479 void
7480 Type::add_methods_for_type(const Type* type,
7481                            const Method::Field_indexes* field_indexes,
7482                            unsigned int depth,
7483                            bool is_embedded_pointer,
7484                            bool needs_stub_method,
7485                            Types_seen* types_seen,
7486                            Methods** methods)
7487 {
7488   // Pointer types may not have methods.
7489   if (type->points_to() != NULL)
7490     return;
7491
7492   const Named_type* nt = type->named_type();
7493   if (nt != NULL)
7494     {
7495       std::pair<Types_seen::iterator, bool> ins = types_seen->insert(nt);
7496       if (!ins.second)
7497         return;
7498     }
7499
7500   if (nt != NULL)
7501     Type::add_local_methods_for_type(nt, field_indexes, depth,
7502                                      is_embedded_pointer, needs_stub_method,
7503                                      methods);
7504
7505   Type::add_embedded_methods_for_type(type, field_indexes, depth,
7506                                       is_embedded_pointer, needs_stub_method,
7507                                       types_seen, methods);
7508
7509   // If we are called with depth > 0, then we are looking at an
7510   // anonymous field of a struct.  If such a field has interface type,
7511   // then we need to add the interface methods.  We don't want to add
7512   // them when depth == 0, because we will already handle them
7513   // following the usual rules for an interface type.
7514   if (depth > 0)
7515     Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
7516 }
7517
7518 // Add the local methods for the named type NT to *METHODS.  The
7519 // parameters are as for add_methods_to_type.
7520
7521 void
7522 Type::add_local_methods_for_type(const Named_type* nt,
7523                                  const Method::Field_indexes* field_indexes,
7524                                  unsigned int depth,
7525                                  bool is_embedded_pointer,
7526                                  bool needs_stub_method,
7527                                  Methods** methods)
7528 {
7529   const Bindings* local_methods = nt->local_methods();
7530   if (local_methods == NULL)
7531     return;
7532
7533   if (*methods == NULL)
7534     *methods = new Methods();
7535
7536   for (Bindings::const_declarations_iterator p =
7537          local_methods->begin_declarations();
7538        p != local_methods->end_declarations();
7539        ++p)
7540     {
7541       Named_object* no = p->second;
7542       bool is_value_method = (is_embedded_pointer
7543                               || !Type::method_expects_pointer(no));
7544       Method* m = new Named_method(no, field_indexes, depth, is_value_method,
7545                                    (needs_stub_method
7546                                     || (depth > 0 && is_value_method)));
7547       if (!(*methods)->insert(no->name(), m))
7548         delete m;
7549     }
7550 }
7551
7552 // Add the embedded methods for TYPE to *METHODS.  These are the
7553 // methods attached to anonymous fields.  The parameters are as for
7554 // add_methods_to_type.
7555
7556 void
7557 Type::add_embedded_methods_for_type(const Type* type,
7558                                     const Method::Field_indexes* field_indexes,
7559                                     unsigned int depth,
7560                                     bool is_embedded_pointer,
7561                                     bool needs_stub_method,
7562                                     Types_seen* types_seen,
7563                                     Methods** methods)
7564 {
7565   // Look for anonymous fields in TYPE.  TYPE has fields if it is a
7566   // struct.
7567   const Struct_type* st = type->struct_type();
7568   if (st == NULL)
7569     return;
7570
7571   const Struct_field_list* fields = st->fields();
7572   if (fields == NULL)
7573     return;
7574
7575   unsigned int i = 0;
7576   for (Struct_field_list::const_iterator pf = fields->begin();
7577        pf != fields->end();
7578        ++pf, ++i)
7579     {
7580       if (!pf->is_anonymous())
7581         continue;
7582
7583       Type* ftype = pf->type();
7584       bool is_pointer = false;
7585       if (ftype->points_to() != NULL)
7586         {
7587           ftype = ftype->points_to();
7588           is_pointer = true;
7589         }
7590       Named_type* fnt = ftype->named_type();
7591       if (fnt == NULL)
7592         {
7593           // This is an error, but it will be diagnosed elsewhere.
7594           continue;
7595         }
7596
7597       Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
7598       sub_field_indexes->next = field_indexes;
7599       sub_field_indexes->field_index = i;
7600
7601       Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
7602                                  (is_embedded_pointer || is_pointer),
7603                                  (needs_stub_method
7604                                   || is_pointer
7605                                   || i > 0),
7606                                  types_seen,
7607                                  methods);
7608     }
7609 }
7610
7611 // If TYPE is an interface type, then add its method to *METHODS.
7612 // This is for interface methods attached to an anonymous field.  The
7613 // parameters are as for add_methods_for_type.
7614
7615 void
7616 Type::add_interface_methods_for_type(const Type* type,
7617                                      const Method::Field_indexes* field_indexes,
7618                                      unsigned int depth,
7619                                      Methods** methods)
7620 {
7621   const Interface_type* it = type->interface_type();
7622   if (it == NULL)
7623     return;
7624
7625   const Typed_identifier_list* imethods = it->methods();
7626   if (imethods == NULL)
7627     return;
7628
7629   if (*methods == NULL)
7630     *methods = new Methods();
7631
7632   for (Typed_identifier_list::const_iterator pm = imethods->begin();
7633        pm != imethods->end();
7634        ++pm)
7635     {
7636       Function_type* fntype = pm->type()->function_type();
7637       if (fntype == NULL)
7638         {
7639           // This is an error, but it should be reported elsewhere
7640           // when we look at the methods for IT.
7641           continue;
7642         }
7643       go_assert(!fntype->is_method());
7644       fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
7645       Method* m = new Interface_method(pm->name(), pm->location(), fntype,
7646                                        field_indexes, depth);
7647       if (!(*methods)->insert(pm->name(), m))
7648         delete m;
7649     }
7650 }
7651
7652 // Build stub methods for TYPE as needed.  METHODS is the set of
7653 // methods for the type.  A stub method may be needed when a type
7654 // inherits a method from an anonymous field.  When we need the
7655 // address of the method, as in a type descriptor, we need to build a
7656 // little stub which does the required field dereferences and jumps to
7657 // the real method.  LOCATION is the location of the type definition.
7658
7659 void
7660 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
7661                          source_location location)
7662 {
7663   if (methods == NULL)
7664     return;
7665   for (Methods::const_iterator p = methods->begin();
7666        p != methods->end();
7667        ++p)
7668     {
7669       Method* m = p->second;
7670       if (m->is_ambiguous() || !m->needs_stub_method())
7671         continue;
7672
7673       const std::string& name(p->first);
7674
7675       // Build a stub method.
7676
7677       const Function_type* fntype = m->type();
7678
7679       static unsigned int counter;
7680       char buf[100];
7681       snprintf(buf, sizeof buf, "$this%u", counter);
7682       ++counter;
7683
7684       Type* receiver_type = const_cast<Type*>(type);
7685       if (!m->is_value_method())
7686         receiver_type = Type::make_pointer_type(receiver_type);
7687       source_location receiver_location = m->receiver_location();
7688       Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
7689                                                         receiver_location);
7690
7691       const Typed_identifier_list* fnparams = fntype->parameters();
7692       Typed_identifier_list* stub_params;
7693       if (fnparams == NULL || fnparams->empty())
7694         stub_params = NULL;
7695       else
7696         {
7697           // We give each stub parameter a unique name.
7698           stub_params = new Typed_identifier_list();
7699           for (Typed_identifier_list::const_iterator pp = fnparams->begin();
7700                pp != fnparams->end();
7701                ++pp)
7702             {
7703               char pbuf[100];
7704               snprintf(pbuf, sizeof pbuf, "$p%u", counter);
7705               stub_params->push_back(Typed_identifier(pbuf, pp->type(),
7706                                                       pp->location()));
7707               ++counter;
7708             }
7709         }
7710
7711       const Typed_identifier_list* fnresults = fntype->results();
7712       Typed_identifier_list* stub_results;
7713       if (fnresults == NULL || fnresults->empty())
7714         stub_results = NULL;
7715       else
7716         {
7717           // We create the result parameters without any names, since
7718           // we won't refer to them.
7719           stub_results = new Typed_identifier_list();
7720           for (Typed_identifier_list::const_iterator pr = fnresults->begin();
7721                pr != fnresults->end();
7722                ++pr)
7723             stub_results->push_back(Typed_identifier("", pr->type(),
7724                                                      pr->location()));
7725         }
7726
7727       Function_type* stub_type = Type::make_function_type(receiver,
7728                                                           stub_params,
7729                                                           stub_results,
7730                                                           fntype->location());
7731       if (fntype->is_varargs())
7732         stub_type->set_is_varargs();
7733
7734       // We only create the function in the package which creates the
7735       // type.
7736       const Package* package;
7737       if (type->named_type() == NULL)
7738         package = NULL;
7739       else
7740         package = type->named_type()->named_object()->package();
7741       Named_object* stub;
7742       if (package != NULL)
7743         stub = Named_object::make_function_declaration(name, package,
7744                                                        stub_type, location);
7745       else
7746         {
7747           stub = gogo->start_function(name, stub_type, false,
7748                                       fntype->location());
7749           Type::build_one_stub_method(gogo, m, buf, stub_params,
7750                                       fntype->is_varargs(), location);
7751           gogo->finish_function(fntype->location());
7752         }
7753
7754       m->set_stub_object(stub);
7755     }
7756 }
7757
7758 // Build a stub method which adjusts the receiver as required to call
7759 // METHOD.  RECEIVER_NAME is the name we used for the receiver.
7760 // PARAMS is the list of function parameters.
7761
7762 void
7763 Type::build_one_stub_method(Gogo* gogo, Method* method,
7764                             const char* receiver_name,
7765                             const Typed_identifier_list* params,
7766                             bool is_varargs,
7767                             source_location location)
7768 {
7769   Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
7770   go_assert(receiver_object != NULL);
7771
7772   Expression* expr = Expression::make_var_reference(receiver_object, location);
7773   expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
7774   if (expr->type()->points_to() == NULL)
7775     expr = Expression::make_unary(OPERATOR_AND, expr, location);
7776
7777   Expression_list* arguments;
7778   if (params == NULL || params->empty())
7779     arguments = NULL;
7780   else
7781     {
7782       arguments = new Expression_list();
7783       for (Typed_identifier_list::const_iterator p = params->begin();
7784            p != params->end();
7785            ++p)
7786         {
7787           Named_object* param = gogo->lookup(p->name(), NULL);
7788           go_assert(param != NULL);
7789           Expression* param_ref = Expression::make_var_reference(param,
7790                                                                  location);
7791           arguments->push_back(param_ref);
7792         }
7793     }
7794
7795   Expression* func = method->bind_method(expr, location);
7796   go_assert(func != NULL);
7797   Call_expression* call = Expression::make_call(func, arguments, is_varargs,
7798                                                 location);
7799   size_t count = call->result_count();
7800   if (count == 0)
7801     gogo->add_statement(Statement::make_statement(call));
7802   else
7803     {
7804       Expression_list* retvals = new Expression_list();
7805       if (count <= 1)
7806         retvals->push_back(call);
7807       else
7808         {
7809           for (size_t i = 0; i < count; ++i)
7810             retvals->push_back(Expression::make_call_result(call, i));
7811         }
7812       Statement* retstat = Statement::make_return_statement(retvals, location);
7813       gogo->add_statement(retstat);
7814     }
7815 }
7816
7817 // Apply FIELD_INDEXES to EXPR.  The field indexes have to be applied
7818 // in reverse order.
7819
7820 Expression*
7821 Type::apply_field_indexes(Expression* expr,
7822                           const Method::Field_indexes* field_indexes,
7823                           source_location location)
7824 {
7825   if (field_indexes == NULL)
7826     return expr;
7827   expr = Type::apply_field_indexes(expr, field_indexes->next, location);
7828   Struct_type* stype = expr->type()->deref()->struct_type();
7829   go_assert(stype != NULL
7830              && field_indexes->field_index < stype->field_count());
7831   if (expr->type()->struct_type() == NULL)
7832     {
7833       go_assert(expr->type()->points_to() != NULL);
7834       expr = Expression::make_unary(OPERATOR_MULT, expr, location);
7835       go_assert(expr->type()->struct_type() == stype);
7836     }
7837   return Expression::make_field_reference(expr, field_indexes->field_index,
7838                                           location);
7839 }
7840
7841 // Return whether NO is a method for which the receiver is a pointer.
7842
7843 bool
7844 Type::method_expects_pointer(const Named_object* no)
7845 {
7846   const Function_type *fntype;
7847   if (no->is_function())
7848     fntype = no->func_value()->type();
7849   else if (no->is_function_declaration())
7850     fntype = no->func_declaration_value()->type();
7851   else
7852     go_unreachable();
7853   return fntype->receiver()->type()->points_to() != NULL;
7854 }
7855
7856 // Given a set of methods for a type, METHODS, return the method NAME,
7857 // or NULL if there isn't one or if it is ambiguous.  If IS_AMBIGUOUS
7858 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
7859 // but is ambiguous (and return NULL).
7860
7861 Method*
7862 Type::method_function(const Methods* methods, const std::string& name,
7863                       bool* is_ambiguous)
7864 {
7865   if (is_ambiguous != NULL)
7866     *is_ambiguous = false;
7867   if (methods == NULL)
7868     return NULL;
7869   Methods::const_iterator p = methods->find(name);
7870   if (p == methods->end())
7871     return NULL;
7872   Method* m = p->second;
7873   if (m->is_ambiguous())
7874     {
7875       if (is_ambiguous != NULL)
7876         *is_ambiguous = true;
7877       return NULL;
7878     }
7879   return m;
7880 }
7881
7882 // Look for field or method NAME for TYPE.  Return an Expression for
7883 // the field or method bound to EXPR.  If there is no such field or
7884 // method, give an appropriate error and return an error expression.
7885
7886 Expression*
7887 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
7888                            const std::string& name,
7889                            source_location location)
7890 {
7891   if (type->deref()->is_error_type())
7892     return Expression::make_error(location);
7893
7894   const Named_type* nt = type->deref()->named_type();
7895   const Struct_type* st = type->deref()->struct_type();
7896   const Interface_type* it = type->interface_type();
7897
7898   // If this is a pointer to a pointer, then it is possible that the
7899   // pointed-to type has methods.
7900   if (nt == NULL
7901       && st == NULL
7902       && it == NULL
7903       && type->points_to() != NULL
7904       && type->points_to()->points_to() != NULL)
7905     {
7906       expr = Expression::make_unary(OPERATOR_MULT, expr, location);
7907       type = type->points_to();
7908       if (type->deref()->is_error_type())
7909         return Expression::make_error(location);
7910       nt = type->points_to()->named_type();
7911       st = type->points_to()->struct_type();
7912     }
7913
7914   bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
7915                                   || expr->is_addressable());
7916   std::vector<const Named_type*> seen;
7917   bool is_method = false;
7918   bool found_pointer_method = false;
7919   std::string ambig1;
7920   std::string ambig2;
7921   if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
7922                                  &seen, NULL, &is_method,
7923                                  &found_pointer_method, &ambig1, &ambig2))
7924     {
7925       Expression* ret;
7926       if (!is_method)
7927         {
7928           go_assert(st != NULL);
7929           if (type->struct_type() == NULL)
7930             {
7931               go_assert(type->points_to() != NULL);
7932               expr = Expression::make_unary(OPERATOR_MULT, expr,
7933                                             location);
7934               go_assert(expr->type()->struct_type() == st);
7935             }
7936           ret = st->field_reference(expr, name, location);
7937         }
7938       else if (it != NULL && it->find_method(name) != NULL)
7939         ret = Expression::make_interface_field_reference(expr, name,
7940                                                          location);
7941       else
7942         {
7943           Method* m;
7944           if (nt != NULL)
7945             m = nt->method_function(name, NULL);
7946           else if (st != NULL)
7947             m = st->method_function(name, NULL);
7948           else
7949             go_unreachable();
7950           go_assert(m != NULL);
7951           if (!m->is_value_method() && expr->type()->points_to() == NULL)
7952             expr = Expression::make_unary(OPERATOR_AND, expr, location);
7953           ret = m->bind_method(expr, location);
7954         }
7955       go_assert(ret != NULL);
7956       return ret;
7957     }
7958   else
7959     {
7960       if (!ambig1.empty())
7961         error_at(location, "%qs is ambiguous via %qs and %qs",
7962                  Gogo::message_name(name).c_str(),
7963                  Gogo::message_name(ambig1).c_str(),
7964                  Gogo::message_name(ambig2).c_str());
7965       else if (found_pointer_method)
7966         error_at(location, "method requires a pointer");
7967       else if (nt == NULL && st == NULL && it == NULL)
7968         error_at(location,
7969                  ("reference to field %qs in object which "
7970                   "has no fields or methods"),
7971                  Gogo::message_name(name).c_str());
7972       else
7973         {
7974           bool is_unexported;
7975           if (!Gogo::is_hidden_name(name))
7976             is_unexported = false;
7977           else
7978             {
7979               std::string unpacked = Gogo::unpack_hidden_name(name);
7980               seen.clear();
7981               is_unexported = Type::is_unexported_field_or_method(gogo, type,
7982                                                                   unpacked,
7983                                                                   &seen);
7984             }
7985           if (is_unexported)
7986             error_at(location, "reference to unexported field or method %qs",
7987                      Gogo::message_name(name).c_str());
7988           else
7989             error_at(location, "reference to undefined field or method %qs",
7990                      Gogo::message_name(name).c_str());
7991         }
7992       return Expression::make_error(location);
7993     }
7994 }
7995
7996 // Look in TYPE for a field or method named NAME, return true if one
7997 // is found.  This looks through embedded anonymous fields and handles
7998 // ambiguity.  If a method is found, sets *IS_METHOD to true;
7999 // otherwise, if a field is found, set it to false.  If
8000 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
8001 // whose address can not be taken.  SEEN is used to avoid infinite
8002 // recursion on invalid types.
8003
8004 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
8005 // method we couldn't use because it requires a pointer.  LEVEL is
8006 // used for recursive calls, and can be NULL for a non-recursive call.
8007 // When this function returns false because it finds that the name is
8008 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
8009 // and *AMBIG2.  If the name is not found at all, *AMBIG1 and *AMBIG2
8010 // will be unchanged.
8011
8012 // This function just returns whether or not there is a field or
8013 // method, and whether it is a field or method.  It doesn't build an
8014 // expression to refer to it.  If it is a method, we then look in the
8015 // list of all methods for the type.  If it is a field, the search has
8016 // to be done again, looking only for fields, and building up the
8017 // expression as we go.
8018
8019 bool
8020 Type::find_field_or_method(const Type* type,
8021                            const std::string& name,
8022                            bool receiver_can_be_pointer,
8023                            std::vector<const Named_type*>* seen,
8024                            int* level,
8025                            bool* is_method,
8026                            bool* found_pointer_method,
8027                            std::string* ambig1,
8028                            std::string* ambig2)
8029 {
8030   // Named types can have locally defined methods.
8031   const Named_type* nt = type->named_type();
8032   if (nt == NULL && type->points_to() != NULL)
8033     nt = type->points_to()->named_type();
8034   if (nt != NULL)
8035     {
8036       Named_object* no = nt->find_local_method(name);
8037       if (no != NULL)
8038         {
8039           if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
8040             {
8041               *is_method = true;
8042               return true;
8043             }
8044
8045           // Record that we have found a pointer method in order to
8046           // give a better error message if we don't find anything
8047           // else.
8048           *found_pointer_method = true;
8049         }
8050
8051       for (std::vector<const Named_type*>::const_iterator p = seen->begin();
8052            p != seen->end();
8053            ++p)
8054         {
8055           if (*p == nt)
8056             {
8057               // We've already seen this type when searching for methods.
8058               return false;
8059             }
8060         }
8061     }
8062
8063   // Interface types can have methods.
8064   const Interface_type* it = type->interface_type();
8065   if (it != NULL && it->find_method(name) != NULL)
8066     {
8067       *is_method = true;
8068       return true;
8069     }
8070
8071   // Struct types can have fields.  They can also inherit fields and
8072   // methods from anonymous fields.
8073   const Struct_type* st = type->deref()->struct_type();
8074   if (st == NULL)
8075     return false;
8076   const Struct_field_list* fields = st->fields();
8077   if (fields == NULL)
8078     return false;
8079
8080   if (nt != NULL)
8081     seen->push_back(nt);
8082
8083   int found_level = 0;
8084   bool found_is_method = false;
8085   std::string found_ambig1;
8086   std::string found_ambig2;
8087   const Struct_field* found_parent = NULL;
8088   for (Struct_field_list::const_iterator pf = fields->begin();
8089        pf != fields->end();
8090        ++pf)
8091     {
8092       if (pf->field_name() == name)
8093         {
8094           *is_method = false;
8095           if (nt != NULL)
8096             seen->pop_back();
8097           return true;
8098         }
8099
8100       if (!pf->is_anonymous())
8101         continue;
8102
8103       if (pf->type()->deref()->is_error_type()
8104           || pf->type()->deref()->is_undefined())
8105         continue;
8106
8107       Named_type* fnt = pf->type()->named_type();
8108       if (fnt == NULL)
8109         fnt = pf->type()->deref()->named_type();
8110       go_assert(fnt != NULL);
8111
8112       int sublevel = level == NULL ? 1 : *level + 1;
8113       bool sub_is_method;
8114       std::string subambig1;
8115       std::string subambig2;
8116       bool subfound = Type::find_field_or_method(fnt,
8117                                                  name,
8118                                                  receiver_can_be_pointer,
8119                                                  seen,
8120                                                  &sublevel,
8121                                                  &sub_is_method,
8122                                                  found_pointer_method,
8123                                                  &subambig1,
8124                                                  &subambig2);
8125       if (!subfound)
8126         {
8127           if (!subambig1.empty())
8128             {
8129               // The name was found via this field, but is ambiguous.
8130               // if the ambiguity is lower or at the same level as
8131               // anything else we have already found, then we want to
8132               // pass the ambiguity back to the caller.
8133               if (found_level == 0 || sublevel <= found_level)
8134                 {
8135                   found_ambig1 = pf->field_name() + '.' + subambig1;
8136                   found_ambig2 = pf->field_name() + '.' + subambig2;
8137                   found_level = sublevel;
8138                 }
8139             }
8140         }
8141       else
8142         {
8143           // The name was found via this field.  Use the level to see
8144           // if we want to use this one, or whether it introduces an
8145           // ambiguity.
8146           if (found_level == 0 || sublevel < found_level)
8147             {
8148               found_level = sublevel;
8149               found_is_method = sub_is_method;
8150               found_ambig1.clear();
8151               found_ambig2.clear();
8152               found_parent = &*pf;
8153             }
8154           else if (sublevel > found_level)
8155             ;
8156           else if (found_ambig1.empty())
8157             {
8158               // We found an ambiguity.
8159               go_assert(found_parent != NULL);
8160               found_ambig1 = found_parent->field_name();
8161               found_ambig2 = pf->field_name();
8162             }
8163           else
8164             {
8165               // We found an ambiguity, but we already know of one.
8166               // Just report the earlier one.
8167             }
8168         }
8169     }
8170
8171   // Here if we didn't find anything FOUND_LEVEL is 0.  If we found
8172   // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
8173   // FOUND_AMBIG2 are not empty.  If we found the field, FOUND_LEVEL
8174   // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
8175
8176   if (nt != NULL)
8177     seen->pop_back();
8178
8179   if (found_level == 0)
8180     return false;
8181   else if (!found_ambig1.empty())
8182     {
8183       go_assert(!found_ambig1.empty());
8184       ambig1->assign(found_ambig1);
8185       ambig2->assign(found_ambig2);
8186       if (level != NULL)
8187         *level = found_level;
8188       return false;
8189     }
8190   else
8191     {
8192       if (level != NULL)
8193         *level = found_level;
8194       *is_method = found_is_method;
8195       return true;
8196     }
8197 }
8198
8199 // Return whether NAME is an unexported field or method for TYPE.
8200
8201 bool
8202 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
8203                                     const std::string& name,
8204                                     std::vector<const Named_type*>* seen)
8205 {
8206   const Named_type* nt = type->named_type();
8207   if (nt == NULL)
8208     nt = type->deref()->named_type();
8209   if (nt != NULL)
8210     {
8211       if (nt->is_unexported_local_method(gogo, name))
8212         return true;
8213
8214       for (std::vector<const Named_type*>::const_iterator p = seen->begin();
8215            p != seen->end();
8216            ++p)
8217         {
8218           if (*p == nt)
8219             {
8220               // We've already seen this type.
8221               return false;
8222             }
8223         }
8224     }
8225
8226   const Interface_type* it = type->interface_type();
8227   if (it != NULL && it->is_unexported_method(gogo, name))
8228     return true;
8229
8230   type = type->deref();
8231
8232   const Struct_type* st = type->struct_type();
8233   if (st != NULL && st->is_unexported_local_field(gogo, name))
8234     return true;
8235
8236   if (st == NULL)
8237     return false;
8238
8239   const Struct_field_list* fields = st->fields();
8240   if (fields == NULL)
8241     return false;
8242
8243   if (nt != NULL)
8244     seen->push_back(nt);
8245
8246   for (Struct_field_list::const_iterator pf = fields->begin();
8247        pf != fields->end();
8248        ++pf)
8249     {
8250       if (pf->is_anonymous()
8251           && !pf->type()->deref()->is_error_type()
8252           && !pf->type()->deref()->is_undefined())
8253         {
8254           Named_type* subtype = pf->type()->named_type();
8255           if (subtype == NULL)
8256             subtype = pf->type()->deref()->named_type();
8257           if (subtype == NULL)
8258             {
8259               // This is an error, but it will be diagnosed elsewhere.
8260               continue;
8261             }
8262           if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
8263             {
8264               if (nt != NULL)
8265                 seen->pop_back();
8266               return true;
8267             }
8268         }
8269     }
8270
8271   if (nt != NULL)
8272     seen->pop_back();
8273
8274   return false;
8275 }
8276
8277 // Class Forward_declaration.
8278
8279 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
8280   : Type(TYPE_FORWARD),
8281     named_object_(named_object->resolve()), warned_(false)
8282 {
8283   go_assert(this->named_object_->is_unknown()
8284              || this->named_object_->is_type_declaration());
8285 }
8286
8287 // Return the named object.
8288
8289 Named_object*
8290 Forward_declaration_type::named_object()
8291 {
8292   return this->named_object_->resolve();
8293 }
8294
8295 const Named_object*
8296 Forward_declaration_type::named_object() const
8297 {
8298   return this->named_object_->resolve();
8299 }
8300
8301 // Return the name of the forward declared type.
8302
8303 const std::string&
8304 Forward_declaration_type::name() const
8305 {
8306   return this->named_object()->name();
8307 }
8308
8309 // Warn about a use of a type which has been declared but not defined.
8310
8311 void
8312 Forward_declaration_type::warn() const
8313 {
8314   Named_object* no = this->named_object_->resolve();
8315   if (no->is_unknown())
8316     {
8317       // The name was not defined anywhere.
8318       if (!this->warned_)
8319         {
8320           error_at(this->named_object_->location(),
8321                    "use of undefined type %qs",
8322                    no->message_name().c_str());
8323           this->warned_ = true;
8324         }
8325     }
8326   else if (no->is_type_declaration())
8327     {
8328       // The name was seen as a type, but the type was never defined.
8329       if (no->type_declaration_value()->using_type())
8330         {
8331           error_at(this->named_object_->location(),
8332                    "use of undefined type %qs",
8333                    no->message_name().c_str());
8334           this->warned_ = true;
8335         }
8336     }
8337   else
8338     {
8339       // The name was defined, but not as a type.
8340       if (!this->warned_)
8341         {
8342           error_at(this->named_object_->location(), "expected type");
8343           this->warned_ = true;
8344         }
8345     }
8346 }
8347
8348 // Get the base type of a declaration.  This gives an error if the
8349 // type has not yet been defined.
8350
8351 Type*
8352 Forward_declaration_type::real_type()
8353 {
8354   if (this->is_defined())
8355     return this->named_object()->type_value();
8356   else
8357     {
8358       this->warn();
8359       return Type::make_error_type();
8360     }
8361 }
8362
8363 const Type*
8364 Forward_declaration_type::real_type() const
8365 {
8366   if (this->is_defined())
8367     return this->named_object()->type_value();
8368   else
8369     {
8370       this->warn();
8371       return Type::make_error_type();
8372     }
8373 }
8374
8375 // Return whether the base type is defined.
8376
8377 bool
8378 Forward_declaration_type::is_defined() const
8379 {
8380   return this->named_object()->is_type();
8381 }
8382
8383 // Add a method.  This is used when methods are defined before the
8384 // type.
8385
8386 Named_object*
8387 Forward_declaration_type::add_method(const std::string& name,
8388                                      Function* function)
8389 {
8390   Named_object* no = this->named_object();
8391   if (no->is_unknown())
8392     no->declare_as_type();
8393   return no->type_declaration_value()->add_method(name, function);
8394 }
8395
8396 // Add a method declaration.  This is used when methods are declared
8397 // before the type.
8398
8399 Named_object*
8400 Forward_declaration_type::add_method_declaration(const std::string& name,
8401                                                  Function_type* type,
8402                                                  source_location location)
8403 {
8404   Named_object* no = this->named_object();
8405   if (no->is_unknown())
8406     no->declare_as_type();
8407   Type_declaration* td = no->type_declaration_value();
8408   return td->add_method_declaration(name, type, location);
8409 }
8410
8411 // Traversal.
8412
8413 int
8414 Forward_declaration_type::do_traverse(Traverse* traverse)
8415 {
8416   if (this->is_defined()
8417       && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
8418     return TRAVERSE_EXIT;
8419   return TRAVERSE_CONTINUE;
8420 }
8421
8422 // Get the backend representation for the type.
8423
8424 Btype*
8425 Forward_declaration_type::do_get_backend(Gogo* gogo)
8426 {
8427   if (this->is_defined())
8428     return Type::get_named_base_btype(gogo, this->real_type());
8429
8430   if (this->warned_)
8431     return gogo->backend()->error_type();
8432
8433   // We represent an undefined type as a struct with no fields.  That
8434   // should work fine for the backend, since the same case can arise
8435   // in C.
8436   std::vector<Backend::Btyped_identifier> fields;
8437   Btype* bt = gogo->backend()->struct_type(fields);
8438   return gogo->backend()->named_type(this->name(), bt,
8439                                      this->named_object()->location());
8440 }
8441
8442 // Build a type descriptor for a forwarded type.
8443
8444 Expression*
8445 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8446 {
8447   if (!this->is_defined())
8448     return Expression::make_nil(BUILTINS_LOCATION);
8449   else
8450     {
8451       Type* t = this->real_type();
8452       if (name != NULL)
8453         return this->named_type_descriptor(gogo, t, name);
8454       else
8455         return Expression::make_type_descriptor(t, BUILTINS_LOCATION);
8456     }
8457 }
8458
8459 // The reflection string.
8460
8461 void
8462 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
8463 {
8464   this->append_reflection(this->real_type(), gogo, ret);
8465 }
8466
8467 // The mangled name.
8468
8469 void
8470 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8471 {
8472   if (this->is_defined())
8473     this->append_mangled_name(this->real_type(), gogo, ret);
8474   else
8475     {
8476       const Named_object* no = this->named_object();
8477       std::string name;
8478       if (no->package() == NULL)
8479         name = gogo->package_name();
8480       else
8481         name = no->package()->name();
8482       name += '.';
8483       name += Gogo::unpack_hidden_name(no->name());
8484       char buf[20];
8485       snprintf(buf, sizeof buf, "N%u_",
8486                static_cast<unsigned int>(name.length()));
8487       ret->append(buf);
8488       ret->append(name);
8489     }
8490 }
8491
8492 // Export a forward declaration.  This can happen when a defined type
8493 // refers to a type which is only declared (and is presumably defined
8494 // in some other file in the same package).
8495
8496 void
8497 Forward_declaration_type::do_export(Export*) const
8498 {
8499   // If there is a base type, that should be exported instead of this.
8500   go_assert(!this->is_defined());
8501
8502   // We don't output anything.
8503 }
8504
8505 // Make a forward declaration.
8506
8507 Type*
8508 Type::make_forward_declaration(Named_object* named_object)
8509 {
8510   return new Forward_declaration_type(named_object);
8511 }
8512
8513 // Class Typed_identifier_list.
8514
8515 // Sort the entries by name.
8516
8517 struct Typed_identifier_list_sort
8518 {
8519  public:
8520   bool
8521   operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
8522   { return t1.name() < t2.name(); }
8523 };
8524
8525 void
8526 Typed_identifier_list::sort_by_name()
8527 {
8528   std::sort(this->entries_.begin(), this->entries_.end(),
8529             Typed_identifier_list_sort());
8530 }
8531
8532 // Traverse types.
8533
8534 int
8535 Typed_identifier_list::traverse(Traverse* traverse)
8536 {
8537   for (Typed_identifier_list::const_iterator p = this->begin();
8538        p != this->end();
8539        ++p)
8540     {
8541       if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
8542         return TRAVERSE_EXIT;
8543     }
8544   return TRAVERSE_CONTINUE;
8545 }
8546
8547 // Copy the list.
8548
8549 Typed_identifier_list*
8550 Typed_identifier_list::copy() const
8551 {
8552   Typed_identifier_list* ret = new Typed_identifier_list();
8553   for (Typed_identifier_list::const_iterator p = this->begin();
8554        p != this->end();
8555        ++p)
8556     ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
8557   return ret;
8558 }