OSDN Git Service

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