OSDN Git Service

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