OSDN Git Service

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