Use backend interface for interface types.
[official-gcc.git] / gcc / go / gofrontend / types.cc
bloba03ab1fbe11ecaf5f991ad4a68e06c01b347d1bc
1 // types.cc -- Go frontend types.
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.
7 #include "go-system.h"
9 #include <gmp.h>
11 #ifndef ENABLE_BUILD_WITH_CXX
12 extern "C"
14 #endif
16 #include "toplev.h"
17 #include "intl.h"
18 #include "tree.h"
19 #include "gimple.h"
20 #include "real.h"
21 #include "convert.h"
23 #ifndef ENABLE_BUILD_WITH_CXX
25 #endif
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"
37 // Class Type.
39 Type::Type(Type_classification classification)
40 : classification_(classification), tree_(NULL_TREE),
41 type_descriptor_decl_(NULL_TREE)
45 Type::~Type()
49 // Get the base type for a type--skip names and forward declarations.
51 Type*
52 Type::base()
54 switch (this->classification_)
56 case TYPE_NAMED:
57 return this->named_type()->named_base();
58 case TYPE_FORWARD:
59 return this->forward_declaration_type()->real_type()->base();
60 default:
61 return this;
65 const Type*
66 Type::base() const
68 switch (this->classification_)
70 case TYPE_NAMED:
71 return this->named_type()->named_base();
72 case TYPE_FORWARD:
73 return this->forward_declaration_type()->real_type()->base();
74 default:
75 return this;
79 // Skip defined forward declarations.
81 Type*
82 Type::forwarded()
84 Type* t = this;
85 Forward_declaration_type* ftype = t->forward_declaration_type();
86 while (ftype != NULL && ftype->is_defined())
88 t = ftype->real_type();
89 ftype = t->forward_declaration_type();
91 return t;
94 const Type*
95 Type::forwarded() const
97 const Type* t = this;
98 const Forward_declaration_type* ftype = t->forward_declaration_type();
99 while (ftype != NULL && ftype->is_defined())
101 t = ftype->real_type();
102 ftype = t->forward_declaration_type();
104 return t;
107 // If this is a named type, return it. Otherwise, return NULL.
109 Named_type*
110 Type::named_type()
112 return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
115 const Named_type*
116 Type::named_type() const
118 return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
121 // Return true if this type is not defined.
123 bool
124 Type::is_undefined() const
126 return this->forwarded()->forward_declaration_type() != NULL;
129 // Return true if this is a basic type: a type which is not composed
130 // of other types, and is not void.
132 bool
133 Type::is_basic_type() const
135 switch (this->classification_)
137 case TYPE_INTEGER:
138 case TYPE_FLOAT:
139 case TYPE_COMPLEX:
140 case TYPE_BOOLEAN:
141 case TYPE_STRING:
142 case TYPE_NIL:
143 return true;
145 case TYPE_ERROR:
146 case TYPE_VOID:
147 case TYPE_FUNCTION:
148 case TYPE_POINTER:
149 case TYPE_STRUCT:
150 case TYPE_ARRAY:
151 case TYPE_MAP:
152 case TYPE_CHANNEL:
153 case TYPE_INTERFACE:
154 return false;
156 case TYPE_NAMED:
157 case TYPE_FORWARD:
158 return this->base()->is_basic_type();
160 default:
161 go_unreachable();
165 // Return true if this is an abstract type.
167 bool
168 Type::is_abstract() const
170 switch (this->classification())
172 case TYPE_INTEGER:
173 return this->integer_type()->is_abstract();
174 case TYPE_FLOAT:
175 return this->float_type()->is_abstract();
176 case TYPE_COMPLEX:
177 return this->complex_type()->is_abstract();
178 case TYPE_STRING:
179 return this->is_abstract_string_type();
180 case TYPE_BOOLEAN:
181 return this->is_abstract_boolean_type();
182 default:
183 return false;
187 // Return a non-abstract version of an abstract type.
189 Type*
190 Type::make_non_abstract_type()
192 go_assert(this->is_abstract());
193 switch (this->classification())
195 case TYPE_INTEGER:
196 return Type::lookup_integer_type("int");
197 case TYPE_FLOAT:
198 return Type::lookup_float_type("float64");
199 case TYPE_COMPLEX:
200 return Type::lookup_complex_type("complex128");
201 case TYPE_STRING:
202 return Type::lookup_string_type();
203 case TYPE_BOOLEAN:
204 return Type::lookup_bool_type();
205 default:
206 go_unreachable();
210 // Return true if this is an error type. Don't give an error if we
211 // try to dereference an undefined forwarding type, as this is called
212 // in the parser when the type may legitimately be undefined.
214 bool
215 Type::is_error_type() const
217 const Type* t = this->forwarded();
218 // Note that we return false for an undefined forward type.
219 switch (t->classification_)
221 case TYPE_ERROR:
222 return true;
223 case TYPE_NAMED:
224 return t->named_type()->is_named_error_type();
225 default:
226 return false;
230 // If this is a pointer type, return the type to which it points.
231 // Otherwise, return NULL.
233 Type*
234 Type::points_to() const
236 const Pointer_type* ptype = this->convert<const Pointer_type,
237 TYPE_POINTER>();
238 return ptype == NULL ? NULL : ptype->points_to();
241 // Return whether this is an open array type.
243 bool
244 Type::is_open_array_type() const
246 return this->array_type() != NULL && this->array_type()->length() == NULL;
249 // Return whether this is the predeclared constant nil being used as a
250 // type.
252 bool
253 Type::is_nil_constant_as_type() const
255 const Type* t = this->forwarded();
256 if (t->forward_declaration_type() != NULL)
258 const Named_object* no = t->forward_declaration_type()->named_object();
259 if (no->is_unknown())
260 no = no->unknown_value()->real_named_object();
261 if (no != NULL
262 && no->is_const()
263 && no->const_value()->expr()->is_nil_expression())
264 return true;
266 return false;
269 // Traverse a type.
272 Type::traverse(Type* type, Traverse* traverse)
274 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
275 || (traverse->traverse_mask()
276 & Traverse::traverse_expressions) != 0);
277 if (traverse->remember_type(type))
279 // We have already traversed this type.
280 return TRAVERSE_CONTINUE;
282 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
284 int t = traverse->type(type);
285 if (t == TRAVERSE_EXIT)
286 return TRAVERSE_EXIT;
287 else if (t == TRAVERSE_SKIP_COMPONENTS)
288 return TRAVERSE_CONTINUE;
290 // An array type has an expression which we need to traverse if
291 // traverse_expressions is set.
292 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
293 return TRAVERSE_EXIT;
294 return TRAVERSE_CONTINUE;
297 // Default implementation for do_traverse for child class.
300 Type::do_traverse(Traverse*)
302 return TRAVERSE_CONTINUE;
305 // Return whether two types are identical. If ERRORS_ARE_IDENTICAL,
306 // then return true for all erroneous types; this is used to avoid
307 // cascading errors. If REASON is not NULL, optionally set *REASON to
308 // the reason the types are not identical.
310 bool
311 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
312 std::string* reason)
314 if (t1 == NULL || t2 == NULL)
316 // Something is wrong.
317 return errors_are_identical ? true : t1 == t2;
320 // Skip defined forward declarations.
321 t1 = t1->forwarded();
322 t2 = t2->forwarded();
324 if (t1 == t2)
325 return true;
327 // An undefined forward declaration is an error.
328 if (t1->forward_declaration_type() != NULL
329 || t2->forward_declaration_type() != NULL)
330 return errors_are_identical;
332 // Avoid cascading errors with error types.
333 if (t1->is_error_type() || t2->is_error_type())
335 if (errors_are_identical)
336 return true;
337 return t1->is_error_type() && t2->is_error_type();
340 // Get a good reason for the sink type. Note that the sink type on
341 // the left hand side of an assignment is handled in are_assignable.
342 if (t1->is_sink_type() || t2->is_sink_type())
344 if (reason != NULL)
345 *reason = "invalid use of _";
346 return false;
349 // A named type is only identical to itself.
350 if (t1->named_type() != NULL || t2->named_type() != NULL)
351 return false;
353 // Check type shapes.
354 if (t1->classification() != t2->classification())
355 return false;
357 switch (t1->classification())
359 case TYPE_VOID:
360 case TYPE_BOOLEAN:
361 case TYPE_STRING:
362 case TYPE_NIL:
363 // These types are always identical.
364 return true;
366 case TYPE_INTEGER:
367 return t1->integer_type()->is_identical(t2->integer_type());
369 case TYPE_FLOAT:
370 return t1->float_type()->is_identical(t2->float_type());
372 case TYPE_COMPLEX:
373 return t1->complex_type()->is_identical(t2->complex_type());
375 case TYPE_FUNCTION:
376 return t1->function_type()->is_identical(t2->function_type(),
377 false,
378 errors_are_identical,
379 reason);
381 case TYPE_POINTER:
382 return Type::are_identical(t1->points_to(), t2->points_to(),
383 errors_are_identical, reason);
385 case TYPE_STRUCT:
386 return t1->struct_type()->is_identical(t2->struct_type(),
387 errors_are_identical);
389 case TYPE_ARRAY:
390 return t1->array_type()->is_identical(t2->array_type(),
391 errors_are_identical);
393 case TYPE_MAP:
394 return t1->map_type()->is_identical(t2->map_type(),
395 errors_are_identical);
397 case TYPE_CHANNEL:
398 return t1->channel_type()->is_identical(t2->channel_type(),
399 errors_are_identical);
401 case TYPE_INTERFACE:
402 return t1->interface_type()->is_identical(t2->interface_type(),
403 errors_are_identical);
405 case TYPE_CALL_MULTIPLE_RESULT:
406 if (reason != NULL)
407 *reason = "invalid use of multiple value function call";
408 return false;
410 default:
411 go_unreachable();
415 // Return true if it's OK to have a binary operation with types LHS
416 // and RHS. This is not used for shifts or comparisons.
418 bool
419 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
421 if (Type::are_identical(lhs, rhs, true, NULL))
422 return true;
424 // A constant of abstract bool type may be mixed with any bool type.
425 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
426 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
427 return true;
429 // A constant of abstract string type may be mixed with any string
430 // type.
431 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
432 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
433 return true;
435 lhs = lhs->base();
436 rhs = rhs->base();
438 // A constant of abstract integer, float, or complex type may be
439 // mixed with an integer, float, or complex type.
440 if ((rhs->is_abstract()
441 && (rhs->integer_type() != NULL
442 || rhs->float_type() != NULL
443 || rhs->complex_type() != NULL)
444 && (lhs->integer_type() != NULL
445 || lhs->float_type() != NULL
446 || lhs->complex_type() != NULL))
447 || (lhs->is_abstract()
448 && (lhs->integer_type() != NULL
449 || lhs->float_type() != NULL
450 || lhs->complex_type() != NULL)
451 && (rhs->integer_type() != NULL
452 || rhs->float_type() != NULL
453 || rhs->complex_type() != NULL)))
454 return true;
456 // The nil type may be compared to a pointer, an interface type, a
457 // slice type, a channel type, a map type, or a function type.
458 if (lhs->is_nil_type()
459 && (rhs->points_to() != NULL
460 || rhs->interface_type() != NULL
461 || rhs->is_open_array_type()
462 || rhs->map_type() != NULL
463 || rhs->channel_type() != NULL
464 || rhs->function_type() != NULL))
465 return true;
466 if (rhs->is_nil_type()
467 && (lhs->points_to() != NULL
468 || lhs->interface_type() != NULL
469 || lhs->is_open_array_type()
470 || lhs->map_type() != NULL
471 || lhs->channel_type() != NULL
472 || lhs->function_type() != NULL))
473 return true;
475 return false;
478 // Return true if a value with type RHS may be assigned to a variable
479 // with type LHS. If CHECK_HIDDEN_FIELDS is true, check whether any
480 // hidden fields are modified. If REASON is not NULL, set *REASON to
481 // the reason the types are not assignable.
483 bool
484 Type::are_assignable_check_hidden(const Type* lhs, const Type* rhs,
485 bool check_hidden_fields,
486 std::string* reason)
488 // Do some checks first. Make sure the types are defined.
489 if (rhs != NULL
490 && rhs->forwarded()->forward_declaration_type() == NULL
491 && rhs->is_void_type())
493 if (reason != NULL)
494 *reason = "non-value used as value";
495 return false;
498 if (lhs != NULL && lhs->forwarded()->forward_declaration_type() == NULL)
500 // Any value may be assigned to the blank identifier.
501 if (lhs->is_sink_type())
502 return true;
504 // All fields of a struct must be exported, or the assignment
505 // must be in the same package.
506 if (check_hidden_fields
507 && rhs != NULL
508 && rhs->forwarded()->forward_declaration_type() == NULL)
510 if (lhs->has_hidden_fields(NULL, reason)
511 || rhs->has_hidden_fields(NULL, reason))
512 return false;
516 // Identical types are assignable.
517 if (Type::are_identical(lhs, rhs, true, reason))
518 return true;
520 // The types are assignable if they have identical underlying types
521 // and either LHS or RHS is not a named type.
522 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
523 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
524 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
525 return true;
527 // The types are assignable if LHS is an interface type and RHS
528 // implements the required methods.
529 const Interface_type* lhs_interface_type = lhs->interface_type();
530 if (lhs_interface_type != NULL)
532 if (lhs_interface_type->implements_interface(rhs, reason))
533 return true;
534 const Interface_type* rhs_interface_type = rhs->interface_type();
535 if (rhs_interface_type != NULL
536 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
537 reason))
538 return true;
541 // The type are assignable if RHS is a bidirectional channel type,
542 // LHS is a channel type, they have identical element types, and
543 // either LHS or RHS is not a named type.
544 if (lhs->channel_type() != NULL
545 && rhs->channel_type() != NULL
546 && rhs->channel_type()->may_send()
547 && rhs->channel_type()->may_receive()
548 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
549 && Type::are_identical(lhs->channel_type()->element_type(),
550 rhs->channel_type()->element_type(),
551 true,
552 reason))
553 return true;
555 // The nil type may be assigned to a pointer, function, slice, map,
556 // channel, or interface type.
557 if (rhs->is_nil_type()
558 && (lhs->points_to() != NULL
559 || lhs->function_type() != NULL
560 || lhs->is_open_array_type()
561 || lhs->map_type() != NULL
562 || lhs->channel_type() != NULL
563 || lhs->interface_type() != NULL))
564 return true;
566 // An untyped numeric constant may be assigned to a numeric type if
567 // it is representable in that type.
568 if ((rhs->is_abstract()
569 && (rhs->integer_type() != NULL
570 || rhs->float_type() != NULL
571 || rhs->complex_type() != NULL))
572 && (lhs->integer_type() != NULL
573 || lhs->float_type() != NULL
574 || lhs->complex_type() != NULL))
575 return true;
577 // Give some better error messages.
578 if (reason != NULL && reason->empty())
580 if (rhs->interface_type() != NULL)
581 reason->assign(_("need explicit conversion"));
582 else if (rhs->is_call_multiple_result_type())
583 reason->assign(_("multiple value function call in "
584 "single value context"));
585 else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
587 size_t len = (lhs->named_type()->name().length()
588 + rhs->named_type()->name().length()
589 + 100);
590 char* buf = new char[len];
591 snprintf(buf, len, _("cannot use type %s as type %s"),
592 rhs->named_type()->message_name().c_str(),
593 lhs->named_type()->message_name().c_str());
594 reason->assign(buf);
595 delete[] buf;
599 return false;
602 // Return true if a value with type RHS may be assigned to a variable
603 // with type LHS. If REASON is not NULL, set *REASON to the reason
604 // the types are not assignable.
606 bool
607 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
609 return Type::are_assignable_check_hidden(lhs, rhs, true, reason);
612 // Like are_assignable but don't check for hidden fields.
614 bool
615 Type::are_assignable_hidden_ok(const Type* lhs, const Type* rhs,
616 std::string* reason)
618 return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
621 // Return true if a value with type RHS may be converted to type LHS.
622 // If REASON is not NULL, set *REASON to the reason the types are not
623 // convertible.
625 bool
626 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
628 // The types are convertible if they are assignable.
629 if (Type::are_assignable(lhs, rhs, reason))
630 return true;
632 // The types are convertible if they have identical underlying
633 // types.
634 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
635 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
636 return true;
638 // The types are convertible if they are both unnamed pointer types
639 // and their pointer base types have identical underlying types.
640 if (lhs->named_type() == NULL
641 && rhs->named_type() == NULL
642 && lhs->points_to() != NULL
643 && rhs->points_to() != NULL
644 && (lhs->points_to()->named_type() != NULL
645 || rhs->points_to()->named_type() != NULL)
646 && Type::are_identical(lhs->points_to()->base(),
647 rhs->points_to()->base(),
648 true,
649 reason))
650 return true;
652 // Integer and floating point types are convertible to each other.
653 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
654 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
655 return true;
657 // Complex types are convertible to each other.
658 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
659 return true;
661 // An integer, or []byte, or []int, may be converted to a string.
662 if (lhs->is_string_type())
664 if (rhs->integer_type() != NULL)
665 return true;
666 if (rhs->is_open_array_type() && rhs->named_type() == NULL)
668 const Type* e = rhs->array_type()->element_type()->forwarded();
669 if (e->integer_type() != NULL
670 && (e == Type::lookup_integer_type("uint8")
671 || e == Type::lookup_integer_type("int")))
672 return true;
676 // A string may be converted to []byte or []int.
677 if (rhs->is_string_type()
678 && lhs->is_open_array_type()
679 && lhs->named_type() == NULL)
681 const Type* e = lhs->array_type()->element_type()->forwarded();
682 if (e->integer_type() != NULL
683 && (e == Type::lookup_integer_type("uint8")
684 || e == Type::lookup_integer_type("int")))
685 return true;
688 // An unsafe.Pointer type may be converted to any pointer type or to
689 // uintptr, and vice-versa.
690 if (lhs->is_unsafe_pointer_type()
691 && (rhs->points_to() != NULL
692 || (rhs->integer_type() != NULL
693 && rhs->forwarded() == Type::lookup_integer_type("uintptr"))))
694 return true;
695 if (rhs->is_unsafe_pointer_type()
696 && (lhs->points_to() != NULL
697 || (lhs->integer_type() != NULL
698 && lhs->forwarded() == Type::lookup_integer_type("uintptr"))))
699 return true;
701 // Give a better error message.
702 if (reason != NULL)
704 if (reason->empty())
705 *reason = "invalid type conversion";
706 else
708 std::string s = "invalid type conversion (";
709 s += *reason;
710 s += ')';
711 *reason = s;
715 return false;
718 // Return whether this type has any hidden fields. This is only a
719 // possibility for a few types.
721 bool
722 Type::has_hidden_fields(const Named_type* within, std::string* reason) const
724 switch (this->forwarded()->classification_)
726 case TYPE_NAMED:
727 return this->named_type()->named_type_has_hidden_fields(reason);
728 case TYPE_STRUCT:
729 return this->struct_type()->struct_has_hidden_fields(within, reason);
730 case TYPE_ARRAY:
731 return this->array_type()->array_has_hidden_fields(within, reason);
732 default:
733 return false;
737 // Return a hash code for the type to be used for method lookup.
739 unsigned int
740 Type::hash_for_method(Gogo* gogo) const
742 unsigned int ret = 0;
743 if (this->classification_ != TYPE_FORWARD)
744 ret += this->classification_;
745 return ret + this->do_hash_for_method(gogo);
748 // Default implementation of do_hash_for_method. This is appropriate
749 // for types with no subfields.
751 unsigned int
752 Type::do_hash_for_method(Gogo*) const
754 return 0;
757 // Return a hash code for a string, given a starting hash.
759 unsigned int
760 Type::hash_string(const std::string& s, unsigned int h)
762 const char* p = s.data();
763 size_t len = s.length();
764 for (; len > 0; --len)
766 h ^= *p++;
767 h*= 16777619;
769 return h;
772 // Default check for the expression passed to make. Any type which
773 // may be used with make implements its own version of this.
775 bool
776 Type::do_check_make_expression(Expression_list*, source_location)
778 go_unreachable();
781 // Return whether an expression has an integer value. Report an error
782 // if not. This is used when handling calls to the predeclared make
783 // function.
785 bool
786 Type::check_int_value(Expression* e, const char* errmsg,
787 source_location location)
789 if (e->type()->integer_type() != NULL)
790 return true;
792 // Check for a floating point constant with integer value.
793 mpfr_t fval;
794 mpfr_init(fval);
796 Type* dummy;
797 if (e->float_constant_value(fval, &dummy) && mpfr_integer_p(fval))
799 mpz_t ival;
800 mpz_init(ival);
802 bool ok = false;
804 mpfr_clear_overflow();
805 mpfr_clear_erangeflag();
806 mpfr_get_z(ival, fval, GMP_RNDN);
807 if (!mpfr_overflow_p()
808 && !mpfr_erangeflag_p()
809 && mpz_sgn(ival) >= 0)
811 Named_type* ntype = Type::lookup_integer_type("int");
812 Integer_type* inttype = ntype->integer_type();
813 mpz_t max;
814 mpz_init_set_ui(max, 1);
815 mpz_mul_2exp(max, max, inttype->bits() - 1);
816 ok = mpz_cmp(ival, max) < 0;
817 mpz_clear(max);
819 mpz_clear(ival);
821 if (ok)
823 mpfr_clear(fval);
824 return true;
828 mpfr_clear(fval);
830 error_at(location, "%s", errmsg);
831 return false;
834 // A hash table mapping unnamed types to trees.
836 Type::Type_trees Type::type_trees;
838 // Return a tree representing this type.
840 tree
841 Type::get_tree(Gogo* gogo)
843 if (this->tree_ != NULL)
844 return this->tree_;
846 if (this->forward_declaration_type() != NULL
847 || this->named_type() != NULL)
848 return this->get_tree_without_hash(gogo);
850 if (this->is_error_type())
851 return error_mark_node;
853 // To avoid confusing the backend, translate all identical Go types
854 // to the same backend type. We use a hash table to do that. There
855 // is no need to use the hash table for named types, as named types
856 // are only identical to themselves.
858 std::pair<Type*, tree> val(this, NULL);
859 std::pair<Type_trees::iterator, bool> ins =
860 Type::type_trees.insert(val);
861 if (!ins.second && ins.first->second != NULL_TREE)
863 if (gogo != NULL && gogo->named_types_are_converted())
864 this->tree_ = ins.first->second;
865 return ins.first->second;
868 tree t = this->get_tree_without_hash(gogo);
870 if (ins.first->second == NULL_TREE)
871 ins.first->second = t;
872 else
874 // We have already created a tree for this type. This can
875 // happen when an unnamed type is defined using a named type
876 // which in turns uses an identical unnamed type. Use the tree
877 // we created earlier and ignore the one we just built.
878 t = ins.first->second;
879 if (gogo == NULL || !gogo->named_types_are_converted())
880 return t;
881 this->tree_ = t;
884 return t;
887 // Return a tree for a type without looking in the hash table for
888 // identical types. This is used for named types, since there is no
889 // point to looking in the hash table for them.
891 tree
892 Type::get_tree_without_hash(Gogo* gogo)
894 if (this->tree_ == NULL_TREE)
896 tree t = this->do_get_tree(gogo);
898 // For a recursive function or pointer type, we will temporarily
899 // return a circular pointer type during the recursion. We
900 // don't want to record that for a forwarding type, as it may
901 // confuse us later.
902 if (this->forward_declaration_type() != NULL
903 && gogo->backend()->is_circular_pointer_type(tree_to_type(t)))
904 return t;
906 if (gogo == NULL || !gogo->named_types_are_converted())
907 return t;
909 this->tree_ = t;
910 go_preserve_from_gc(t);
913 return this->tree_;
916 // Return the backend representation for a type without looking in the
917 // hash table for identical types. This is used for named types,
918 // since a named type is never identical to any other type.
920 Btype*
921 Type::get_btype_without_hash(Gogo* gogo)
923 return tree_to_type(this->get_tree_without_hash(gogo));
926 // Return a tree representing a zero initialization for this type.
928 tree
929 Type::get_init_tree(Gogo* gogo, bool is_clear)
931 tree type_tree = this->get_tree(gogo);
932 if (type_tree == error_mark_node)
933 return error_mark_node;
934 return this->do_get_init_tree(gogo, type_tree, is_clear);
937 // Any type which supports the builtin make function must implement
938 // this.
940 tree
941 Type::do_make_expression_tree(Translate_context*, Expression_list*,
942 source_location)
944 go_unreachable();
947 // Return a pointer to the type descriptor for this type.
949 tree
950 Type::type_descriptor_pointer(Gogo* gogo)
952 Type* t = this->forwarded();
953 if (t->type_descriptor_decl_ == NULL_TREE)
955 Expression* e = t->do_type_descriptor(gogo, NULL);
956 gogo->build_type_descriptor_decl(t, e, &t->type_descriptor_decl_);
957 go_assert(t->type_descriptor_decl_ != NULL_TREE
958 && (t->type_descriptor_decl_ == error_mark_node
959 || DECL_P(t->type_descriptor_decl_)));
961 if (t->type_descriptor_decl_ == error_mark_node)
962 return error_mark_node;
963 return build_fold_addr_expr(t->type_descriptor_decl_);
966 // Return a composite literal for a type descriptor.
968 Expression*
969 Type::type_descriptor(Gogo* gogo, Type* type)
971 return type->do_type_descriptor(gogo, NULL);
974 // Return a composite literal for a type descriptor with a name.
976 Expression*
977 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
979 go_assert(name != NULL && type->named_type() != name);
980 return type->do_type_descriptor(gogo, name);
983 // Make a builtin struct type from a list of fields. The fields are
984 // pairs of a name and a type.
986 Struct_type*
987 Type::make_builtin_struct_type(int nfields, ...)
989 va_list ap;
990 va_start(ap, nfields);
992 source_location bloc = BUILTINS_LOCATION;
993 Struct_field_list* sfl = new Struct_field_list();
994 for (int i = 0; i < nfields; i++)
996 const char* field_name = va_arg(ap, const char *);
997 Type* type = va_arg(ap, Type*);
998 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1001 va_end(ap);
1003 return Type::make_struct_type(sfl, bloc);
1006 // A list of builtin named types.
1008 std::vector<Named_type*> Type::named_builtin_types;
1010 // Make a builtin named type.
1012 Named_type*
1013 Type::make_builtin_named_type(const char* name, Type* type)
1015 source_location bloc = BUILTINS_LOCATION;
1016 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1017 Named_type* ret = no->type_value();
1018 Type::named_builtin_types.push_back(ret);
1019 return ret;
1022 // Convert the named builtin types.
1024 void
1025 Type::convert_builtin_named_types(Gogo* gogo)
1027 for (std::vector<Named_type*>::const_iterator p =
1028 Type::named_builtin_types.begin();
1029 p != Type::named_builtin_types.end();
1030 ++p)
1032 bool r = (*p)->verify();
1033 go_assert(r);
1034 (*p)->convert(gogo);
1038 // Return the type of a type descriptor. We should really tie this to
1039 // runtime.Type rather than copying it. This must match commonType in
1040 // libgo/go/runtime/type.go.
1042 Type*
1043 Type::make_type_descriptor_type()
1045 static Type* ret;
1046 if (ret == NULL)
1048 source_location bloc = BUILTINS_LOCATION;
1050 Type* uint8_type = Type::lookup_integer_type("uint8");
1051 Type* uint32_type = Type::lookup_integer_type("uint32");
1052 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1053 Type* string_type = Type::lookup_string_type();
1054 Type* pointer_string_type = Type::make_pointer_type(string_type);
1056 // This is an unnamed version of unsafe.Pointer. Perhaps we
1057 // should use the named version instead, although that would
1058 // require us to create the unsafe package if it has not been
1059 // imported. It probably doesn't matter.
1060 Type* void_type = Type::make_void_type();
1061 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1063 // Forward declaration for the type descriptor type.
1064 Named_object* named_type_descriptor_type =
1065 Named_object::make_type_declaration("commonType", NULL, bloc);
1066 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1067 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1069 // The type of a method on a concrete type.
1070 Struct_type* method_type =
1071 Type::make_builtin_struct_type(5,
1072 "name", pointer_string_type,
1073 "pkgPath", pointer_string_type,
1074 "mtyp", pointer_type_descriptor_type,
1075 "typ", pointer_type_descriptor_type,
1076 "tfn", unsafe_pointer_type);
1077 Named_type* named_method_type =
1078 Type::make_builtin_named_type("method", method_type);
1080 // Information for types with a name or methods.
1081 Type* slice_named_method_type =
1082 Type::make_array_type(named_method_type, NULL);
1083 Struct_type* uncommon_type =
1084 Type::make_builtin_struct_type(3,
1085 "name", pointer_string_type,
1086 "pkgPath", pointer_string_type,
1087 "methods", slice_named_method_type);
1088 Named_type* named_uncommon_type =
1089 Type::make_builtin_named_type("uncommonType", uncommon_type);
1091 Type* pointer_uncommon_type =
1092 Type::make_pointer_type(named_uncommon_type);
1094 // The type descriptor type.
1096 Typed_identifier_list* params = new Typed_identifier_list();
1097 params->push_back(Typed_identifier("", unsafe_pointer_type, bloc));
1098 params->push_back(Typed_identifier("", uintptr_type, bloc));
1100 Typed_identifier_list* results = new Typed_identifier_list();
1101 results->push_back(Typed_identifier("", uintptr_type, bloc));
1103 Type* hashfn_type = Type::make_function_type(NULL, params, results, bloc);
1105 params = new Typed_identifier_list();
1106 params->push_back(Typed_identifier("", unsafe_pointer_type, bloc));
1107 params->push_back(Typed_identifier("", unsafe_pointer_type, bloc));
1108 params->push_back(Typed_identifier("", uintptr_type, bloc));
1110 results = new Typed_identifier_list();
1111 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1113 Type* equalfn_type = Type::make_function_type(NULL, params, results,
1114 bloc);
1116 Struct_type* type_descriptor_type =
1117 Type::make_builtin_struct_type(10,
1118 "Kind", uint8_type,
1119 "align", uint8_type,
1120 "fieldAlign", uint8_type,
1121 "size", uintptr_type,
1122 "hash", uint32_type,
1123 "hashfn", hashfn_type,
1124 "equalfn", equalfn_type,
1125 "string", pointer_string_type,
1126 "", pointer_uncommon_type,
1127 "ptrToThis",
1128 pointer_type_descriptor_type);
1130 Named_type* named = Type::make_builtin_named_type("commonType",
1131 type_descriptor_type);
1133 named_type_descriptor_type->set_type_value(named);
1135 ret = named;
1138 return ret;
1141 // Make the type of a pointer to a type descriptor as represented in
1142 // Go.
1144 Type*
1145 Type::make_type_descriptor_ptr_type()
1147 static Type* ret;
1148 if (ret == NULL)
1149 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1150 return ret;
1153 // Return the names of runtime functions which compute a hash code for
1154 // this type and which compare whether two values of this type are
1155 // equal.
1157 void
1158 Type::type_functions(const char** hash_fn, const char** equal_fn) const
1160 switch (this->base()->classification())
1162 case Type::TYPE_ERROR:
1163 case Type::TYPE_VOID:
1164 case Type::TYPE_NIL:
1165 // These types can not be hashed or compared.
1166 *hash_fn = "__go_type_hash_error";
1167 *equal_fn = "__go_type_equal_error";
1168 break;
1170 case Type::TYPE_BOOLEAN:
1171 case Type::TYPE_INTEGER:
1172 case Type::TYPE_FLOAT:
1173 case Type::TYPE_COMPLEX:
1174 case Type::TYPE_POINTER:
1175 case Type::TYPE_FUNCTION:
1176 case Type::TYPE_MAP:
1177 case Type::TYPE_CHANNEL:
1178 *hash_fn = "__go_type_hash_identity";
1179 *equal_fn = "__go_type_equal_identity";
1180 break;
1182 case Type::TYPE_STRING:
1183 *hash_fn = "__go_type_hash_string";
1184 *equal_fn = "__go_type_equal_string";
1185 break;
1187 case Type::TYPE_STRUCT:
1188 case Type::TYPE_ARRAY:
1189 // These types can not be hashed or compared.
1190 *hash_fn = "__go_type_hash_error";
1191 *equal_fn = "__go_type_equal_error";
1192 break;
1194 case Type::TYPE_INTERFACE:
1195 if (this->interface_type()->is_empty())
1197 *hash_fn = "__go_type_hash_empty_interface";
1198 *equal_fn = "__go_type_equal_empty_interface";
1200 else
1202 *hash_fn = "__go_type_hash_interface";
1203 *equal_fn = "__go_type_equal_interface";
1205 break;
1207 case Type::TYPE_NAMED:
1208 case Type::TYPE_FORWARD:
1209 go_unreachable();
1211 default:
1212 go_unreachable();
1216 // Return a composite literal for the type descriptor for a plain type
1217 // of kind RUNTIME_TYPE_KIND named NAME.
1219 Expression*
1220 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
1221 Named_type* name, const Methods* methods,
1222 bool only_value_methods)
1224 source_location bloc = BUILTINS_LOCATION;
1226 Type* td_type = Type::make_type_descriptor_type();
1227 const Struct_field_list* fields = td_type->struct_type()->fields();
1229 Expression_list* vals = new Expression_list();
1230 vals->reserve(9);
1232 Struct_field_list::const_iterator p = fields->begin();
1233 go_assert(p->field_name() == "Kind");
1234 mpz_t iv;
1235 mpz_init_set_ui(iv, runtime_type_kind);
1236 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1238 ++p;
1239 go_assert(p->field_name() == "align");
1240 Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT;
1241 vals->push_back(Expression::make_type_info(this, type_info));
1243 ++p;
1244 go_assert(p->field_name() == "fieldAlign");
1245 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
1246 vals->push_back(Expression::make_type_info(this, type_info));
1248 ++p;
1249 go_assert(p->field_name() == "size");
1250 type_info = Expression::TYPE_INFO_SIZE;
1251 vals->push_back(Expression::make_type_info(this, type_info));
1253 ++p;
1254 go_assert(p->field_name() == "hash");
1255 mpz_set_ui(iv, this->hash_for_method(gogo));
1256 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1258 const char* hash_fn;
1259 const char* equal_fn;
1260 this->type_functions(&hash_fn, &equal_fn);
1262 ++p;
1263 go_assert(p->field_name() == "hashfn");
1264 Function_type* fntype = p->type()->function_type();
1265 Named_object* no = Named_object::make_function_declaration(hash_fn, NULL,
1266 fntype,
1267 bloc);
1268 no->func_declaration_value()->set_asm_name(hash_fn);
1269 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
1271 ++p;
1272 go_assert(p->field_name() == "equalfn");
1273 fntype = p->type()->function_type();
1274 no = Named_object::make_function_declaration(equal_fn, NULL, fntype, bloc);
1275 no->func_declaration_value()->set_asm_name(equal_fn);
1276 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
1278 ++p;
1279 go_assert(p->field_name() == "string");
1280 Expression* s = Expression::make_string((name != NULL
1281 ? name->reflection(gogo)
1282 : this->reflection(gogo)),
1283 bloc);
1284 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1286 ++p;
1287 go_assert(p->field_name() == "uncommonType");
1288 if (name == NULL && methods == NULL)
1289 vals->push_back(Expression::make_nil(bloc));
1290 else
1292 if (methods == NULL)
1293 methods = name->methods();
1294 vals->push_back(this->uncommon_type_constructor(gogo,
1295 p->type()->deref(),
1296 name, methods,
1297 only_value_methods));
1300 ++p;
1301 go_assert(p->field_name() == "ptrToThis");
1302 if (name == NULL)
1303 vals->push_back(Expression::make_nil(bloc));
1304 else
1306 Type* pt = Type::make_pointer_type(name);
1307 vals->push_back(Expression::make_type_descriptor(pt, bloc));
1310 ++p;
1311 go_assert(p == fields->end());
1313 mpz_clear(iv);
1315 return Expression::make_struct_composite_literal(td_type, vals, bloc);
1318 // Return a composite literal for the uncommon type information for
1319 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
1320 // struct. If name is not NULL, it is the name of the type. If
1321 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
1322 // is true if only value methods should be included. At least one of
1323 // NAME and METHODS must not be NULL.
1325 Expression*
1326 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
1327 Named_type* name, const Methods* methods,
1328 bool only_value_methods) const
1330 source_location bloc = BUILTINS_LOCATION;
1332 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
1334 Expression_list* vals = new Expression_list();
1335 vals->reserve(3);
1337 Struct_field_list::const_iterator p = fields->begin();
1338 go_assert(p->field_name() == "name");
1340 ++p;
1341 go_assert(p->field_name() == "pkgPath");
1343 if (name == NULL)
1345 vals->push_back(Expression::make_nil(bloc));
1346 vals->push_back(Expression::make_nil(bloc));
1348 else
1350 Named_object* no = name->named_object();
1351 std::string n = Gogo::unpack_hidden_name(no->name());
1352 Expression* s = Expression::make_string(n, bloc);
1353 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1355 if (name->is_builtin())
1356 vals->push_back(Expression::make_nil(bloc));
1357 else
1359 const Package* package = no->package();
1360 const std::string& unique_prefix(package == NULL
1361 ? gogo->unique_prefix()
1362 : package->unique_prefix());
1363 const std::string& package_name(package == NULL
1364 ? gogo->package_name()
1365 : package->name());
1366 n.assign(unique_prefix);
1367 n.append(1, '.');
1368 n.append(package_name);
1369 if (name->in_function() != NULL)
1371 n.append(1, '.');
1372 n.append(Gogo::unpack_hidden_name(name->in_function()->name()));
1374 s = Expression::make_string(n, bloc);
1375 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1379 ++p;
1380 go_assert(p->field_name() == "methods");
1381 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
1382 only_value_methods));
1384 ++p;
1385 go_assert(p == fields->end());
1387 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
1388 vals, bloc);
1389 return Expression::make_unary(OPERATOR_AND, r, bloc);
1392 // Sort methods by name.
1394 class Sort_methods
1396 public:
1397 bool
1398 operator()(const std::pair<std::string, const Method*>& m1,
1399 const std::pair<std::string, const Method*>& m2) const
1400 { return m1.first < m2.first; }
1403 // Return a composite literal for the type method table for this type.
1404 // METHODS_TYPE is the type of the table, and is a slice type.
1405 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
1406 // then only value methods are used.
1408 Expression*
1409 Type::methods_constructor(Gogo* gogo, Type* methods_type,
1410 const Methods* methods,
1411 bool only_value_methods) const
1413 source_location bloc = BUILTINS_LOCATION;
1415 std::vector<std::pair<std::string, const Method*> > smethods;
1416 if (methods != NULL)
1418 smethods.reserve(methods->count());
1419 for (Methods::const_iterator p = methods->begin();
1420 p != methods->end();
1421 ++p)
1423 if (p->second->is_ambiguous())
1424 continue;
1425 if (only_value_methods && !p->second->is_value_method())
1426 continue;
1427 smethods.push_back(std::make_pair(p->first, p->second));
1431 if (smethods.empty())
1432 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
1434 std::sort(smethods.begin(), smethods.end(), Sort_methods());
1436 Type* method_type = methods_type->array_type()->element_type();
1438 Expression_list* vals = new Expression_list();
1439 vals->reserve(smethods.size());
1440 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
1441 = smethods.begin();
1442 p != smethods.end();
1443 ++p)
1444 vals->push_back(this->method_constructor(gogo, method_type, p->first,
1445 p->second));
1447 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
1450 // Return a composite literal for a single method. METHOD_TYPE is the
1451 // type of the entry. METHOD_NAME is the name of the method and M is
1452 // the method information.
1454 Expression*
1455 Type::method_constructor(Gogo*, Type* method_type,
1456 const std::string& method_name,
1457 const Method* m) const
1459 source_location bloc = BUILTINS_LOCATION;
1461 const Struct_field_list* fields = method_type->struct_type()->fields();
1463 Expression_list* vals = new Expression_list();
1464 vals->reserve(5);
1466 Struct_field_list::const_iterator p = fields->begin();
1467 go_assert(p->field_name() == "name");
1468 const std::string n = Gogo::unpack_hidden_name(method_name);
1469 Expression* s = Expression::make_string(n, bloc);
1470 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1472 ++p;
1473 go_assert(p->field_name() == "pkgPath");
1474 if (!Gogo::is_hidden_name(method_name))
1475 vals->push_back(Expression::make_nil(bloc));
1476 else
1478 s = Expression::make_string(Gogo::hidden_name_prefix(method_name), bloc);
1479 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1482 Named_object* no = (m->needs_stub_method()
1483 ? m->stub_object()
1484 : m->named_object());
1486 Function_type* mtype;
1487 if (no->is_function())
1488 mtype = no->func_value()->type();
1489 else
1490 mtype = no->func_declaration_value()->type();
1491 go_assert(mtype->is_method());
1492 Type* nonmethod_type = mtype->copy_without_receiver();
1494 ++p;
1495 go_assert(p->field_name() == "mtyp");
1496 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
1498 ++p;
1499 go_assert(p->field_name() == "typ");
1500 vals->push_back(Expression::make_type_descriptor(mtype, bloc));
1502 ++p;
1503 go_assert(p->field_name() == "tfn");
1504 vals->push_back(Expression::make_func_reference(no, NULL, bloc));
1506 ++p;
1507 go_assert(p == fields->end());
1509 return Expression::make_struct_composite_literal(method_type, vals, bloc);
1512 // Return a composite literal for the type descriptor of a plain type.
1513 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
1514 // NULL, it is the name to use as well as the list of methods.
1516 Expression*
1517 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
1518 Named_type* name)
1520 return this->type_descriptor_constructor(gogo, runtime_type_kind,
1521 name, NULL, true);
1524 // Return the type reflection string for this type.
1526 std::string
1527 Type::reflection(Gogo* gogo) const
1529 std::string ret;
1531 // The do_reflection virtual function should set RET to the
1532 // reflection string.
1533 this->do_reflection(gogo, &ret);
1535 return ret;
1538 // Return a mangled name for the type.
1540 std::string
1541 Type::mangled_name(Gogo* gogo) const
1543 std::string ret;
1545 // The do_mangled_name virtual function should set RET to the
1546 // mangled name. For a composite type it should append a code for
1547 // the composition and then call do_mangled_name on the components.
1548 this->do_mangled_name(gogo, &ret);
1550 return ret;
1553 // Default function to export a type.
1555 void
1556 Type::do_export(Export*) const
1558 go_unreachable();
1561 // Import a type.
1563 Type*
1564 Type::import_type(Import* imp)
1566 if (imp->match_c_string("("))
1567 return Function_type::do_import(imp);
1568 else if (imp->match_c_string("*"))
1569 return Pointer_type::do_import(imp);
1570 else if (imp->match_c_string("struct "))
1571 return Struct_type::do_import(imp);
1572 else if (imp->match_c_string("["))
1573 return Array_type::do_import(imp);
1574 else if (imp->match_c_string("map "))
1575 return Map_type::do_import(imp);
1576 else if (imp->match_c_string("chan "))
1577 return Channel_type::do_import(imp);
1578 else if (imp->match_c_string("interface"))
1579 return Interface_type::do_import(imp);
1580 else
1582 error_at(imp->location(), "import error: expected type");
1583 return Type::make_error_type();
1587 // A type used to indicate a parsing error. This exists to simplify
1588 // later error detection.
1590 class Error_type : public Type
1592 public:
1593 Error_type()
1594 : Type(TYPE_ERROR)
1597 protected:
1598 tree
1599 do_get_tree(Gogo*)
1600 { return error_mark_node; }
1602 tree
1603 do_get_init_tree(Gogo*, tree, bool)
1604 { return error_mark_node; }
1606 Expression*
1607 do_type_descriptor(Gogo*, Named_type*)
1608 { return Expression::make_error(BUILTINS_LOCATION); }
1610 void
1611 do_reflection(Gogo*, std::string*) const
1612 { go_assert(saw_errors()); }
1614 void
1615 do_mangled_name(Gogo*, std::string* ret) const
1616 { ret->push_back('E'); }
1619 Type*
1620 Type::make_error_type()
1622 static Error_type singleton_error_type;
1623 return &singleton_error_type;
1626 // The void type.
1628 class Void_type : public Type
1630 public:
1631 Void_type()
1632 : Type(TYPE_VOID)
1635 protected:
1636 tree
1637 do_get_tree(Gogo* gogo)
1639 Btype* btype = gogo->backend()->void_type();
1640 return type_to_tree(btype);
1643 tree
1644 do_get_init_tree(Gogo*, tree, bool)
1645 { go_unreachable(); }
1647 Expression*
1648 do_type_descriptor(Gogo*, Named_type*)
1649 { go_unreachable(); }
1651 void
1652 do_reflection(Gogo*, std::string*) const
1655 void
1656 do_mangled_name(Gogo*, std::string* ret) const
1657 { ret->push_back('v'); }
1660 Type*
1661 Type::make_void_type()
1663 static Void_type singleton_void_type;
1664 return &singleton_void_type;
1667 // The boolean type.
1669 class Boolean_type : public Type
1671 public:
1672 Boolean_type()
1673 : Type(TYPE_BOOLEAN)
1676 protected:
1677 tree
1678 do_get_tree(Gogo* gogo)
1680 Btype* btype = gogo->backend()->bool_type();
1681 return type_to_tree(btype);
1684 tree
1685 do_get_init_tree(Gogo*, tree type_tree, bool is_clear)
1686 { return is_clear ? NULL : fold_convert(type_tree, boolean_false_node); }
1688 Expression*
1689 do_type_descriptor(Gogo*, Named_type* name);
1691 // We should not be asked for the reflection string of a basic type.
1692 void
1693 do_reflection(Gogo*, std::string* ret) const
1694 { ret->append("bool"); }
1696 void
1697 do_mangled_name(Gogo*, std::string* ret) const
1698 { ret->push_back('b'); }
1701 // Make the type descriptor.
1703 Expression*
1704 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
1706 if (name != NULL)
1707 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
1708 else
1710 Named_object* no = gogo->lookup_global("bool");
1711 go_assert(no != NULL);
1712 return Type::type_descriptor(gogo, no->type_value());
1716 Type*
1717 Type::make_boolean_type()
1719 static Boolean_type boolean_type;
1720 return &boolean_type;
1723 // The named type "bool".
1725 static Named_type* named_bool_type;
1727 // Get the named type "bool".
1729 Named_type*
1730 Type::lookup_bool_type()
1732 return named_bool_type;
1735 // Make the named type "bool".
1737 Named_type*
1738 Type::make_named_bool_type()
1740 Type* bool_type = Type::make_boolean_type();
1741 Named_object* named_object = Named_object::make_type("bool", NULL,
1742 bool_type,
1743 BUILTINS_LOCATION);
1744 Named_type* named_type = named_object->type_value();
1745 named_bool_type = named_type;
1746 return named_type;
1749 // Class Integer_type.
1751 Integer_type::Named_integer_types Integer_type::named_integer_types;
1753 // Create a new integer type. Non-abstract integer types always have
1754 // names.
1756 Named_type*
1757 Integer_type::create_integer_type(const char* name, bool is_unsigned,
1758 int bits, int runtime_type_kind)
1760 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
1761 runtime_type_kind);
1762 std::string sname(name);
1763 Named_object* named_object = Named_object::make_type(sname, NULL,
1764 integer_type,
1765 BUILTINS_LOCATION);
1766 Named_type* named_type = named_object->type_value();
1767 std::pair<Named_integer_types::iterator, bool> ins =
1768 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
1769 go_assert(ins.second);
1770 return named_type;
1773 // Look up an existing integer type.
1775 Named_type*
1776 Integer_type::lookup_integer_type(const char* name)
1778 Named_integer_types::const_iterator p =
1779 Integer_type::named_integer_types.find(name);
1780 go_assert(p != Integer_type::named_integer_types.end());
1781 return p->second;
1784 // Create a new abstract integer type.
1786 Integer_type*
1787 Integer_type::create_abstract_integer_type()
1789 static Integer_type* abstract_type;
1790 if (abstract_type == NULL)
1791 abstract_type = new Integer_type(true, false, INT_TYPE_SIZE,
1792 RUNTIME_TYPE_KIND_INT);
1793 return abstract_type;
1796 // Integer type compatibility.
1798 bool
1799 Integer_type::is_identical(const Integer_type* t) const
1801 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
1802 return false;
1803 return this->is_abstract_ == t->is_abstract_;
1806 // Hash code.
1808 unsigned int
1809 Integer_type::do_hash_for_method(Gogo*) const
1811 return ((this->bits_ << 4)
1812 + ((this->is_unsigned_ ? 1 : 0) << 8)
1813 + ((this->is_abstract_ ? 1 : 0) << 9));
1816 // Convert an Integer_type to the backend representation.
1818 tree
1819 Integer_type::do_get_tree(Gogo* gogo)
1821 if (this->is_abstract_)
1823 go_assert(saw_errors());
1824 return error_mark_node;
1827 Btype* btype = gogo->backend()->integer_type(this->is_unsigned_,
1828 this->bits_);
1829 return type_to_tree(btype);
1832 tree
1833 Integer_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear)
1835 return is_clear ? NULL : build_int_cst(type_tree, 0);
1838 // The type descriptor for an integer type. Integer types are always
1839 // named.
1841 Expression*
1842 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
1844 go_assert(name != NULL);
1845 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
1848 // We should not be asked for the reflection string of a basic type.
1850 void
1851 Integer_type::do_reflection(Gogo*, std::string*) const
1853 go_assert(saw_errors());
1856 // Mangled name.
1858 void
1859 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
1861 char buf[100];
1862 snprintf(buf, sizeof buf, "i%s%s%de",
1863 this->is_abstract_ ? "a" : "",
1864 this->is_unsigned_ ? "u" : "",
1865 this->bits_);
1866 ret->append(buf);
1869 // Make an integer type.
1871 Named_type*
1872 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
1873 int runtime_type_kind)
1875 return Integer_type::create_integer_type(name, is_unsigned, bits,
1876 runtime_type_kind);
1879 // Make an abstract integer type.
1881 Integer_type*
1882 Type::make_abstract_integer_type()
1884 return Integer_type::create_abstract_integer_type();
1887 // Look up an integer type.
1889 Named_type*
1890 Type::lookup_integer_type(const char* name)
1892 return Integer_type::lookup_integer_type(name);
1895 // Class Float_type.
1897 Float_type::Named_float_types Float_type::named_float_types;
1899 // Create a new float type. Non-abstract float types always have
1900 // names.
1902 Named_type*
1903 Float_type::create_float_type(const char* name, int bits,
1904 int runtime_type_kind)
1906 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
1907 std::string sname(name);
1908 Named_object* named_object = Named_object::make_type(sname, NULL, float_type,
1909 BUILTINS_LOCATION);
1910 Named_type* named_type = named_object->type_value();
1911 std::pair<Named_float_types::iterator, bool> ins =
1912 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
1913 go_assert(ins.second);
1914 return named_type;
1917 // Look up an existing float type.
1919 Named_type*
1920 Float_type::lookup_float_type(const char* name)
1922 Named_float_types::const_iterator p =
1923 Float_type::named_float_types.find(name);
1924 go_assert(p != Float_type::named_float_types.end());
1925 return p->second;
1928 // Create a new abstract float type.
1930 Float_type*
1931 Float_type::create_abstract_float_type()
1933 static Float_type* abstract_type;
1934 if (abstract_type == NULL)
1935 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
1936 return abstract_type;
1939 // Whether this type is identical with T.
1941 bool
1942 Float_type::is_identical(const Float_type* t) const
1944 if (this->bits_ != t->bits_)
1945 return false;
1946 return this->is_abstract_ == t->is_abstract_;
1949 // Hash code.
1951 unsigned int
1952 Float_type::do_hash_for_method(Gogo*) const
1954 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
1957 // Convert to the backend representation.
1959 tree
1960 Float_type::do_get_tree(Gogo* gogo)
1962 Btype* btype = gogo->backend()->float_type(this->bits_);
1963 return type_to_tree(btype);
1966 tree
1967 Float_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear)
1969 if (is_clear)
1970 return NULL;
1971 REAL_VALUE_TYPE r;
1972 real_from_integer(&r, TYPE_MODE(type_tree), 0, 0, 0);
1973 return build_real(type_tree, r);
1976 // The type descriptor for a float type. Float types are always named.
1978 Expression*
1979 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
1981 go_assert(name != NULL);
1982 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
1985 // We should not be asked for the reflection string of a basic type.
1987 void
1988 Float_type::do_reflection(Gogo*, std::string*) const
1990 go_assert(saw_errors());
1993 // Mangled name.
1995 void
1996 Float_type::do_mangled_name(Gogo*, std::string* ret) const
1998 char buf[100];
1999 snprintf(buf, sizeof buf, "f%s%de",
2000 this->is_abstract_ ? "a" : "",
2001 this->bits_);
2002 ret->append(buf);
2005 // Make a floating point type.
2007 Named_type*
2008 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
2010 return Float_type::create_float_type(name, bits, runtime_type_kind);
2013 // Make an abstract float type.
2015 Float_type*
2016 Type::make_abstract_float_type()
2018 return Float_type::create_abstract_float_type();
2021 // Look up a float type.
2023 Named_type*
2024 Type::lookup_float_type(const char* name)
2026 return Float_type::lookup_float_type(name);
2029 // Class Complex_type.
2031 Complex_type::Named_complex_types Complex_type::named_complex_types;
2033 // Create a new complex type. Non-abstract complex types always have
2034 // names.
2036 Named_type*
2037 Complex_type::create_complex_type(const char* name, int bits,
2038 int runtime_type_kind)
2040 Complex_type* complex_type = new Complex_type(false, bits,
2041 runtime_type_kind);
2042 std::string sname(name);
2043 Named_object* named_object = Named_object::make_type(sname, NULL,
2044 complex_type,
2045 BUILTINS_LOCATION);
2046 Named_type* named_type = named_object->type_value();
2047 std::pair<Named_complex_types::iterator, bool> ins =
2048 Complex_type::named_complex_types.insert(std::make_pair(sname,
2049 named_type));
2050 go_assert(ins.second);
2051 return named_type;
2054 // Look up an existing complex type.
2056 Named_type*
2057 Complex_type::lookup_complex_type(const char* name)
2059 Named_complex_types::const_iterator p =
2060 Complex_type::named_complex_types.find(name);
2061 go_assert(p != Complex_type::named_complex_types.end());
2062 return p->second;
2065 // Create a new abstract complex type.
2067 Complex_type*
2068 Complex_type::create_abstract_complex_type()
2070 static Complex_type* abstract_type;
2071 if (abstract_type == NULL)
2072 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
2073 return abstract_type;
2076 // Whether this type is identical with T.
2078 bool
2079 Complex_type::is_identical(const Complex_type *t) const
2081 if (this->bits_ != t->bits_)
2082 return false;
2083 return this->is_abstract_ == t->is_abstract_;
2086 // Hash code.
2088 unsigned int
2089 Complex_type::do_hash_for_method(Gogo*) const
2091 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2094 // Convert to the backend representation.
2096 tree
2097 Complex_type::do_get_tree(Gogo* gogo)
2099 return type_to_tree(gogo->backend()->complex_type(this->bits_));
2102 // Zero initializer.
2104 tree
2105 Complex_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear)
2107 if (is_clear)
2108 return NULL;
2109 REAL_VALUE_TYPE r;
2110 real_from_integer(&r, TYPE_MODE(TREE_TYPE(type_tree)), 0, 0, 0);
2111 return build_complex(type_tree, build_real(TREE_TYPE(type_tree), r),
2112 build_real(TREE_TYPE(type_tree), r));
2115 // The type descriptor for a complex type. Complex types are always
2116 // named.
2118 Expression*
2119 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2121 go_assert(name != NULL);
2122 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2125 // We should not be asked for the reflection string of a basic type.
2127 void
2128 Complex_type::do_reflection(Gogo*, std::string*) const
2130 go_assert(saw_errors());
2133 // Mangled name.
2135 void
2136 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
2138 char buf[100];
2139 snprintf(buf, sizeof buf, "c%s%de",
2140 this->is_abstract_ ? "a" : "",
2141 this->bits_);
2142 ret->append(buf);
2145 // Make a complex type.
2147 Named_type*
2148 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
2150 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
2153 // Make an abstract complex type.
2155 Complex_type*
2156 Type::make_abstract_complex_type()
2158 return Complex_type::create_abstract_complex_type();
2161 // Look up a complex type.
2163 Named_type*
2164 Type::lookup_complex_type(const char* name)
2166 return Complex_type::lookup_complex_type(name);
2169 // Class String_type.
2171 // Convert String_type to the backend representation. A string is a
2172 // struct with two fields: a pointer to the characters and a length.
2174 tree
2175 String_type::do_get_tree(Gogo*)
2177 static tree struct_type;
2178 return Gogo::builtin_struct(&struct_type, "__go_string", NULL_TREE, 2,
2179 "__data",
2180 build_pointer_type(unsigned_char_type_node),
2181 "__length",
2182 integer_type_node);
2185 // Return a tree for the length of STRING.
2187 tree
2188 String_type::length_tree(Gogo*, tree string)
2190 tree string_type = TREE_TYPE(string);
2191 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2192 tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type));
2193 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)),
2194 "__length") == 0);
2195 return fold_build3(COMPONENT_REF, integer_type_node, string,
2196 length_field, NULL_TREE);
2199 // Return a tree for a pointer to the bytes of STRING.
2201 tree
2202 String_type::bytes_tree(Gogo*, tree string)
2204 tree string_type = TREE_TYPE(string);
2205 go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2206 tree bytes_field = TYPE_FIELDS(string_type);
2207 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)),
2208 "__data") == 0);
2209 return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string,
2210 bytes_field, NULL_TREE);
2213 // We initialize a string to { NULL, 0 }.
2215 tree
2216 String_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear)
2218 if (is_clear)
2219 return NULL_TREE;
2221 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
2223 VEC(constructor_elt, gc)* init = VEC_alloc(constructor_elt, gc, 2);
2225 for (tree field = TYPE_FIELDS(type_tree);
2226 field != NULL_TREE;
2227 field = DECL_CHAIN(field))
2229 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
2230 elt->index = field;
2231 elt->value = fold_convert(TREE_TYPE(field), size_zero_node);
2234 tree ret = build_constructor(type_tree, init);
2235 TREE_CONSTANT(ret) = 1;
2236 return ret;
2239 // The type descriptor for the string type.
2241 Expression*
2242 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2244 if (name != NULL)
2245 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
2246 else
2248 Named_object* no = gogo->lookup_global("string");
2249 go_assert(no != NULL);
2250 return Type::type_descriptor(gogo, no->type_value());
2254 // We should not be asked for the reflection string of a basic type.
2256 void
2257 String_type::do_reflection(Gogo*, std::string* ret) const
2259 ret->append("string");
2262 // Mangled name of a string type.
2264 void
2265 String_type::do_mangled_name(Gogo*, std::string* ret) const
2267 ret->push_back('z');
2270 // Make a string type.
2272 Type*
2273 Type::make_string_type()
2275 static String_type string_type;
2276 return &string_type;
2279 // The named type "string".
2281 static Named_type* named_string_type;
2283 // Get the named type "string".
2285 Named_type*
2286 Type::lookup_string_type()
2288 return named_string_type;
2291 // Make the named type string.
2293 Named_type*
2294 Type::make_named_string_type()
2296 Type* string_type = Type::make_string_type();
2297 Named_object* named_object = Named_object::make_type("string", NULL,
2298 string_type,
2299 BUILTINS_LOCATION);
2300 Named_type* named_type = named_object->type_value();
2301 named_string_type = named_type;
2302 return named_type;
2305 // The sink type. This is the type of the blank identifier _. Any
2306 // type may be assigned to it.
2308 class Sink_type : public Type
2310 public:
2311 Sink_type()
2312 : Type(TYPE_SINK)
2315 protected:
2316 tree
2317 do_get_tree(Gogo*)
2318 { go_unreachable(); }
2320 tree
2321 do_get_init_tree(Gogo*, tree, bool)
2322 { go_unreachable(); }
2324 Expression*
2325 do_type_descriptor(Gogo*, Named_type*)
2326 { go_unreachable(); }
2328 void
2329 do_reflection(Gogo*, std::string*) const
2330 { go_unreachable(); }
2332 void
2333 do_mangled_name(Gogo*, std::string*) const
2334 { go_unreachable(); }
2337 // Make the sink type.
2339 Type*
2340 Type::make_sink_type()
2342 static Sink_type sink_type;
2343 return &sink_type;
2346 // Class Function_type.
2348 // Traversal.
2351 Function_type::do_traverse(Traverse* traverse)
2353 if (this->receiver_ != NULL
2354 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
2355 return TRAVERSE_EXIT;
2356 if (this->parameters_ != NULL
2357 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
2358 return TRAVERSE_EXIT;
2359 if (this->results_ != NULL
2360 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
2361 return TRAVERSE_EXIT;
2362 return TRAVERSE_CONTINUE;
2365 // Returns whether T is a valid redeclaration of this type. If this
2366 // returns false, and REASON is not NULL, *REASON may be set to a
2367 // brief explanation of why it returned false.
2369 bool
2370 Function_type::is_valid_redeclaration(const Function_type* t,
2371 std::string* reason) const
2373 if (!this->is_identical(t, false, true, reason))
2374 return false;
2376 // A redeclaration of a function is required to use the same names
2377 // for the receiver and parameters.
2378 if (this->receiver() != NULL
2379 && this->receiver()->name() != t->receiver()->name()
2380 && this->receiver()->name() != Import::import_marker
2381 && t->receiver()->name() != Import::import_marker)
2383 if (reason != NULL)
2384 *reason = "receiver name changed";
2385 return false;
2388 const Typed_identifier_list* parms1 = this->parameters();
2389 const Typed_identifier_list* parms2 = t->parameters();
2390 if (parms1 != NULL)
2392 Typed_identifier_list::const_iterator p1 = parms1->begin();
2393 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
2394 p2 != parms2->end();
2395 ++p2, ++p1)
2397 if (p1->name() != p2->name()
2398 && p1->name() != Import::import_marker
2399 && p2->name() != Import::import_marker)
2401 if (reason != NULL)
2402 *reason = "parameter name changed";
2403 return false;
2406 // This is called at parse time, so we may have unknown
2407 // types.
2408 Type* t1 = p1->type()->forwarded();
2409 Type* t2 = p2->type()->forwarded();
2410 if (t1 != t2
2411 && t1->forward_declaration_type() != NULL
2412 && (t2->forward_declaration_type() == NULL
2413 || (t1->forward_declaration_type()->named_object()
2414 != t2->forward_declaration_type()->named_object())))
2415 return false;
2419 const Typed_identifier_list* results1 = this->results();
2420 const Typed_identifier_list* results2 = t->results();
2421 if (results1 != NULL)
2423 Typed_identifier_list::const_iterator res1 = results1->begin();
2424 for (Typed_identifier_list::const_iterator res2 = results2->begin();
2425 res2 != results2->end();
2426 ++res2, ++res1)
2428 if (res1->name() != res2->name()
2429 && res1->name() != Import::import_marker
2430 && res2->name() != Import::import_marker)
2432 if (reason != NULL)
2433 *reason = "result name changed";
2434 return false;
2437 // This is called at parse time, so we may have unknown
2438 // types.
2439 Type* t1 = res1->type()->forwarded();
2440 Type* t2 = res2->type()->forwarded();
2441 if (t1 != t2
2442 && t1->forward_declaration_type() != NULL
2443 && (t2->forward_declaration_type() == NULL
2444 || (t1->forward_declaration_type()->named_object()
2445 != t2->forward_declaration_type()->named_object())))
2446 return false;
2450 return true;
2453 // Check whether T is the same as this type.
2455 bool
2456 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
2457 bool errors_are_identical,
2458 std::string* reason) const
2460 if (!ignore_receiver)
2462 const Typed_identifier* r1 = this->receiver();
2463 const Typed_identifier* r2 = t->receiver();
2464 if ((r1 != NULL) != (r2 != NULL))
2466 if (reason != NULL)
2467 *reason = _("different receiver types");
2468 return false;
2470 if (r1 != NULL)
2472 if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
2473 reason))
2475 if (reason != NULL && !reason->empty())
2476 *reason = "receiver: " + *reason;
2477 return false;
2482 const Typed_identifier_list* parms1 = this->parameters();
2483 const Typed_identifier_list* parms2 = t->parameters();
2484 if ((parms1 != NULL) != (parms2 != NULL))
2486 if (reason != NULL)
2487 *reason = _("different number of parameters");
2488 return false;
2490 if (parms1 != NULL)
2492 Typed_identifier_list::const_iterator p1 = parms1->begin();
2493 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
2494 p2 != parms2->end();
2495 ++p2, ++p1)
2497 if (p1 == parms1->end())
2499 if (reason != NULL)
2500 *reason = _("different number of parameters");
2501 return false;
2504 if (!Type::are_identical(p1->type(), p2->type(),
2505 errors_are_identical, NULL))
2507 if (reason != NULL)
2508 *reason = _("different parameter types");
2509 return false;
2512 if (p1 != parms1->end())
2514 if (reason != NULL)
2515 *reason = _("different number of parameters");
2516 return false;
2520 if (this->is_varargs() != t->is_varargs())
2522 if (reason != NULL)
2523 *reason = _("different varargs");
2524 return false;
2527 const Typed_identifier_list* results1 = this->results();
2528 const Typed_identifier_list* results2 = t->results();
2529 if ((results1 != NULL) != (results2 != NULL))
2531 if (reason != NULL)
2532 *reason = _("different number of results");
2533 return false;
2535 if (results1 != NULL)
2537 Typed_identifier_list::const_iterator res1 = results1->begin();
2538 for (Typed_identifier_list::const_iterator res2 = results2->begin();
2539 res2 != results2->end();
2540 ++res2, ++res1)
2542 if (res1 == results1->end())
2544 if (reason != NULL)
2545 *reason = _("different number of results");
2546 return false;
2549 if (!Type::are_identical(res1->type(), res2->type(),
2550 errors_are_identical, NULL))
2552 if (reason != NULL)
2553 *reason = _("different result types");
2554 return false;
2557 if (res1 != results1->end())
2559 if (reason != NULL)
2560 *reason = _("different number of results");
2561 return false;
2565 return true;
2568 // Hash code.
2570 unsigned int
2571 Function_type::do_hash_for_method(Gogo* gogo) const
2573 unsigned int ret = 0;
2574 // We ignore the receiver type for hash codes, because we need to
2575 // get the same hash code for a method in an interface and a method
2576 // declared for a type. The former will not have a receiver.
2577 if (this->parameters_ != NULL)
2579 int shift = 1;
2580 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
2581 p != this->parameters_->end();
2582 ++p, ++shift)
2583 ret += p->type()->hash_for_method(gogo) << shift;
2585 if (this->results_ != NULL)
2587 int shift = 2;
2588 for (Typed_identifier_list::const_iterator p = this->results_->begin();
2589 p != this->results_->end();
2590 ++p, ++shift)
2591 ret += p->type()->hash_for_method(gogo) << shift;
2593 if (this->is_varargs_)
2594 ret += 1;
2595 ret <<= 4;
2596 return ret;
2599 // Get the tree for a function type.
2601 tree
2602 Function_type::do_get_tree(Gogo* gogo)
2604 Backend::Btyped_identifier breceiver;
2605 if (this->receiver_ != NULL)
2607 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
2609 // We always pass the address of the receiver parameter, in
2610 // order to make interface calls work with unknown types.
2611 Type* rtype = this->receiver_->type();
2612 if (rtype->points_to() == NULL)
2613 rtype = Type::make_pointer_type(rtype);
2614 breceiver.btype = tree_to_type(rtype->get_tree(gogo));
2615 breceiver.location = this->receiver_->location();
2618 std::vector<Backend::Btyped_identifier> bparameters;
2619 if (this->parameters_ != NULL)
2621 bparameters.resize(this->parameters_->size());
2622 size_t i = 0;
2623 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
2624 p != this->parameters_->end();
2625 ++p, ++i)
2627 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
2628 bparameters[i].btype = tree_to_type(p->type()->get_tree(gogo));
2629 bparameters[i].location = p->location();
2631 go_assert(i == bparameters.size());
2634 std::vector<Backend::Btyped_identifier> bresults;
2635 if (this->results_ != NULL)
2637 bresults.resize(this->results_->size());
2638 size_t i = 0;
2639 for (Typed_identifier_list::const_iterator p = this->results_->begin();
2640 p != this->results_->end();
2641 ++p, ++i)
2643 bresults[i].name = Gogo::unpack_hidden_name(p->name());
2644 bresults[i].btype = tree_to_type(p->type()->get_tree(gogo));
2645 bresults[i].location = p->location();
2647 go_assert(i == bresults.size());
2650 Btype* fntype = gogo->backend()->function_type(breceiver, bparameters,
2651 bresults, this->location());
2652 return type_to_tree(fntype);
2655 // Functions are initialized to NULL.
2657 tree
2658 Function_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear)
2660 if (is_clear)
2661 return NULL;
2662 return fold_convert(type_tree, null_pointer_node);
2665 // The type of a function type descriptor.
2667 Type*
2668 Function_type::make_function_type_descriptor_type()
2670 static Type* ret;
2671 if (ret == NULL)
2673 Type* tdt = Type::make_type_descriptor_type();
2674 Type* ptdt = Type::make_type_descriptor_ptr_type();
2676 Type* bool_type = Type::lookup_bool_type();
2678 Type* slice_type = Type::make_array_type(ptdt, NULL);
2680 Struct_type* s = Type::make_builtin_struct_type(4,
2681 "", tdt,
2682 "dotdotdot", bool_type,
2683 "in", slice_type,
2684 "out", slice_type);
2686 ret = Type::make_builtin_named_type("FuncType", s);
2689 return ret;
2692 // The type descriptor for a function type.
2694 Expression*
2695 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2697 source_location bloc = BUILTINS_LOCATION;
2699 Type* ftdt = Function_type::make_function_type_descriptor_type();
2701 const Struct_field_list* fields = ftdt->struct_type()->fields();
2703 Expression_list* vals = new Expression_list();
2704 vals->reserve(4);
2706 Struct_field_list::const_iterator p = fields->begin();
2707 go_assert(p->field_name() == "commonType");
2708 vals->push_back(this->type_descriptor_constructor(gogo,
2709 RUNTIME_TYPE_KIND_FUNC,
2710 name, NULL, true));
2712 ++p;
2713 go_assert(p->field_name() == "dotdotdot");
2714 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
2716 ++p;
2717 go_assert(p->field_name() == "in");
2718 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
2719 this->parameters()));
2721 ++p;
2722 go_assert(p->field_name() == "out");
2723 vals->push_back(this->type_descriptor_params(p->type(), NULL,
2724 this->results()));
2726 ++p;
2727 go_assert(p == fields->end());
2729 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
2732 // Return a composite literal for the parameters or results of a type
2733 // descriptor.
2735 Expression*
2736 Function_type::type_descriptor_params(Type* params_type,
2737 const Typed_identifier* receiver,
2738 const Typed_identifier_list* params)
2740 source_location bloc = BUILTINS_LOCATION;
2742 if (receiver == NULL && params == NULL)
2743 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
2745 Expression_list* vals = new Expression_list();
2746 vals->reserve((params == NULL ? 0 : params->size())
2747 + (receiver != NULL ? 1 : 0));
2749 if (receiver != NULL)
2751 Type* rtype = receiver->type();
2752 // The receiver is always passed as a pointer. FIXME: Is this
2753 // right? Should that fact affect the type descriptor?
2754 if (rtype->points_to() == NULL)
2755 rtype = Type::make_pointer_type(rtype);
2756 vals->push_back(Expression::make_type_descriptor(rtype, bloc));
2759 if (params != NULL)
2761 for (Typed_identifier_list::const_iterator p = params->begin();
2762 p != params->end();
2763 ++p)
2764 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
2767 return Expression::make_slice_composite_literal(params_type, vals, bloc);
2770 // The reflection string.
2772 void
2773 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
2775 // FIXME: Turn this off until we straighten out the type of the
2776 // struct field used in a go statement which calls a method.
2777 // go_assert(this->receiver_ == NULL);
2779 ret->append("func");
2781 if (this->receiver_ != NULL)
2783 ret->push_back('(');
2784 this->append_reflection(this->receiver_->type(), gogo, ret);
2785 ret->push_back(')');
2788 ret->push_back('(');
2789 const Typed_identifier_list* params = this->parameters();
2790 if (params != NULL)
2792 bool is_varargs = this->is_varargs_;
2793 for (Typed_identifier_list::const_iterator p = params->begin();
2794 p != params->end();
2795 ++p)
2797 if (p != params->begin())
2798 ret->append(", ");
2799 if (!is_varargs || p + 1 != params->end())
2800 this->append_reflection(p->type(), gogo, ret);
2801 else
2803 ret->append("...");
2804 this->append_reflection(p->type()->array_type()->element_type(),
2805 gogo, ret);
2809 ret->push_back(')');
2811 const Typed_identifier_list* results = this->results();
2812 if (results != NULL && !results->empty())
2814 if (results->size() == 1)
2815 ret->push_back(' ');
2816 else
2817 ret->append(" (");
2818 for (Typed_identifier_list::const_iterator p = results->begin();
2819 p != results->end();
2820 ++p)
2822 if (p != results->begin())
2823 ret->append(", ");
2824 this->append_reflection(p->type(), gogo, ret);
2826 if (results->size() > 1)
2827 ret->push_back(')');
2831 // Mangled name.
2833 void
2834 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
2836 ret->push_back('F');
2838 if (this->receiver_ != NULL)
2840 ret->push_back('m');
2841 this->append_mangled_name(this->receiver_->type(), gogo, ret);
2844 const Typed_identifier_list* params = this->parameters();
2845 if (params != NULL)
2847 ret->push_back('p');
2848 for (Typed_identifier_list::const_iterator p = params->begin();
2849 p != params->end();
2850 ++p)
2851 this->append_mangled_name(p->type(), gogo, ret);
2852 if (this->is_varargs_)
2853 ret->push_back('V');
2854 ret->push_back('e');
2857 const Typed_identifier_list* results = this->results();
2858 if (results != NULL)
2860 ret->push_back('r');
2861 for (Typed_identifier_list::const_iterator p = results->begin();
2862 p != results->end();
2863 ++p)
2864 this->append_mangled_name(p->type(), gogo, ret);
2865 ret->push_back('e');
2868 ret->push_back('e');
2871 // Export a function type.
2873 void
2874 Function_type::do_export(Export* exp) const
2876 // We don't write out the receiver. The only function types which
2877 // should have a receiver are the ones associated with explicitly
2878 // defined methods. For those the receiver type is written out by
2879 // Function::export_func.
2881 exp->write_c_string("(");
2882 bool first = true;
2883 if (this->parameters_ != NULL)
2885 bool is_varargs = this->is_varargs_;
2886 for (Typed_identifier_list::const_iterator p =
2887 this->parameters_->begin();
2888 p != this->parameters_->end();
2889 ++p)
2891 if (first)
2892 first = false;
2893 else
2894 exp->write_c_string(", ");
2895 if (!is_varargs || p + 1 != this->parameters_->end())
2896 exp->write_type(p->type());
2897 else
2899 exp->write_c_string("...");
2900 exp->write_type(p->type()->array_type()->element_type());
2904 exp->write_c_string(")");
2906 const Typed_identifier_list* results = this->results_;
2907 if (results != NULL)
2909 exp->write_c_string(" ");
2910 if (results->size() == 1)
2911 exp->write_type(results->begin()->type());
2912 else
2914 first = true;
2915 exp->write_c_string("(");
2916 for (Typed_identifier_list::const_iterator p = results->begin();
2917 p != results->end();
2918 ++p)
2920 if (first)
2921 first = false;
2922 else
2923 exp->write_c_string(", ");
2924 exp->write_type(p->type());
2926 exp->write_c_string(")");
2931 // Import a function type.
2933 Function_type*
2934 Function_type::do_import(Import* imp)
2936 imp->require_c_string("(");
2937 Typed_identifier_list* parameters;
2938 bool is_varargs = false;
2939 if (imp->peek_char() == ')')
2940 parameters = NULL;
2941 else
2943 parameters = new Typed_identifier_list();
2944 while (true)
2946 if (imp->match_c_string("..."))
2948 imp->advance(3);
2949 is_varargs = true;
2952 Type* ptype = imp->read_type();
2953 if (is_varargs)
2954 ptype = Type::make_array_type(ptype, NULL);
2955 parameters->push_back(Typed_identifier(Import::import_marker,
2956 ptype, imp->location()));
2957 if (imp->peek_char() != ',')
2958 break;
2959 go_assert(!is_varargs);
2960 imp->require_c_string(", ");
2963 imp->require_c_string(")");
2965 Typed_identifier_list* results;
2966 if (imp->peek_char() != ' ')
2967 results = NULL;
2968 else
2970 imp->advance(1);
2971 results = new Typed_identifier_list;
2972 if (imp->peek_char() != '(')
2974 Type* rtype = imp->read_type();
2975 results->push_back(Typed_identifier(Import::import_marker, rtype,
2976 imp->location()));
2978 else
2980 imp->advance(1);
2981 while (true)
2983 Type* rtype = imp->read_type();
2984 results->push_back(Typed_identifier(Import::import_marker,
2985 rtype, imp->location()));
2986 if (imp->peek_char() != ',')
2987 break;
2988 imp->require_c_string(", ");
2990 imp->require_c_string(")");
2994 Function_type* ret = Type::make_function_type(NULL, parameters, results,
2995 imp->location());
2996 if (is_varargs)
2997 ret->set_is_varargs();
2998 return ret;
3001 // Make a copy of a function type without a receiver.
3003 Function_type*
3004 Function_type::copy_without_receiver() const
3006 go_assert(this->is_method());
3007 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
3008 this->results_,
3009 this->location_);
3010 if (this->is_varargs())
3011 ret->set_is_varargs();
3012 if (this->is_builtin())
3013 ret->set_is_builtin();
3014 return ret;
3017 // Make a copy of a function type with a receiver.
3019 Function_type*
3020 Function_type::copy_with_receiver(Type* receiver_type) const
3022 go_assert(!this->is_method());
3023 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
3024 this->location_);
3025 return Type::make_function_type(receiver, this->parameters_,
3026 this->results_, this->location_);
3029 // Make a function type.
3031 Function_type*
3032 Type::make_function_type(Typed_identifier* receiver,
3033 Typed_identifier_list* parameters,
3034 Typed_identifier_list* results,
3035 source_location location)
3037 return new Function_type(receiver, parameters, results, location);
3040 // Class Pointer_type.
3042 // Traversal.
3045 Pointer_type::do_traverse(Traverse* traverse)
3047 return Type::traverse(this->to_type_, traverse);
3050 // Hash code.
3052 unsigned int
3053 Pointer_type::do_hash_for_method(Gogo* gogo) const
3055 return this->to_type_->hash_for_method(gogo) << 4;
3058 // The tree for a pointer type.
3060 tree
3061 Pointer_type::do_get_tree(Gogo* gogo)
3063 Btype* to_btype = tree_to_type(this->to_type_->get_tree(gogo));
3064 Btype* btype = gogo->backend()->pointer_type(to_btype);
3065 return type_to_tree(btype);
3068 // Initialize a pointer type.
3070 tree
3071 Pointer_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear)
3073 if (is_clear)
3074 return NULL;
3075 return fold_convert(type_tree, null_pointer_node);
3078 // The type of a pointer type descriptor.
3080 Type*
3081 Pointer_type::make_pointer_type_descriptor_type()
3083 static Type* ret;
3084 if (ret == NULL)
3086 Type* tdt = Type::make_type_descriptor_type();
3087 Type* ptdt = Type::make_type_descriptor_ptr_type();
3089 Struct_type* s = Type::make_builtin_struct_type(2,
3090 "", tdt,
3091 "elem", ptdt);
3093 ret = Type::make_builtin_named_type("PtrType", s);
3096 return ret;
3099 // The type descriptor for a pointer type.
3101 Expression*
3102 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3104 if (this->is_unsafe_pointer_type())
3106 go_assert(name != NULL);
3107 return this->plain_type_descriptor(gogo,
3108 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
3109 name);
3111 else
3113 source_location bloc = BUILTINS_LOCATION;
3115 const Methods* methods;
3116 Type* deref = this->points_to();
3117 if (deref->named_type() != NULL)
3118 methods = deref->named_type()->methods();
3119 else if (deref->struct_type() != NULL)
3120 methods = deref->struct_type()->methods();
3121 else
3122 methods = NULL;
3124 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
3126 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
3128 Expression_list* vals = new Expression_list();
3129 vals->reserve(2);
3131 Struct_field_list::const_iterator p = fields->begin();
3132 go_assert(p->field_name() == "commonType");
3133 vals->push_back(this->type_descriptor_constructor(gogo,
3134 RUNTIME_TYPE_KIND_PTR,
3135 name, methods, false));
3137 ++p;
3138 go_assert(p->field_name() == "elem");
3139 vals->push_back(Expression::make_type_descriptor(deref, bloc));
3141 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
3145 // Reflection string.
3147 void
3148 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
3150 ret->push_back('*');
3151 this->append_reflection(this->to_type_, gogo, ret);
3154 // Mangled name.
3156 void
3157 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3159 ret->push_back('p');
3160 this->append_mangled_name(this->to_type_, gogo, ret);
3163 // Export.
3165 void
3166 Pointer_type::do_export(Export* exp) const
3168 exp->write_c_string("*");
3169 if (this->is_unsafe_pointer_type())
3170 exp->write_c_string("any");
3171 else
3172 exp->write_type(this->to_type_);
3175 // Import.
3177 Pointer_type*
3178 Pointer_type::do_import(Import* imp)
3180 imp->require_c_string("*");
3181 if (imp->match_c_string("any"))
3183 imp->advance(3);
3184 return Type::make_pointer_type(Type::make_void_type());
3186 Type* to = imp->read_type();
3187 return Type::make_pointer_type(to);
3190 // Make a pointer type.
3192 Pointer_type*
3193 Type::make_pointer_type(Type* to_type)
3195 typedef Unordered_map(Type*, Pointer_type*) Hashtable;
3196 static Hashtable pointer_types;
3197 Hashtable::const_iterator p = pointer_types.find(to_type);
3198 if (p != pointer_types.end())
3199 return p->second;
3200 Pointer_type* ret = new Pointer_type(to_type);
3201 pointer_types[to_type] = ret;
3202 return ret;
3205 // The nil type. We use a special type for nil because it is not the
3206 // same as any other type. In C term nil has type void*, but there is
3207 // no such type in Go.
3209 class Nil_type : public Type
3211 public:
3212 Nil_type()
3213 : Type(TYPE_NIL)
3216 protected:
3217 tree
3218 do_get_tree(Gogo*)
3219 { return ptr_type_node; }
3221 tree
3222 do_get_init_tree(Gogo*, tree type_tree, bool is_clear)
3223 { return is_clear ? NULL : fold_convert(type_tree, null_pointer_node); }
3225 Expression*
3226 do_type_descriptor(Gogo*, Named_type*)
3227 { go_unreachable(); }
3229 void
3230 do_reflection(Gogo*, std::string*) const
3231 { go_unreachable(); }
3233 void
3234 do_mangled_name(Gogo*, std::string* ret) const
3235 { ret->push_back('n'); }
3238 // Make the nil type.
3240 Type*
3241 Type::make_nil_type()
3243 static Nil_type singleton_nil_type;
3244 return &singleton_nil_type;
3247 // The type of a function call which returns multiple values. This is
3248 // really a struct, but we don't want to confuse a function call which
3249 // returns a struct with a function call which returns multiple
3250 // values.
3252 class Call_multiple_result_type : public Type
3254 public:
3255 Call_multiple_result_type(Call_expression* call)
3256 : Type(TYPE_CALL_MULTIPLE_RESULT),
3257 call_(call)
3260 protected:
3261 bool
3262 do_has_pointer() const
3264 go_assert(saw_errors());
3265 return false;
3268 tree
3269 do_get_tree(Gogo*);
3271 tree
3272 do_get_init_tree(Gogo*, tree, bool)
3274 go_assert(saw_errors());
3275 return error_mark_node;
3278 Expression*
3279 do_type_descriptor(Gogo*, Named_type*)
3281 go_assert(saw_errors());
3282 return Expression::make_error(UNKNOWN_LOCATION);
3285 void
3286 do_reflection(Gogo*, std::string*) const
3287 { go_assert(saw_errors()); }
3289 void
3290 do_mangled_name(Gogo*, std::string*) const
3291 { go_assert(saw_errors()); }
3293 private:
3294 // The expression being called.
3295 Call_expression* call_;
3298 // Return the tree for a call result.
3300 tree
3301 Call_multiple_result_type::do_get_tree(Gogo* gogo)
3303 Function_type* fntype = this->call_->get_function_type();
3304 go_assert(fntype != NULL);
3305 const Typed_identifier_list* results = fntype->results();
3306 go_assert(results != NULL && results->size() > 1);
3307 tree fntype_tree = fntype->get_tree(gogo);
3308 if (fntype_tree == error_mark_node)
3309 return error_mark_node;
3310 return TREE_TYPE(fntype_tree);
3313 // Make a call result type.
3315 Type*
3316 Type::make_call_multiple_result_type(Call_expression* call)
3318 return new Call_multiple_result_type(call);
3321 // Class Struct_field.
3323 // Get the name of a field.
3325 const std::string&
3326 Struct_field::field_name() const
3328 const std::string& name(this->typed_identifier_.name());
3329 if (!name.empty())
3330 return name;
3331 else
3333 // This is called during parsing, before anything is lowered, so
3334 // we have to be pretty careful to avoid dereferencing an
3335 // unknown type name.
3336 Type* t = this->typed_identifier_.type();
3337 Type* dt = t;
3338 if (t->classification() == Type::TYPE_POINTER)
3340 // Very ugly.
3341 Pointer_type* ptype = static_cast<Pointer_type*>(t);
3342 dt = ptype->points_to();
3344 if (dt->forward_declaration_type() != NULL)
3345 return dt->forward_declaration_type()->name();
3346 else if (dt->named_type() != NULL)
3347 return dt->named_type()->name();
3348 else if (t->is_error_type() || dt->is_error_type())
3350 static const std::string error_string = "*error*";
3351 return error_string;
3353 else
3355 // Avoid crashing in the erroneous case where T is named but
3356 // DT is not.
3357 go_assert(t != dt);
3358 if (t->forward_declaration_type() != NULL)
3359 return t->forward_declaration_type()->name();
3360 else if (t->named_type() != NULL)
3361 return t->named_type()->name();
3362 else
3363 go_unreachable();
3368 // Class Struct_type.
3370 // Traversal.
3373 Struct_type::do_traverse(Traverse* traverse)
3375 Struct_field_list* fields = this->fields_;
3376 if (fields != NULL)
3378 for (Struct_field_list::iterator p = fields->begin();
3379 p != fields->end();
3380 ++p)
3382 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
3383 return TRAVERSE_EXIT;
3386 return TRAVERSE_CONTINUE;
3389 // Verify that the struct type is complete and valid.
3391 bool
3392 Struct_type::do_verify()
3394 Struct_field_list* fields = this->fields_;
3395 if (fields == NULL)
3396 return true;
3397 bool ret = true;
3398 for (Struct_field_list::iterator p = fields->begin();
3399 p != fields->end();
3400 ++p)
3402 Type* t = p->type();
3403 if (t->is_undefined())
3405 error_at(p->location(), "struct field type is incomplete");
3406 p->set_type(Type::make_error_type());
3407 ret = false;
3409 else if (p->is_anonymous())
3411 if (t->named_type() != NULL && t->points_to() != NULL)
3413 error_at(p->location(), "embedded type may not be a pointer");
3414 p->set_type(Type::make_error_type());
3415 return false;
3417 if (t->points_to() != NULL
3418 && t->points_to()->interface_type() != NULL)
3420 error_at(p->location(),
3421 "embedded type may not be pointer to interface");
3422 p->set_type(Type::make_error_type());
3423 return false;
3427 return ret;
3430 // Whether this contains a pointer.
3432 bool
3433 Struct_type::do_has_pointer() const
3435 const Struct_field_list* fields = this->fields();
3436 if (fields == NULL)
3437 return false;
3438 for (Struct_field_list::const_iterator p = fields->begin();
3439 p != fields->end();
3440 ++p)
3442 if (p->type()->has_pointer())
3443 return true;
3445 return false;
3448 // Whether this type is identical to T.
3450 bool
3451 Struct_type::is_identical(const Struct_type* t,
3452 bool errors_are_identical) const
3454 const Struct_field_list* fields1 = this->fields();
3455 const Struct_field_list* fields2 = t->fields();
3456 if (fields1 == NULL || fields2 == NULL)
3457 return fields1 == fields2;
3458 Struct_field_list::const_iterator pf2 = fields2->begin();
3459 for (Struct_field_list::const_iterator pf1 = fields1->begin();
3460 pf1 != fields1->end();
3461 ++pf1, ++pf2)
3463 if (pf2 == fields2->end())
3464 return false;
3465 if (pf1->field_name() != pf2->field_name())
3466 return false;
3467 if (pf1->is_anonymous() != pf2->is_anonymous()
3468 || !Type::are_identical(pf1->type(), pf2->type(),
3469 errors_are_identical, NULL))
3470 return false;
3471 if (!pf1->has_tag())
3473 if (pf2->has_tag())
3474 return false;
3476 else
3478 if (!pf2->has_tag())
3479 return false;
3480 if (pf1->tag() != pf2->tag())
3481 return false;
3484 if (pf2 != fields2->end())
3485 return false;
3486 return true;
3489 // Whether this struct type has any hidden fields.
3491 bool
3492 Struct_type::struct_has_hidden_fields(const Named_type* within,
3493 std::string* reason) const
3495 const Struct_field_list* fields = this->fields();
3496 if (fields == NULL)
3497 return false;
3498 const Package* within_package = (within == NULL
3499 ? NULL
3500 : within->named_object()->package());
3501 for (Struct_field_list::const_iterator pf = fields->begin();
3502 pf != fields->end();
3503 ++pf)
3505 if (within_package != NULL
3506 && !pf->is_anonymous()
3507 && Gogo::is_hidden_name(pf->field_name()))
3509 if (reason != NULL)
3511 std::string within_name = within->named_object()->message_name();
3512 std::string name = Gogo::message_name(pf->field_name());
3513 size_t bufsize = 200 + within_name.length() + name.length();
3514 char* buf = new char[bufsize];
3515 snprintf(buf, bufsize,
3516 _("implicit assignment of %s%s%s hidden field %s%s%s"),
3517 open_quote, within_name.c_str(), close_quote,
3518 open_quote, name.c_str(), close_quote);
3519 reason->assign(buf);
3520 delete[] buf;
3522 return true;
3525 if (pf->type()->has_hidden_fields(within, reason))
3526 return true;
3529 return false;
3532 // Hash code.
3534 unsigned int
3535 Struct_type::do_hash_for_method(Gogo* gogo) const
3537 unsigned int ret = 0;
3538 if (this->fields() != NULL)
3540 for (Struct_field_list::const_iterator pf = this->fields()->begin();
3541 pf != this->fields()->end();
3542 ++pf)
3543 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
3545 return ret <<= 2;
3548 // Find the local field NAME.
3550 const Struct_field*
3551 Struct_type::find_local_field(const std::string& name,
3552 unsigned int *pindex) const
3554 const Struct_field_list* fields = this->fields_;
3555 if (fields == NULL)
3556 return NULL;
3557 unsigned int i = 0;
3558 for (Struct_field_list::const_iterator pf = fields->begin();
3559 pf != fields->end();
3560 ++pf, ++i)
3562 if (pf->field_name() == name)
3564 if (pindex != NULL)
3565 *pindex = i;
3566 return &*pf;
3569 return NULL;
3572 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
3574 Field_reference_expression*
3575 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
3576 source_location location) const
3578 unsigned int depth;
3579 return this->field_reference_depth(struct_expr, name, location, NULL,
3580 &depth);
3583 // Return an expression for a field, along with the depth at which it
3584 // was found.
3586 Field_reference_expression*
3587 Struct_type::field_reference_depth(Expression* struct_expr,
3588 const std::string& name,
3589 source_location location,
3590 Saw_named_type* saw,
3591 unsigned int* depth) const
3593 const Struct_field_list* fields = this->fields_;
3594 if (fields == NULL)
3595 return NULL;
3597 // Look for a field with this name.
3598 unsigned int i = 0;
3599 for (Struct_field_list::const_iterator pf = fields->begin();
3600 pf != fields->end();
3601 ++pf, ++i)
3603 if (pf->field_name() == name)
3605 *depth = 0;
3606 return Expression::make_field_reference(struct_expr, i, location);
3610 // Look for an anonymous field which contains a field with this
3611 // name.
3612 unsigned int found_depth = 0;
3613 Field_reference_expression* ret = NULL;
3614 i = 0;
3615 for (Struct_field_list::const_iterator pf = fields->begin();
3616 pf != fields->end();
3617 ++pf, ++i)
3619 if (!pf->is_anonymous())
3620 continue;
3622 Struct_type* st = pf->type()->deref()->struct_type();
3623 if (st == NULL)
3624 continue;
3626 Saw_named_type* hold_saw = saw;
3627 Saw_named_type saw_here;
3628 Named_type* nt = pf->type()->named_type();
3629 if (nt == NULL)
3630 nt = pf->type()->deref()->named_type();
3631 if (nt != NULL)
3633 Saw_named_type* q;
3634 for (q = saw; q != NULL; q = q->next)
3636 if (q->nt == nt)
3638 // If this is an error, it will be reported
3639 // elsewhere.
3640 break;
3643 if (q != NULL)
3644 continue;
3645 saw_here.next = saw;
3646 saw_here.nt = nt;
3647 saw = &saw_here;
3650 // Look for a reference using a NULL struct expression. If we
3651 // find one, fill in the struct expression with a reference to
3652 // this field.
3653 unsigned int subdepth;
3654 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
3655 location,
3656 saw,
3657 &subdepth);
3659 saw = hold_saw;
3661 if (sub == NULL)
3662 continue;
3664 if (ret == NULL || subdepth < found_depth)
3666 if (ret != NULL)
3667 delete ret;
3668 ret = sub;
3669 found_depth = subdepth;
3670 Expression* here = Expression::make_field_reference(struct_expr, i,
3671 location);
3672 if (pf->type()->points_to() != NULL)
3673 here = Expression::make_unary(OPERATOR_MULT, here, location);
3674 while (sub->expr() != NULL)
3676 sub = sub->expr()->deref()->field_reference_expression();
3677 go_assert(sub != NULL);
3679 sub->set_struct_expression(here);
3681 else if (subdepth > found_depth)
3682 delete sub;
3683 else
3685 // We do not handle ambiguity here--it should be handled by
3686 // Type::bind_field_or_method.
3687 delete sub;
3688 found_depth = 0;
3689 ret = NULL;
3693 if (ret != NULL)
3694 *depth = found_depth + 1;
3696 return ret;
3699 // Return the total number of fields, including embedded fields.
3701 unsigned int
3702 Struct_type::total_field_count() const
3704 if (this->fields_ == NULL)
3705 return 0;
3706 unsigned int ret = 0;
3707 for (Struct_field_list::const_iterator pf = this->fields_->begin();
3708 pf != this->fields_->end();
3709 ++pf)
3711 if (!pf->is_anonymous() || pf->type()->deref()->struct_type() == NULL)
3712 ++ret;
3713 else
3714 ret += pf->type()->struct_type()->total_field_count();
3716 return ret;
3719 // Return whether NAME is an unexported field, for better error reporting.
3721 bool
3722 Struct_type::is_unexported_local_field(Gogo* gogo,
3723 const std::string& name) const
3725 const Struct_field_list* fields = this->fields_;
3726 if (fields != NULL)
3728 for (Struct_field_list::const_iterator pf = fields->begin();
3729 pf != fields->end();
3730 ++pf)
3732 const std::string& field_name(pf->field_name());
3733 if (Gogo::is_hidden_name(field_name)
3734 && name == Gogo::unpack_hidden_name(field_name)
3735 && gogo->pack_hidden_name(name, false) != field_name)
3736 return true;
3739 return false;
3742 // Finalize the methods of an unnamed struct.
3744 void
3745 Struct_type::finalize_methods(Gogo* gogo)
3747 if (this->all_methods_ != NULL)
3748 return;
3749 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
3752 // Return the method NAME, or NULL if there isn't one or if it is
3753 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
3754 // ambiguous.
3756 Method*
3757 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
3759 return Type::method_function(this->all_methods_, name, is_ambiguous);
3762 // Convert struct fields to the backend representation. This is not
3763 // declared in types.h so that types.h doesn't have to #include
3764 // backend.h.
3766 static void
3767 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
3768 std::vector<Backend::Btyped_identifier>* bfields)
3770 bfields->resize(fields->size());
3771 size_t i = 0;
3772 for (Struct_field_list::const_iterator p = fields->begin();
3773 p != fields->end();
3774 ++p, ++i)
3776 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
3777 (*bfields)[i].btype = tree_to_type(p->type()->get_tree(gogo));
3778 (*bfields)[i].location = p->location();
3780 go_assert(i == fields->size());
3783 // Get the tree for a struct type.
3785 tree
3786 Struct_type::do_get_tree(Gogo* gogo)
3788 std::vector<Backend::Btyped_identifier> bfields;
3789 get_backend_struct_fields(gogo, this->fields_, &bfields);
3790 Btype* btype = gogo->backend()->struct_type(bfields);
3791 return type_to_tree(btype);
3794 // Initialize struct fields.
3796 tree
3797 Struct_type::do_get_init_tree(Gogo* gogo, tree type_tree, bool is_clear)
3799 if (this->fields_ == NULL || this->fields_->empty())
3801 if (is_clear)
3802 return NULL;
3803 else
3805 tree ret = build_constructor(type_tree,
3806 VEC_alloc(constructor_elt, gc, 0));
3807 TREE_CONSTANT(ret) = 1;
3808 return ret;
3812 bool is_constant = true;
3813 bool any_fields_set = false;
3814 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc,
3815 this->fields_->size());
3817 tree field = TYPE_FIELDS(type_tree);
3818 for (Struct_field_list::const_iterator p = this->fields_->begin();
3819 p != this->fields_->end();
3820 ++p, field = DECL_CHAIN(field))
3822 tree value = p->type()->get_init_tree(gogo, is_clear);
3823 if (value == error_mark_node)
3824 return error_mark_node;
3825 go_assert(field != NULL_TREE);
3826 if (value != NULL)
3828 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
3829 elt->index = field;
3830 elt->value = value;
3831 any_fields_set = true;
3832 if (!TREE_CONSTANT(value))
3833 is_constant = false;
3836 go_assert(field == NULL_TREE);
3838 if (!any_fields_set)
3840 go_assert(is_clear);
3841 VEC_free(constructor_elt, gc, init);
3842 return NULL;
3845 tree ret = build_constructor(type_tree, init);
3846 if (is_constant)
3847 TREE_CONSTANT(ret) = 1;
3848 return ret;
3851 // The type of a struct type descriptor.
3853 Type*
3854 Struct_type::make_struct_type_descriptor_type()
3856 static Type* ret;
3857 if (ret == NULL)
3859 Type* tdt = Type::make_type_descriptor_type();
3860 Type* ptdt = Type::make_type_descriptor_ptr_type();
3862 Type* uintptr_type = Type::lookup_integer_type("uintptr");
3863 Type* string_type = Type::lookup_string_type();
3864 Type* pointer_string_type = Type::make_pointer_type(string_type);
3866 Struct_type* sf =
3867 Type::make_builtin_struct_type(5,
3868 "name", pointer_string_type,
3869 "pkgPath", pointer_string_type,
3870 "typ", ptdt,
3871 "tag", pointer_string_type,
3872 "offset", uintptr_type);
3873 Type* nsf = Type::make_builtin_named_type("structField", sf);
3875 Type* slice_type = Type::make_array_type(nsf, NULL);
3877 Struct_type* s = Type::make_builtin_struct_type(2,
3878 "", tdt,
3879 "fields", slice_type);
3881 ret = Type::make_builtin_named_type("StructType", s);
3884 return ret;
3887 // Build a type descriptor for a struct type.
3889 Expression*
3890 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3892 source_location bloc = BUILTINS_LOCATION;
3894 Type* stdt = Struct_type::make_struct_type_descriptor_type();
3896 const Struct_field_list* fields = stdt->struct_type()->fields();
3898 Expression_list* vals = new Expression_list();
3899 vals->reserve(2);
3901 const Methods* methods = this->methods();
3902 // A named struct should not have methods--the methods should attach
3903 // to the named type.
3904 go_assert(methods == NULL || name == NULL);
3906 Struct_field_list::const_iterator ps = fields->begin();
3907 go_assert(ps->field_name() == "commonType");
3908 vals->push_back(this->type_descriptor_constructor(gogo,
3909 RUNTIME_TYPE_KIND_STRUCT,
3910 name, methods, true));
3912 ++ps;
3913 go_assert(ps->field_name() == "fields");
3915 Expression_list* elements = new Expression_list();
3916 elements->reserve(this->fields_->size());
3917 Type* element_type = ps->type()->array_type()->element_type();
3918 for (Struct_field_list::const_iterator pf = this->fields_->begin();
3919 pf != this->fields_->end();
3920 ++pf)
3922 const Struct_field_list* f = element_type->struct_type()->fields();
3924 Expression_list* fvals = new Expression_list();
3925 fvals->reserve(5);
3927 Struct_field_list::const_iterator q = f->begin();
3928 go_assert(q->field_name() == "name");
3929 if (pf->is_anonymous())
3930 fvals->push_back(Expression::make_nil(bloc));
3931 else
3933 std::string n = Gogo::unpack_hidden_name(pf->field_name());
3934 Expression* s = Expression::make_string(n, bloc);
3935 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3938 ++q;
3939 go_assert(q->field_name() == "pkgPath");
3940 if (!Gogo::is_hidden_name(pf->field_name()))
3941 fvals->push_back(Expression::make_nil(bloc));
3942 else
3944 std::string n = Gogo::hidden_name_prefix(pf->field_name());
3945 Expression* s = Expression::make_string(n, bloc);
3946 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3949 ++q;
3950 go_assert(q->field_name() == "typ");
3951 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
3953 ++q;
3954 go_assert(q->field_name() == "tag");
3955 if (!pf->has_tag())
3956 fvals->push_back(Expression::make_nil(bloc));
3957 else
3959 Expression* s = Expression::make_string(pf->tag(), bloc);
3960 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3963 ++q;
3964 go_assert(q->field_name() == "offset");
3965 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
3967 Expression* v = Expression::make_struct_composite_literal(element_type,
3968 fvals, bloc);
3969 elements->push_back(v);
3972 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
3973 elements, bloc));
3975 return Expression::make_struct_composite_literal(stdt, vals, bloc);
3978 // Reflection string.
3980 void
3981 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
3983 ret->append("struct { ");
3985 for (Struct_field_list::const_iterator p = this->fields_->begin();
3986 p != this->fields_->end();
3987 ++p)
3989 if (p != this->fields_->begin())
3990 ret->append("; ");
3991 if (p->is_anonymous())
3992 ret->push_back('?');
3993 else
3994 ret->append(Gogo::unpack_hidden_name(p->field_name()));
3995 ret->push_back(' ');
3996 this->append_reflection(p->type(), gogo, ret);
3998 if (p->has_tag())
4000 const std::string& tag(p->tag());
4001 ret->append(" \"");
4002 for (std::string::const_iterator p = tag.begin();
4003 p != tag.end();
4004 ++p)
4006 if (*p == '\0')
4007 ret->append("\\x00");
4008 else if (*p == '\n')
4009 ret->append("\\n");
4010 else if (*p == '\t')
4011 ret->append("\\t");
4012 else if (*p == '"')
4013 ret->append("\\\"");
4014 else if (*p == '\\')
4015 ret->append("\\\\");
4016 else
4017 ret->push_back(*p);
4019 ret->push_back('"');
4023 ret->append(" }");
4026 // Mangled name.
4028 void
4029 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4031 ret->push_back('S');
4033 const Struct_field_list* fields = this->fields_;
4034 if (fields != NULL)
4036 for (Struct_field_list::const_iterator p = fields->begin();
4037 p != fields->end();
4038 ++p)
4040 if (p->is_anonymous())
4041 ret->append("0_");
4042 else
4044 std::string n = Gogo::unpack_hidden_name(p->field_name());
4045 char buf[20];
4046 snprintf(buf, sizeof buf, "%u_",
4047 static_cast<unsigned int>(n.length()));
4048 ret->append(buf);
4049 ret->append(n);
4051 this->append_mangled_name(p->type(), gogo, ret);
4052 if (p->has_tag())
4054 const std::string& tag(p->tag());
4055 std::string out;
4056 for (std::string::const_iterator p = tag.begin();
4057 p != tag.end();
4058 ++p)
4060 if (ISALNUM(*p) || *p == '_')
4061 out.push_back(*p);
4062 else
4064 char buf[20];
4065 snprintf(buf, sizeof buf, ".%x.",
4066 static_cast<unsigned int>(*p));
4067 out.append(buf);
4070 char buf[20];
4071 snprintf(buf, sizeof buf, "T%u_",
4072 static_cast<unsigned int>(out.length()));
4073 ret->append(buf);
4074 ret->append(out);
4079 ret->push_back('e');
4082 // Export.
4084 void
4085 Struct_type::do_export(Export* exp) const
4087 exp->write_c_string("struct { ");
4088 const Struct_field_list* fields = this->fields_;
4089 go_assert(fields != NULL);
4090 for (Struct_field_list::const_iterator p = fields->begin();
4091 p != fields->end();
4092 ++p)
4094 if (p->is_anonymous())
4095 exp->write_string("? ");
4096 else
4098 exp->write_string(p->field_name());
4099 exp->write_c_string(" ");
4101 exp->write_type(p->type());
4103 if (p->has_tag())
4105 exp->write_c_string(" ");
4106 Expression* expr = Expression::make_string(p->tag(),
4107 BUILTINS_LOCATION);
4108 expr->export_expression(exp);
4109 delete expr;
4112 exp->write_c_string("; ");
4114 exp->write_c_string("}");
4117 // Import.
4119 Struct_type*
4120 Struct_type::do_import(Import* imp)
4122 imp->require_c_string("struct { ");
4123 Struct_field_list* fields = new Struct_field_list;
4124 if (imp->peek_char() != '}')
4126 while (true)
4128 std::string name;
4129 if (imp->match_c_string("? "))
4130 imp->advance(2);
4131 else
4133 name = imp->read_identifier();
4134 imp->require_c_string(" ");
4136 Type* ftype = imp->read_type();
4138 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
4140 if (imp->peek_char() == ' ')
4142 imp->advance(1);
4143 Expression* expr = Expression::import_expression(imp);
4144 String_expression* sexpr = expr->string_expression();
4145 go_assert(sexpr != NULL);
4146 sf.set_tag(sexpr->val());
4147 delete sexpr;
4150 imp->require_c_string("; ");
4151 fields->push_back(sf);
4152 if (imp->peek_char() == '}')
4153 break;
4156 imp->require_c_string("}");
4158 return Type::make_struct_type(fields, imp->location());
4161 // Make a struct type.
4163 Struct_type*
4164 Type::make_struct_type(Struct_field_list* fields,
4165 source_location location)
4167 return new Struct_type(fields, location);
4170 // Class Array_type.
4172 // Whether two array types are identical.
4174 bool
4175 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
4177 if (!Type::are_identical(this->element_type(), t->element_type(),
4178 errors_are_identical, NULL))
4179 return false;
4181 Expression* l1 = this->length();
4182 Expression* l2 = t->length();
4184 // Slices of the same element type are identical.
4185 if (l1 == NULL && l2 == NULL)
4186 return true;
4188 // Arrays of the same element type are identical if they have the
4189 // same length.
4190 if (l1 != NULL && l2 != NULL)
4192 if (l1 == l2)
4193 return true;
4195 // Try to determine the lengths. If we can't, assume the arrays
4196 // are not identical.
4197 bool ret = false;
4198 mpz_t v1;
4199 mpz_init(v1);
4200 Type* type1;
4201 mpz_t v2;
4202 mpz_init(v2);
4203 Type* type2;
4204 if (l1->integer_constant_value(true, v1, &type1)
4205 && l2->integer_constant_value(true, v2, &type2))
4206 ret = mpz_cmp(v1, v2) == 0;
4207 mpz_clear(v1);
4208 mpz_clear(v2);
4209 return ret;
4212 // Otherwise the arrays are not identical.
4213 return false;
4216 // Traversal.
4219 Array_type::do_traverse(Traverse* traverse)
4221 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
4222 return TRAVERSE_EXIT;
4223 if (this->length_ != NULL
4224 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
4225 return TRAVERSE_EXIT;
4226 return TRAVERSE_CONTINUE;
4229 // Check that the length is valid.
4231 bool
4232 Array_type::verify_length()
4234 if (this->length_ == NULL)
4235 return true;
4237 Type_context context(Type::lookup_integer_type("int"), false);
4238 this->length_->determine_type(&context);
4240 if (!this->length_->is_constant())
4242 error_at(this->length_->location(), "array bound is not constant");
4243 return false;
4246 mpz_t val;
4247 mpz_init(val);
4248 Type* vt;
4249 if (!this->length_->integer_constant_value(true, val, &vt))
4251 mpfr_t fval;
4252 mpfr_init(fval);
4253 if (!this->length_->float_constant_value(fval, &vt))
4255 if (this->length_->type()->integer_type() != NULL
4256 || this->length_->type()->float_type() != NULL)
4257 error_at(this->length_->location(),
4258 "array bound is not constant");
4259 else
4260 error_at(this->length_->location(),
4261 "array bound is not numeric");
4262 mpfr_clear(fval);
4263 mpz_clear(val);
4264 return false;
4266 if (!mpfr_integer_p(fval))
4268 error_at(this->length_->location(),
4269 "array bound truncated to integer");
4270 mpfr_clear(fval);
4271 mpz_clear(val);
4272 return false;
4274 mpz_init(val);
4275 mpfr_get_z(val, fval, GMP_RNDN);
4276 mpfr_clear(fval);
4279 if (mpz_sgn(val) < 0)
4281 error_at(this->length_->location(), "negative array bound");
4282 mpz_clear(val);
4283 return false;
4286 Type* int_type = Type::lookup_integer_type("int");
4287 int tbits = int_type->integer_type()->bits();
4288 int vbits = mpz_sizeinbase(val, 2);
4289 if (vbits + 1 > tbits)
4291 error_at(this->length_->location(), "array bound overflows");
4292 mpz_clear(val);
4293 return false;
4296 mpz_clear(val);
4298 return true;
4301 // Verify the type.
4303 bool
4304 Array_type::do_verify()
4306 if (!this->verify_length())
4308 this->length_ = Expression::make_error(this->length_->location());
4309 return false;
4311 return true;
4314 // Array type hash code.
4316 unsigned int
4317 Array_type::do_hash_for_method(Gogo* gogo) const
4319 // There is no very convenient way to get a hash code for the
4320 // length.
4321 return this->element_type_->hash_for_method(gogo) + 1;
4324 // See if the expression passed to make is suitable. The first
4325 // argument is required, and gives the length. An optional second
4326 // argument is permitted for the capacity.
4328 bool
4329 Array_type::do_check_make_expression(Expression_list* args,
4330 source_location location)
4332 go_assert(this->length_ == NULL);
4333 if (args == NULL || args->empty())
4335 error_at(location, "length required when allocating a slice");
4336 return false;
4338 else if (args->size() > 2)
4340 error_at(location, "too many expressions passed to make");
4341 return false;
4343 else
4345 if (!Type::check_int_value(args->front(),
4346 _("bad length when making slice"), location))
4347 return false;
4349 if (args->size() > 1)
4351 if (!Type::check_int_value(args->back(),
4352 _("bad capacity when making slice"),
4353 location))
4354 return false;
4357 return true;
4361 // Get a tree for the length of a fixed array. The length may be
4362 // computed using a function call, so we must only evaluate it once.
4364 tree
4365 Array_type::get_length_tree(Gogo* gogo)
4367 go_assert(this->length_ != NULL);
4368 if (this->length_tree_ == NULL_TREE)
4370 mpz_t val;
4371 mpz_init(val);
4372 Type* t;
4373 if (this->length_->integer_constant_value(true, val, &t))
4375 if (t == NULL)
4376 t = Type::lookup_integer_type("int");
4377 else if (t->is_abstract())
4378 t = t->make_non_abstract_type();
4379 tree tt = t->get_tree(gogo);
4380 this->length_tree_ = Expression::integer_constant_tree(val, tt);
4381 mpz_clear(val);
4383 else
4385 mpz_clear(val);
4387 // Make up a translation context for the array length
4388 // expression. FIXME: This won't work in general.
4389 Translate_context context(gogo, NULL, NULL, NULL);
4390 tree len = this->length_->get_tree(&context);
4391 if (len != error_mark_node)
4393 len = convert_to_integer(integer_type_node, len);
4394 len = save_expr(len);
4396 this->length_tree_ = len;
4399 return this->length_tree_;
4402 // Get the backend representation of the fields of a slice. This is
4403 // not declared in types.h so that types.h doesn't have to #include
4404 // backend.h.
4406 // We use int for the count and capacity fields. This matches 6g.
4407 // The language more or less assumes that we can't allocate space of a
4408 // size which does not fit in int.
4410 static void
4411 get_backend_slice_fields(Gogo* gogo, Array_type* type,
4412 std::vector<Backend::Btyped_identifier>* bfields)
4414 bfields->resize(3);
4416 Type* pet = Type::make_pointer_type(type->element_type());
4417 Btype* pbet = tree_to_type(pet->get_tree(gogo));
4419 Backend::Btyped_identifier* p = &(*bfields)[0];
4420 p->name = "__values";
4421 p->btype = pbet;
4422 p->location = UNKNOWN_LOCATION;
4424 Type* int_type = Type::lookup_integer_type("int");
4426 p = &(*bfields)[1];
4427 p->name = "__count";
4428 p->btype = tree_to_type(int_type->get_tree(gogo));
4429 p->location = UNKNOWN_LOCATION;
4431 p = &(*bfields)[2];
4432 p->name = "__capacity";
4433 p->btype = tree_to_type(int_type->get_tree(gogo));
4434 p->location = UNKNOWN_LOCATION;
4437 // Get a tree for the type of this array. A fixed array is simply
4438 // represented as ARRAY_TYPE with the appropriate index--i.e., it is
4439 // just like an array in C. An open array is a struct with three
4440 // fields: a data pointer, the length, and the capacity.
4442 tree
4443 Array_type::do_get_tree(Gogo* gogo)
4445 if (this->length_ == NULL)
4447 std::vector<Backend::Btyped_identifier> bfields;
4448 get_backend_slice_fields(gogo, this, &bfields);
4449 return type_to_tree(gogo->backend()->struct_type(bfields));
4451 else
4453 Btype* element = this->get_backend_element(gogo);
4454 Bexpression* len = this->get_backend_length(gogo);
4455 Btype* ret = gogo->backend()->array_type(element, len);
4456 return type_to_tree(ret);
4460 // Return the backend representation of the element type.
4461 Btype*
4462 Array_type::get_backend_element(Gogo* gogo)
4464 return tree_to_type(this->element_type_->get_tree(gogo));
4467 // Return the backend representation of the length.
4469 Bexpression*
4470 Array_type::get_backend_length(Gogo* gogo)
4472 return tree_to_expr(this->get_length_tree(gogo));
4475 // Return an initializer for an array type.
4477 tree
4478 Array_type::do_get_init_tree(Gogo* gogo, tree type_tree, bool is_clear)
4480 if (this->length_ == NULL)
4482 // Open array.
4484 if (is_clear)
4485 return NULL;
4487 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
4489 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
4491 for (tree field = TYPE_FIELDS(type_tree);
4492 field != NULL_TREE;
4493 field = DECL_CHAIN(field))
4495 constructor_elt* elt = VEC_quick_push(constructor_elt, init,
4496 NULL);
4497 elt->index = field;
4498 elt->value = fold_convert(TREE_TYPE(field), size_zero_node);
4501 tree ret = build_constructor(type_tree, init);
4502 TREE_CONSTANT(ret) = 1;
4503 return ret;
4505 else
4507 // Fixed array.
4509 tree value = this->element_type_->get_init_tree(gogo, is_clear);
4510 if (value == NULL)
4511 return NULL;
4512 if (value == error_mark_node)
4513 return error_mark_node;
4515 tree length_tree = this->get_length_tree(gogo);
4516 if (length_tree == error_mark_node)
4517 return error_mark_node;
4519 length_tree = fold_convert(sizetype, length_tree);
4520 tree range = build2(RANGE_EXPR, sizetype, size_zero_node,
4521 fold_build2(MINUS_EXPR, sizetype,
4522 length_tree, size_one_node));
4523 tree ret = build_constructor_single(type_tree, range, value);
4524 if (TREE_CONSTANT(value))
4525 TREE_CONSTANT(ret) = 1;
4526 return ret;
4530 // Handle the builtin make function for a slice.
4532 tree
4533 Array_type::do_make_expression_tree(Translate_context* context,
4534 Expression_list* args,
4535 source_location location)
4537 go_assert(this->length_ == NULL);
4539 Gogo* gogo = context->gogo();
4540 tree type_tree = this->get_tree(gogo);
4541 if (type_tree == error_mark_node)
4542 return error_mark_node;
4544 tree values_field = TYPE_FIELDS(type_tree);
4545 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(values_field)),
4546 "__values") == 0);
4548 tree count_field = DECL_CHAIN(values_field);
4549 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(count_field)),
4550 "__count") == 0);
4552 tree element_type_tree = this->element_type_->get_tree(gogo);
4553 if (element_type_tree == error_mark_node)
4554 return error_mark_node;
4555 tree element_size_tree = TYPE_SIZE_UNIT(element_type_tree);
4557 tree value = this->element_type_->get_init_tree(gogo, true);
4558 if (value == error_mark_node)
4559 return error_mark_node;
4561 // The first argument is the number of elements, the optional second
4562 // argument is the capacity.
4563 go_assert(args != NULL && args->size() >= 1 && args->size() <= 2);
4565 tree length_tree = args->front()->get_tree(context);
4566 if (length_tree == error_mark_node)
4567 return error_mark_node;
4568 if (!DECL_P(length_tree))
4569 length_tree = save_expr(length_tree);
4570 if (!INTEGRAL_TYPE_P(TREE_TYPE(length_tree)))
4571 length_tree = convert_to_integer(TREE_TYPE(count_field), length_tree);
4573 tree bad_index = Expression::check_bounds(length_tree,
4574 TREE_TYPE(count_field),
4575 NULL_TREE, location);
4577 length_tree = fold_convert_loc(location, TREE_TYPE(count_field), length_tree);
4578 tree capacity_tree;
4579 if (args->size() == 1)
4580 capacity_tree = length_tree;
4581 else
4583 capacity_tree = args->back()->get_tree(context);
4584 if (capacity_tree == error_mark_node)
4585 return error_mark_node;
4586 if (!DECL_P(capacity_tree))
4587 capacity_tree = save_expr(capacity_tree);
4588 if (!INTEGRAL_TYPE_P(TREE_TYPE(capacity_tree)))
4589 capacity_tree = convert_to_integer(TREE_TYPE(count_field),
4590 capacity_tree);
4592 bad_index = Expression::check_bounds(capacity_tree,
4593 TREE_TYPE(count_field),
4594 bad_index, location);
4596 tree chktype = (((TYPE_SIZE(TREE_TYPE(capacity_tree))
4597 > TYPE_SIZE(TREE_TYPE(length_tree)))
4598 || ((TYPE_SIZE(TREE_TYPE(capacity_tree))
4599 == TYPE_SIZE(TREE_TYPE(length_tree)))
4600 && TYPE_UNSIGNED(TREE_TYPE(capacity_tree))))
4601 ? TREE_TYPE(capacity_tree)
4602 : TREE_TYPE(length_tree));
4603 tree chk = fold_build2_loc(location, LT_EXPR, boolean_type_node,
4604 fold_convert_loc(location, chktype,
4605 capacity_tree),
4606 fold_convert_loc(location, chktype,
4607 length_tree));
4608 if (bad_index == NULL_TREE)
4609 bad_index = chk;
4610 else
4611 bad_index = fold_build2_loc(location, TRUTH_OR_EXPR, boolean_type_node,
4612 bad_index, chk);
4614 capacity_tree = fold_convert_loc(location, TREE_TYPE(count_field),
4615 capacity_tree);
4618 tree size_tree = fold_build2_loc(location, MULT_EXPR, sizetype,
4619 element_size_tree,
4620 fold_convert_loc(location, sizetype,
4621 capacity_tree));
4623 tree chk = fold_build2_loc(location, TRUTH_AND_EXPR, boolean_type_node,
4624 fold_build2_loc(location, GT_EXPR,
4625 boolean_type_node,
4626 fold_convert_loc(location,
4627 sizetype,
4628 capacity_tree),
4629 size_zero_node),
4630 fold_build2_loc(location, LT_EXPR,
4631 boolean_type_node,
4632 size_tree, element_size_tree));
4633 if (bad_index == NULL_TREE)
4634 bad_index = chk;
4635 else
4636 bad_index = fold_build2_loc(location, TRUTH_OR_EXPR, boolean_type_node,
4637 bad_index, chk);
4639 tree space = context->gogo()->allocate_memory(this->element_type_,
4640 size_tree, location);
4642 if (value != NULL_TREE)
4643 space = save_expr(space);
4645 space = fold_convert(TREE_TYPE(values_field), space);
4647 if (bad_index != NULL_TREE && bad_index != boolean_false_node)
4649 tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_SLICE_OUT_OF_BOUNDS,
4650 location);
4651 space = build2(COMPOUND_EXPR, TREE_TYPE(space),
4652 build3(COND_EXPR, void_type_node,
4653 bad_index, crash, NULL_TREE),
4654 space);
4657 tree constructor = gogo->slice_constructor(type_tree, space, length_tree,
4658 capacity_tree);
4660 if (value == NULL_TREE)
4662 // The array contents are zero initialized.
4663 return constructor;
4666 // The elements must be initialized.
4668 tree max = fold_build2_loc(location, MINUS_EXPR, TREE_TYPE(count_field),
4669 capacity_tree,
4670 fold_convert_loc(location, TREE_TYPE(count_field),
4671 integer_one_node));
4673 tree array_type = build_array_type(element_type_tree,
4674 build_index_type(max));
4676 tree value_pointer = fold_convert_loc(location,
4677 build_pointer_type(array_type),
4678 space);
4680 tree range = build2(RANGE_EXPR, sizetype, size_zero_node, max);
4681 tree space_init = build_constructor_single(array_type, range, value);
4683 return build2(COMPOUND_EXPR, TREE_TYPE(constructor),
4684 build2(MODIFY_EXPR, void_type_node,
4685 build_fold_indirect_ref(value_pointer),
4686 space_init),
4687 constructor);
4690 // Return a tree for a pointer to the values in ARRAY.
4692 tree
4693 Array_type::value_pointer_tree(Gogo*, tree array) const
4695 tree ret;
4696 if (this->length() != NULL)
4698 // Fixed array.
4699 ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))),
4700 build_fold_addr_expr(array));
4702 else
4704 // Open array.
4705 tree field = TYPE_FIELDS(TREE_TYPE(array));
4706 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
4707 "__values") == 0);
4708 ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field,
4709 NULL_TREE);
4711 if (TREE_CONSTANT(array))
4712 TREE_CONSTANT(ret) = 1;
4713 return ret;
4716 // Return a tree for the length of the array ARRAY which has this
4717 // type.
4719 tree
4720 Array_type::length_tree(Gogo* gogo, tree array)
4722 if (this->length_ != NULL)
4724 if (TREE_CODE(array) == SAVE_EXPR)
4725 return fold_convert(integer_type_node, this->get_length_tree(gogo));
4726 else
4727 return omit_one_operand(integer_type_node,
4728 this->get_length_tree(gogo), array);
4731 // This is an open array. We need to read the length field.
4733 tree type = TREE_TYPE(array);
4734 go_assert(TREE_CODE(type) == RECORD_TYPE);
4736 tree field = DECL_CHAIN(TYPE_FIELDS(type));
4737 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
4739 tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
4740 if (TREE_CONSTANT(array))
4741 TREE_CONSTANT(ret) = 1;
4742 return ret;
4745 // Return a tree for the capacity of the array ARRAY which has this
4746 // type.
4748 tree
4749 Array_type::capacity_tree(Gogo* gogo, tree array)
4751 if (this->length_ != NULL)
4752 return omit_one_operand(sizetype, this->get_length_tree(gogo), array);
4754 // This is an open array. We need to read the capacity field.
4756 tree type = TREE_TYPE(array);
4757 go_assert(TREE_CODE(type) == RECORD_TYPE);
4759 tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type)));
4760 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
4762 return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
4765 // Export.
4767 void
4768 Array_type::do_export(Export* exp) const
4770 exp->write_c_string("[");
4771 if (this->length_ != NULL)
4772 this->length_->export_expression(exp);
4773 exp->write_c_string("] ");
4774 exp->write_type(this->element_type_);
4777 // Import.
4779 Array_type*
4780 Array_type::do_import(Import* imp)
4782 imp->require_c_string("[");
4783 Expression* length;
4784 if (imp->peek_char() == ']')
4785 length = NULL;
4786 else
4787 length = Expression::import_expression(imp);
4788 imp->require_c_string("] ");
4789 Type* element_type = imp->read_type();
4790 return Type::make_array_type(element_type, length);
4793 // The type of an array type descriptor.
4795 Type*
4796 Array_type::make_array_type_descriptor_type()
4798 static Type* ret;
4799 if (ret == NULL)
4801 Type* tdt = Type::make_type_descriptor_type();
4802 Type* ptdt = Type::make_type_descriptor_ptr_type();
4804 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4806 Struct_type* sf =
4807 Type::make_builtin_struct_type(3,
4808 "", tdt,
4809 "elem", ptdt,
4810 "len", uintptr_type);
4812 ret = Type::make_builtin_named_type("ArrayType", sf);
4815 return ret;
4818 // The type of an slice type descriptor.
4820 Type*
4821 Array_type::make_slice_type_descriptor_type()
4823 static Type* ret;
4824 if (ret == NULL)
4826 Type* tdt = Type::make_type_descriptor_type();
4827 Type* ptdt = Type::make_type_descriptor_ptr_type();
4829 Struct_type* sf =
4830 Type::make_builtin_struct_type(2,
4831 "", tdt,
4832 "elem", ptdt);
4834 ret = Type::make_builtin_named_type("SliceType", sf);
4837 return ret;
4840 // Build a type descriptor for an array/slice type.
4842 Expression*
4843 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4845 if (this->length_ != NULL)
4846 return this->array_type_descriptor(gogo, name);
4847 else
4848 return this->slice_type_descriptor(gogo, name);
4851 // Build a type descriptor for an array type.
4853 Expression*
4854 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
4856 source_location bloc = BUILTINS_LOCATION;
4858 Type* atdt = Array_type::make_array_type_descriptor_type();
4860 const Struct_field_list* fields = atdt->struct_type()->fields();
4862 Expression_list* vals = new Expression_list();
4863 vals->reserve(3);
4865 Struct_field_list::const_iterator p = fields->begin();
4866 go_assert(p->field_name() == "commonType");
4867 vals->push_back(this->type_descriptor_constructor(gogo,
4868 RUNTIME_TYPE_KIND_ARRAY,
4869 name, NULL, true));
4871 ++p;
4872 go_assert(p->field_name() == "elem");
4873 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
4875 ++p;
4876 go_assert(p->field_name() == "len");
4877 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
4879 ++p;
4880 go_assert(p == fields->end());
4882 return Expression::make_struct_composite_literal(atdt, vals, bloc);
4885 // Build a type descriptor for a slice type.
4887 Expression*
4888 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
4890 source_location bloc = BUILTINS_LOCATION;
4892 Type* stdt = Array_type::make_slice_type_descriptor_type();
4894 const Struct_field_list* fields = stdt->struct_type()->fields();
4896 Expression_list* vals = new Expression_list();
4897 vals->reserve(2);
4899 Struct_field_list::const_iterator p = fields->begin();
4900 go_assert(p->field_name() == "commonType");
4901 vals->push_back(this->type_descriptor_constructor(gogo,
4902 RUNTIME_TYPE_KIND_SLICE,
4903 name, NULL, true));
4905 ++p;
4906 go_assert(p->field_name() == "elem");
4907 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
4909 ++p;
4910 go_assert(p == fields->end());
4912 return Expression::make_struct_composite_literal(stdt, vals, bloc);
4915 // Reflection string.
4917 void
4918 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
4920 ret->push_back('[');
4921 if (this->length_ != NULL)
4923 mpz_t val;
4924 mpz_init(val);
4925 Type* type;
4926 if (!this->length_->integer_constant_value(true, val, &type))
4927 error_at(this->length_->location(),
4928 "array length must be integer constant expression");
4929 else if (mpz_cmp_si(val, 0) < 0)
4930 error_at(this->length_->location(), "array length is negative");
4931 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
4932 error_at(this->length_->location(), "array length is too large");
4933 else
4935 char buf[50];
4936 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
4937 ret->append(buf);
4939 mpz_clear(val);
4941 ret->push_back(']');
4943 this->append_reflection(this->element_type_, gogo, ret);
4946 // Mangled name.
4948 void
4949 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4951 ret->push_back('A');
4952 this->append_mangled_name(this->element_type_, gogo, ret);
4953 if (this->length_ != NULL)
4955 mpz_t val;
4956 mpz_init(val);
4957 Type* type;
4958 if (!this->length_->integer_constant_value(true, val, &type))
4959 error_at(this->length_->location(),
4960 "array length must be integer constant expression");
4961 else if (mpz_cmp_si(val, 0) < 0)
4962 error_at(this->length_->location(), "array length is negative");
4963 else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0)
4964 error_at(this->length_->location(), "array size is too large");
4965 else
4967 char buf[50];
4968 snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val));
4969 ret->append(buf);
4971 mpz_clear(val);
4973 ret->push_back('e');
4976 // Make an array type.
4978 Array_type*
4979 Type::make_array_type(Type* element_type, Expression* length)
4981 return new Array_type(element_type, length);
4984 // Class Map_type.
4986 // Traversal.
4989 Map_type::do_traverse(Traverse* traverse)
4991 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
4992 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
4993 return TRAVERSE_EXIT;
4994 return TRAVERSE_CONTINUE;
4997 // Check that the map type is OK.
4999 bool
5000 Map_type::do_verify()
5002 if (this->key_type_->struct_type() != NULL
5003 || this->key_type_->array_type() != NULL)
5005 error_at(this->location_, "invalid map key type");
5006 return false;
5008 return true;
5011 // Whether two map types are identical.
5013 bool
5014 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
5016 return (Type::are_identical(this->key_type(), t->key_type(),
5017 errors_are_identical, NULL)
5018 && Type::are_identical(this->val_type(), t->val_type(),
5019 errors_are_identical, NULL));
5022 // Hash code.
5024 unsigned int
5025 Map_type::do_hash_for_method(Gogo* gogo) const
5027 return (this->key_type_->hash_for_method(gogo)
5028 + this->val_type_->hash_for_method(gogo)
5029 + 2);
5032 // Check that a call to the builtin make function is valid. For a map
5033 // the optional argument is the number of spaces to preallocate for
5034 // values.
5036 bool
5037 Map_type::do_check_make_expression(Expression_list* args,
5038 source_location location)
5040 if (args != NULL && !args->empty())
5042 if (!Type::check_int_value(args->front(), _("bad size when making map"),
5043 location))
5044 return false;
5045 else if (args->size() > 1)
5047 error_at(location, "too many arguments when making map");
5048 return false;
5051 return true;
5054 // Get a tree for a map type. A map type is represented as a pointer
5055 // to a struct. The struct is __go_map in libgo/map.h.
5057 tree
5058 Map_type::do_get_tree(Gogo* gogo)
5060 static tree type_tree;
5061 if (type_tree == NULL_TREE)
5063 tree struct_type = make_node(RECORD_TYPE);
5065 tree map_descriptor_type = gogo->map_descriptor_type();
5066 tree const_map_descriptor_type =
5067 build_qualified_type(map_descriptor_type, TYPE_QUAL_CONST);
5068 tree name = get_identifier("__descriptor");
5069 tree field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name,
5070 build_pointer_type(const_map_descriptor_type));
5071 DECL_CONTEXT(field) = struct_type;
5072 TYPE_FIELDS(struct_type) = field;
5073 tree last_field = field;
5075 name = get_identifier("__element_count");
5076 field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name, sizetype);
5077 DECL_CONTEXT(field) = struct_type;
5078 DECL_CHAIN(last_field) = field;
5079 last_field = field;
5081 name = get_identifier("__bucket_count");
5082 field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name, sizetype);
5083 DECL_CONTEXT(field) = struct_type;
5084 DECL_CHAIN(last_field) = field;
5085 last_field = field;
5087 name = get_identifier("__buckets");
5088 field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name,
5089 build_pointer_type(ptr_type_node));
5090 DECL_CONTEXT(field) = struct_type;
5091 DECL_CHAIN(last_field) = field;
5093 layout_type(struct_type);
5095 // Give the struct a name for better debugging info.
5096 name = get_identifier("__go_map");
5097 tree type_decl = build_decl(BUILTINS_LOCATION, TYPE_DECL, name,
5098 struct_type);
5099 DECL_ARTIFICIAL(type_decl) = 1;
5100 TYPE_NAME(struct_type) = type_decl;
5101 go_preserve_from_gc(type_decl);
5102 rest_of_decl_compilation(type_decl, 1, 0);
5104 type_tree = build_pointer_type(struct_type);
5105 go_preserve_from_gc(type_tree);
5108 return type_tree;
5111 // Initialize a map.
5113 tree
5114 Map_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear)
5116 if (is_clear)
5117 return NULL;
5118 return fold_convert(type_tree, null_pointer_node);
5121 // Return an expression for a newly allocated map.
5123 tree
5124 Map_type::do_make_expression_tree(Translate_context* context,
5125 Expression_list* args,
5126 source_location location)
5128 tree bad_index = NULL_TREE;
5130 tree expr_tree;
5131 if (args == NULL || args->empty())
5132 expr_tree = size_zero_node;
5133 else
5135 expr_tree = args->front()->get_tree(context);
5136 if (expr_tree == error_mark_node)
5137 return error_mark_node;
5138 if (!DECL_P(expr_tree))
5139 expr_tree = save_expr(expr_tree);
5140 if (!INTEGRAL_TYPE_P(TREE_TYPE(expr_tree)))
5141 expr_tree = convert_to_integer(sizetype, expr_tree);
5142 bad_index = Expression::check_bounds(expr_tree, sizetype, bad_index,
5143 location);
5146 tree map_type = this->get_tree(context->gogo());
5148 static tree new_map_fndecl;
5149 tree ret = Gogo::call_builtin(&new_map_fndecl,
5150 location,
5151 "__go_new_map",
5153 map_type,
5154 TREE_TYPE(TYPE_FIELDS(TREE_TYPE(map_type))),
5155 context->gogo()->map_descriptor(this),
5156 sizetype,
5157 expr_tree);
5158 if (ret == error_mark_node)
5159 return error_mark_node;
5160 // This can panic if the capacity is out of range.
5161 TREE_NOTHROW(new_map_fndecl) = 0;
5163 if (bad_index == NULL_TREE)
5164 return ret;
5165 else
5167 tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_MAP_OUT_OF_BOUNDS,
5168 location);
5169 return build2(COMPOUND_EXPR, TREE_TYPE(ret),
5170 build3(COND_EXPR, void_type_node,
5171 bad_index, crash, NULL_TREE),
5172 ret);
5176 // The type of a map type descriptor.
5178 Type*
5179 Map_type::make_map_type_descriptor_type()
5181 static Type* ret;
5182 if (ret == NULL)
5184 Type* tdt = Type::make_type_descriptor_type();
5185 Type* ptdt = Type::make_type_descriptor_ptr_type();
5187 Struct_type* sf =
5188 Type::make_builtin_struct_type(3,
5189 "", tdt,
5190 "key", ptdt,
5191 "elem", ptdt);
5193 ret = Type::make_builtin_named_type("MapType", sf);
5196 return ret;
5199 // Build a type descriptor for a map type.
5201 Expression*
5202 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5204 source_location bloc = BUILTINS_LOCATION;
5206 Type* mtdt = Map_type::make_map_type_descriptor_type();
5208 const Struct_field_list* fields = mtdt->struct_type()->fields();
5210 Expression_list* vals = new Expression_list();
5211 vals->reserve(3);
5213 Struct_field_list::const_iterator p = fields->begin();
5214 go_assert(p->field_name() == "commonType");
5215 vals->push_back(this->type_descriptor_constructor(gogo,
5216 RUNTIME_TYPE_KIND_MAP,
5217 name, NULL, true));
5219 ++p;
5220 go_assert(p->field_name() == "key");
5221 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
5223 ++p;
5224 go_assert(p->field_name() == "elem");
5225 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
5227 ++p;
5228 go_assert(p == fields->end());
5230 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
5233 // Reflection string for a map.
5235 void
5236 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
5238 ret->append("map[");
5239 this->append_reflection(this->key_type_, gogo, ret);
5240 ret->append("] ");
5241 this->append_reflection(this->val_type_, gogo, ret);
5244 // Mangled name for a map.
5246 void
5247 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5249 ret->push_back('M');
5250 this->append_mangled_name(this->key_type_, gogo, ret);
5251 ret->append("__");
5252 this->append_mangled_name(this->val_type_, gogo, ret);
5255 // Export a map type.
5257 void
5258 Map_type::do_export(Export* exp) const
5260 exp->write_c_string("map [");
5261 exp->write_type(this->key_type_);
5262 exp->write_c_string("] ");
5263 exp->write_type(this->val_type_);
5266 // Import a map type.
5268 Map_type*
5269 Map_type::do_import(Import* imp)
5271 imp->require_c_string("map [");
5272 Type* key_type = imp->read_type();
5273 imp->require_c_string("] ");
5274 Type* val_type = imp->read_type();
5275 return Type::make_map_type(key_type, val_type, imp->location());
5278 // Make a map type.
5280 Map_type*
5281 Type::make_map_type(Type* key_type, Type* val_type, source_location location)
5283 return new Map_type(key_type, val_type, location);
5286 // Class Channel_type.
5288 // Hash code.
5290 unsigned int
5291 Channel_type::do_hash_for_method(Gogo* gogo) const
5293 unsigned int ret = 0;
5294 if (this->may_send_)
5295 ret += 1;
5296 if (this->may_receive_)
5297 ret += 2;
5298 if (this->element_type_ != NULL)
5299 ret += this->element_type_->hash_for_method(gogo) << 2;
5300 return ret << 3;
5303 // Whether this type is the same as T.
5305 bool
5306 Channel_type::is_identical(const Channel_type* t,
5307 bool errors_are_identical) const
5309 if (!Type::are_identical(this->element_type(), t->element_type(),
5310 errors_are_identical, NULL))
5311 return false;
5312 return (this->may_send_ == t->may_send_
5313 && this->may_receive_ == t->may_receive_);
5316 // Check whether the parameters for a call to the builtin function
5317 // make are OK for a channel. A channel can take an optional single
5318 // parameter which is the buffer size.
5320 bool
5321 Channel_type::do_check_make_expression(Expression_list* args,
5322 source_location location)
5324 if (args != NULL && !args->empty())
5326 if (!Type::check_int_value(args->front(),
5327 _("bad buffer size when making channel"),
5328 location))
5329 return false;
5330 else if (args->size() > 1)
5332 error_at(location, "too many arguments when making channel");
5333 return false;
5336 return true;
5339 // Return the tree for a channel type. A channel is a pointer to a
5340 // __go_channel struct. The __go_channel struct is defined in
5341 // libgo/runtime/channel.h.
5343 tree
5344 Channel_type::do_get_tree(Gogo*)
5346 static tree type_tree;
5347 if (type_tree == NULL_TREE)
5349 tree ret = make_node(RECORD_TYPE);
5350 TYPE_NAME(ret) = get_identifier("__go_channel");
5351 TYPE_STUB_DECL(ret) = build_decl(BUILTINS_LOCATION, TYPE_DECL, NULL_TREE,
5352 ret);
5353 type_tree = build_pointer_type(ret);
5354 go_preserve_from_gc(type_tree);
5356 return type_tree;
5359 // Initialize a channel variable.
5361 tree
5362 Channel_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear)
5364 if (is_clear)
5365 return NULL;
5366 return fold_convert(type_tree, null_pointer_node);
5369 // Handle the builtin function make for a channel.
5371 tree
5372 Channel_type::do_make_expression_tree(Translate_context* context,
5373 Expression_list* args,
5374 source_location location)
5376 Gogo* gogo = context->gogo();
5377 tree channel_type = this->get_tree(gogo);
5379 tree element_tree = this->element_type_->get_tree(gogo);
5380 tree element_size_tree = size_in_bytes(element_tree);
5382 tree bad_index = NULL_TREE;
5384 tree expr_tree;
5385 if (args == NULL || args->empty())
5386 expr_tree = size_zero_node;
5387 else
5389 expr_tree = args->front()->get_tree(context);
5390 if (expr_tree == error_mark_node)
5391 return error_mark_node;
5392 if (!DECL_P(expr_tree))
5393 expr_tree = save_expr(expr_tree);
5394 if (!INTEGRAL_TYPE_P(TREE_TYPE(expr_tree)))
5395 expr_tree = convert_to_integer(sizetype, expr_tree);
5396 bad_index = Expression::check_bounds(expr_tree, sizetype, bad_index,
5397 location);
5400 static tree new_channel_fndecl;
5401 tree ret = Gogo::call_builtin(&new_channel_fndecl,
5402 location,
5403 "__go_new_channel",
5405 channel_type,
5406 sizetype,
5407 element_size_tree,
5408 sizetype,
5409 expr_tree);
5410 if (ret == error_mark_node)
5411 return error_mark_node;
5412 // This can panic if the capacity is out of range.
5413 TREE_NOTHROW(new_channel_fndecl) = 0;
5415 if (bad_index == NULL_TREE)
5416 return ret;
5417 else
5419 tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_CHAN_OUT_OF_BOUNDS,
5420 location);
5421 return build2(COMPOUND_EXPR, TREE_TYPE(ret),
5422 build3(COND_EXPR, void_type_node,
5423 bad_index, crash, NULL_TREE),
5424 ret);
5428 // Build a type descriptor for a channel type.
5430 Type*
5431 Channel_type::make_chan_type_descriptor_type()
5433 static Type* ret;
5434 if (ret == NULL)
5436 Type* tdt = Type::make_type_descriptor_type();
5437 Type* ptdt = Type::make_type_descriptor_ptr_type();
5439 Type* uintptr_type = Type::lookup_integer_type("uintptr");
5441 Struct_type* sf =
5442 Type::make_builtin_struct_type(3,
5443 "", tdt,
5444 "elem", ptdt,
5445 "dir", uintptr_type);
5447 ret = Type::make_builtin_named_type("ChanType", sf);
5450 return ret;
5453 // Build a type descriptor for a map type.
5455 Expression*
5456 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5458 source_location bloc = BUILTINS_LOCATION;
5460 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
5462 const Struct_field_list* fields = ctdt->struct_type()->fields();
5464 Expression_list* vals = new Expression_list();
5465 vals->reserve(3);
5467 Struct_field_list::const_iterator p = fields->begin();
5468 go_assert(p->field_name() == "commonType");
5469 vals->push_back(this->type_descriptor_constructor(gogo,
5470 RUNTIME_TYPE_KIND_CHAN,
5471 name, NULL, true));
5473 ++p;
5474 go_assert(p->field_name() == "elem");
5475 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5477 ++p;
5478 go_assert(p->field_name() == "dir");
5479 // These bits must match the ones in libgo/runtime/go-type.h.
5480 int val = 0;
5481 if (this->may_receive_)
5482 val |= 1;
5483 if (this->may_send_)
5484 val |= 2;
5485 mpz_t iv;
5486 mpz_init_set_ui(iv, val);
5487 vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
5488 mpz_clear(iv);
5490 ++p;
5491 go_assert(p == fields->end());
5493 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
5496 // Reflection string.
5498 void
5499 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
5501 if (!this->may_send_)
5502 ret->append("<-");
5503 ret->append("chan");
5504 if (!this->may_receive_)
5505 ret->append("<-");
5506 ret->push_back(' ');
5507 this->append_reflection(this->element_type_, gogo, ret);
5510 // Mangled name.
5512 void
5513 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5515 ret->push_back('C');
5516 this->append_mangled_name(this->element_type_, gogo, ret);
5517 if (this->may_send_)
5518 ret->push_back('s');
5519 if (this->may_receive_)
5520 ret->push_back('r');
5521 ret->push_back('e');
5524 // Export.
5526 void
5527 Channel_type::do_export(Export* exp) const
5529 exp->write_c_string("chan ");
5530 if (this->may_send_ && !this->may_receive_)
5531 exp->write_c_string("-< ");
5532 else if (this->may_receive_ && !this->may_send_)
5533 exp->write_c_string("<- ");
5534 exp->write_type(this->element_type_);
5537 // Import.
5539 Channel_type*
5540 Channel_type::do_import(Import* imp)
5542 imp->require_c_string("chan ");
5544 bool may_send;
5545 bool may_receive;
5546 if (imp->match_c_string("-< "))
5548 imp->advance(3);
5549 may_send = true;
5550 may_receive = false;
5552 else if (imp->match_c_string("<- "))
5554 imp->advance(3);
5555 may_receive = true;
5556 may_send = false;
5558 else
5560 may_send = true;
5561 may_receive = true;
5564 Type* element_type = imp->read_type();
5566 return Type::make_channel_type(may_send, may_receive, element_type);
5569 // Make a new channel type.
5571 Channel_type*
5572 Type::make_channel_type(bool send, bool receive, Type* element_type)
5574 return new Channel_type(send, receive, element_type);
5577 // Class Interface_type.
5579 // Traversal.
5582 Interface_type::do_traverse(Traverse* traverse)
5584 if (this->methods_ == NULL)
5585 return TRAVERSE_CONTINUE;
5586 return this->methods_->traverse(traverse);
5589 // Finalize the methods. This handles interface inheritance.
5591 void
5592 Interface_type::finalize_methods()
5594 if (this->methods_ == NULL)
5595 return;
5596 std::vector<Named_type*> seen;
5597 bool is_recursive = false;
5598 size_t from = 0;
5599 size_t to = 0;
5600 while (from < this->methods_->size())
5602 const Typed_identifier* p = &this->methods_->at(from);
5603 if (!p->name().empty())
5605 size_t i;
5606 for (i = 0; i < to; ++i)
5608 if (this->methods_->at(i).name() == p->name())
5610 error_at(p->location(), "duplicate method %qs",
5611 Gogo::message_name(p->name()).c_str());
5612 break;
5615 if (i == to)
5617 if (from != to)
5618 this->methods_->set(to, *p);
5619 ++to;
5621 ++from;
5622 continue;
5625 Interface_type* it = p->type()->interface_type();
5626 if (it == NULL)
5628 error_at(p->location(), "interface contains embedded non-interface");
5629 ++from;
5630 continue;
5632 if (it == this)
5634 if (!is_recursive)
5636 error_at(p->location(), "invalid recursive interface");
5637 is_recursive = true;
5639 ++from;
5640 continue;
5643 Named_type* nt = p->type()->named_type();
5644 if (nt != NULL)
5646 std::vector<Named_type*>::const_iterator q;
5647 for (q = seen.begin(); q != seen.end(); ++q)
5649 if (*q == nt)
5651 error_at(p->location(), "inherited interface loop");
5652 break;
5655 if (q != seen.end())
5657 ++from;
5658 continue;
5660 seen.push_back(nt);
5663 const Typed_identifier_list* methods = it->methods();
5664 if (methods == NULL)
5666 ++from;
5667 continue;
5669 for (Typed_identifier_list::const_iterator q = methods->begin();
5670 q != methods->end();
5671 ++q)
5673 if (q->name().empty())
5675 if (q->type()->forwarded() == p->type()->forwarded())
5676 error_at(p->location(), "interface inheritance loop");
5677 else
5679 size_t i;
5680 for (i = from + 1; i < this->methods_->size(); ++i)
5682 const Typed_identifier* r = &this->methods_->at(i);
5683 if (r->name().empty()
5684 && r->type()->forwarded() == q->type()->forwarded())
5686 error_at(p->location(),
5687 "inherited interface listed twice");
5688 break;
5691 if (i == this->methods_->size())
5692 this->methods_->push_back(Typed_identifier(q->name(),
5693 q->type(),
5694 p->location()));
5697 else if (this->find_method(q->name()) == NULL)
5698 this->methods_->push_back(Typed_identifier(q->name(), q->type(),
5699 p->location()));
5700 else
5702 if (!is_recursive)
5703 error_at(p->location(), "inherited method %qs is ambiguous",
5704 Gogo::message_name(q->name()).c_str());
5707 ++from;
5709 if (to == 0)
5711 delete this->methods_;
5712 this->methods_ = NULL;
5714 else
5716 this->methods_->resize(to);
5717 this->methods_->sort_by_name();
5721 // Return the method NAME, or NULL.
5723 const Typed_identifier*
5724 Interface_type::find_method(const std::string& name) const
5726 if (this->methods_ == NULL)
5727 return NULL;
5728 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5729 p != this->methods_->end();
5730 ++p)
5731 if (p->name() == name)
5732 return &*p;
5733 return NULL;
5736 // Return the method index.
5738 size_t
5739 Interface_type::method_index(const std::string& name) const
5741 go_assert(this->methods_ != NULL);
5742 size_t ret = 0;
5743 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5744 p != this->methods_->end();
5745 ++p, ++ret)
5746 if (p->name() == name)
5747 return ret;
5748 go_unreachable();
5751 // Return whether NAME is an unexported method, for better error
5752 // reporting.
5754 bool
5755 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
5757 if (this->methods_ == NULL)
5758 return false;
5759 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5760 p != this->methods_->end();
5761 ++p)
5763 const std::string& method_name(p->name());
5764 if (Gogo::is_hidden_name(method_name)
5765 && name == Gogo::unpack_hidden_name(method_name)
5766 && gogo->pack_hidden_name(name, false) != method_name)
5767 return true;
5769 return false;
5772 // Whether this type is identical with T.
5774 bool
5775 Interface_type::is_identical(const Interface_type* t,
5776 bool errors_are_identical) const
5778 // We require the same methods with the same types. The methods
5779 // have already been sorted.
5780 if (this->methods() == NULL || t->methods() == NULL)
5781 return this->methods() == t->methods();
5783 Typed_identifier_list::const_iterator p1 = this->methods()->begin();
5784 for (Typed_identifier_list::const_iterator p2 = t->methods()->begin();
5785 p2 != t->methods()->end();
5786 ++p1, ++p2)
5788 if (p1 == this->methods()->end())
5789 return false;
5790 if (p1->name() != p2->name()
5791 || !Type::are_identical(p1->type(), p2->type(),
5792 errors_are_identical, NULL))
5793 return false;
5795 if (p1 != this->methods()->end())
5796 return false;
5797 return true;
5800 // Whether we can assign the interface type T to this type. The types
5801 // are known to not be identical. An interface assignment is only
5802 // permitted if T is known to implement all methods in THIS.
5803 // Otherwise a type guard is required.
5805 bool
5806 Interface_type::is_compatible_for_assign(const Interface_type* t,
5807 std::string* reason) const
5809 if (this->methods() == NULL)
5810 return true;
5811 for (Typed_identifier_list::const_iterator p = this->methods()->begin();
5812 p != this->methods()->end();
5813 ++p)
5815 const Typed_identifier* m = t->find_method(p->name());
5816 if (m == NULL)
5818 if (reason != NULL)
5820 char buf[200];
5821 snprintf(buf, sizeof buf,
5822 _("need explicit conversion; missing method %s%s%s"),
5823 open_quote, Gogo::message_name(p->name()).c_str(),
5824 close_quote);
5825 reason->assign(buf);
5827 return false;
5830 std::string subreason;
5831 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
5833 if (reason != NULL)
5835 std::string n = Gogo::message_name(p->name());
5836 size_t len = 100 + n.length() + subreason.length();
5837 char* buf = new char[len];
5838 if (subreason.empty())
5839 snprintf(buf, len, _("incompatible type for method %s%s%s"),
5840 open_quote, n.c_str(), close_quote);
5841 else
5842 snprintf(buf, len,
5843 _("incompatible type for method %s%s%s (%s)"),
5844 open_quote, n.c_str(), close_quote,
5845 subreason.c_str());
5846 reason->assign(buf);
5847 delete[] buf;
5849 return false;
5853 return true;
5856 // Hash code.
5858 unsigned int
5859 Interface_type::do_hash_for_method(Gogo* gogo) const
5861 unsigned int ret = 0;
5862 if (this->methods_ != NULL)
5864 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5865 p != this->methods_->end();
5866 ++p)
5868 ret = Type::hash_string(p->name(), ret);
5869 ret += p->type()->hash_for_method(gogo);
5870 ret <<= 1;
5873 return ret;
5876 // Return true if T implements the interface. If it does not, and
5877 // REASON is not NULL, set *REASON to a useful error message.
5879 bool
5880 Interface_type::implements_interface(const Type* t, std::string* reason) const
5882 if (this->methods_ == NULL)
5883 return true;
5885 bool is_pointer = false;
5886 const Named_type* nt = t->named_type();
5887 const Struct_type* st = t->struct_type();
5888 // If we start with a named type, we don't dereference it to find
5889 // methods.
5890 if (nt == NULL)
5892 const Type* pt = t->points_to();
5893 if (pt != NULL)
5895 // If T is a pointer to a named type, then we need to look at
5896 // the type to which it points.
5897 is_pointer = true;
5898 nt = pt->named_type();
5899 st = pt->struct_type();
5903 // If we have a named type, get the methods from it rather than from
5904 // any struct type.
5905 if (nt != NULL)
5906 st = NULL;
5908 // Only named and struct types have methods.
5909 if (nt == NULL && st == NULL)
5911 if (reason != NULL)
5913 if (t->points_to() != NULL
5914 && t->points_to()->interface_type() != NULL)
5915 reason->assign(_("pointer to interface type has no methods"));
5916 else
5917 reason->assign(_("type has no methods"));
5919 return false;
5922 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
5924 if (reason != NULL)
5926 if (t->points_to() != NULL
5927 && t->points_to()->interface_type() != NULL)
5928 reason->assign(_("pointer to interface type has no methods"));
5929 else
5930 reason->assign(_("type has no methods"));
5932 return false;
5935 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
5936 p != this->methods_->end();
5937 ++p)
5939 bool is_ambiguous = false;
5940 Method* m = (nt != NULL
5941 ? nt->method_function(p->name(), &is_ambiguous)
5942 : st->method_function(p->name(), &is_ambiguous));
5943 if (m == NULL)
5945 if (reason != NULL)
5947 std::string n = Gogo::message_name(p->name());
5948 size_t len = n.length() + 100;
5949 char* buf = new char[len];
5950 if (is_ambiguous)
5951 snprintf(buf, len, _("ambiguous method %s%s%s"),
5952 open_quote, n.c_str(), close_quote);
5953 else
5954 snprintf(buf, len, _("missing method %s%s%s"),
5955 open_quote, n.c_str(), close_quote);
5956 reason->assign(buf);
5957 delete[] buf;
5959 return false;
5962 Function_type *p_fn_type = p->type()->function_type();
5963 Function_type* m_fn_type = m->type()->function_type();
5964 go_assert(p_fn_type != NULL && m_fn_type != NULL);
5965 std::string subreason;
5966 if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
5968 if (reason != NULL)
5970 std::string n = Gogo::message_name(p->name());
5971 size_t len = 100 + n.length() + subreason.length();
5972 char* buf = new char[len];
5973 if (subreason.empty())
5974 snprintf(buf, len, _("incompatible type for method %s%s%s"),
5975 open_quote, n.c_str(), close_quote);
5976 else
5977 snprintf(buf, len,
5978 _("incompatible type for method %s%s%s (%s)"),
5979 open_quote, n.c_str(), close_quote,
5980 subreason.c_str());
5981 reason->assign(buf);
5982 delete[] buf;
5984 return false;
5987 if (!is_pointer && !m->is_value_method())
5989 if (reason != NULL)
5991 std::string n = Gogo::message_name(p->name());
5992 size_t len = 100 + n.length();
5993 char* buf = new char[len];
5994 snprintf(buf, len, _("method %s%s%s requires a pointer"),
5995 open_quote, n.c_str(), close_quote);
5996 reason->assign(buf);
5997 delete[] buf;
5999 return false;
6003 return true;
6006 // Return the backend representation of the empty interface type. We
6007 // use the same struct for all empty interfaces.
6009 Btype*
6010 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
6012 static Btype* empty_interface_type;
6013 if (empty_interface_type == NULL)
6015 std::vector<Backend::Btyped_identifier> bfields(2);
6017 Type* pdt = Type::make_type_descriptor_ptr_type();
6018 bfields[0].name = "__type_descriptor";
6019 bfields[0].btype = tree_to_type(pdt->get_tree(gogo));
6020 bfields[0].location = UNKNOWN_LOCATION;
6022 Type* vt = Type::make_pointer_type(Type::make_void_type());
6023 bfields[1].name = "__object";
6024 bfields[1].btype = tree_to_type(vt->get_tree(gogo));
6025 bfields[1].location = UNKNOWN_LOCATION;
6027 empty_interface_type = gogo->backend()->struct_type(bfields);
6029 return empty_interface_type;
6032 // Return the fields of a non-empty interface type. This is not
6033 // declared in types.h so that types.h doesn't have to #include
6034 // backend.h.
6036 static void
6037 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
6038 std::vector<Backend::Btyped_identifier>* bfields)
6040 source_location loc = type->location();
6042 std::vector<Backend::Btyped_identifier> mfields(type->methods()->size() + 1);
6044 Type* pdt = Type::make_type_descriptor_ptr_type();
6045 mfields[0].name = "__type_descriptor";
6046 mfields[0].btype = tree_to_type(pdt->get_tree(gogo));
6047 mfields[0].location = loc;
6049 std::string last_name = "";
6050 size_t i = 1;
6051 for (Typed_identifier_list::const_iterator p = type->methods()->begin();
6052 p != type->methods()->end();
6053 ++p, ++i)
6055 mfields[i].name = Gogo::unpack_hidden_name(p->name());
6056 mfields[i].btype = tree_to_type(p->type()->get_tree(gogo));
6057 mfields[i].location = loc;
6058 // Sanity check: the names should be sorted.
6059 go_assert(p->name() > last_name);
6060 last_name = p->name();
6063 Btype* methods = gogo->backend()->struct_type(mfields);
6065 bfields->resize(2);
6067 (*bfields)[0].name = "__methods";
6068 (*bfields)[0].btype = gogo->backend()->pointer_type(methods);
6069 (*bfields)[0].location = loc;
6071 Type* vt = Type::make_pointer_type(Type::make_void_type());
6072 (*bfields)[1].name = "__object";
6073 (*bfields)[1].btype = tree_to_type(vt->get_tree(gogo));
6074 (*bfields)[1].location = UNKNOWN_LOCATION;
6077 // Return a tree for an interface type. An interface is a pointer to
6078 // a struct. The struct has three fields. The first field is a
6079 // pointer to the type descriptor for the dynamic type of the object.
6080 // The second field is a pointer to a table of methods for the
6081 // interface to be used with the object. The third field is the value
6082 // of the object itself.
6084 tree
6085 Interface_type::do_get_tree(Gogo* gogo)
6087 if (this->methods_ == NULL)
6089 Btype* bt = Interface_type::get_backend_empty_interface_type(gogo);
6090 return type_to_tree(bt);
6092 else
6094 std::vector<Backend::Btyped_identifier> bfields;
6095 get_backend_interface_fields(gogo, this, &bfields);
6096 Btype* bt = gogo->backend()->struct_type(bfields);
6097 return type_to_tree(bt);
6101 // Initialization value.
6103 tree
6104 Interface_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear)
6106 if (is_clear)
6107 return NULL;
6109 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
6110 for (tree field = TYPE_FIELDS(type_tree);
6111 field != NULL_TREE;
6112 field = DECL_CHAIN(field))
6114 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
6115 elt->index = field;
6116 elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
6119 tree ret = build_constructor(type_tree, init);
6120 TREE_CONSTANT(ret) = 1;
6121 return ret;
6124 // The type of an interface type descriptor.
6126 Type*
6127 Interface_type::make_interface_type_descriptor_type()
6129 static Type* ret;
6130 if (ret == NULL)
6132 Type* tdt = Type::make_type_descriptor_type();
6133 Type* ptdt = Type::make_type_descriptor_ptr_type();
6135 Type* string_type = Type::lookup_string_type();
6136 Type* pointer_string_type = Type::make_pointer_type(string_type);
6138 Struct_type* sm =
6139 Type::make_builtin_struct_type(3,
6140 "name", pointer_string_type,
6141 "pkgPath", pointer_string_type,
6142 "typ", ptdt);
6144 Type* nsm = Type::make_builtin_named_type("imethod", sm);
6146 Type* slice_nsm = Type::make_array_type(nsm, NULL);
6148 Struct_type* s = Type::make_builtin_struct_type(2,
6149 "", tdt,
6150 "methods", slice_nsm);
6152 ret = Type::make_builtin_named_type("InterfaceType", s);
6155 return ret;
6158 // Build a type descriptor for an interface type.
6160 Expression*
6161 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6163 source_location bloc = BUILTINS_LOCATION;
6165 Type* itdt = Interface_type::make_interface_type_descriptor_type();
6167 const Struct_field_list* ifields = itdt->struct_type()->fields();
6169 Expression_list* ivals = new Expression_list();
6170 ivals->reserve(2);
6172 Struct_field_list::const_iterator pif = ifields->begin();
6173 go_assert(pif->field_name() == "commonType");
6174 ivals->push_back(this->type_descriptor_constructor(gogo,
6175 RUNTIME_TYPE_KIND_INTERFACE,
6176 name, NULL, true));
6178 ++pif;
6179 go_assert(pif->field_name() == "methods");
6181 Expression_list* methods = new Expression_list();
6182 if (this->methods_ != NULL && !this->methods_->empty())
6184 Type* elemtype = pif->type()->array_type()->element_type();
6186 methods->reserve(this->methods_->size());
6187 for (Typed_identifier_list::const_iterator pm = this->methods_->begin();
6188 pm != this->methods_->end();
6189 ++pm)
6191 const Struct_field_list* mfields = elemtype->struct_type()->fields();
6193 Expression_list* mvals = new Expression_list();
6194 mvals->reserve(3);
6196 Struct_field_list::const_iterator pmf = mfields->begin();
6197 go_assert(pmf->field_name() == "name");
6198 std::string s = Gogo::unpack_hidden_name(pm->name());
6199 Expression* e = Expression::make_string(s, bloc);
6200 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
6202 ++pmf;
6203 go_assert(pmf->field_name() == "pkgPath");
6204 if (!Gogo::is_hidden_name(pm->name()))
6205 mvals->push_back(Expression::make_nil(bloc));
6206 else
6208 s = Gogo::hidden_name_prefix(pm->name());
6209 e = Expression::make_string(s, bloc);
6210 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
6213 ++pmf;
6214 go_assert(pmf->field_name() == "typ");
6215 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
6217 ++pmf;
6218 go_assert(pmf == mfields->end());
6220 e = Expression::make_struct_composite_literal(elemtype, mvals,
6221 bloc);
6222 methods->push_back(e);
6226 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
6227 methods, bloc));
6229 ++pif;
6230 go_assert(pif == ifields->end());
6232 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
6235 // Reflection string.
6237 void
6238 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
6240 ret->append("interface {");
6241 if (this->methods_ != NULL)
6243 for (Typed_identifier_list::const_iterator p = this->methods_->begin();
6244 p != this->methods_->end();
6245 ++p)
6247 if (p != this->methods_->begin())
6248 ret->append(";");
6249 ret->push_back(' ');
6250 ret->append(Gogo::unpack_hidden_name(p->name()));
6251 std::string sub = p->type()->reflection(gogo);
6252 go_assert(sub.compare(0, 4, "func") == 0);
6253 sub = sub.substr(4);
6254 ret->append(sub);
6257 ret->append(" }");
6260 // Mangled name.
6262 void
6263 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6265 ret->push_back('I');
6267 const Typed_identifier_list* methods = this->methods_;
6268 if (methods != NULL)
6270 for (Typed_identifier_list::const_iterator p = methods->begin();
6271 p != methods->end();
6272 ++p)
6274 std::string n = Gogo::unpack_hidden_name(p->name());
6275 char buf[20];
6276 snprintf(buf, sizeof buf, "%u_",
6277 static_cast<unsigned int>(n.length()));
6278 ret->append(buf);
6279 ret->append(n);
6280 this->append_mangled_name(p->type(), gogo, ret);
6284 ret->push_back('e');
6287 // Export.
6289 void
6290 Interface_type::do_export(Export* exp) const
6292 exp->write_c_string("interface { ");
6294 const Typed_identifier_list* methods = this->methods_;
6295 if (methods != NULL)
6297 for (Typed_identifier_list::const_iterator pm = methods->begin();
6298 pm != methods->end();
6299 ++pm)
6301 exp->write_string(pm->name());
6302 exp->write_c_string(" (");
6304 const Function_type* fntype = pm->type()->function_type();
6306 bool first = true;
6307 const Typed_identifier_list* parameters = fntype->parameters();
6308 if (parameters != NULL)
6310 bool is_varargs = fntype->is_varargs();
6311 for (Typed_identifier_list::const_iterator pp =
6312 parameters->begin();
6313 pp != parameters->end();
6314 ++pp)
6316 if (first)
6317 first = false;
6318 else
6319 exp->write_c_string(", ");
6320 if (!is_varargs || pp + 1 != parameters->end())
6321 exp->write_type(pp->type());
6322 else
6324 exp->write_c_string("...");
6325 Type *pptype = pp->type();
6326 exp->write_type(pptype->array_type()->element_type());
6331 exp->write_c_string(")");
6333 const Typed_identifier_list* results = fntype->results();
6334 if (results != NULL)
6336 exp->write_c_string(" ");
6337 if (results->size() == 1)
6338 exp->write_type(results->begin()->type());
6339 else
6341 first = true;
6342 exp->write_c_string("(");
6343 for (Typed_identifier_list::const_iterator p =
6344 results->begin();
6345 p != results->end();
6346 ++p)
6348 if (first)
6349 first = false;
6350 else
6351 exp->write_c_string(", ");
6352 exp->write_type(p->type());
6354 exp->write_c_string(")");
6358 exp->write_c_string("; ");
6362 exp->write_c_string("}");
6365 // Import an interface type.
6367 Interface_type*
6368 Interface_type::do_import(Import* imp)
6370 imp->require_c_string("interface { ");
6372 Typed_identifier_list* methods = new Typed_identifier_list;
6373 while (imp->peek_char() != '}')
6375 std::string name = imp->read_identifier();
6376 imp->require_c_string(" (");
6378 Typed_identifier_list* parameters;
6379 bool is_varargs = false;
6380 if (imp->peek_char() == ')')
6381 parameters = NULL;
6382 else
6384 parameters = new Typed_identifier_list;
6385 while (true)
6387 if (imp->match_c_string("..."))
6389 imp->advance(3);
6390 is_varargs = true;
6393 Type* ptype = imp->read_type();
6394 if (is_varargs)
6395 ptype = Type::make_array_type(ptype, NULL);
6396 parameters->push_back(Typed_identifier(Import::import_marker,
6397 ptype, imp->location()));
6398 if (imp->peek_char() != ',')
6399 break;
6400 go_assert(!is_varargs);
6401 imp->require_c_string(", ");
6404 imp->require_c_string(")");
6406 Typed_identifier_list* results;
6407 if (imp->peek_char() != ' ')
6408 results = NULL;
6409 else
6411 results = new Typed_identifier_list;
6412 imp->advance(1);
6413 if (imp->peek_char() != '(')
6415 Type* rtype = imp->read_type();
6416 results->push_back(Typed_identifier(Import::import_marker,
6417 rtype, imp->location()));
6419 else
6421 imp->advance(1);
6422 while (true)
6424 Type* rtype = imp->read_type();
6425 results->push_back(Typed_identifier(Import::import_marker,
6426 rtype, imp->location()));
6427 if (imp->peek_char() != ',')
6428 break;
6429 imp->require_c_string(", ");
6431 imp->require_c_string(")");
6435 Function_type* fntype = Type::make_function_type(NULL, parameters,
6436 results,
6437 imp->location());
6438 if (is_varargs)
6439 fntype->set_is_varargs();
6440 methods->push_back(Typed_identifier(name, fntype, imp->location()));
6442 imp->require_c_string("; ");
6445 imp->require_c_string("}");
6447 if (methods->empty())
6449 delete methods;
6450 methods = NULL;
6453 return Type::make_interface_type(methods, imp->location());
6456 // Make an interface type.
6458 Interface_type*
6459 Type::make_interface_type(Typed_identifier_list* methods,
6460 source_location location)
6462 return new Interface_type(methods, location);
6465 // Class Method.
6467 // Bind a method to an object.
6469 Expression*
6470 Method::bind_method(Expression* expr, source_location location) const
6472 if (this->stub_ == NULL)
6474 // When there is no stub object, the binding is determined by
6475 // the child class.
6476 return this->do_bind_method(expr, location);
6479 Expression* func = Expression::make_func_reference(this->stub_, NULL,
6480 location);
6481 return Expression::make_bound_method(expr, func, location);
6484 // Return the named object associated with a method. This may only be
6485 // called after methods are finalized.
6487 Named_object*
6488 Method::named_object() const
6490 if (this->stub_ != NULL)
6491 return this->stub_;
6492 return this->do_named_object();
6495 // Class Named_method.
6497 // The type of the method.
6499 Function_type*
6500 Named_method::do_type() const
6502 if (this->named_object_->is_function())
6503 return this->named_object_->func_value()->type();
6504 else if (this->named_object_->is_function_declaration())
6505 return this->named_object_->func_declaration_value()->type();
6506 else
6507 go_unreachable();
6510 // Return the location of the method receiver.
6512 source_location
6513 Named_method::do_receiver_location() const
6515 return this->do_type()->receiver()->location();
6518 // Bind a method to an object.
6520 Expression*
6521 Named_method::do_bind_method(Expression* expr, source_location location) const
6523 Expression* func = Expression::make_func_reference(this->named_object_, NULL,
6524 location);
6525 Bound_method_expression* bme = Expression::make_bound_method(expr, func,
6526 location);
6527 // If this is not a local method, and it does not use a stub, then
6528 // the real method expects a different type. We need to cast the
6529 // first argument.
6530 if (this->depth() > 0 && !this->needs_stub_method())
6532 Function_type* ftype = this->do_type();
6533 go_assert(ftype->is_method());
6534 Type* frtype = ftype->receiver()->type();
6535 bme->set_first_argument_type(frtype);
6537 return bme;
6540 // Class Interface_method.
6542 // Bind a method to an object.
6544 Expression*
6545 Interface_method::do_bind_method(Expression* expr,
6546 source_location location) const
6548 return Expression::make_interface_field_reference(expr, this->name_,
6549 location);
6552 // Class Methods.
6554 // Insert a new method. Return true if it was inserted, false
6555 // otherwise.
6557 bool
6558 Methods::insert(const std::string& name, Method* m)
6560 std::pair<Method_map::iterator, bool> ins =
6561 this->methods_.insert(std::make_pair(name, m));
6562 if (ins.second)
6563 return true;
6564 else
6566 Method* old_method = ins.first->second;
6567 if (m->depth() < old_method->depth())
6569 delete old_method;
6570 ins.first->second = m;
6571 return true;
6573 else
6575 if (m->depth() == old_method->depth())
6576 old_method->set_is_ambiguous();
6577 return false;
6582 // Return the number of unambiguous methods.
6584 size_t
6585 Methods::count() const
6587 size_t ret = 0;
6588 for (Method_map::const_iterator p = this->methods_.begin();
6589 p != this->methods_.end();
6590 ++p)
6591 if (!p->second->is_ambiguous())
6592 ++ret;
6593 return ret;
6596 // Class Named_type.
6598 // Return the name of the type.
6600 const std::string&
6601 Named_type::name() const
6603 return this->named_object_->name();
6606 // Return the name of the type to use in an error message.
6608 std::string
6609 Named_type::message_name() const
6611 return this->named_object_->message_name();
6614 // Return the base type for this type. We have to be careful about
6615 // circular type definitions, which are invalid but may be seen here.
6617 Type*
6618 Named_type::named_base()
6620 if (this->seen_ > 0)
6621 return this;
6622 ++this->seen_;
6623 Type* ret = this->type_->base();
6624 --this->seen_;
6625 return ret;
6628 const Type*
6629 Named_type::named_base() const
6631 if (this->seen_ > 0)
6632 return this;
6633 ++this->seen_;
6634 const Type* ret = this->type_->base();
6635 --this->seen_;
6636 return ret;
6639 // Return whether this is an error type. We have to be careful about
6640 // circular type definitions, which are invalid but may be seen here.
6642 bool
6643 Named_type::is_named_error_type() const
6645 if (this->seen_ > 0)
6646 return false;
6647 ++this->seen_;
6648 bool ret = this->type_->is_error_type();
6649 --this->seen_;
6650 return ret;
6653 // Add a method to this type.
6655 Named_object*
6656 Named_type::add_method(const std::string& name, Function* function)
6658 if (this->local_methods_ == NULL)
6659 this->local_methods_ = new Bindings(NULL);
6660 return this->local_methods_->add_function(name, NULL, function);
6663 // Add a method declaration to this type.
6665 Named_object*
6666 Named_type::add_method_declaration(const std::string& name, Package* package,
6667 Function_type* type,
6668 source_location location)
6670 if (this->local_methods_ == NULL)
6671 this->local_methods_ = new Bindings(NULL);
6672 return this->local_methods_->add_function_declaration(name, package, type,
6673 location);
6676 // Add an existing method to this type.
6678 void
6679 Named_type::add_existing_method(Named_object* no)
6681 if (this->local_methods_ == NULL)
6682 this->local_methods_ = new Bindings(NULL);
6683 this->local_methods_->add_named_object(no);
6686 // Look for a local method NAME, and returns its named object, or NULL
6687 // if not there.
6689 Named_object*
6690 Named_type::find_local_method(const std::string& name) const
6692 if (this->local_methods_ == NULL)
6693 return NULL;
6694 return this->local_methods_->lookup(name);
6697 // Return whether NAME is an unexported field or method, for better
6698 // error reporting.
6700 bool
6701 Named_type::is_unexported_local_method(Gogo* gogo,
6702 const std::string& name) const
6704 Bindings* methods = this->local_methods_;
6705 if (methods != NULL)
6707 for (Bindings::const_declarations_iterator p =
6708 methods->begin_declarations();
6709 p != methods->end_declarations();
6710 ++p)
6712 if (Gogo::is_hidden_name(p->first)
6713 && name == Gogo::unpack_hidden_name(p->first)
6714 && gogo->pack_hidden_name(name, false) != p->first)
6715 return true;
6718 return false;
6721 // Build the complete list of methods for this type, which means
6722 // recursively including all methods for anonymous fields. Create all
6723 // stub methods.
6725 void
6726 Named_type::finalize_methods(Gogo* gogo)
6728 if (this->all_methods_ != NULL)
6729 return;
6731 if (this->local_methods_ != NULL
6732 && (this->points_to() != NULL || this->interface_type() != NULL))
6734 const Bindings* lm = this->local_methods_;
6735 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
6736 p != lm->end_declarations();
6737 ++p)
6738 error_at(p->second->location(),
6739 "invalid pointer or interface receiver type");
6740 delete this->local_methods_;
6741 this->local_methods_ = NULL;
6742 return;
6745 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6748 // Return the method NAME, or NULL if there isn't one or if it is
6749 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6750 // ambiguous.
6752 Method*
6753 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
6755 return Type::method_function(this->all_methods_, name, is_ambiguous);
6758 // Return a pointer to the interface method table for this type for
6759 // the interface INTERFACE. IS_POINTER is true if this is for a
6760 // pointer to THIS.
6762 tree
6763 Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface,
6764 bool is_pointer)
6766 go_assert(!interface->is_empty());
6768 Interface_method_tables** pimt = (is_pointer
6769 ? &this->interface_method_tables_
6770 : &this->pointer_interface_method_tables_);
6772 if (*pimt == NULL)
6773 *pimt = new Interface_method_tables(5);
6775 std::pair<const Interface_type*, tree> val(interface, NULL_TREE);
6776 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
6778 if (ins.second)
6780 // This is a new entry in the hash table.
6781 go_assert(ins.first->second == NULL_TREE);
6782 ins.first->second = gogo->interface_method_table_for_type(interface,
6783 this,
6784 is_pointer);
6787 tree decl = ins.first->second;
6788 if (decl == error_mark_node)
6789 return error_mark_node;
6790 go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL);
6791 return build_fold_addr_expr(decl);
6794 // Return whether a named type has any hidden fields.
6796 bool
6797 Named_type::named_type_has_hidden_fields(std::string* reason) const
6799 if (this->seen_ > 0)
6800 return false;
6801 ++this->seen_;
6802 bool ret = this->type_->has_hidden_fields(this, reason);
6803 --this->seen_;
6804 return ret;
6807 // Look for a use of a complete type within another type. This is
6808 // used to check that we don't try to use a type within itself.
6810 class Find_type_use : public Traverse
6812 public:
6813 Find_type_use(Named_type* find_type)
6814 : Traverse(traverse_types),
6815 find_type_(find_type), found_(false)
6818 // Whether we found the type.
6819 bool
6820 found() const
6821 { return this->found_; }
6823 protected:
6825 type(Type*);
6827 private:
6828 // The type we are looking for.
6829 Named_type* find_type_;
6830 // Whether we found the type.
6831 bool found_;
6834 // Check for FIND_TYPE in TYPE.
6837 Find_type_use::type(Type* type)
6839 if (type->named_type() != NULL && this->find_type_ == type->named_type())
6841 this->found_ = true;
6842 return TRAVERSE_EXIT;
6845 // It's OK if we see a reference to the type in any type which is
6846 // essentially a pointer: a pointer, a slice, a function, a map, or
6847 // a channel.
6848 if (type->points_to() != NULL
6849 || type->is_open_array_type()
6850 || type->function_type() != NULL
6851 || type->map_type() != NULL
6852 || type->channel_type() != NULL)
6853 return TRAVERSE_SKIP_COMPONENTS;
6855 // For an interface, a reference to the type in a method type should
6856 // be ignored, but we have to consider direct inheritance. When
6857 // this is called, there may be cases of direct inheritance
6858 // represented as a method with no name.
6859 if (type->interface_type() != NULL)
6861 const Typed_identifier_list* methods = type->interface_type()->methods();
6862 if (methods != NULL)
6864 for (Typed_identifier_list::const_iterator p = methods->begin();
6865 p != methods->end();
6866 ++p)
6868 if (p->name().empty())
6870 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
6871 return TRAVERSE_EXIT;
6875 return TRAVERSE_SKIP_COMPONENTS;
6878 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
6879 // to convert TYPE to the backend representation before we convert
6880 // FIND_TYPE_.
6881 if (type->named_type() != NULL)
6883 switch (type->base()->classification())
6885 case Type::TYPE_ERROR:
6886 case Type::TYPE_BOOLEAN:
6887 case Type::TYPE_INTEGER:
6888 case Type::TYPE_FLOAT:
6889 case Type::TYPE_COMPLEX:
6890 case Type::TYPE_STRING:
6891 case Type::TYPE_NIL:
6892 break;
6894 case Type::TYPE_ARRAY:
6895 case Type::TYPE_STRUCT:
6896 this->find_type_->add_dependency(type->named_type());
6897 break;
6899 case Type::TYPE_VOID:
6900 case Type::TYPE_SINK:
6901 case Type::TYPE_FUNCTION:
6902 case Type::TYPE_POINTER:
6903 case Type::TYPE_CALL_MULTIPLE_RESULT:
6904 case Type::TYPE_MAP:
6905 case Type::TYPE_CHANNEL:
6906 case Type::TYPE_INTERFACE:
6907 case Type::TYPE_NAMED:
6908 case Type::TYPE_FORWARD:
6909 default:
6910 go_unreachable();
6914 return TRAVERSE_CONTINUE;
6917 // Verify that a named type does not refer to itself.
6919 bool
6920 Named_type::do_verify()
6922 Find_type_use find(this);
6923 Type::traverse(this->type_, &find);
6924 if (find.found())
6926 error_at(this->location_, "invalid recursive type %qs",
6927 this->message_name().c_str());
6928 this->is_error_ = true;
6929 return false;
6932 // Check whether any of the local methods overloads an existing
6933 // struct field or interface method. We don't need to check the
6934 // list of methods against itself: that is handled by the Bindings
6935 // code.
6936 if (this->local_methods_ != NULL)
6938 Struct_type* st = this->type_->struct_type();
6939 bool found_dup = false;
6940 if (st != NULL)
6942 for (Bindings::const_declarations_iterator p =
6943 this->local_methods_->begin_declarations();
6944 p != this->local_methods_->end_declarations();
6945 ++p)
6947 const std::string& name(p->first);
6948 if (st != NULL && st->find_local_field(name, NULL) != NULL)
6950 error_at(p->second->location(),
6951 "method %qs redeclares struct field name",
6952 Gogo::message_name(name).c_str());
6953 found_dup = true;
6957 if (found_dup)
6958 return false;
6961 return true;
6964 // Return whether this type is or contains a pointer.
6966 bool
6967 Named_type::do_has_pointer() const
6969 if (this->seen_ > 0)
6970 return false;
6971 ++this->seen_;
6972 bool ret = this->type_->has_pointer();
6973 --this->seen_;
6974 return ret;
6977 // Return a hash code. This is used for method lookup. We simply
6978 // hash on the name itself.
6980 unsigned int
6981 Named_type::do_hash_for_method(Gogo* gogo) const
6983 const std::string& name(this->named_object()->name());
6984 unsigned int ret = Type::hash_string(name, 0);
6986 // GOGO will be NULL here when called from Type_hash_identical.
6987 // That is OK because that is only used for internal hash tables
6988 // where we are going to be comparing named types for equality. In
6989 // other cases, which are cases where the runtime is going to
6990 // compare hash codes to see if the types are the same, we need to
6991 // include the package prefix and name in the hash.
6992 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
6994 const Package* package = this->named_object()->package();
6995 if (package == NULL)
6997 ret = Type::hash_string(gogo->unique_prefix(), ret);
6998 ret = Type::hash_string(gogo->package_name(), ret);
7000 else
7002 ret = Type::hash_string(package->unique_prefix(), ret);
7003 ret = Type::hash_string(package->name(), ret);
7007 return ret;
7010 // Convert a named type to the backend representation. In order to
7011 // get dependencies right, we fill in a dummy structure for this type,
7012 // then convert all the dependencies, then complete this type. When
7013 // this function is complete, the size of the type is known.
7015 void
7016 Named_type::convert(Gogo* gogo)
7018 if (this->is_error_ || this->is_converted_)
7019 return;
7021 this->create_placeholder(gogo);
7023 // Convert all the dependencies. If they refer indirectly back to
7024 // this type, they will pick up the intermediate tree we just
7025 // created.
7026 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
7027 p != this->dependencies_.end();
7028 ++p)
7029 (*p)->convert(gogo);
7031 // Complete this type.
7032 Btype* bt = this->named_btype_;
7033 Type* base = this->type_->base();
7034 switch (base->classification())
7036 case TYPE_VOID:
7037 case TYPE_BOOLEAN:
7038 case TYPE_INTEGER:
7039 case TYPE_FLOAT:
7040 case TYPE_COMPLEX:
7041 case TYPE_STRING:
7042 case TYPE_NIL:
7043 break;
7045 case TYPE_MAP:
7046 case TYPE_CHANNEL:
7047 break;
7049 case TYPE_FUNCTION:
7050 case TYPE_POINTER:
7051 // The size of these types is already correct. We don't worry
7052 // about filling them in until later, when we also track
7053 // circular references.
7054 break;
7056 case TYPE_STRUCT:
7058 std::vector<Backend::Btyped_identifier> bfields;
7059 get_backend_struct_fields(gogo, base->struct_type()->fields(),
7060 &bfields);
7061 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
7062 bt = gogo->backend()->error_type();
7064 break;
7066 case TYPE_ARRAY:
7067 // Slice types were completed in create_placeholder.
7068 if (!base->is_open_array_type())
7070 Btype* bet = base->array_type()->get_backend_element(gogo);
7071 Bexpression* blen = base->array_type()->get_backend_length(gogo);
7072 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
7073 bt = gogo->backend()->error_type();
7075 break;
7077 case TYPE_INTERFACE:
7078 // Interface types were completed in create_placeholder.
7079 break;
7081 case TYPE_ERROR:
7082 return;
7084 default:
7085 case TYPE_SINK:
7086 case TYPE_CALL_MULTIPLE_RESULT:
7087 case TYPE_NAMED:
7088 case TYPE_FORWARD:
7089 go_unreachable();
7092 this->named_btype_ = bt;
7093 this->is_converted_ = true;
7096 // Create the placeholder for a named type. This is the first step in
7097 // converting to the backend representation.
7099 void
7100 Named_type::create_placeholder(Gogo* gogo)
7102 if (this->is_error_)
7103 this->named_btype_ = gogo->backend()->error_type();
7105 if (this->named_btype_ != NULL)
7106 return;
7108 // Create the structure for this type. Note that because we call
7109 // base() here, we don't attempt to represent a named type defined
7110 // as another named type. Instead both named types will point to
7111 // different base representations.
7112 Type* base = this->type_->base();
7113 Btype* bt;
7114 bool set_name = true;
7115 switch (base->classification())
7117 case TYPE_ERROR:
7118 this->is_error_ = true;
7119 this->named_btype_ = gogo->backend()->error_type();
7120 return;
7122 case TYPE_VOID:
7123 case TYPE_BOOLEAN:
7124 case TYPE_INTEGER:
7125 case TYPE_FLOAT:
7126 case TYPE_COMPLEX:
7127 case TYPE_STRING:
7128 case TYPE_NIL:
7129 // These are simple basic types, we can just create them
7130 // directly.
7131 bt = Type::get_named_base_btype(gogo, base);
7132 break;
7134 case TYPE_MAP:
7135 case TYPE_CHANNEL:
7136 // All maps and channels have the same backend representation.
7137 bt = Type::get_named_base_btype(gogo, base);
7138 break;
7140 case TYPE_FUNCTION:
7141 case TYPE_POINTER:
7143 bool for_function = base->classification() == TYPE_FUNCTION;
7144 bt = gogo->backend()->placeholder_pointer_type(this->name(),
7145 this->location_,
7146 for_function);
7147 set_name = false;
7149 break;
7151 case TYPE_STRUCT:
7152 bt = gogo->backend()->placeholder_struct_type(this->name(),
7153 this->location_);
7154 set_name = false;
7155 break;
7157 case TYPE_ARRAY:
7158 if (base->is_open_array_type())
7159 bt = gogo->backend()->placeholder_struct_type(this->name(),
7160 this->location_);
7161 else
7162 bt = gogo->backend()->placeholder_array_type(this->name(),
7163 this->location_);
7164 set_name = false;
7165 break;
7167 case TYPE_INTERFACE:
7168 if (base->interface_type()->is_empty())
7169 bt = Interface_type::get_backend_empty_interface_type(gogo);
7170 else
7172 bt = gogo->backend()->placeholder_struct_type(this->name(),
7173 this->location_);
7174 set_name = false;
7176 break;
7178 default:
7179 case TYPE_SINK:
7180 case TYPE_CALL_MULTIPLE_RESULT:
7181 case TYPE_NAMED:
7182 case TYPE_FORWARD:
7183 go_unreachable();
7186 if (set_name)
7187 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
7189 this->named_btype_ = bt;
7191 if (base->is_open_array_type())
7193 // We do not record slices as dependencies of other types,
7194 // because we can fill them in completely here with the final
7195 // size.
7196 std::vector<Backend::Btyped_identifier> bfields;
7197 get_backend_slice_fields(gogo, base->array_type(), &bfields);
7198 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
7199 this->named_btype_ = gogo->backend()->error_type();
7201 else if (base->interface_type() != NULL
7202 && !base->interface_type()->is_empty())
7204 // We do not record interfaces as dependencies of other types,
7205 // because we can fill them in completely here with the final
7206 // size.
7207 std::vector<Backend::Btyped_identifier> bfields;
7208 get_backend_interface_fields(gogo, base->interface_type(), &bfields);
7209 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
7210 this->named_btype_ = gogo->backend()->error_type();
7214 // Get a tree for a named type.
7216 tree
7217 Named_type::do_get_tree(Gogo* gogo)
7219 if (this->is_error_)
7220 return error_mark_node;
7222 Btype* bt = this->named_btype_;
7224 if (!gogo->named_types_are_converted())
7226 // We have not completed converting named types. NAMED_BTYPE_
7227 // is a placeholder and we shouldn't do anything further.
7228 if (bt != NULL)
7229 return type_to_tree(bt);
7231 // We don't build dependencies for types whose sizes do not
7232 // change or are not relevant, so we may see them here while
7233 // converting types.
7234 this->create_placeholder(gogo);
7235 bt = this->named_btype_;
7236 go_assert(bt != NULL);
7237 return type_to_tree(bt);
7240 // We are not converting types. This should only be called if the
7241 // type has already been converted.
7242 if (!this->is_converted_)
7244 go_assert(saw_errors());
7245 return error_mark_node;
7248 go_assert(bt != NULL);
7250 // Complete the tree.
7251 Type* base = this->type_->base();
7252 Btype* bt1;
7253 switch (base->classification())
7255 case TYPE_ERROR:
7256 return error_mark_node;
7258 case TYPE_VOID:
7259 case TYPE_BOOLEAN:
7260 case TYPE_INTEGER:
7261 case TYPE_FLOAT:
7262 case TYPE_COMPLEX:
7263 case TYPE_STRING:
7264 case TYPE_NIL:
7265 case TYPE_MAP:
7266 case TYPE_CHANNEL:
7267 case TYPE_STRUCT:
7268 case TYPE_ARRAY:
7269 case TYPE_INTERFACE:
7270 return type_to_tree(bt);
7272 case TYPE_FUNCTION:
7273 // Don't build a circular data structure. GENERIC can't handle
7274 // it.
7275 if (this->seen_ > 0)
7277 this->is_circular_ = true;
7278 bt1 = gogo->backend()->circular_pointer_type(bt, true);
7279 return type_to_tree(bt1);
7281 ++this->seen_;
7282 bt1 = Type::get_named_base_btype(gogo, base);
7283 --this->seen_;
7284 if (this->is_circular_)
7285 bt1 = gogo->backend()->circular_pointer_type(bt, true);
7286 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
7287 bt = gogo->backend()->error_type();
7288 return type_to_tree(bt);
7290 case TYPE_POINTER:
7291 // Don't build a circular data structure. GENERIC can't handle
7292 // it.
7293 if (this->seen_ > 0)
7295 this->is_circular_ = true;
7296 bt1 = gogo->backend()->circular_pointer_type(bt, false);
7297 return type_to_tree(bt1);
7299 ++this->seen_;
7300 bt1 = Type::get_named_base_btype(gogo, base);
7301 --this->seen_;
7302 if (this->is_circular_)
7303 bt1 = gogo->backend()->circular_pointer_type(bt, false);
7304 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
7305 bt = gogo->backend()->error_type();
7306 return type_to_tree(bt);
7308 default:
7309 case TYPE_SINK:
7310 case TYPE_CALL_MULTIPLE_RESULT:
7311 case TYPE_NAMED:
7312 case TYPE_FORWARD:
7313 go_unreachable();
7316 go_unreachable();
7319 // Build a type descriptor for a named type.
7321 Expression*
7322 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7324 // If NAME is not NULL, then we don't really want the type
7325 // descriptor for this type; we want the descriptor for the
7326 // underlying type, giving it the name NAME.
7327 return this->named_type_descriptor(gogo, this->type_,
7328 name == NULL ? this : name);
7331 // Add to the reflection string. This is used mostly for the name of
7332 // the type used in a type descriptor, not for actual reflection
7333 // strings.
7335 void
7336 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
7338 if (this->location() != BUILTINS_LOCATION)
7340 const Package* package = this->named_object_->package();
7341 if (package != NULL)
7342 ret->append(package->name());
7343 else
7344 ret->append(gogo->package_name());
7345 ret->push_back('.');
7347 if (this->in_function_ != NULL)
7349 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
7350 ret->push_back('$');
7352 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
7355 // Get the mangled name.
7357 void
7358 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7360 Named_object* no = this->named_object_;
7361 std::string name;
7362 if (this->location() == BUILTINS_LOCATION)
7363 go_assert(this->in_function_ == NULL);
7364 else
7366 const std::string& unique_prefix(no->package() == NULL
7367 ? gogo->unique_prefix()
7368 : no->package()->unique_prefix());
7369 const std::string& package_name(no->package() == NULL
7370 ? gogo->package_name()
7371 : no->package()->name());
7372 name = unique_prefix;
7373 name.append(1, '.');
7374 name.append(package_name);
7375 name.append(1, '.');
7376 if (this->in_function_ != NULL)
7378 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
7379 name.append(1, '$');
7382 name.append(Gogo::unpack_hidden_name(no->name()));
7383 char buf[20];
7384 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
7385 ret->append(buf);
7386 ret->append(name);
7389 // Export the type. This is called to export a global type.
7391 void
7392 Named_type::export_named_type(Export* exp, const std::string&) const
7394 // We don't need to write the name of the type here, because it will
7395 // be written by Export::write_type anyhow.
7396 exp->write_c_string("type ");
7397 exp->write_type(this);
7398 exp->write_c_string(";\n");
7401 // Import a named type.
7403 void
7404 Named_type::import_named_type(Import* imp, Named_type** ptype)
7406 imp->require_c_string("type ");
7407 Type *type = imp->read_type();
7408 *ptype = type->named_type();
7409 go_assert(*ptype != NULL);
7410 imp->require_c_string(";\n");
7413 // Export the type when it is referenced by another type. In this
7414 // case Export::export_type will already have issued the name.
7416 void
7417 Named_type::do_export(Export* exp) const
7419 exp->write_type(this->type_);
7421 // To save space, we only export the methods directly attached to
7422 // this type.
7423 Bindings* methods = this->local_methods_;
7424 if (methods == NULL)
7425 return;
7427 exp->write_c_string("\n");
7428 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
7429 p != methods->end_definitions();
7430 ++p)
7432 exp->write_c_string(" ");
7433 (*p)->export_named_object(exp);
7436 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
7437 p != methods->end_declarations();
7438 ++p)
7440 if (p->second->is_function_declaration())
7442 exp->write_c_string(" ");
7443 p->second->export_named_object(exp);
7448 // Make a named type.
7450 Named_type*
7451 Type::make_named_type(Named_object* named_object, Type* type,
7452 source_location location)
7454 return new Named_type(named_object, type, location);
7457 // Finalize the methods for TYPE. It will be a named type or a struct
7458 // type. This sets *ALL_METHODS to the list of methods, and builds
7459 // all required stubs.
7461 void
7462 Type::finalize_methods(Gogo* gogo, const Type* type, source_location location,
7463 Methods** all_methods)
7465 *all_methods = NULL;
7466 Types_seen types_seen;
7467 Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen,
7468 all_methods);
7469 Type::build_stub_methods(gogo, type, *all_methods, location);
7472 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
7473 // build up the struct field indexes as we go. DEPTH is the depth of
7474 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
7475 // adding these methods for an anonymous field with pointer type.
7476 // NEEDS_STUB_METHOD is true if we need to use a stub method which
7477 // calls the real method. TYPES_SEEN is used to avoid infinite
7478 // recursion.
7480 void
7481 Type::add_methods_for_type(const Type* type,
7482 const Method::Field_indexes* field_indexes,
7483 unsigned int depth,
7484 bool is_embedded_pointer,
7485 bool needs_stub_method,
7486 Types_seen* types_seen,
7487 Methods** methods)
7489 // Pointer types may not have methods.
7490 if (type->points_to() != NULL)
7491 return;
7493 const Named_type* nt = type->named_type();
7494 if (nt != NULL)
7496 std::pair<Types_seen::iterator, bool> ins = types_seen->insert(nt);
7497 if (!ins.second)
7498 return;
7501 if (nt != NULL)
7502 Type::add_local_methods_for_type(nt, field_indexes, depth,
7503 is_embedded_pointer, needs_stub_method,
7504 methods);
7506 Type::add_embedded_methods_for_type(type, field_indexes, depth,
7507 is_embedded_pointer, needs_stub_method,
7508 types_seen, methods);
7510 // If we are called with depth > 0, then we are looking at an
7511 // anonymous field of a struct. If such a field has interface type,
7512 // then we need to add the interface methods. We don't want to add
7513 // them when depth == 0, because we will already handle them
7514 // following the usual rules for an interface type.
7515 if (depth > 0)
7516 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
7519 // Add the local methods for the named type NT to *METHODS. The
7520 // parameters are as for add_methods_to_type.
7522 void
7523 Type::add_local_methods_for_type(const Named_type* nt,
7524 const Method::Field_indexes* field_indexes,
7525 unsigned int depth,
7526 bool is_embedded_pointer,
7527 bool needs_stub_method,
7528 Methods** methods)
7530 const Bindings* local_methods = nt->local_methods();
7531 if (local_methods == NULL)
7532 return;
7534 if (*methods == NULL)
7535 *methods = new Methods();
7537 for (Bindings::const_declarations_iterator p =
7538 local_methods->begin_declarations();
7539 p != local_methods->end_declarations();
7540 ++p)
7542 Named_object* no = p->second;
7543 bool is_value_method = (is_embedded_pointer
7544 || !Type::method_expects_pointer(no));
7545 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
7546 (needs_stub_method
7547 || (depth > 0 && is_value_method)));
7548 if (!(*methods)->insert(no->name(), m))
7549 delete m;
7553 // Add the embedded methods for TYPE to *METHODS. These are the
7554 // methods attached to anonymous fields. The parameters are as for
7555 // add_methods_to_type.
7557 void
7558 Type::add_embedded_methods_for_type(const Type* type,
7559 const Method::Field_indexes* field_indexes,
7560 unsigned int depth,
7561 bool is_embedded_pointer,
7562 bool needs_stub_method,
7563 Types_seen* types_seen,
7564 Methods** methods)
7566 // Look for anonymous fields in TYPE. TYPE has fields if it is a
7567 // struct.
7568 const Struct_type* st = type->struct_type();
7569 if (st == NULL)
7570 return;
7572 const Struct_field_list* fields = st->fields();
7573 if (fields == NULL)
7574 return;
7576 unsigned int i = 0;
7577 for (Struct_field_list::const_iterator pf = fields->begin();
7578 pf != fields->end();
7579 ++pf, ++i)
7581 if (!pf->is_anonymous())
7582 continue;
7584 Type* ftype = pf->type();
7585 bool is_pointer = false;
7586 if (ftype->points_to() != NULL)
7588 ftype = ftype->points_to();
7589 is_pointer = true;
7591 Named_type* fnt = ftype->named_type();
7592 if (fnt == NULL)
7594 // This is an error, but it will be diagnosed elsewhere.
7595 continue;
7598 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
7599 sub_field_indexes->next = field_indexes;
7600 sub_field_indexes->field_index = i;
7602 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
7603 (is_embedded_pointer || is_pointer),
7604 (needs_stub_method
7605 || is_pointer
7606 || i > 0),
7607 types_seen,
7608 methods);
7612 // If TYPE is an interface type, then add its method to *METHODS.
7613 // This is for interface methods attached to an anonymous field. The
7614 // parameters are as for add_methods_for_type.
7616 void
7617 Type::add_interface_methods_for_type(const Type* type,
7618 const Method::Field_indexes* field_indexes,
7619 unsigned int depth,
7620 Methods** methods)
7622 const Interface_type* it = type->interface_type();
7623 if (it == NULL)
7624 return;
7626 const Typed_identifier_list* imethods = it->methods();
7627 if (imethods == NULL)
7628 return;
7630 if (*methods == NULL)
7631 *methods = new Methods();
7633 for (Typed_identifier_list::const_iterator pm = imethods->begin();
7634 pm != imethods->end();
7635 ++pm)
7637 Function_type* fntype = pm->type()->function_type();
7638 if (fntype == NULL)
7640 // This is an error, but it should be reported elsewhere
7641 // when we look at the methods for IT.
7642 continue;
7644 go_assert(!fntype->is_method());
7645 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
7646 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
7647 field_indexes, depth);
7648 if (!(*methods)->insert(pm->name(), m))
7649 delete m;
7653 // Build stub methods for TYPE as needed. METHODS is the set of
7654 // methods for the type. A stub method may be needed when a type
7655 // inherits a method from an anonymous field. When we need the
7656 // address of the method, as in a type descriptor, we need to build a
7657 // little stub which does the required field dereferences and jumps to
7658 // the real method. LOCATION is the location of the type definition.
7660 void
7661 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
7662 source_location location)
7664 if (methods == NULL)
7665 return;
7666 for (Methods::const_iterator p = methods->begin();
7667 p != methods->end();
7668 ++p)
7670 Method* m = p->second;
7671 if (m->is_ambiguous() || !m->needs_stub_method())
7672 continue;
7674 const std::string& name(p->first);
7676 // Build a stub method.
7678 const Function_type* fntype = m->type();
7680 static unsigned int counter;
7681 char buf[100];
7682 snprintf(buf, sizeof buf, "$this%u", counter);
7683 ++counter;
7685 Type* receiver_type = const_cast<Type*>(type);
7686 if (!m->is_value_method())
7687 receiver_type = Type::make_pointer_type(receiver_type);
7688 source_location receiver_location = m->receiver_location();
7689 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
7690 receiver_location);
7692 const Typed_identifier_list* fnparams = fntype->parameters();
7693 Typed_identifier_list* stub_params;
7694 if (fnparams == NULL || fnparams->empty())
7695 stub_params = NULL;
7696 else
7698 // We give each stub parameter a unique name.
7699 stub_params = new Typed_identifier_list();
7700 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
7701 pp != fnparams->end();
7702 ++pp)
7704 char pbuf[100];
7705 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
7706 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
7707 pp->location()));
7708 ++counter;
7712 const Typed_identifier_list* fnresults = fntype->results();
7713 Typed_identifier_list* stub_results;
7714 if (fnresults == NULL || fnresults->empty())
7715 stub_results = NULL;
7716 else
7718 // We create the result parameters without any names, since
7719 // we won't refer to them.
7720 stub_results = new Typed_identifier_list();
7721 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
7722 pr != fnresults->end();
7723 ++pr)
7724 stub_results->push_back(Typed_identifier("", pr->type(),
7725 pr->location()));
7728 Function_type* stub_type = Type::make_function_type(receiver,
7729 stub_params,
7730 stub_results,
7731 fntype->location());
7732 if (fntype->is_varargs())
7733 stub_type->set_is_varargs();
7735 // We only create the function in the package which creates the
7736 // type.
7737 const Package* package;
7738 if (type->named_type() == NULL)
7739 package = NULL;
7740 else
7741 package = type->named_type()->named_object()->package();
7742 Named_object* stub;
7743 if (package != NULL)
7744 stub = Named_object::make_function_declaration(name, package,
7745 stub_type, location);
7746 else
7748 stub = gogo->start_function(name, stub_type, false,
7749 fntype->location());
7750 Type::build_one_stub_method(gogo, m, buf, stub_params,
7751 fntype->is_varargs(), location);
7752 gogo->finish_function(fntype->location());
7755 m->set_stub_object(stub);
7759 // Build a stub method which adjusts the receiver as required to call
7760 // METHOD. RECEIVER_NAME is the name we used for the receiver.
7761 // PARAMS is the list of function parameters.
7763 void
7764 Type::build_one_stub_method(Gogo* gogo, Method* method,
7765 const char* receiver_name,
7766 const Typed_identifier_list* params,
7767 bool is_varargs,
7768 source_location location)
7770 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
7771 go_assert(receiver_object != NULL);
7773 Expression* expr = Expression::make_var_reference(receiver_object, location);
7774 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
7775 if (expr->type()->points_to() == NULL)
7776 expr = Expression::make_unary(OPERATOR_AND, expr, location);
7778 Expression_list* arguments;
7779 if (params == NULL || params->empty())
7780 arguments = NULL;
7781 else
7783 arguments = new Expression_list();
7784 for (Typed_identifier_list::const_iterator p = params->begin();
7785 p != params->end();
7786 ++p)
7788 Named_object* param = gogo->lookup(p->name(), NULL);
7789 go_assert(param != NULL);
7790 Expression* param_ref = Expression::make_var_reference(param,
7791 location);
7792 arguments->push_back(param_ref);
7796 Expression* func = method->bind_method(expr, location);
7797 go_assert(func != NULL);
7798 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
7799 location);
7800 size_t count = call->result_count();
7801 if (count == 0)
7802 gogo->add_statement(Statement::make_statement(call));
7803 else
7805 Expression_list* retvals = new Expression_list();
7806 if (count <= 1)
7807 retvals->push_back(call);
7808 else
7810 for (size_t i = 0; i < count; ++i)
7811 retvals->push_back(Expression::make_call_result(call, i));
7813 Statement* retstat = Statement::make_return_statement(retvals, location);
7814 gogo->add_statement(retstat);
7818 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
7819 // in reverse order.
7821 Expression*
7822 Type::apply_field_indexes(Expression* expr,
7823 const Method::Field_indexes* field_indexes,
7824 source_location location)
7826 if (field_indexes == NULL)
7827 return expr;
7828 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
7829 Struct_type* stype = expr->type()->deref()->struct_type();
7830 go_assert(stype != NULL
7831 && field_indexes->field_index < stype->field_count());
7832 if (expr->type()->struct_type() == NULL)
7834 go_assert(expr->type()->points_to() != NULL);
7835 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
7836 go_assert(expr->type()->struct_type() == stype);
7838 return Expression::make_field_reference(expr, field_indexes->field_index,
7839 location);
7842 // Return whether NO is a method for which the receiver is a pointer.
7844 bool
7845 Type::method_expects_pointer(const Named_object* no)
7847 const Function_type *fntype;
7848 if (no->is_function())
7849 fntype = no->func_value()->type();
7850 else if (no->is_function_declaration())
7851 fntype = no->func_declaration_value()->type();
7852 else
7853 go_unreachable();
7854 return fntype->receiver()->type()->points_to() != NULL;
7857 // Given a set of methods for a type, METHODS, return the method NAME,
7858 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
7859 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
7860 // but is ambiguous (and return NULL).
7862 Method*
7863 Type::method_function(const Methods* methods, const std::string& name,
7864 bool* is_ambiguous)
7866 if (is_ambiguous != NULL)
7867 *is_ambiguous = false;
7868 if (methods == NULL)
7869 return NULL;
7870 Methods::const_iterator p = methods->find(name);
7871 if (p == methods->end())
7872 return NULL;
7873 Method* m = p->second;
7874 if (m->is_ambiguous())
7876 if (is_ambiguous != NULL)
7877 *is_ambiguous = true;
7878 return NULL;
7880 return m;
7883 // Look for field or method NAME for TYPE. Return an Expression for
7884 // the field or method bound to EXPR. If there is no such field or
7885 // method, give an appropriate error and return an error expression.
7887 Expression*
7888 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
7889 const std::string& name,
7890 source_location location)
7892 if (type->deref()->is_error_type())
7893 return Expression::make_error(location);
7895 const Named_type* nt = type->deref()->named_type();
7896 const Struct_type* st = type->deref()->struct_type();
7897 const Interface_type* it = type->interface_type();
7899 // If this is a pointer to a pointer, then it is possible that the
7900 // pointed-to type has methods.
7901 if (nt == NULL
7902 && st == NULL
7903 && it == NULL
7904 && type->points_to() != NULL
7905 && type->points_to()->points_to() != NULL)
7907 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
7908 type = type->points_to();
7909 if (type->deref()->is_error_type())
7910 return Expression::make_error(location);
7911 nt = type->points_to()->named_type();
7912 st = type->points_to()->struct_type();
7915 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
7916 || expr->is_addressable());
7917 std::vector<const Named_type*> seen;
7918 bool is_method = false;
7919 bool found_pointer_method = false;
7920 std::string ambig1;
7921 std::string ambig2;
7922 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
7923 &seen, NULL, &is_method,
7924 &found_pointer_method, &ambig1, &ambig2))
7926 Expression* ret;
7927 if (!is_method)
7929 go_assert(st != NULL);
7930 if (type->struct_type() == NULL)
7932 go_assert(type->points_to() != NULL);
7933 expr = Expression::make_unary(OPERATOR_MULT, expr,
7934 location);
7935 go_assert(expr->type()->struct_type() == st);
7937 ret = st->field_reference(expr, name, location);
7939 else if (it != NULL && it->find_method(name) != NULL)
7940 ret = Expression::make_interface_field_reference(expr, name,
7941 location);
7942 else
7944 Method* m;
7945 if (nt != NULL)
7946 m = nt->method_function(name, NULL);
7947 else if (st != NULL)
7948 m = st->method_function(name, NULL);
7949 else
7950 go_unreachable();
7951 go_assert(m != NULL);
7952 if (!m->is_value_method() && expr->type()->points_to() == NULL)
7953 expr = Expression::make_unary(OPERATOR_AND, expr, location);
7954 ret = m->bind_method(expr, location);
7956 go_assert(ret != NULL);
7957 return ret;
7959 else
7961 if (!ambig1.empty())
7962 error_at(location, "%qs is ambiguous via %qs and %qs",
7963 Gogo::message_name(name).c_str(),
7964 Gogo::message_name(ambig1).c_str(),
7965 Gogo::message_name(ambig2).c_str());
7966 else if (found_pointer_method)
7967 error_at(location, "method requires a pointer");
7968 else if (nt == NULL && st == NULL && it == NULL)
7969 error_at(location,
7970 ("reference to field %qs in object which "
7971 "has no fields or methods"),
7972 Gogo::message_name(name).c_str());
7973 else
7975 bool is_unexported;
7976 if (!Gogo::is_hidden_name(name))
7977 is_unexported = false;
7978 else
7980 std::string unpacked = Gogo::unpack_hidden_name(name);
7981 seen.clear();
7982 is_unexported = Type::is_unexported_field_or_method(gogo, type,
7983 unpacked,
7984 &seen);
7986 if (is_unexported)
7987 error_at(location, "reference to unexported field or method %qs",
7988 Gogo::message_name(name).c_str());
7989 else
7990 error_at(location, "reference to undefined field or method %qs",
7991 Gogo::message_name(name).c_str());
7993 return Expression::make_error(location);
7997 // Look in TYPE for a field or method named NAME, return true if one
7998 // is found. This looks through embedded anonymous fields and handles
7999 // ambiguity. If a method is found, sets *IS_METHOD to true;
8000 // otherwise, if a field is found, set it to false. If
8001 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
8002 // whose address can not be taken. SEEN is used to avoid infinite
8003 // recursion on invalid types.
8005 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
8006 // method we couldn't use because it requires a pointer. LEVEL is
8007 // used for recursive calls, and can be NULL for a non-recursive call.
8008 // When this function returns false because it finds that the name is
8009 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
8010 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
8011 // will be unchanged.
8013 // This function just returns whether or not there is a field or
8014 // method, and whether it is a field or method. It doesn't build an
8015 // expression to refer to it. If it is a method, we then look in the
8016 // list of all methods for the type. If it is a field, the search has
8017 // to be done again, looking only for fields, and building up the
8018 // expression as we go.
8020 bool
8021 Type::find_field_or_method(const Type* type,
8022 const std::string& name,
8023 bool receiver_can_be_pointer,
8024 std::vector<const Named_type*>* seen,
8025 int* level,
8026 bool* is_method,
8027 bool* found_pointer_method,
8028 std::string* ambig1,
8029 std::string* ambig2)
8031 // Named types can have locally defined methods.
8032 const Named_type* nt = type->named_type();
8033 if (nt == NULL && type->points_to() != NULL)
8034 nt = type->points_to()->named_type();
8035 if (nt != NULL)
8037 Named_object* no = nt->find_local_method(name);
8038 if (no != NULL)
8040 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
8042 *is_method = true;
8043 return true;
8046 // Record that we have found a pointer method in order to
8047 // give a better error message if we don't find anything
8048 // else.
8049 *found_pointer_method = true;
8052 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
8053 p != seen->end();
8054 ++p)
8056 if (*p == nt)
8058 // We've already seen this type when searching for methods.
8059 return false;
8064 // Interface types can have methods.
8065 const Interface_type* it = type->interface_type();
8066 if (it != NULL && it->find_method(name) != NULL)
8068 *is_method = true;
8069 return true;
8072 // Struct types can have fields. They can also inherit fields and
8073 // methods from anonymous fields.
8074 const Struct_type* st = type->deref()->struct_type();
8075 if (st == NULL)
8076 return false;
8077 const Struct_field_list* fields = st->fields();
8078 if (fields == NULL)
8079 return false;
8081 if (nt != NULL)
8082 seen->push_back(nt);
8084 int found_level = 0;
8085 bool found_is_method = false;
8086 std::string found_ambig1;
8087 std::string found_ambig2;
8088 const Struct_field* found_parent = NULL;
8089 for (Struct_field_list::const_iterator pf = fields->begin();
8090 pf != fields->end();
8091 ++pf)
8093 if (pf->field_name() == name)
8095 *is_method = false;
8096 if (nt != NULL)
8097 seen->pop_back();
8098 return true;
8101 if (!pf->is_anonymous())
8102 continue;
8104 if (pf->type()->deref()->is_error_type()
8105 || pf->type()->deref()->is_undefined())
8106 continue;
8108 Named_type* fnt = pf->type()->named_type();
8109 if (fnt == NULL)
8110 fnt = pf->type()->deref()->named_type();
8111 go_assert(fnt != NULL);
8113 int sublevel = level == NULL ? 1 : *level + 1;
8114 bool sub_is_method;
8115 std::string subambig1;
8116 std::string subambig2;
8117 bool subfound = Type::find_field_or_method(fnt,
8118 name,
8119 receiver_can_be_pointer,
8120 seen,
8121 &sublevel,
8122 &sub_is_method,
8123 found_pointer_method,
8124 &subambig1,
8125 &subambig2);
8126 if (!subfound)
8128 if (!subambig1.empty())
8130 // The name was found via this field, but is ambiguous.
8131 // if the ambiguity is lower or at the same level as
8132 // anything else we have already found, then we want to
8133 // pass the ambiguity back to the caller.
8134 if (found_level == 0 || sublevel <= found_level)
8136 found_ambig1 = pf->field_name() + '.' + subambig1;
8137 found_ambig2 = pf->field_name() + '.' + subambig2;
8138 found_level = sublevel;
8142 else
8144 // The name was found via this field. Use the level to see
8145 // if we want to use this one, or whether it introduces an
8146 // ambiguity.
8147 if (found_level == 0 || sublevel < found_level)
8149 found_level = sublevel;
8150 found_is_method = sub_is_method;
8151 found_ambig1.clear();
8152 found_ambig2.clear();
8153 found_parent = &*pf;
8155 else if (sublevel > found_level)
8157 else if (found_ambig1.empty())
8159 // We found an ambiguity.
8160 go_assert(found_parent != NULL);
8161 found_ambig1 = found_parent->field_name();
8162 found_ambig2 = pf->field_name();
8164 else
8166 // We found an ambiguity, but we already know of one.
8167 // Just report the earlier one.
8172 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
8173 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
8174 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
8175 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
8177 if (nt != NULL)
8178 seen->pop_back();
8180 if (found_level == 0)
8181 return false;
8182 else if (!found_ambig1.empty())
8184 go_assert(!found_ambig1.empty());
8185 ambig1->assign(found_ambig1);
8186 ambig2->assign(found_ambig2);
8187 if (level != NULL)
8188 *level = found_level;
8189 return false;
8191 else
8193 if (level != NULL)
8194 *level = found_level;
8195 *is_method = found_is_method;
8196 return true;
8200 // Return whether NAME is an unexported field or method for TYPE.
8202 bool
8203 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
8204 const std::string& name,
8205 std::vector<const Named_type*>* seen)
8207 const Named_type* nt = type->named_type();
8208 if (nt == NULL)
8209 nt = type->deref()->named_type();
8210 if (nt != NULL)
8212 if (nt->is_unexported_local_method(gogo, name))
8213 return true;
8215 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
8216 p != seen->end();
8217 ++p)
8219 if (*p == nt)
8221 // We've already seen this type.
8222 return false;
8227 const Interface_type* it = type->interface_type();
8228 if (it != NULL && it->is_unexported_method(gogo, name))
8229 return true;
8231 type = type->deref();
8233 const Struct_type* st = type->struct_type();
8234 if (st != NULL && st->is_unexported_local_field(gogo, name))
8235 return true;
8237 if (st == NULL)
8238 return false;
8240 const Struct_field_list* fields = st->fields();
8241 if (fields == NULL)
8242 return false;
8244 if (nt != NULL)
8245 seen->push_back(nt);
8247 for (Struct_field_list::const_iterator pf = fields->begin();
8248 pf != fields->end();
8249 ++pf)
8251 if (pf->is_anonymous()
8252 && !pf->type()->deref()->is_error_type()
8253 && !pf->type()->deref()->is_undefined())
8255 Named_type* subtype = pf->type()->named_type();
8256 if (subtype == NULL)
8257 subtype = pf->type()->deref()->named_type();
8258 if (subtype == NULL)
8260 // This is an error, but it will be diagnosed elsewhere.
8261 continue;
8263 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
8265 if (nt != NULL)
8266 seen->pop_back();
8267 return true;
8272 if (nt != NULL)
8273 seen->pop_back();
8275 return false;
8278 // Class Forward_declaration.
8280 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
8281 : Type(TYPE_FORWARD),
8282 named_object_(named_object->resolve()), warned_(false)
8284 go_assert(this->named_object_->is_unknown()
8285 || this->named_object_->is_type_declaration());
8288 // Return the named object.
8290 Named_object*
8291 Forward_declaration_type::named_object()
8293 return this->named_object_->resolve();
8296 const Named_object*
8297 Forward_declaration_type::named_object() const
8299 return this->named_object_->resolve();
8302 // Return the name of the forward declared type.
8304 const std::string&
8305 Forward_declaration_type::name() const
8307 return this->named_object()->name();
8310 // Warn about a use of a type which has been declared but not defined.
8312 void
8313 Forward_declaration_type::warn() const
8315 Named_object* no = this->named_object_->resolve();
8316 if (no->is_unknown())
8318 // The name was not defined anywhere.
8319 if (!this->warned_)
8321 error_at(this->named_object_->location(),
8322 "use of undefined type %qs",
8323 no->message_name().c_str());
8324 this->warned_ = true;
8327 else if (no->is_type_declaration())
8329 // The name was seen as a type, but the type was never defined.
8330 if (no->type_declaration_value()->using_type())
8332 error_at(this->named_object_->location(),
8333 "use of undefined type %qs",
8334 no->message_name().c_str());
8335 this->warned_ = true;
8338 else
8340 // The name was defined, but not as a type.
8341 if (!this->warned_)
8343 error_at(this->named_object_->location(), "expected type");
8344 this->warned_ = true;
8349 // Get the base type of a declaration. This gives an error if the
8350 // type has not yet been defined.
8352 Type*
8353 Forward_declaration_type::real_type()
8355 if (this->is_defined())
8356 return this->named_object()->type_value();
8357 else
8359 this->warn();
8360 return Type::make_error_type();
8364 const Type*
8365 Forward_declaration_type::real_type() const
8367 if (this->is_defined())
8368 return this->named_object()->type_value();
8369 else
8371 this->warn();
8372 return Type::make_error_type();
8376 // Return whether the base type is defined.
8378 bool
8379 Forward_declaration_type::is_defined() const
8381 return this->named_object()->is_type();
8384 // Add a method. This is used when methods are defined before the
8385 // type.
8387 Named_object*
8388 Forward_declaration_type::add_method(const std::string& name,
8389 Function* function)
8391 Named_object* no = this->named_object();
8392 if (no->is_unknown())
8393 no->declare_as_type();
8394 return no->type_declaration_value()->add_method(name, function);
8397 // Add a method declaration. This is used when methods are declared
8398 // before the type.
8400 Named_object*
8401 Forward_declaration_type::add_method_declaration(const std::string& name,
8402 Function_type* type,
8403 source_location location)
8405 Named_object* no = this->named_object();
8406 if (no->is_unknown())
8407 no->declare_as_type();
8408 Type_declaration* td = no->type_declaration_value();
8409 return td->add_method_declaration(name, type, location);
8412 // Traversal.
8415 Forward_declaration_type::do_traverse(Traverse* traverse)
8417 if (this->is_defined()
8418 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
8419 return TRAVERSE_EXIT;
8420 return TRAVERSE_CONTINUE;
8423 // Get a tree for the type.
8425 tree
8426 Forward_declaration_type::do_get_tree(Gogo* gogo)
8428 if (this->is_defined())
8429 return type_to_tree(Type::get_named_base_btype(gogo, this->real_type()));
8431 if (this->warned_)
8432 return error_mark_node;
8434 // We represent an undefined type as a struct with no fields. That
8435 // should work fine for the middle-end, since the same case can
8436 // arise in C.
8437 Named_object* no = this->named_object();
8438 tree type_tree = make_node(RECORD_TYPE);
8439 tree id = no->get_id(gogo);
8440 tree decl = build_decl(no->location(), TYPE_DECL, id, type_tree);
8441 TYPE_NAME(type_tree) = decl;
8442 layout_type(type_tree);
8443 return type_tree;
8446 // Build a type descriptor for a forwarded type.
8448 Expression*
8449 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8451 if (!this->is_defined())
8452 return Expression::make_nil(BUILTINS_LOCATION);
8453 else
8455 Type* t = this->real_type();
8456 if (name != NULL)
8457 return this->named_type_descriptor(gogo, t, name);
8458 else
8459 return Expression::make_type_descriptor(t, BUILTINS_LOCATION);
8463 // The reflection string.
8465 void
8466 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
8468 this->append_reflection(this->real_type(), gogo, ret);
8471 // The mangled name.
8473 void
8474 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8476 if (this->is_defined())
8477 this->append_mangled_name(this->real_type(), gogo, ret);
8478 else
8480 const Named_object* no = this->named_object();
8481 std::string name;
8482 if (no->package() == NULL)
8483 name = gogo->package_name();
8484 else
8485 name = no->package()->name();
8486 name += '.';
8487 name += Gogo::unpack_hidden_name(no->name());
8488 char buf[20];
8489 snprintf(buf, sizeof buf, "N%u_",
8490 static_cast<unsigned int>(name.length()));
8491 ret->append(buf);
8492 ret->append(name);
8496 // Export a forward declaration. This can happen when a defined type
8497 // refers to a type which is only declared (and is presumably defined
8498 // in some other file in the same package).
8500 void
8501 Forward_declaration_type::do_export(Export*) const
8503 // If there is a base type, that should be exported instead of this.
8504 go_assert(!this->is_defined());
8506 // We don't output anything.
8509 // Make a forward declaration.
8511 Type*
8512 Type::make_forward_declaration(Named_object* named_object)
8514 return new Forward_declaration_type(named_object);
8517 // Class Typed_identifier_list.
8519 // Sort the entries by name.
8521 struct Typed_identifier_list_sort
8523 public:
8524 bool
8525 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
8526 { return t1.name() < t2.name(); }
8529 void
8530 Typed_identifier_list::sort_by_name()
8532 std::sort(this->entries_.begin(), this->entries_.end(),
8533 Typed_identifier_list_sort());
8536 // Traverse types.
8539 Typed_identifier_list::traverse(Traverse* traverse)
8541 for (Typed_identifier_list::const_iterator p = this->begin();
8542 p != this->end();
8543 ++p)
8545 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
8546 return TRAVERSE_EXIT;
8548 return TRAVERSE_CONTINUE;
8551 // Copy the list.
8553 Typed_identifier_list*
8554 Typed_identifier_list::copy() const
8556 Typed_identifier_list* ret = new Typed_identifier_list();
8557 for (Typed_identifier_list::const_iterator p = this->begin();
8558 p != this->end();
8559 ++p)
8560 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
8561 return ret;