OSDN Git Service

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