OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [gcc/] [go/] [gofrontend/] [types.cc] - Blame information for rev 714

Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.