From e8f79869d7d78364931e69665b9c8f876fa1bb73 Mon Sep 17 00:00:00 2001 From: "H.J. Lu" Date: Sun, 5 Jun 2011 13:57:58 -0700 Subject: [PATCH] Revert accidental checkin. From-SVN: r174662 --- .../expressions.cc.merge-left.r167407 | 12264 --------------- .../expressions.cc.merge-right.r172891 | 12843 ---------------- gcc/go/gofrontend/expressions.cc.working | 12663 --------------- gcc/go/gofrontend/go.cc.merge-left.r167407 | 153 - gcc/go/gofrontend/go.cc.merge-right.r172891 | 151 - gcc/go/gofrontend/go.cc.working | 150 - .../gogo-tree.cc.merge-left.r167407 | 3105 ---- .../gogo-tree.cc.merge-right.r172891 | 2697 ---- gcc/go/gofrontend/gogo-tree.cc.working | 3145 ---- gcc/go/gofrontend/gogo.cc.merge-left.r167407 | 4274 ----- gcc/go/gofrontend/gogo.cc.merge-right.r172891 | 4796 ------ gcc/go/gofrontend/gogo.cc.working | 4514 ------ gcc/go/gofrontend/gogo.h.merge-left.r167407 | 2484 --- gcc/go/gofrontend/gogo.h.merge-right.r172891 | 2612 ---- gcc/go/gofrontend/gogo.h.working | 2537 --- gcc/go/gofrontend/parse.cc.merge-left.r167407 | 4730 ------ .../gofrontend/parse.cc.merge-right.r172891 | 5131 ------ gcc/go/gofrontend/parse.cc.working | 5015 ------ gcc/go/gofrontend/parse.h.merge-left.r167407 | 307 - gcc/go/gofrontend/parse.h.merge-right.r172891 | 309 - gcc/go/gofrontend/parse.h.working | 310 - .../statements.cc.merge-left.r167407 | 5146 ------- .../statements.cc.merge-right.r172891 | 5073 ------ gcc/go/gofrontend/statements.cc.working | 5396 ------- .../statements.h.merge-left.r167407 | 1420 -- .../statements.h.merge-right.r172891 | 1446 -- gcc/go/gofrontend/statements.h.working | 1461 -- gcc/go/gofrontend/types.cc.merge-left.r167407 | 8078 ---------- .../gofrontend/types.cc.merge-right.r172891 | 8676 ----------- gcc/go/gofrontend/types.cc.working | 8656 ----------- .../gofrontend/unsafe.cc.merge-left.r167407 | 134 - .../gofrontend/unsafe.cc.merge-right.r172891 | 146 - gcc/go/gofrontend/unsafe.cc.working | 146 - 33 files changed, 129968 deletions(-) delete mode 100644 gcc/go/gofrontend/expressions.cc.merge-left.r167407 delete mode 100644 gcc/go/gofrontend/expressions.cc.merge-right.r172891 delete mode 100644 gcc/go/gofrontend/expressions.cc.working delete mode 100644 gcc/go/gofrontend/go.cc.merge-left.r167407 delete mode 100644 gcc/go/gofrontend/go.cc.merge-right.r172891 delete mode 100644 gcc/go/gofrontend/go.cc.working delete mode 100644 gcc/go/gofrontend/gogo-tree.cc.merge-left.r167407 delete mode 100644 gcc/go/gofrontend/gogo-tree.cc.merge-right.r172891 delete mode 100644 gcc/go/gofrontend/gogo-tree.cc.working delete mode 100644 gcc/go/gofrontend/gogo.cc.merge-left.r167407 delete mode 100644 gcc/go/gofrontend/gogo.cc.merge-right.r172891 delete mode 100644 gcc/go/gofrontend/gogo.cc.working delete mode 100644 gcc/go/gofrontend/gogo.h.merge-left.r167407 delete mode 100644 gcc/go/gofrontend/gogo.h.merge-right.r172891 delete mode 100644 gcc/go/gofrontend/gogo.h.working delete mode 100644 gcc/go/gofrontend/parse.cc.merge-left.r167407 delete mode 100644 gcc/go/gofrontend/parse.cc.merge-right.r172891 delete mode 100644 gcc/go/gofrontend/parse.cc.working delete mode 100644 gcc/go/gofrontend/parse.h.merge-left.r167407 delete mode 100644 gcc/go/gofrontend/parse.h.merge-right.r172891 delete mode 100644 gcc/go/gofrontend/parse.h.working delete mode 100644 gcc/go/gofrontend/statements.cc.merge-left.r167407 delete mode 100644 gcc/go/gofrontend/statements.cc.merge-right.r172891 delete mode 100644 gcc/go/gofrontend/statements.cc.working delete mode 100644 gcc/go/gofrontend/statements.h.merge-left.r167407 delete mode 100644 gcc/go/gofrontend/statements.h.merge-right.r172891 delete mode 100644 gcc/go/gofrontend/statements.h.working delete mode 100644 gcc/go/gofrontend/types.cc.merge-left.r167407 delete mode 100644 gcc/go/gofrontend/types.cc.merge-right.r172891 delete mode 100644 gcc/go/gofrontend/types.cc.working delete mode 100644 gcc/go/gofrontend/unsafe.cc.merge-left.r167407 delete mode 100644 gcc/go/gofrontend/unsafe.cc.merge-right.r172891 delete mode 100644 gcc/go/gofrontend/unsafe.cc.working diff --git a/gcc/go/gofrontend/expressions.cc.merge-left.r167407 b/gcc/go/gofrontend/expressions.cc.merge-left.r167407 deleted file mode 100644 index f35b3639aaf..00000000000 --- a/gcc/go/gofrontend/expressions.cc.merge-left.r167407 +++ /dev/null @@ -1,12264 +0,0 @@ -// expressions.cc -- Go frontend expression handling. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include - -#ifndef ENABLE_BUILD_WITH_CXX -extern "C" -{ -#endif - -#include "toplev.h" -#include "intl.h" -#include "tree.h" -#include "gimple.h" -#include "tree-iterator.h" -#include "convert.h" -#include "real.h" -#include "realmpfr.h" -#include "tm.h" -#include "tm_p.h" - -#ifndef ENABLE_BUILD_WITH_CXX -} -#endif - -#include "go-c.h" -#include "gogo.h" -#include "types.h" -#include "export.h" -#include "import.h" -#include "statements.h" -#include "lex.h" -#include "expressions.h" - -// Class Expression. - -Expression::Expression(Expression_classification classification, - source_location location) - : classification_(classification), location_(location) -{ -} - -Expression::~Expression() -{ -} - -// If this expression has a constant integer value, return it. - -bool -Expression::integer_constant_value(bool iota_is_constant, mpz_t val, - Type** ptype) const -{ - *ptype = NULL; - return this->do_integer_constant_value(iota_is_constant, val, ptype); -} - -// If this expression has a constant floating point value, return it. - -bool -Expression::float_constant_value(mpfr_t val, Type** ptype) const -{ - *ptype = NULL; - if (this->do_float_constant_value(val, ptype)) - return true; - mpz_t ival; - mpz_init(ival); - Type* t; - bool ret; - if (!this->do_integer_constant_value(false, ival, &t)) - ret = false; - else - { - mpfr_set_z(val, ival, GMP_RNDN); - ret = true; - } - mpz_clear(ival); - return ret; -} - -// If this expression has a constant complex value, return it. - -bool -Expression::complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - *ptype = NULL; - if (this->do_complex_constant_value(real, imag, ptype)) - return true; - Type *t; - if (this->float_constant_value(real, &t)) - { - mpfr_set_ui(imag, 0, GMP_RNDN); - return true; - } - return false; -} - -// Traverse the expressions. - -int -Expression::traverse(Expression** pexpr, Traverse* traverse) -{ - Expression* expr = *pexpr; - if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0) - { - int t = traverse->expression(pexpr); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - return TRAVERSE_CONTINUE; - } - return expr->do_traverse(traverse); -} - -// Traverse subexpressions of this expression. - -int -Expression::traverse_subexpressions(Traverse* traverse) -{ - return this->do_traverse(traverse); -} - -// Default implementation for do_traverse for child classes. - -int -Expression::do_traverse(Traverse*) -{ - return TRAVERSE_CONTINUE; -} - -// This virtual function is called by the parser if the value of this -// expression is being discarded. By default, we warn. Expressions -// with side effects override. - -void -Expression::do_discarding_value() -{ - this->warn_about_unused_value(); -} - -// This virtual function is called to export expressions. This will -// only be used by expressions which may be constant. - -void -Expression::do_export(Export*) const -{ - gcc_unreachable(); -} - -// Warn that the value of the expression is not used. - -void -Expression::warn_about_unused_value() -{ - warning_at(this->location(), OPT_Wunused_value, "value computed is not used"); -} - -// Note that this expression is an error. This is called by children -// when they discover an error. - -void -Expression::set_is_error() -{ - this->classification_ = EXPRESSION_ERROR; -} - -// For children to call to report an error conveniently. - -void -Expression::report_error(const char* msg) -{ - error_at(this->location_, "%s", msg); - this->set_is_error(); -} - -// Set types of variables and constants. This is implemented by the -// child class. - -void -Expression::determine_type(const Type_context* context) -{ - this->do_determine_type(context); -} - -// Set types when there is no context. - -void -Expression::determine_type_no_context() -{ - Type_context context; - this->do_determine_type(&context); -} - -// Return a tree handling any conversions which must be done during -// assignment. - -tree -Expression::convert_for_assignment(Translate_context* context, Type* lhs_type, - Type* rhs_type, tree rhs_tree, - source_location location) -{ - if (lhs_type == rhs_type) - return rhs_tree; - - if (lhs_type->is_error_type() || rhs_type->is_error_type()) - return error_mark_node; - - if (lhs_type->is_undefined() || rhs_type->is_undefined()) - { - // Make sure we report the error. - lhs_type->base(); - rhs_type->base(); - return error_mark_node; - } - - if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node) - return error_mark_node; - - Gogo* gogo = context->gogo(); - - tree lhs_type_tree = lhs_type->get_tree(gogo); - if (lhs_type_tree == error_mark_node) - return error_mark_node; - - if (lhs_type->interface_type() != NULL) - { - if (rhs_type->interface_type() == NULL) - return Expression::convert_type_to_interface(context, lhs_type, - rhs_type, rhs_tree, - location); - else - return Expression::convert_interface_to_interface(context, lhs_type, - rhs_type, rhs_tree, - false, location); - } - else if (rhs_type->interface_type() != NULL) - return Expression::convert_interface_to_type(context, lhs_type, rhs_type, - rhs_tree, location); - else if (lhs_type->is_open_array_type() - && rhs_type->is_nil_type()) - { - // Assigning nil to an open array. - gcc_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(lhs_type_tree); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__values") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), null_pointer_node); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__count") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), integer_zero_node); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__capacity") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), integer_zero_node); - - tree val = build_constructor(lhs_type_tree, init); - TREE_CONSTANT(val) = 1; - - return val; - } - else if (rhs_type->is_nil_type()) - { - // The left hand side should be a pointer type at the tree - // level. - gcc_assert(POINTER_TYPE_P(lhs_type_tree)); - return fold_convert(lhs_type_tree, null_pointer_node); - } - else if (lhs_type_tree == TREE_TYPE(rhs_tree)) - { - // No conversion is needed. - return rhs_tree; - } - else if (POINTER_TYPE_P(lhs_type_tree) - || INTEGRAL_TYPE_P(lhs_type_tree) - || SCALAR_FLOAT_TYPE_P(lhs_type_tree) - || COMPLEX_FLOAT_TYPE_P(lhs_type_tree)) - return fold_convert_loc(location, lhs_type_tree, rhs_tree); - else if (TREE_CODE(lhs_type_tree) == RECORD_TYPE - && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE) - { - // This conversion must be permitted by Go, or we wouldn't have - // gotten here. - gcc_assert(int_size_in_bytes(lhs_type_tree) - == int_size_in_bytes(TREE_TYPE(rhs_tree))); - return fold_build1_loc(location, VIEW_CONVERT_EXPR, lhs_type_tree, - rhs_tree); - } - else - { - gcc_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree))); - return rhs_tree; - } -} - -// Return a tree for a conversion from a non-interface type to an -// interface type. - -tree -Expression::convert_type_to_interface(Translate_context* context, - Type* lhs_type, Type* rhs_type, - tree rhs_tree, source_location location) -{ - Gogo* gogo = context->gogo(); - Interface_type* lhs_interface_type = lhs_type->interface_type(); - bool lhs_is_empty = lhs_interface_type->is_empty(); - - // Since RHS_TYPE is a static type, we can create the interface - // method table at compile time. - - // When setting an interface to nil, we just set both fields to - // NULL. - if (rhs_type->is_nil_type()) - return lhs_type->get_init_tree(gogo, false); - - // This should have been checked already. - gcc_assert(lhs_interface_type->implements_interface(rhs_type, NULL)); - - tree lhs_type_tree = lhs_type->get_tree(gogo); - if (lhs_type_tree == error_mark_node) - return error_mark_node; - - // An interface is a tuple. If LHS_TYPE is an empty interface type, - // then the first field is the type descriptor for RHS_TYPE. - // Otherwise it is the interface method table for RHS_TYPE. - tree first_field_value; - if (lhs_is_empty) - first_field_value = rhs_type->type_descriptor_pointer(gogo); - else - { - // Build the interface method table for this interface and this - // object type: a list of function pointers for each interface - // method. - Named_type* rhs_named_type = rhs_type->named_type(); - bool is_pointer = false; - if (rhs_named_type == NULL) - { - rhs_named_type = rhs_type->deref()->named_type(); - is_pointer = true; - } - tree method_table; - if (rhs_named_type == NULL) - method_table = null_pointer_node; - else - method_table = - rhs_named_type->interface_method_table(gogo, lhs_interface_type, - is_pointer); - first_field_value = fold_convert_loc(location, const_ptr_type_node, - method_table); - } - - // Start building a constructor for the value we will return. - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(lhs_type_tree); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0); - elt->index = field; - elt->value = fold_convert_loc(location, TREE_TYPE(field), first_field_value); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0); - elt->index = field; - - if (rhs_type->points_to() != NULL) - { - // We are assigning a pointer to the interface; the interface - // holds the pointer itself. - elt->value = rhs_tree; - return build_constructor(lhs_type_tree, init); - } - - // We are assigning a non-pointer value to the interface; the - // interface gets a copy of the value in the heap. - - tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree)); - - tree space = gogo->allocate_memory(rhs_type, object_size, location); - space = fold_convert_loc(location, build_pointer_type(TREE_TYPE(rhs_tree)), - space); - space = save_expr(space); - - tree ref = build_fold_indirect_ref_loc(location, space); - TREE_THIS_NOTRAP(ref) = 1; - tree set = fold_build2_loc(location, MODIFY_EXPR, void_type_node, - ref, rhs_tree); - - elt->value = fold_convert_loc(location, TREE_TYPE(field), space); - - return build2(COMPOUND_EXPR, lhs_type_tree, set, - build_constructor(lhs_type_tree, init)); -} - -// Return a tree for the type descriptor of RHS_TREE, which has -// interface type RHS_TYPE. If RHS_TREE is nil the result will be -// NULL. - -tree -Expression::get_interface_type_descriptor(Translate_context*, - Type* rhs_type, tree rhs_tree, - source_location location) -{ - tree rhs_type_tree = TREE_TYPE(rhs_tree); - gcc_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE); - tree rhs_field = TYPE_FIELDS(rhs_type_tree); - tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field, - NULL_TREE); - if (rhs_type->interface_type()->is_empty()) - { - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), - "__type_descriptor") == 0); - return v; - } - - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods") - == 0); - gcc_assert(POINTER_TYPE_P(TREE_TYPE(v))); - v = save_expr(v); - tree v1 = build_fold_indirect_ref_loc(location, v); - gcc_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE); - tree f = TYPE_FIELDS(TREE_TYPE(v1)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor") - == 0); - v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE); - - tree eq = fold_build2_loc(location, EQ_EXPR, boolean_type_node, v, - fold_convert_loc(location, TREE_TYPE(v), - null_pointer_node)); - tree n = fold_convert_loc(location, TREE_TYPE(v1), null_pointer_node); - return fold_build3_loc(location, COND_EXPR, TREE_TYPE(v1), - eq, n, v1); -} - -// Return a tree for the conversion of an interface type to an -// interface type. - -tree -Expression::convert_interface_to_interface(Translate_context* context, - Type *lhs_type, Type *rhs_type, - tree rhs_tree, bool for_type_guard, - source_location location) -{ - Gogo* gogo = context->gogo(); - Interface_type* lhs_interface_type = lhs_type->interface_type(); - bool lhs_is_empty = lhs_interface_type->is_empty(); - - tree lhs_type_tree = lhs_type->get_tree(gogo); - if (lhs_type_tree == error_mark_node) - return error_mark_node; - - // In the general case this requires runtime examination of the type - // method table to match it up with the interface methods. - - // FIXME: If all of the methods in the right hand side interface - // also appear in the left hand side interface, then we don't need - // to do a runtime check, although we still need to build a new - // method table. - - // Get the type descriptor for the right hand side. This will be - // NULL for a nil interface. - - if (!DECL_P(rhs_tree)) - rhs_tree = save_expr(rhs_tree); - - tree rhs_type_descriptor = - Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree, - location); - - // The result is going to be a two element constructor. - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(lhs_type_tree); - elt->index = field; - - if (for_type_guard) - { - // A type assertion fails when converting a nil interface. - tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo); - static tree assert_interface_decl; - tree call = Gogo::call_builtin(&assert_interface_decl, - location, - "__go_assert_interface", - 2, - ptr_type_node, - TREE_TYPE(lhs_type_descriptor), - lhs_type_descriptor, - TREE_TYPE(rhs_type_descriptor), - rhs_type_descriptor); - // This will panic if the interface conversion fails. - TREE_NOTHROW(assert_interface_decl) = 0; - elt->value = fold_convert_loc(location, TREE_TYPE(field), call); - } - else if (lhs_is_empty) - { - // A convertion to an empty interface always succeeds, and the - // first field is just the type descriptor of the object. - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__type_descriptor") == 0); - gcc_assert(TREE_TYPE(field) == TREE_TYPE(rhs_type_descriptor)); - elt->value = rhs_type_descriptor; - } - else - { - // A conversion to a non-empty interface may fail, but unlike a - // type assertion converting nil will always succeed. - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") - == 0); - tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo); - static tree convert_interface_decl; - tree call = Gogo::call_builtin(&convert_interface_decl, - location, - "__go_convert_interface", - 2, - ptr_type_node, - TREE_TYPE(lhs_type_descriptor), - lhs_type_descriptor, - TREE_TYPE(rhs_type_descriptor), - rhs_type_descriptor); - // This will panic if the interface conversion fails. - TREE_NOTHROW(convert_interface_decl) = 0; - elt->value = fold_convert_loc(location, TREE_TYPE(field), call); - } - - // The second field is simply the object pointer. - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0); - elt->index = field; - - tree rhs_type_tree = TREE_TYPE(rhs_tree); - gcc_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE); - tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0); - elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field, - NULL_TREE); - - return build_constructor(lhs_type_tree, init); -} - -// Return a tree for the conversion of an interface type to a -// non-interface type. - -tree -Expression::convert_interface_to_type(Translate_context* context, - Type *lhs_type, Type* rhs_type, - tree rhs_tree, source_location location) -{ - Gogo* gogo = context->gogo(); - tree rhs_type_tree = TREE_TYPE(rhs_tree); - - tree lhs_type_tree = lhs_type->get_tree(gogo); - if (lhs_type_tree == error_mark_node) - return error_mark_node; - - // Call a function to check that the type is valid. The function - // will panic with an appropriate runtime type error if the type is - // not valid. - - tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo); - - if (!DECL_P(rhs_tree)) - rhs_tree = save_expr(rhs_tree); - - tree rhs_type_descriptor = - Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree, - location); - - tree rhs_inter_descriptor = rhs_type->type_descriptor_pointer(gogo); - - static tree check_interface_type_decl; - tree call = Gogo::call_builtin(&check_interface_type_decl, - location, - "__go_check_interface_type", - 3, - void_type_node, - TREE_TYPE(lhs_type_descriptor), - lhs_type_descriptor, - TREE_TYPE(rhs_type_descriptor), - rhs_type_descriptor, - TREE_TYPE(rhs_inter_descriptor), - rhs_inter_descriptor); - // This call will panic if the conversion is invalid. - TREE_NOTHROW(check_interface_type_decl) = 0; - - // If the call succeeds, pull out the value. - gcc_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE); - tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0); - tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field, - NULL_TREE); - - // If the value is a pointer, then it is the value we want. - // Otherwise it points to the value. - if (lhs_type->points_to() == NULL) - { - val = fold_convert_loc(location, build_pointer_type(lhs_type_tree), val); - val = build_fold_indirect_ref_loc(location, val); - } - - return build2(COMPOUND_EXPR, lhs_type_tree, call, - fold_convert_loc(location, lhs_type_tree, val)); -} - -// Convert an expression to a tree. This is implemented by the child -// class. Not that it is not in general safe to call this multiple -// times for a single expression, but that we don't catch such errors. - -tree -Expression::get_tree(Translate_context* context) -{ - // The child may have marked this expression as having an error. - if (this->classification_ == EXPRESSION_ERROR) - return error_mark_node; - - return this->do_get_tree(context); -} - -// Return a tree for VAL in TYPE. - -tree -Expression::integer_constant_tree(mpz_t val, tree type) -{ - if (type == error_mark_node) - return error_mark_node; - else if (TREE_CODE(type) == INTEGER_TYPE) - return double_int_to_tree(type, - mpz_get_double_int(type, val, true)); - else if (TREE_CODE(type) == REAL_TYPE) - { - mpfr_t fval; - mpfr_init_set_z(fval, val, GMP_RNDN); - tree ret = Expression::float_constant_tree(fval, type); - mpfr_clear(fval); - return ret; - } - else if (TREE_CODE(type) == COMPLEX_TYPE) - { - mpfr_t fval; - mpfr_init_set_z(fval, val, GMP_RNDN); - tree real = Expression::float_constant_tree(fval, TREE_TYPE(type)); - mpfr_clear(fval); - tree imag = build_real_from_int_cst(TREE_TYPE(type), - integer_zero_node); - return build_complex(type, real, imag); - } - else - gcc_unreachable(); -} - -// Return a tree for VAL in TYPE. - -tree -Expression::float_constant_tree(mpfr_t val, tree type) -{ - if (type == error_mark_node) - return error_mark_node; - else if (TREE_CODE(type) == INTEGER_TYPE) - { - mpz_t ival; - mpz_init(ival); - mpfr_get_z(ival, val, GMP_RNDN); - tree ret = Expression::integer_constant_tree(ival, type); - mpz_clear(ival); - return ret; - } - else if (TREE_CODE(type) == REAL_TYPE) - { - REAL_VALUE_TYPE r1; - real_from_mpfr(&r1, val, type, GMP_RNDN); - REAL_VALUE_TYPE r2; - real_convert(&r2, TYPE_MODE(type), &r1); - return build_real(type, r2); - } - else if (TREE_CODE(type) == COMPLEX_TYPE) - { - REAL_VALUE_TYPE r1; - real_from_mpfr(&r1, val, TREE_TYPE(type), GMP_RNDN); - REAL_VALUE_TYPE r2; - real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1); - tree imag = build_real_from_int_cst(TREE_TYPE(type), - integer_zero_node); - return build_complex(type, build_real(TREE_TYPE(type), r2), imag); - } - else - gcc_unreachable(); -} - -// Return a tree for REAL/IMAG in TYPE. - -tree -Expression::complex_constant_tree(mpfr_t real, mpfr_t imag, tree type) -{ - if (TREE_CODE(type) == COMPLEX_TYPE) - { - REAL_VALUE_TYPE r1; - real_from_mpfr(&r1, real, TREE_TYPE(type), GMP_RNDN); - REAL_VALUE_TYPE r2; - real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1); - - REAL_VALUE_TYPE r3; - real_from_mpfr(&r3, imag, TREE_TYPE(type), GMP_RNDN); - REAL_VALUE_TYPE r4; - real_convert(&r4, TYPE_MODE(TREE_TYPE(type)), &r3); - - return build_complex(type, build_real(TREE_TYPE(type), r2), - build_real(TREE_TYPE(type), r4)); - } - else - gcc_unreachable(); -} - -// Return a tree which evaluates to true if VAL, of arbitrary integer -// type, is negative or is more than the maximum value of BOUND_TYPE. -// If SOFAR is not NULL, it is or'red into the result. The return -// value may be NULL if SOFAR is NULL. - -tree -Expression::check_bounds(tree val, tree bound_type, tree sofar, - source_location loc) -{ - tree val_type = TREE_TYPE(val); - tree ret = NULL_TREE; - - if (!TYPE_UNSIGNED(val_type)) - { - ret = fold_build2_loc(loc, LT_EXPR, boolean_type_node, val, - build_int_cst(val_type, 0)); - if (ret == boolean_false_node) - ret = NULL_TREE; - } - - if ((TYPE_UNSIGNED(val_type) && !TYPE_UNSIGNED(bound_type)) - || TYPE_SIZE(val_type) > TYPE_SIZE(bound_type)) - { - tree max = TYPE_MAX_VALUE(bound_type); - tree big = fold_build2_loc(loc, GT_EXPR, boolean_type_node, val, - fold_convert_loc(loc, val_type, max)); - if (big == boolean_false_node) - ; - else if (ret == NULL_TREE) - ret = big; - else - ret = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - ret, big); - } - - if (ret == NULL_TREE) - return sofar; - else if (sofar == NULL_TREE) - return ret; - else - return fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - sofar, ret); -} - -// Error expressions. This are used to avoid cascading errors. - -class Error_expression : public Expression -{ - public: - Error_expression(source_location location) - : Expression(EXPRESSION_ERROR, location) - { } - - protected: - bool - do_is_constant() const - { return true; } - - bool - do_integer_constant_value(bool, mpz_t val, Type**) const - { - mpz_set_ui(val, 0); - return true; - } - - bool - do_float_constant_value(mpfr_t val, Type**) const - { - mpfr_set_ui(val, 0, GMP_RNDN); - return true; - } - - bool - do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const - { - mpfr_set_ui(real, 0, GMP_RNDN); - mpfr_set_ui(imag, 0, GMP_RNDN); - return true; - } - - void - do_discarding_value() - { } - - Type* - do_type() - { return Type::make_error_type(); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - bool - do_is_addressable() const - { return true; } - - tree - do_get_tree(Translate_context*) - { return error_mark_node; } -}; - -Expression* -Expression::make_error(source_location location) -{ - return new Error_expression(location); -} - -// An expression which is really a type. This is used during parsing. -// It is an error if these survive after lowering. - -class -Type_expression : public Expression -{ - public: - Type_expression(Type* type, source_location location) - : Expression(EXPRESSION_TYPE, location), - type_(type) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return Type::traverse(this->type_, traverse); } - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*) - { } - - void - do_check_types(Gogo*) - { this->report_error(_("invalid use of type")); } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // The type which we are representing as an expression. - Type* type_; -}; - -Expression* -Expression::make_type(Type* type, source_location location) -{ - return new Type_expression(type, location); -} - -// Class Var_expression. - -// Lower a variable expression. Here we just make sure that the -// initialization expression of the variable has been lowered. This -// ensures that we will be able to determine the type of the variable -// if necessary. - -Expression* -Var_expression::do_lower(Gogo* gogo, Named_object* function, int) -{ - if (this->variable_->is_variable()) - { - Variable* var = this->variable_->var_value(); - // This is either a local variable or a global variable. A - // reference to a variable which is local to an enclosing - // function will be a reference to a field in a closure. - if (var->is_global()) - function = NULL; - var->lower_init_expression(gogo, function); - } - return this; -} - -// Return the name of the variable. - -const std::string& -Var_expression::name() const -{ - return this->variable_->name(); -} - -// Return the type of a reference to a variable. - -Type* -Var_expression::do_type() -{ - if (this->variable_->is_variable()) - return this->variable_->var_value()->type(); - else if (this->variable_->is_result_variable()) - return this->variable_->result_var_value()->type(); - else - gcc_unreachable(); -} - -// Something takes the address of this variable. This means that we -// may want to move the variable onto the heap. - -void -Var_expression::do_address_taken(bool escapes) -{ - if (!escapes) - ; - else if (this->variable_->is_variable()) - this->variable_->var_value()->set_address_taken(); - else if (this->variable_->is_result_variable()) - this->variable_->result_var_value()->set_address_taken(); - else - gcc_unreachable(); -} - -// Get the tree for a reference to a variable. - -tree -Var_expression::do_get_tree(Translate_context* context) -{ - return this->variable_->get_tree(context->gogo(), context->function()); -} - -// Make a reference to a variable in an expression. - -Expression* -Expression::make_var_reference(Named_object* var, source_location location) -{ - if (var->is_sink()) - return Expression::make_sink(location); - - // FIXME: Creating a new object for each reference to a variable is - // wasteful. - return new Var_expression(var, location); -} - -// Class Temporary_reference_expression. - -// The type. - -Type* -Temporary_reference_expression::do_type() -{ - return this->statement_->type(); -} - -// Called if something takes the address of this temporary variable. -// We never have to move temporary variables to the heap, but we do -// need to know that they must live in the stack rather than in a -// register. - -void -Temporary_reference_expression::do_address_taken(bool) -{ - this->statement_->set_is_address_taken(); -} - -// Get a tree referring to the variable. - -tree -Temporary_reference_expression::do_get_tree(Translate_context*) -{ - return this->statement_->get_decl(); -} - -// Make a reference to a temporary variable. - -Expression* -Expression::make_temporary_reference(Temporary_statement* statement, - source_location location) -{ - return new Temporary_reference_expression(statement, location); -} - -// A sink expression--a use of the blank identifier _. - -class Sink_expression : public Expression -{ - public: - Sink_expression(source_location location) - : Expression(EXPRESSION_SINK, location), - type_(NULL), var_(NULL_TREE) - { } - - protected: - void - do_discarding_value() - { } - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - Expression* - do_copy() - { return new Sink_expression(this->location()); } - - tree - do_get_tree(Translate_context*); - - private: - // The type of this sink variable. - Type* type_; - // The temporary variable we generate. - tree var_; -}; - -// Return the type of a sink expression. - -Type* -Sink_expression::do_type() -{ - if (this->type_ == NULL) - return Type::make_sink_type(); - return this->type_; -} - -// Determine the type of a sink expression. - -void -Sink_expression::do_determine_type(const Type_context* context) -{ - if (context->type != NULL) - this->type_ = context->type; -} - -// Return a temporary variable for a sink expression. This will -// presumably be a write-only variable which the middle-end will drop. - -tree -Sink_expression::do_get_tree(Translate_context* context) -{ - if (this->var_ == NULL_TREE) - { - gcc_assert(this->type_ != NULL && !this->type_->is_sink_type()); - this->var_ = create_tmp_var(this->type_->get_tree(context->gogo()), - "blank"); - } - return this->var_; -} - -// Make a sink expression. - -Expression* -Expression::make_sink(source_location location) -{ - return new Sink_expression(location); -} - -// Class Func_expression. - -// FIXME: Can a function expression appear in a constant expression? -// The value is unchanging. Initializing a constant to the address of -// a function seems like it could work, though there might be little -// point to it. - -// Return the name of the function. - -const std::string& -Func_expression::name() const -{ - return this->function_->name(); -} - -// Traversal. - -int -Func_expression::do_traverse(Traverse* traverse) -{ - return (this->closure_ == NULL - ? TRAVERSE_CONTINUE - : Expression::traverse(&this->closure_, traverse)); -} - -// Return the type of a function expression. - -Type* -Func_expression::do_type() -{ - if (this->function_->is_function()) - return this->function_->func_value()->type(); - else if (this->function_->is_function_declaration()) - return this->function_->func_declaration_value()->type(); - else - gcc_unreachable(); -} - -// Get the tree for a function expression without evaluating the -// closure. - -tree -Func_expression::get_tree_without_closure(Gogo* gogo) -{ - Function_type* fntype; - if (this->function_->is_function()) - fntype = this->function_->func_value()->type(); - else if (this->function_->is_function_declaration()) - fntype = this->function_->func_declaration_value()->type(); - else - gcc_unreachable(); - - // Builtin functions are handled specially by Call_expression. We - // can't take their address. - if (fntype->is_builtin()) - { - error_at(this->location(), "invalid use of special builtin function %qs", - this->function_->name().c_str()); - return error_mark_node; - } - - Named_object* no = this->function_; - tree id = this->function_->get_id(gogo); - tree fndecl; - if (no->is_function()) - fndecl = no->func_value()->get_or_make_decl(gogo, no, id); - else if (no->is_function_declaration()) - fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no, id); - else - gcc_unreachable(); - - return build_fold_addr_expr_loc(this->location(), fndecl); -} - -// Get the tree for a function expression. This is used when we take -// the address of a function rather than simply calling it. If the -// function has a closure, we must use a trampoline. - -tree -Func_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - - tree fnaddr = this->get_tree_without_closure(gogo); - if (fnaddr == error_mark_node) - return error_mark_node; - - gcc_assert(TREE_CODE(fnaddr) == ADDR_EXPR - && TREE_CODE(TREE_OPERAND(fnaddr, 0)) == FUNCTION_DECL); - TREE_ADDRESSABLE(TREE_OPERAND(fnaddr, 0)) = 1; - - // For a normal non-nested function call, that is all we have to do. - if (!this->function_->is_function() - || this->function_->func_value()->enclosing() == NULL) - { - gcc_assert(this->closure_ == NULL); - return fnaddr; - } - - // For a nested function call, we have to always allocate a - // trampoline. If we don't always allocate, then closures will not - // be reliably distinct. - Expression* closure = this->closure_; - tree closure_tree; - if (closure == NULL) - closure_tree = null_pointer_node; - else - { - // Get the value of the closure. This will be a pointer to - // space allocated on the heap. - closure_tree = closure->get_tree(context); - if (closure_tree == error_mark_node) - return error_mark_node; - gcc_assert(POINTER_TYPE_P(TREE_TYPE(closure_tree))); - } - - // Now we need to build some code on the heap. This code will load - // the static chain pointer with the closure and then jump to the - // body of the function. The normal gcc approach is to build the - // code on the stack. Unfortunately we can not do that, as Go - // permits us to return the function pointer. - - return gogo->make_trampoline(fnaddr, closure_tree, this->location()); -} - -// Make a reference to a function in an expression. - -Expression* -Expression::make_func_reference(Named_object* function, Expression* closure, - source_location location) -{ - return new Func_expression(function, closure, location); -} - -// Class Unknown_expression. - -// Return the name of an unknown expression. - -const std::string& -Unknown_expression::name() const -{ - return this->named_object_->name(); -} - -// Lower a reference to an unknown name. - -Expression* -Unknown_expression::do_lower(Gogo*, Named_object*, int) -{ - source_location location = this->location(); - Named_object* no = this->named_object_; - Named_object* real = no->unknown_value()->real_named_object(); - if (real == NULL) - { - if (this->is_composite_literal_key_) - return this; - error_at(location, "reference to undefined name %qs", - this->named_object_->message_name().c_str()); - return Expression::make_error(location); - } - switch (real->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - return Expression::make_const_reference(real, location); - case Named_object::NAMED_OBJECT_TYPE: - return Expression::make_type(real->type_value(), location); - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - if (this->is_composite_literal_key_) - return this; - error_at(location, "reference to undefined type %qs", - real->message_name().c_str()); - return Expression::make_error(location); - case Named_object::NAMED_OBJECT_VAR: - return Expression::make_var_reference(real, location); - case Named_object::NAMED_OBJECT_FUNC: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - return Expression::make_func_reference(real, NULL, location); - case Named_object::NAMED_OBJECT_PACKAGE: - if (this->is_composite_literal_key_) - return this; - error_at(location, "unexpected reference to package"); - return Expression::make_error(location); - default: - gcc_unreachable(); - } -} - -// Make a reference to an unknown name. - -Expression* -Expression::make_unknown_reference(Named_object* no, source_location location) -{ - gcc_assert(no->resolve()->is_unknown()); - return new Unknown_expression(no, location); -} - -// A boolean expression. - -class Boolean_expression : public Expression -{ - public: - Boolean_expression(bool val, source_location location) - : Expression(EXPRESSION_BOOLEAN, location), - val_(val), type_(NULL) - { } - - static Expression* - do_import(Import*); - - protected: - bool - do_is_constant() const - { return true; } - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context*) - { return this->val_ ? boolean_true_node : boolean_false_node; } - - void - do_export(Export* exp) const - { exp->write_c_string(this->val_ ? "true" : "false"); } - - private: - // The constant. - bool val_; - // The type as determined by context. - Type* type_; -}; - -// Get the type. - -Type* -Boolean_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_boolean_type(); - return this->type_; -} - -// Set the type from the context. - -void -Boolean_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL && context->type->is_boolean_type()) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_bool_type(); -} - -// Import a boolean constant. - -Expression* -Boolean_expression::do_import(Import* imp) -{ - if (imp->peek_char() == 't') - { - imp->require_c_string("true"); - return Expression::make_boolean(true, imp->location()); - } - else - { - imp->require_c_string("false"); - return Expression::make_boolean(false, imp->location()); - } -} - -// Make a boolean expression. - -Expression* -Expression::make_boolean(bool val, source_location location) -{ - return new Boolean_expression(val, location); -} - -// Class String_expression. - -// Get the type. - -Type* -String_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_string_type(); - return this->type_; -} - -// Set the type from the context. - -void -String_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL && context->type->is_string_type()) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_string_type(); -} - -// Build a string constant. - -tree -String_expression::do_get_tree(Translate_context* context) -{ - return context->gogo()->go_string_constant_tree(this->val_); -} - -// Export a string expression. - -void -String_expression::do_export(Export* exp) const -{ - std::string s; - s.reserve(this->val_.length() * 4 + 2); - s += '"'; - for (std::string::const_iterator p = this->val_.begin(); - p != this->val_.end(); - ++p) - { - if (*p == '\\' || *p == '"') - { - s += '\\'; - s += *p; - } - else if (*p >= 0x20 && *p < 0x7f) - s += *p; - else if (*p == '\n') - s += "\\n"; - else if (*p == '\t') - s += "\\t"; - else - { - s += "\\x"; - unsigned char c = *p; - unsigned int dig = c >> 4; - s += dig < 10 ? '0' + dig : 'A' + dig - 10; - dig = c & 0xf; - s += dig < 10 ? '0' + dig : 'A' + dig - 10; - } - } - s += '"'; - exp->write_string(s); -} - -// Import a string expression. - -Expression* -String_expression::do_import(Import* imp) -{ - imp->require_c_string("\""); - std::string val; - while (true) - { - int c = imp->get_char(); - if (c == '"' || c == -1) - break; - if (c != '\\') - val += static_cast(c); - else - { - c = imp->get_char(); - if (c == '\\' || c == '"') - val += static_cast(c); - else if (c == 'n') - val += '\n'; - else if (c == 't') - val += '\t'; - else if (c == 'x') - { - c = imp->get_char(); - unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10; - c = imp->get_char(); - unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10; - char v = (vh << 4) | vl; - val += v; - } - else - { - error_at(imp->location(), "bad string constant"); - return Expression::make_error(imp->location()); - } - } - } - return Expression::make_string(val, imp->location()); -} - -// Make a string expression. - -Expression* -Expression::make_string(const std::string& val, source_location location) -{ - return new String_expression(val, location); -} - -// Make an integer expression. - -class Integer_expression : public Expression -{ - public: - Integer_expression(const mpz_t* val, Type* type, source_location location) - : Expression(EXPRESSION_INTEGER, location), - type_(type) - { mpz_init_set(this->val_, *val); } - - static Expression* - do_import(Import*); - - // Return whether VAL fits in the type. - static bool - check_constant(mpz_t val, Type*, source_location); - - // Write VAL to export data. - static void - export_integer(Export* exp, const mpz_t val); - - protected: - bool - do_is_constant() const - { return true; } - - bool - do_integer_constant_value(bool, mpz_t val, Type** ptype) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context* context); - - void - do_check_types(Gogo*); - - tree - do_get_tree(Translate_context*); - - Expression* - do_copy() - { return Expression::make_integer(&this->val_, this->type_, - this->location()); } - - void - do_export(Export*) const; - - private: - // The integer value. - mpz_t val_; - // The type so far. - Type* type_; -}; - -// Return an integer constant value. - -bool -Integer_expression::do_integer_constant_value(bool, mpz_t val, - Type** ptype) const -{ - if (this->type_ != NULL) - *ptype = this->type_; - mpz_set(val, this->val_); - return true; -} - -// Return the current type. If we haven't set the type yet, we return -// an abstract integer type. - -Type* -Integer_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_abstract_integer_type(); - return this->type_; -} - -// Set the type of the integer value. Here we may switch from an -// abstract type to a real type. - -void -Integer_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL - && (context->type->integer_type() != NULL - || context->type->float_type() != NULL - || context->type->complex_type() != NULL)) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_integer_type("int"); -} - -// Return true if the integer VAL fits in the range of the type TYPE. -// Otherwise give an error and return false. TYPE may be NULL. - -bool -Integer_expression::check_constant(mpz_t val, Type* type, - source_location location) -{ - if (type == NULL) - return true; - Integer_type* itype = type->integer_type(); - if (itype == NULL || itype->is_abstract()) - return true; - - int bits = mpz_sizeinbase(val, 2); - - if (itype->is_unsigned()) - { - // For an unsigned type we can only accept a nonnegative number, - // and we must be able to represent at least BITS. - if (mpz_sgn(val) >= 0 - && bits <= itype->bits()) - return true; - } - else - { - // For a signed type we need an extra bit to indicate the sign. - // We have to handle the most negative integer specially. - if (bits + 1 <= itype->bits() - || (bits <= itype->bits() - && mpz_sgn(val) < 0 - && (mpz_scan1(val, 0) - == static_cast(itype->bits() - 1)) - && mpz_scan0(val, itype->bits()) == ULONG_MAX)) - return true; - } - - error_at(location, "integer constant overflow"); - return false; -} - -// Check the type of an integer constant. - -void -Integer_expression::do_check_types(Gogo*) -{ - if (this->type_ == NULL) - return; - if (!Integer_expression::check_constant(this->val_, this->type_, - this->location())) - this->set_is_error(); -} - -// Get a tree for an integer constant. - -tree -Integer_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type; - if (this->type_ != NULL && !this->type_->is_abstract()) - type = this->type_->get_tree(gogo); - else if (this->type_ != NULL && this->type_->float_type() != NULL) - { - // We are converting to an abstract floating point type. - type = Type::lookup_float_type("float64")->get_tree(gogo); - } - else if (this->type_ != NULL && this->type_->complex_type() != NULL) - { - // We are converting to an abstract complex type. - type = Type::lookup_complex_type("complex128")->get_tree(gogo); - } - else - { - // If we still have an abstract type here, then this is being - // used in a constant expression which didn't get reduced for - // some reason. Use a type which will fit the value. We use <, - // not <=, because we need an extra bit for the sign bit. - int bits = mpz_sizeinbase(this->val_, 2); - if (bits < INT_TYPE_SIZE) - type = Type::lookup_integer_type("int")->get_tree(gogo); - else if (bits < 64) - type = Type::lookup_integer_type("int64")->get_tree(gogo); - else - type = long_long_integer_type_node; - } - return Expression::integer_constant_tree(this->val_, type); -} - -// Write VAL to export data. - -void -Integer_expression::export_integer(Export* exp, const mpz_t val) -{ - char* s = mpz_get_str(NULL, 10, val); - exp->write_c_string(s); - free(s); -} - -// Export an integer in a constant expression. - -void -Integer_expression::do_export(Export* exp) const -{ - Integer_expression::export_integer(exp, this->val_); - // A trailing space lets us reliably identify the end of the number. - exp->write_c_string(" "); -} - -// Import an integer, floating point, or complex value. This handles -// all these types because they all start with digits. - -Expression* -Integer_expression::do_import(Import* imp) -{ - std::string num = imp->read_identifier(); - imp->require_c_string(" "); - if (!num.empty() && num[num.length() - 1] == 'i') - { - mpfr_t real; - size_t plus_pos = num.find('+', 1); - size_t minus_pos = num.find('-', 1); - size_t pos; - if (plus_pos == std::string::npos) - pos = minus_pos; - else if (minus_pos == std::string::npos) - pos = plus_pos; - else - { - error_at(imp->location(), "bad number in import data: %qs", - num.c_str()); - return Expression::make_error(imp->location()); - } - if (pos == std::string::npos) - mpfr_set_ui(real, 0, GMP_RNDN); - else - { - std::string real_str = num.substr(0, pos); - if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0) - { - error_at(imp->location(), "bad number in import data: %qs", - real_str.c_str()); - return Expression::make_error(imp->location()); - } - } - - std::string imag_str; - if (pos == std::string::npos) - imag_str = num; - else - imag_str = num.substr(pos); - imag_str = imag_str.substr(0, imag_str.size() - 1); - mpfr_t imag; - if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0) - { - error_at(imp->location(), "bad number in import data: %qs", - imag_str.c_str()); - return Expression::make_error(imp->location()); - } - Expression* ret = Expression::make_complex(&real, &imag, NULL, - imp->location()); - mpfr_clear(real); - mpfr_clear(imag); - return ret; - } - else if (num.find('.') == std::string::npos - && num.find('E') == std::string::npos) - { - mpz_t val; - if (mpz_init_set_str(val, num.c_str(), 10) != 0) - { - error_at(imp->location(), "bad number in import data: %qs", - num.c_str()); - return Expression::make_error(imp->location()); - } - Expression* ret = Expression::make_integer(&val, NULL, imp->location()); - mpz_clear(val); - return ret; - } - else - { - mpfr_t val; - if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0) - { - error_at(imp->location(), "bad number in import data: %qs", - num.c_str()); - return Expression::make_error(imp->location()); - } - Expression* ret = Expression::make_float(&val, NULL, imp->location()); - mpfr_clear(val); - return ret; - } -} - -// Build a new integer value. - -Expression* -Expression::make_integer(const mpz_t* val, Type* type, - source_location location) -{ - return new Integer_expression(val, type, location); -} - -// Floats. - -class Float_expression : public Expression -{ - public: - Float_expression(const mpfr_t* val, Type* type, source_location location) - : Expression(EXPRESSION_FLOAT, location), - type_(type) - { - mpfr_init_set(this->val_, *val, GMP_RNDN); - } - - // Constrain VAL to fit into TYPE. - static void - constrain_float(mpfr_t val, Type* type); - - // Return whether VAL fits in the type. - static bool - check_constant(mpfr_t val, Type*, source_location); - - // Write VAL to export data. - static void - export_float(Export* exp, const mpfr_t val); - - protected: - bool - do_is_constant() const - { return true; } - - bool - do_float_constant_value(mpfr_t val, Type**) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { return Expression::make_float(&this->val_, this->type_, - this->location()); } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The floating point value. - mpfr_t val_; - // The type so far. - Type* type_; -}; - -// Constrain VAL to fit into TYPE. - -void -Float_expression::constrain_float(mpfr_t val, Type* type) -{ - Float_type* ftype = type->float_type(); - if (ftype != NULL && !ftype->is_abstract()) - { - tree type_tree = ftype->type_tree(); - REAL_VALUE_TYPE rvt; - real_from_mpfr(&rvt, val, type_tree, GMP_RNDN); - real_convert(&rvt, TYPE_MODE(type_tree), &rvt); - mpfr_from_real(val, &rvt, GMP_RNDN); - } -} - -// Return a floating point constant value. - -bool -Float_expression::do_float_constant_value(mpfr_t val, Type** ptype) const -{ - if (this->type_ != NULL) - *ptype = this->type_; - mpfr_set(val, this->val_, GMP_RNDN); - return true; -} - -// Return the current type. If we haven't set the type yet, we return -// an abstract float type. - -Type* -Float_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_abstract_float_type(); - return this->type_; -} - -// Set the type of the float value. Here we may switch from an -// abstract type to a real type. - -void -Float_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL - && (context->type->integer_type() != NULL - || context->type->float_type() != NULL - || context->type->complex_type() != NULL)) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_float_type("float"); -} - -// Return true if the floating point value VAL fits in the range of -// the type TYPE. Otherwise give an error and return false. TYPE may -// be NULL. - -bool -Float_expression::check_constant(mpfr_t val, Type* type, - source_location location) -{ - if (type == NULL) - return true; - Float_type* ftype = type->float_type(); - if (ftype == NULL || ftype->is_abstract()) - return true; - - // A NaN or Infinity always fits in the range of the type. - if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val)) - return true; - - mp_exp_t exp = mpfr_get_exp(val); - mp_exp_t max_exp; - switch (ftype->bits()) - { - case 32: - max_exp = 128; - break; - case 64: - max_exp = 1024; - break; - default: - gcc_unreachable(); - } - if (exp > max_exp) - { - error_at(location, "floating point constant overflow"); - return false; - } - return true; -} - -// Check the type of a float value. - -void -Float_expression::do_check_types(Gogo*) -{ - if (this->type_ == NULL) - return; - - if (!Float_expression::check_constant(this->val_, this->type_, - this->location())) - this->set_is_error(); - - Integer_type* integer_type = this->type_->integer_type(); - if (integer_type != NULL) - { - if (!mpfr_integer_p(this->val_)) - this->report_error(_("floating point constant truncated to integer")); - else - { - gcc_assert(!integer_type->is_abstract()); - mpz_t ival; - mpz_init(ival); - mpfr_get_z(ival, this->val_, GMP_RNDN); - Integer_expression::check_constant(ival, integer_type, - this->location()); - mpz_clear(ival); - } - } -} - -// Get a tree for a float constant. - -tree -Float_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type; - if (this->type_ != NULL && !this->type_->is_abstract()) - type = this->type_->get_tree(gogo); - else if (this->type_ != NULL && this->type_->integer_type() != NULL) - { - // We have an abstract integer type. We just hope for the best. - type = Type::lookup_integer_type("int")->get_tree(gogo); - } - else - { - // If we still have an abstract type here, then this is being - // used in a constant expression which didn't get reduced. We - // just use float64 and hope for the best. - type = Type::lookup_float_type("float64")->get_tree(gogo); - } - return Expression::float_constant_tree(this->val_, type); -} - -// Write a floating point number to export data. - -void -Float_expression::export_float(Export *exp, const mpfr_t val) -{ - mp_exp_t exponent; - char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN); - if (*s == '-') - exp->write_c_string("-"); - exp->write_c_string("0."); - exp->write_c_string(*s == '-' ? s + 1 : s); - mpfr_free_str(s); - char buf[30]; - snprintf(buf, sizeof buf, "E%ld", exponent); - exp->write_c_string(buf); -} - -// Export a floating point number in a constant expression. - -void -Float_expression::do_export(Export* exp) const -{ - Float_expression::export_float(exp, this->val_); - // A trailing space lets us reliably identify the end of the number. - exp->write_c_string(" "); -} - -// Make a float expression. - -Expression* -Expression::make_float(const mpfr_t* val, Type* type, source_location location) -{ - return new Float_expression(val, type, location); -} - -// Complex numbers. - -class Complex_expression : public Expression -{ - public: - Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type, - source_location location) - : Expression(EXPRESSION_COMPLEX, location), - type_(type) - { - mpfr_init_set(this->real_, *real, GMP_RNDN); - mpfr_init_set(this->imag_, *imag, GMP_RNDN); - } - - // Constrain REAL/IMAG to fit into TYPE. - static void - constrain_complex(mpfr_t real, mpfr_t imag, Type* type); - - // Return whether REAL/IMAG fits in the type. - static bool - check_constant(mpfr_t real, mpfr_t imag, Type*, source_location); - - // Write REAL/IMAG to export data. - static void - export_complex(Export* exp, const mpfr_t real, const mpfr_t val); - - protected: - bool - do_is_constant() const - { return true; } - - bool - do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return Expression::make_complex(&this->real_, &this->imag_, this->type_, - this->location()); - } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The real part. - mpfr_t real_; - // The imaginary part; - mpfr_t imag_; - // The type if known. - Type* type_; -}; - -// Constrain REAL/IMAG to fit into TYPE. - -void -Complex_expression::constrain_complex(mpfr_t real, mpfr_t imag, Type* type) -{ - Complex_type* ctype = type->complex_type(); - if (ctype != NULL && !ctype->is_abstract()) - { - tree type_tree = ctype->type_tree(); - - REAL_VALUE_TYPE rvt; - real_from_mpfr(&rvt, real, TREE_TYPE(type_tree), GMP_RNDN); - real_convert(&rvt, TYPE_MODE(TREE_TYPE(type_tree)), &rvt); - mpfr_from_real(real, &rvt, GMP_RNDN); - - real_from_mpfr(&rvt, imag, TREE_TYPE(type_tree), GMP_RNDN); - real_convert(&rvt, TYPE_MODE(TREE_TYPE(type_tree)), &rvt); - mpfr_from_real(imag, &rvt, GMP_RNDN); - } -} - -// Return a complex constant value. - -bool -Complex_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - if (this->type_ != NULL) - *ptype = this->type_; - mpfr_set(real, this->real_, GMP_RNDN); - mpfr_set(imag, this->imag_, GMP_RNDN); - return true; -} - -// Return the current type. If we haven't set the type yet, we return -// an abstract complex type. - -Type* -Complex_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_abstract_complex_type(); - return this->type_; -} - -// Set the type of the complex value. Here we may switch from an -// abstract type to a real type. - -void -Complex_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL - && context->type->complex_type() != NULL) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_complex_type("complex"); -} - -// Return true if the complex value REAL/IMAG fits in the range of the -// type TYPE. Otherwise give an error and return false. TYPE may be -// NULL. - -bool -Complex_expression::check_constant(mpfr_t real, mpfr_t imag, Type* type, - source_location location) -{ - if (type == NULL) - return true; - Complex_type* ctype = type->complex_type(); - if (ctype == NULL || ctype->is_abstract()) - return true; - - mp_exp_t max_exp; - switch (ctype->bits()) - { - case 64: - max_exp = 128; - break; - case 128: - max_exp = 1024; - break; - default: - gcc_unreachable(); - } - - // A NaN or Infinity always fits in the range of the type. - if (!mpfr_nan_p(real) && !mpfr_inf_p(real) && !mpfr_zero_p(real)) - { - if (mpfr_get_exp(real) > max_exp) - { - error_at(location, "complex real part constant overflow"); - return false; - } - } - - if (!mpfr_nan_p(imag) && !mpfr_inf_p(imag) && !mpfr_zero_p(imag)) - { - if (mpfr_get_exp(imag) > max_exp) - { - error_at(location, "complex imaginary part constant overflow"); - return false; - } - } - - return true; -} - -// Check the type of a complex value. - -void -Complex_expression::do_check_types(Gogo*) -{ - if (this->type_ == NULL) - return; - - if (!Complex_expression::check_constant(this->real_, this->imag_, - this->type_, this->location())) - this->set_is_error(); -} - -// Get a tree for a complex constant. - -tree -Complex_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type; - if (this->type_ != NULL && !this->type_->is_abstract()) - type = this->type_->get_tree(gogo); - else - { - // If we still have an abstract type here, this this is being - // used in a constant expression which didn't get reduced. We - // just use complex128 and hope for the best. - type = Type::lookup_complex_type("complex128")->get_tree(gogo); - } - return Expression::complex_constant_tree(this->real_, this->imag_, type); -} - -// Write REAL/IMAG to export data. - -void -Complex_expression::export_complex(Export* exp, const mpfr_t real, - const mpfr_t imag) -{ - if (!mpfr_zero_p(real)) - { - Float_expression::export_float(exp, real); - if (mpfr_sgn(imag) > 0) - exp->write_c_string("+"); - } - Float_expression::export_float(exp, imag); - exp->write_c_string("i"); -} - -// Export a complex number in a constant expression. - -void -Complex_expression::do_export(Export* exp) const -{ - Complex_expression::export_complex(exp, this->real_, this->imag_); - // A trailing space lets us reliably identify the end of the number. - exp->write_c_string(" "); -} - -// Make a complex expression. - -Expression* -Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type, - source_location location) -{ - return new Complex_expression(real, imag, type, location); -} - -// A reference to a const in an expression. - -class Const_expression : public Expression -{ - public: - Const_expression(Named_object* constant, source_location location) - : Expression(EXPRESSION_CONST_REFERENCE, location), - constant_(constant), type_(NULL) - { } - - const std::string& - name() const - { return this->constant_->name(); } - - protected: - Expression* - do_lower(Gogo*, Named_object*, int); - - bool - do_is_constant() const - { return true; } - - bool - do_integer_constant_value(bool, mpz_t val, Type**) const; - - bool - do_float_constant_value(mpfr_t val, Type**) const; - - bool - do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const; - - bool - do_string_constant_value(std::string* val) const - { return this->constant_->const_value()->expr()->string_constant_value(val); } - - Type* - do_type(); - - // The type of a const is set by the declaration, not the use. - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context* context); - - // When exporting a reference to a const as part of a const - // expression, we export the value. We ignore the fact that it has - // a name. - void - do_export(Export* exp) const - { this->constant_->const_value()->expr()->export_expression(exp); } - - private: - // The constant. - Named_object* constant_; - // The type of this reference. This is used if the constant has an - // abstract type. - Type* type_; -}; - -// Lower a constant expression. This is where we convert the -// predeclared constant iota into an integer value. - -Expression* -Const_expression::do_lower(Gogo* gogo, Named_object*, int iota_value) -{ - if (this->constant_->const_value()->expr()->classification() - == EXPRESSION_IOTA) - { - if (iota_value == -1) - { - error_at(this->location(), - "iota is only defined in const declarations"); - iota_value = 0; - } - mpz_t val; - mpz_init_set_ui(val, static_cast(iota_value)); - Expression* ret = Expression::make_integer(&val, NULL, - this->location()); - mpz_clear(val); - return ret; - } - - // Make sure that the constant itself has been lowered. - gogo->lower_constant(this->constant_); - - return this; -} - -// Return an integer constant value. - -bool -Const_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val, - Type** ptype) const -{ - Type* ctype; - if (this->type_ != NULL) - ctype = this->type_; - else - ctype = this->constant_->const_value()->type(); - if (ctype != NULL && ctype->integer_type() == NULL) - return false; - - Expression* e = this->constant_->const_value()->expr(); - Type* t; - bool r = e->integer_constant_value(iota_is_constant, val, &t); - - if (r - && ctype != NULL - && !Integer_expression::check_constant(val, ctype, this->location())) - return false; - - *ptype = ctype != NULL ? ctype : t; - return r; -} - -// Return a floating point constant value. - -bool -Const_expression::do_float_constant_value(mpfr_t val, Type** ptype) const -{ - Type* ctype; - if (this->type_ != NULL) - ctype = this->type_; - else - ctype = this->constant_->const_value()->type(); - if (ctype != NULL && ctype->float_type() == NULL) - return false; - - Type* t; - bool r = this->constant_->const_value()->expr()->float_constant_value(val, - &t); - if (r && ctype != NULL) - { - if (!Float_expression::check_constant(val, ctype, this->location())) - return false; - Float_expression::constrain_float(val, ctype); - } - *ptype = ctype != NULL ? ctype : t; - return r; -} - -// Return a complex constant value. - -bool -Const_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type **ptype) const -{ - Type* ctype; - if (this->type_ != NULL) - ctype = this->type_; - else - ctype = this->constant_->const_value()->type(); - if (ctype != NULL && ctype->complex_type() == NULL) - return false; - - Type *t; - bool r = this->constant_->const_value()->expr()->complex_constant_value(real, - imag, - &t); - if (r && ctype != NULL) - { - if (!Complex_expression::check_constant(real, imag, ctype, - this->location())) - return false; - Complex_expression::constrain_complex(real, imag, ctype); - } - *ptype = ctype != NULL ? ctype : t; - return r; -} - -// Return the type of the const reference. - -Type* -Const_expression::do_type() -{ - if (this->type_ != NULL) - return this->type_; - Named_constant* nc = this->constant_->const_value(); - Type* ret = nc->type(); - if (ret != NULL) - return ret; - // During parsing, a named constant may have a NULL type, but we - // must not return a NULL type here. - return nc->expr()->type(); -} - -// Set the type of the const reference. - -void -Const_expression::do_determine_type(const Type_context* context) -{ - Type* ctype = this->constant_->const_value()->type(); - Type* cetype = (ctype != NULL - ? ctype - : this->constant_->const_value()->expr()->type()); - if (ctype != NULL && !ctype->is_abstract()) - ; - else if (context->type != NULL - && (context->type->integer_type() != NULL - || context->type->float_type() != NULL - || context->type->complex_type() != NULL) - && (cetype->integer_type() != NULL - || cetype->float_type() != NULL - || cetype->complex_type() != NULL)) - this->type_ = context->type; - else if (context->type != NULL - && context->type->is_string_type() - && cetype->is_string_type()) - this->type_ = context->type; - else if (context->type != NULL - && context->type->is_boolean_type() - && cetype->is_boolean_type()) - this->type_ = context->type; - else if (!context->may_be_abstract) - { - if (cetype->is_abstract()) - cetype = cetype->make_non_abstract_type(); - this->type_ = cetype; - } -} - -// Check types of a const reference. - -void -Const_expression::do_check_types(Gogo*) -{ - if (this->type_ == NULL || this->type_->is_abstract()) - return; - - // Check for integer overflow. - if (this->type_->integer_type() != NULL) - { - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (!this->integer_constant_value(true, ival, &dummy)) - { - mpfr_t fval; - mpfr_init(fval); - Expression* cexpr = this->constant_->const_value()->expr(); - if (cexpr->float_constant_value(fval, &dummy)) - { - if (!mpfr_integer_p(fval)) - this->report_error(_("floating point constant " - "truncated to integer")); - else - { - mpfr_get_z(ival, fval, GMP_RNDN); - Integer_expression::check_constant(ival, this->type_, - this->location()); - } - } - mpfr_clear(fval); - } - mpz_clear(ival); - } -} - -// Return a tree for the const reference. - -tree -Const_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type_tree; - if (this->type_ == NULL) - type_tree = NULL_TREE; - else - { - type_tree = this->type_->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - } - - // If the type has been set for this expression, but the underlying - // object is an abstract int or float, we try to get the abstract - // value. Otherwise we may lose something in the conversion. - if (this->type_ != NULL - && this->constant_->const_value()->type()->is_abstract()) - { - Expression* expr = this->constant_->const_value()->expr(); - mpz_t ival; - mpz_init(ival); - Type* t; - if (expr->integer_constant_value(true, ival, &t)) - { - tree ret = Expression::integer_constant_tree(ival, type_tree); - mpz_clear(ival); - return ret; - } - mpz_clear(ival); - - mpfr_t fval; - mpfr_init(fval); - if (expr->float_constant_value(fval, &t)) - { - tree ret = Expression::float_constant_tree(fval, type_tree); - mpfr_clear(fval); - return ret; - } - - mpfr_t imag; - mpfr_init(imag); - if (expr->complex_constant_value(fval, imag, &t)) - { - tree ret = Expression::complex_constant_tree(fval, imag, type_tree); - mpfr_clear(fval); - mpfr_clear(imag); - return ret; - } - mpfr_clear(imag); - mpfr_clear(fval); - } - - tree const_tree = this->constant_->get_tree(gogo, context->function()); - if (this->type_ == NULL - || const_tree == error_mark_node - || TREE_TYPE(const_tree) == error_mark_node) - return const_tree; - - tree ret; - if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree))) - ret = fold_convert(type_tree, const_tree); - else if (TREE_CODE(type_tree) == INTEGER_TYPE) - ret = fold(convert_to_integer(type_tree, const_tree)); - else if (TREE_CODE(type_tree) == REAL_TYPE) - ret = fold(convert_to_real(type_tree, const_tree)); - else if (TREE_CODE(type_tree) == COMPLEX_TYPE) - ret = fold(convert_to_complex(type_tree, const_tree)); - else - gcc_unreachable(); - return ret; -} - -// Make a reference to a constant in an expression. - -Expression* -Expression::make_const_reference(Named_object* constant, - source_location location) -{ - return new Const_expression(constant, location); -} - -// The nil value. - -class Nil_expression : public Expression -{ - public: - Nil_expression(source_location location) - : Expression(EXPRESSION_NIL, location) - { } - - static Expression* - do_import(Import*); - - protected: - bool - do_is_constant() const - { return true; } - - Type* - do_type() - { return Type::make_nil_type(); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context*) - { return null_pointer_node; } - - void - do_export(Export* exp) const - { exp->write_c_string("nil"); } -}; - -// Import a nil expression. - -Expression* -Nil_expression::do_import(Import* imp) -{ - imp->require_c_string("nil"); - return Expression::make_nil(imp->location()); -} - -// Make a nil expression. - -Expression* -Expression::make_nil(source_location location) -{ - return new Nil_expression(location); -} - -// The value of the predeclared constant iota. This is little more -// than a marker. This will be lowered to an integer in -// Const_expression::do_lower, which is where we know the value that -// it should have. - -class Iota_expression : public Parser_expression -{ - public: - Iota_expression(source_location location) - : Parser_expression(EXPRESSION_IOTA, location) - { } - - protected: - Expression* - do_lower(Gogo*, Named_object*, int) - { gcc_unreachable(); } - - // There should only ever be one of these. - Expression* - do_copy() - { gcc_unreachable(); } -}; - -// Make an iota expression. This is only called for one case: the -// value of the predeclared constant iota. - -Expression* -Expression::make_iota() -{ - static Iota_expression iota_expression(UNKNOWN_LOCATION); - return &iota_expression; -} - -// A type conversion expression. - -class Type_conversion_expression : public Expression -{ - public: - Type_conversion_expression(Type* type, Expression* expr, - source_location location) - : Expression(EXPRESSION_CONVERSION, location), - type_(type), expr_(expr), may_convert_function_types_(false) - { } - - // Return the type to which we are converting. - Type* - type() const - { return this->type_; } - - // Return the expression which we are converting. - Expression* - expr() const - { return this->expr_; } - - // Permit converting from one function type to another. This is - // used internally for method expressions. - void - set_may_convert_function_types() - { - this->may_convert_function_types_ = true; - } - - // Import a type conversion expression. - static Expression* - do_import(Import*); - - protected: - int - do_traverse(Traverse* traverse); - - Expression* - do_lower(Gogo*, Named_object*, int); - - bool - do_is_constant() const - { return this->expr_->is_constant(); } - - bool - do_integer_constant_value(bool, mpz_t, Type**) const; - - bool - do_float_constant_value(mpfr_t, Type**) const; - - bool - do_complex_constant_value(mpfr_t, mpfr_t, Type**) const; - - bool - do_string_constant_value(std::string*) const; - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*) - { - Type_context subcontext(this->type_, false); - this->expr_->determine_type(&subcontext); - } - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Type_conversion_expression(this->type_, this->expr_->copy(), - this->location()); - } - - tree - do_get_tree(Translate_context* context); - - void - do_export(Export*) const; - - private: - // The type to convert to. - Type* type_; - // The expression to convert. - Expression* expr_; - // True if this is permitted to convert function types. This is - // used internally for method expressions. - bool may_convert_function_types_; -}; - -// Traversal. - -int -Type_conversion_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT - || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Convert to a constant at lowering time. - -Expression* -Type_conversion_expression::do_lower(Gogo*, Named_object*, int) -{ - Type* type = this->type_; - Expression* val = this->expr_; - source_location location = this->location(); - - if (type->integer_type() != NULL) - { - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (val->integer_constant_value(false, ival, &dummy)) - { - if (!Integer_expression::check_constant(ival, type, location)) - mpz_set_ui(ival, 0); - Expression* ret = Expression::make_integer(&ival, type, location); - mpz_clear(ival); - return ret; - } - - mpfr_t fval; - mpfr_init(fval); - if (val->float_constant_value(fval, &dummy)) - { - if (!mpfr_integer_p(fval)) - { - error_at(location, - "floating point constant truncated to integer"); - return Expression::make_error(location); - } - mpfr_get_z(ival, fval, GMP_RNDN); - if (!Integer_expression::check_constant(ival, type, location)) - mpz_set_ui(ival, 0); - Expression* ret = Expression::make_integer(&ival, type, location); - mpfr_clear(fval); - mpz_clear(ival); - return ret; - } - mpfr_clear(fval); - mpz_clear(ival); - } - - if (type->float_type() != NULL) - { - mpfr_t fval; - mpfr_init(fval); - Type* dummy; - if (val->float_constant_value(fval, &dummy)) - { - if (!Float_expression::check_constant(fval, type, location)) - mpfr_set_ui(fval, 0, GMP_RNDN); - Float_expression::constrain_float(fval, type); - Expression *ret = Expression::make_float(&fval, type, location); - mpfr_clear(fval); - return ret; - } - mpfr_clear(fval); - } - - if (type->complex_type() != NULL) - { - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - Type* dummy; - if (val->complex_constant_value(real, imag, &dummy)) - { - if (!Complex_expression::check_constant(real, imag, type, location)) - { - mpfr_set_ui(real, 0, GMP_RNDN); - mpfr_set_ui(imag, 0, GMP_RNDN); - } - Complex_expression::constrain_complex(real, imag, type); - Expression* ret = Expression::make_complex(&real, &imag, type, - location); - mpfr_clear(real); - mpfr_clear(imag); - return ret; - } - mpfr_clear(real); - mpfr_clear(imag); - } - - if (type->is_open_array_type() && type->named_type() == NULL) - { - Type* element_type = type->array_type()->element_type()->forwarded(); - bool is_byte = element_type == Type::lookup_integer_type("uint8"); - bool is_int = element_type == Type::lookup_integer_type("int"); - if (is_byte || is_int) - { - std::string s; - if (val->string_constant_value(&s)) - { - Expression_list* vals = new Expression_list(); - if (is_byte) - { - for (std::string::const_iterator p = s.begin(); - p != s.end(); - p++) - { - mpz_t val; - mpz_init_set_ui(val, static_cast(*p)); - Expression* v = Expression::make_integer(&val, - element_type, - location); - vals->push_back(v); - mpz_clear(val); - } - } - else - { - const char *p = s.data(); - const char *pend = s.data() + s.length(); - while (p < pend) - { - unsigned int c; - int adv = Lex::fetch_char(p, &c); - if (adv == 0) - { - warning_at(this->location(), 0, - "invalid UTF-8 encoding"); - adv = 1; - } - p += adv; - mpz_t val; - mpz_init_set_ui(val, c); - Expression* v = Expression::make_integer(&val, - element_type, - location); - vals->push_back(v); - mpz_clear(val); - } - } - - return Expression::make_slice_composite_literal(type, vals, - location); - } - } - } - - return this; -} - -// Return the constant integer value if there is one. - -bool -Type_conversion_expression::do_integer_constant_value(bool iota_is_constant, - mpz_t val, - Type** ptype) const -{ - if (this->type_->integer_type() == NULL) - return false; - - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (this->expr_->integer_constant_value(iota_is_constant, ival, &dummy)) - { - if (!Integer_expression::check_constant(ival, this->type_, - this->location())) - { - mpz_clear(ival); - return false; - } - mpz_set(val, ival); - mpz_clear(ival); - *ptype = this->type_; - return true; - } - mpz_clear(ival); - - mpfr_t fval; - mpfr_init(fval); - if (this->expr_->float_constant_value(fval, &dummy)) - { - mpfr_get_z(val, fval, GMP_RNDN); - mpfr_clear(fval); - if (!Integer_expression::check_constant(val, this->type_, - this->location())) - return false; - *ptype = this->type_; - return true; - } - mpfr_clear(fval); - - return false; -} - -// Return the constant floating point value if there is one. - -bool -Type_conversion_expression::do_float_constant_value(mpfr_t val, - Type** ptype) const -{ - if (this->type_->float_type() == NULL) - return false; - - mpfr_t fval; - mpfr_init(fval); - Type* dummy; - if (this->expr_->float_constant_value(fval, &dummy)) - { - if (!Float_expression::check_constant(fval, this->type_, - this->location())) - { - mpfr_clear(fval); - return false; - } - mpfr_set(val, fval, GMP_RNDN); - mpfr_clear(fval); - Float_expression::constrain_float(val, this->type_); - *ptype = this->type_; - return true; - } - mpfr_clear(fval); - - return false; -} - -// Return the constant complex value if there is one. - -bool -Type_conversion_expression::do_complex_constant_value(mpfr_t real, - mpfr_t imag, - Type **ptype) const -{ - if (this->type_->complex_type() == NULL) - return false; - - mpfr_t rval; - mpfr_t ival; - mpfr_init(rval); - mpfr_init(ival); - Type* dummy; - if (this->expr_->complex_constant_value(rval, ival, &dummy)) - { - if (!Complex_expression::check_constant(rval, ival, this->type_, - this->location())) - { - mpfr_clear(rval); - mpfr_clear(ival); - return false; - } - mpfr_set(real, rval, GMP_RNDN); - mpfr_set(imag, ival, GMP_RNDN); - mpfr_clear(rval); - mpfr_clear(ival); - Complex_expression::constrain_complex(real, imag, this->type_); - *ptype = this->type_; - return true; - } - mpfr_clear(rval); - mpfr_clear(ival); - - return false; -} - -// Return the constant string value if there is one. - -bool -Type_conversion_expression::do_string_constant_value(std::string* val) const -{ - if (this->type_->is_string_type() - && this->expr_->type()->integer_type() != NULL) - { - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (this->expr_->integer_constant_value(false, ival, &dummy)) - { - unsigned long ulval = mpz_get_ui(ival); - if (mpz_cmp_ui(ival, ulval) == 0) - { - Lex::append_char(ulval, true, val, this->location()); - mpz_clear(ival); - return true; - } - } - mpz_clear(ival); - } - - // FIXME: Could handle conversion from const []int here. - - return false; -} - -// Check that types are convertible. - -void -Type_conversion_expression::do_check_types(Gogo*) -{ - Type* type = this->type_; - Type* expr_type = this->expr_->type(); - std::string reason; - - if (this->may_convert_function_types_ - && type->function_type() != NULL - && expr_type->function_type() != NULL) - return; - - if (Type::are_convertible(type, expr_type, &reason)) - return; - - error_at(this->location(), "%s", reason.c_str()); - this->set_is_error(); -} - -// Get a tree for a type conversion. - -tree -Type_conversion_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type_tree = this->type_->get_tree(gogo); - tree expr_tree = this->expr_->get_tree(context); - - if (type_tree == error_mark_node - || expr_tree == error_mark_node - || TREE_TYPE(expr_tree) == error_mark_node) - return error_mark_node; - - if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree))) - return fold_convert(type_tree, expr_tree); - - Type* type = this->type_; - Type* expr_type = this->expr_->type(); - tree ret; - if (type->interface_type() != NULL || expr_type->interface_type() != NULL) - ret = Expression::convert_for_assignment(context, type, expr_type, - expr_tree, this->location()); - else if (type->integer_type() != NULL) - { - if (expr_type->integer_type() != NULL - || expr_type->float_type() != NULL - || expr_type->is_unsafe_pointer_type()) - ret = fold(convert_to_integer(type_tree, expr_tree)); - else - gcc_unreachable(); - } - else if (type->float_type() != NULL) - { - if (expr_type->integer_type() != NULL - || expr_type->float_type() != NULL) - ret = fold(convert_to_real(type_tree, expr_tree)); - else - gcc_unreachable(); - } - else if (type->complex_type() != NULL) - { - if (expr_type->complex_type() != NULL) - ret = fold(convert_to_complex(type_tree, expr_tree)); - else - gcc_unreachable(); - } - else if (type->is_string_type() - && expr_type->integer_type() != NULL) - { - expr_tree = fold_convert(integer_type_node, expr_tree); - if (host_integerp(expr_tree, 0)) - { - HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0); - std::string s; - Lex::append_char(intval, true, &s, this->location()); - Expression* se = Expression::make_string(s, this->location()); - return se->get_tree(context); - } - - static tree int_to_string_fndecl; - ret = Gogo::call_builtin(&int_to_string_fndecl, - this->location(), - "__go_int_to_string", - 1, - type_tree, - integer_type_node, - fold_convert(integer_type_node, expr_tree)); - } - else if (type->is_string_type() - && (expr_type->array_type() != NULL - || (expr_type->points_to() != NULL - && expr_type->points_to()->array_type() != NULL))) - { - Type* t = expr_type; - if (t->points_to() != NULL) - { - t = t->points_to(); - expr_tree = build_fold_indirect_ref(expr_tree); - } - if (!DECL_P(expr_tree)) - expr_tree = save_expr(expr_tree); - Array_type* a = t->array_type(); - Type* e = a->element_type()->forwarded(); - gcc_assert(e->integer_type() != NULL); - tree valptr = fold_convert(const_ptr_type_node, - a->value_pointer_tree(gogo, expr_tree)); - tree len = a->length_tree(gogo, expr_tree); - len = fold_convert_loc(this->location(), size_type_node, len); - if (e->integer_type()->is_unsigned() - && e->integer_type()->bits() == 8) - { - static tree byte_array_to_string_fndecl; - ret = Gogo::call_builtin(&byte_array_to_string_fndecl, - this->location(), - "__go_byte_array_to_string", - 2, - type_tree, - const_ptr_type_node, - valptr, - size_type_node, - len); - } - else - { - gcc_assert(e == Type::lookup_integer_type("int")); - static tree int_array_to_string_fndecl; - ret = Gogo::call_builtin(&int_array_to_string_fndecl, - this->location(), - "__go_int_array_to_string", - 2, - type_tree, - const_ptr_type_node, - valptr, - size_type_node, - len); - } - } - else if (type->is_open_array_type() && expr_type->is_string_type()) - { - Type* e = type->array_type()->element_type()->forwarded(); - gcc_assert(e->integer_type() != NULL); - if (e->integer_type()->is_unsigned() - && e->integer_type()->bits() == 8) - { - static tree string_to_byte_array_fndecl; - ret = Gogo::call_builtin(&string_to_byte_array_fndecl, - this->location(), - "__go_string_to_byte_array", - 1, - type_tree, - TREE_TYPE(expr_tree), - expr_tree); - } - else - { - gcc_assert(e == Type::lookup_integer_type("int")); - static tree string_to_int_array_fndecl; - ret = Gogo::call_builtin(&string_to_int_array_fndecl, - this->location(), - "__go_string_to_int_array", - 1, - type_tree, - TREE_TYPE(expr_tree), - expr_tree); - } - } - else if ((type->is_unsafe_pointer_type() - && expr_type->points_to() != NULL) - || (expr_type->is_unsafe_pointer_type() - && type->points_to() != NULL)) - ret = fold_convert(type_tree, expr_tree); - else if (type->is_unsafe_pointer_type() - && expr_type->integer_type() != NULL) - ret = convert_to_pointer(type_tree, expr_tree); - else if (this->may_convert_function_types_ - && type->function_type() != NULL - && expr_type->function_type() != NULL) - ret = fold_convert_loc(this->location(), type_tree, expr_tree); - else - ret = Expression::convert_for_assignment(context, type, expr_type, - expr_tree, this->location()); - - return ret; -} - -// Output a type conversion in a constant expression. - -void -Type_conversion_expression::do_export(Export* exp) const -{ - exp->write_c_string("convert("); - exp->write_type(this->type_); - exp->write_c_string(", "); - this->expr_->export_expression(exp); - exp->write_c_string(")"); -} - -// Import a type conversion or a struct construction. - -Expression* -Type_conversion_expression::do_import(Import* imp) -{ - imp->require_c_string("convert("); - Type* type = imp->read_type(); - imp->require_c_string(", "); - Expression* val = Expression::import_expression(imp); - imp->require_c_string(")"); - return Expression::make_cast(type, val, imp->location()); -} - -// Make a type cast expression. - -Expression* -Expression::make_cast(Type* type, Expression* val, source_location location) -{ - if (type->is_error_type() || val->is_error_expression()) - return Expression::make_error(location); - return new Type_conversion_expression(type, val, location); -} - -// Unary expressions. - -class Unary_expression : public Expression -{ - public: - Unary_expression(Operator op, Expression* expr, source_location location) - : Expression(EXPRESSION_UNARY, location), - op_(op), escapes_(true), expr_(expr) - { } - - // Return the operator. - Operator - op() const - { return this->op_; } - - // Return the operand. - Expression* - operand() const - { return this->expr_; } - - // Record that an address expression does not escape. - void - set_does_not_escape() - { - gcc_assert(this->op_ == OPERATOR_AND); - this->escapes_ = false; - } - - // Apply unary opcode OP to UVAL, setting VAL. Return true if this - // could be done, false if not. - static bool - eval_integer(Operator op, Type* utype, mpz_t uval, mpz_t val, - source_location); - - // Apply unary opcode OP to UVAL, setting VAL. Return true if this - // could be done, false if not. - static bool - eval_float(Operator op, mpfr_t uval, mpfr_t val); - - // Apply unary opcode OP to UREAL/UIMAG, setting REAL/IMAG. Return - // true if this could be done, false if not. - static bool - eval_complex(Operator op, mpfr_t ureal, mpfr_t uimag, mpfr_t real, - mpfr_t imag); - - static Expression* - do_import(Import*); - - protected: - int - do_traverse(Traverse* traverse) - { return Expression::traverse(&this->expr_, traverse); } - - Expression* - do_lower(Gogo*, Named_object*, int); - - bool - do_is_constant() const; - - bool - do_integer_constant_value(bool, mpz_t, Type**) const; - - bool - do_float_constant_value(mpfr_t, Type**) const; - - bool - do_complex_constant_value(mpfr_t, mpfr_t, Type**) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return Expression::make_unary(this->op_, this->expr_->copy(), - this->location()); - } - - bool - do_is_addressable() const - { return this->op_ == OPERATOR_MULT; } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The unary operator to apply. - Operator op_; - // Normally true. False if this is an address expression which does - // not escape the current function. - bool escapes_; - // The operand. - Expression* expr_; -}; - -// If we are taking the address of a composite literal, and the -// contents are not constant, then we want to make a heap composite -// instead. - -Expression* -Unary_expression::do_lower(Gogo*, Named_object*, int) -{ - source_location loc = this->location(); - Operator op = this->op_; - Expression* expr = this->expr_; - - if (op == OPERATOR_MULT && expr->is_type_expression()) - return Expression::make_type(Type::make_pointer_type(expr->type()), loc); - - // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require - // moving x to the heap. FIXME: Is it worth doing a real escape - // analysis here? This case is found in math/unsafe.go and is - // therefore worth special casing. - if (op == OPERATOR_MULT) - { - Expression* e = expr; - while (e->classification() == EXPRESSION_CONVERSION) - { - Type_conversion_expression* te - = static_cast(e); - e = te->expr(); - } - - if (e->classification() == EXPRESSION_UNARY) - { - Unary_expression* ue = static_cast(e); - if (ue->op_ == OPERATOR_AND) - { - if (e == expr) - { - // *&x == x. - return ue->expr_; - } - ue->set_does_not_escape(); - } - } - } - - if (op == OPERATOR_PLUS || op == OPERATOR_MINUS - || op == OPERATOR_NOT || op == OPERATOR_XOR) - { - Expression* ret = NULL; - - mpz_t eval; - mpz_init(eval); - Type* etype; - if (expr->integer_constant_value(false, eval, &etype)) - { - mpz_t val; - mpz_init(val); - if (Unary_expression::eval_integer(op, etype, eval, val, loc)) - ret = Expression::make_integer(&val, etype, loc); - mpz_clear(val); - } - mpz_clear(eval); - if (ret != NULL) - return ret; - - if (op == OPERATOR_PLUS || op == OPERATOR_MINUS) - { - mpfr_t fval; - mpfr_init(fval); - Type* ftype; - if (expr->float_constant_value(fval, &ftype)) - { - mpfr_t val; - mpfr_init(val); - if (Unary_expression::eval_float(op, fval, val)) - ret = Expression::make_float(&val, ftype, loc); - mpfr_clear(val); - } - if (ret != NULL) - { - mpfr_clear(fval); - return ret; - } - - mpfr_t ival; - mpfr_init(ival); - if (expr->complex_constant_value(fval, ival, &ftype)) - { - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - if (Unary_expression::eval_complex(op, fval, ival, real, imag)) - ret = Expression::make_complex(&real, &imag, ftype, loc); - mpfr_clear(real); - mpfr_clear(imag); - } - mpfr_clear(ival); - mpfr_clear(fval); - if (ret != NULL) - return ret; - } - } - - return this; -} - -// Return whether a unary expression is a constant. - -bool -Unary_expression::do_is_constant() const -{ - if (this->op_ == OPERATOR_MULT) - { - // Indirecting through a pointer is only constant if the object - // to which the expression points is constant, but we currently - // have no way to determine that. - return false; - } - else if (this->op_ == OPERATOR_AND) - { - // Taking the address of a variable is constant if it is a - // global variable, not constant otherwise. In other cases - // taking the address is probably not a constant. - Var_expression* ve = this->expr_->var_expression(); - if (ve != NULL) - { - Named_object* no = ve->named_object(); - return no->is_variable() && no->var_value()->is_global(); - } - return false; - } - else - return this->expr_->is_constant(); -} - -// Apply unary opcode OP to UVAL, setting VAL. UTYPE is the type of -// UVAL, if known; it may be NULL. Return true if this could be done, -// false if not. - -bool -Unary_expression::eval_integer(Operator op, Type* utype, mpz_t uval, mpz_t val, - source_location location) -{ - switch (op) - { - case OPERATOR_PLUS: - mpz_set(val, uval); - return true; - case OPERATOR_MINUS: - mpz_neg(val, uval); - return Integer_expression::check_constant(val, utype, location); - case OPERATOR_NOT: - mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0); - return true; - case OPERATOR_XOR: - if (utype == NULL - || utype->integer_type() == NULL - || utype->integer_type()->is_abstract()) - mpz_com(val, uval); - else - { - // The number of HOST_WIDE_INTs that it takes to represent - // UVAL. - size_t count = ((mpz_sizeinbase(uval, 2) - + HOST_BITS_PER_WIDE_INT - - 1) - / HOST_BITS_PER_WIDE_INT); - - unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count]; - memset(phwi, 0, count * sizeof(HOST_WIDE_INT)); - - size_t ecount; - mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval); - gcc_assert(ecount <= count); - - // Trim down to the number of words required by the type. - size_t obits = utype->integer_type()->bits(); - if (!utype->integer_type()->is_unsigned()) - ++obits; - size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1) - / HOST_BITS_PER_WIDE_INT); - gcc_assert(ocount <= ocount); - - for (size_t i = 0; i < ocount; ++i) - phwi[i] = ~phwi[i]; - - size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits; - if (clearbits != 0) - phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1) - >> clearbits); - - mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi); - - delete[] phwi; - } - return Integer_expression::check_constant(val, utype, location); - case OPERATOR_AND: - case OPERATOR_MULT: - return false; - default: - gcc_unreachable(); - } -} - -// Apply unary opcode OP to UVAL, setting VAL. Return true if this -// could be done, false if not. - -bool -Unary_expression::eval_float(Operator op, mpfr_t uval, mpfr_t val) -{ - switch (op) - { - case OPERATOR_PLUS: - mpfr_set(val, uval, GMP_RNDN); - return true; - case OPERATOR_MINUS: - mpfr_neg(val, uval, GMP_RNDN); - return true; - case OPERATOR_NOT: - case OPERATOR_XOR: - case OPERATOR_AND: - case OPERATOR_MULT: - return false; - default: - gcc_unreachable(); - } -} - -// Apply unary opcode OP to RVAL/IVAL, setting REAL/IMAG. Return true -// if this could be done, false if not. - -bool -Unary_expression::eval_complex(Operator op, mpfr_t rval, mpfr_t ival, - mpfr_t real, mpfr_t imag) -{ - switch (op) - { - case OPERATOR_PLUS: - mpfr_set(real, rval, GMP_RNDN); - mpfr_set(imag, ival, GMP_RNDN); - return true; - case OPERATOR_MINUS: - mpfr_neg(real, rval, GMP_RNDN); - mpfr_neg(imag, ival, GMP_RNDN); - return true; - case OPERATOR_NOT: - case OPERATOR_XOR: - case OPERATOR_AND: - case OPERATOR_MULT: - return false; - default: - gcc_unreachable(); - } -} - -// Return the integral constant value of a unary expression, if it has one. - -bool -Unary_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val, - Type** ptype) const -{ - mpz_t uval; - mpz_init(uval); - bool ret; - if (!this->expr_->integer_constant_value(iota_is_constant, uval, ptype)) - ret = false; - else - ret = Unary_expression::eval_integer(this->op_, *ptype, uval, val, - this->location()); - mpz_clear(uval); - return ret; -} - -// Return the floating point constant value of a unary expression, if -// it has one. - -bool -Unary_expression::do_float_constant_value(mpfr_t val, Type** ptype) const -{ - mpfr_t uval; - mpfr_init(uval); - bool ret; - if (!this->expr_->float_constant_value(uval, ptype)) - ret = false; - else - ret = Unary_expression::eval_float(this->op_, uval, val); - mpfr_clear(uval); - return ret; -} - -// Return the complex constant value of a unary expression, if it has -// one. - -bool -Unary_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - mpfr_t rval; - mpfr_t ival; - mpfr_init(rval); - mpfr_init(ival); - bool ret; - if (!this->expr_->complex_constant_value(rval, ival, ptype)) - ret = false; - else - ret = Unary_expression::eval_complex(this->op_, rval, ival, real, imag); - mpfr_clear(rval); - mpfr_clear(ival); - return ret; -} - -// Return the type of a unary expression. - -Type* -Unary_expression::do_type() -{ - switch (this->op_) - { - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_NOT: - case OPERATOR_XOR: - return this->expr_->type(); - - case OPERATOR_AND: - return Type::make_pointer_type(this->expr_->type()); - - case OPERATOR_MULT: - { - Type* subtype = this->expr_->type(); - Type* points_to = subtype->points_to(); - if (points_to == NULL) - return Type::make_error_type(); - return points_to; - } - - default: - gcc_unreachable(); - } -} - -// Determine abstract types for a unary expression. - -void -Unary_expression::do_determine_type(const Type_context* context) -{ - switch (this->op_) - { - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_NOT: - case OPERATOR_XOR: - this->expr_->determine_type(context); - break; - - case OPERATOR_AND: - // Taking the address of something. - { - Type* subtype = (context->type == NULL - ? NULL - : context->type->points_to()); - Type_context subcontext(subtype, false); - this->expr_->determine_type(&subcontext); - } - break; - - case OPERATOR_MULT: - // Indirecting through a pointer. - { - Type* subtype = (context->type == NULL - ? NULL - : Type::make_pointer_type(context->type)); - Type_context subcontext(subtype, false); - this->expr_->determine_type(&subcontext); - } - break; - - default: - gcc_unreachable(); - } -} - -// Check types for a unary expression. - -void -Unary_expression::do_check_types(Gogo*) -{ - switch (this->op_) - { - case OPERATOR_PLUS: - case OPERATOR_MINUS: - { - Type* type = this->expr_->type(); - if (type->integer_type() == NULL - && type->float_type() == NULL - && type->complex_type() == NULL - && !type->is_error_type()) - this->report_error(_("expected numeric type")); - } - break; - - case OPERATOR_NOT: - case OPERATOR_XOR: - { - Type* type = this->expr_->type(); - if (type->integer_type() == NULL - && !type->is_boolean_type() - && !type->is_error_type()) - this->report_error(_("expected integer or boolean type")); - } - break; - - case OPERATOR_AND: - if (!this->expr_->is_addressable()) - this->report_error(_("invalid operand for unary %<&%>")); - else - this->expr_->address_taken(this->escapes_); - break; - - case OPERATOR_MULT: - // Indirecting through a pointer. - { - Type* type = this->expr_->type(); - if (type->points_to() == NULL - && !type->is_error_type()) - this->report_error(_("expected pointer")); - } - break; - - default: - gcc_unreachable(); - } -} - -// Get a tree for a unary expression. - -tree -Unary_expression::do_get_tree(Translate_context* context) -{ - tree expr = this->expr_->get_tree(context); - if (expr == error_mark_node) - return error_mark_node; - - source_location loc = this->location(); - switch (this->op_) - { - case OPERATOR_PLUS: - return expr; - - case OPERATOR_MINUS: - { - tree type = TREE_TYPE(expr); - tree compute_type = excess_precision_type(type); - if (compute_type != NULL_TREE) - expr = ::convert(compute_type, expr); - tree ret = fold_build1_loc(loc, NEGATE_EXPR, - (compute_type != NULL_TREE - ? compute_type - : type), - expr); - if (compute_type != NULL_TREE) - ret = ::convert(type, ret); - return ret; - } - - case OPERATOR_NOT: - if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE) - return fold_build1_loc(loc, TRUTH_NOT_EXPR, TREE_TYPE(expr), expr); - else - return fold_build2_loc(loc, NE_EXPR, boolean_type_node, expr, - build_int_cst(TREE_TYPE(expr), 0)); - - case OPERATOR_XOR: - return fold_build1_loc(loc, BIT_NOT_EXPR, TREE_TYPE(expr), expr); - - case OPERATOR_AND: - // We should not see a non-constant constructor here; cases - // where we would see one should have been moved onto the heap - // at parse time. Taking the address of a nonconstant - // constructor will not do what the programmer expects. - gcc_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr)); - gcc_assert(TREE_CODE(expr) != ADDR_EXPR); - - // Build a decl for a constant constructor. - if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr)) - { - tree decl = build_decl(this->location(), VAR_DECL, - create_tmp_var_name("C"), TREE_TYPE(expr)); - DECL_EXTERNAL(decl) = 0; - TREE_PUBLIC(decl) = 0; - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - TREE_STATIC(decl) = 1; - TREE_ADDRESSABLE(decl) = 1; - DECL_ARTIFICIAL(decl) = 1; - DECL_INITIAL(decl) = expr; - rest_of_decl_compilation(decl, 1, 0); - expr = decl; - } - - return build_fold_addr_expr_loc(loc, expr); - - case OPERATOR_MULT: - { - gcc_assert(POINTER_TYPE_P(TREE_TYPE(expr))); - - // If we are dereferencing the pointer to a large struct, we - // need to check for nil. We don't bother to check for small - // structs because we expect the system to crash on a nil - // pointer dereference. - HOST_WIDE_INT s = int_size_in_bytes(TREE_TYPE(TREE_TYPE(expr))); - if (s == -1 || s >= 4096) - { - if (!DECL_P(expr)) - expr = save_expr(expr); - tree compare = fold_build2_loc(loc, EQ_EXPR, boolean_type_node, - expr, - fold_convert(TREE_TYPE(expr), - null_pointer_node)); - tree crash = Gogo::runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, - loc); - expr = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(expr), - build3(COND_EXPR, void_type_node, - compare, crash, NULL_TREE), - expr); - } - - // If the type of EXPR is a recursive pointer type, then we - // need to insert a cast before indirecting. - if (TREE_TYPE(TREE_TYPE(expr)) == ptr_type_node) - { - Type* pt = this->expr_->type()->points_to(); - tree ind = pt->get_tree(context->gogo()); - expr = fold_convert_loc(loc, build_pointer_type(ind), expr); - } - - return build_fold_indirect_ref_loc(loc, expr); - } - - default: - gcc_unreachable(); - } -} - -// Export a unary expression. - -void -Unary_expression::do_export(Export* exp) const -{ - switch (this->op_) - { - case OPERATOR_PLUS: - exp->write_c_string("+ "); - break; - case OPERATOR_MINUS: - exp->write_c_string("- "); - break; - case OPERATOR_NOT: - exp->write_c_string("! "); - break; - case OPERATOR_XOR: - exp->write_c_string("^ "); - break; - case OPERATOR_AND: - case OPERATOR_MULT: - default: - gcc_unreachable(); - } - this->expr_->export_expression(exp); -} - -// Import a unary expression. - -Expression* -Unary_expression::do_import(Import* imp) -{ - Operator op; - switch (imp->get_char()) - { - case '+': - op = OPERATOR_PLUS; - break; - case '-': - op = OPERATOR_MINUS; - break; - case '!': - op = OPERATOR_NOT; - break; - case '^': - op = OPERATOR_XOR; - break; - default: - gcc_unreachable(); - } - imp->require_c_string(" "); - Expression* expr = Expression::import_expression(imp); - return Expression::make_unary(op, expr, imp->location()); -} - -// Make a unary expression. - -Expression* -Expression::make_unary(Operator op, Expression* expr, source_location location) -{ - return new Unary_expression(op, expr, location); -} - -// If this is an indirection through a pointer, return the expression -// being pointed through. Otherwise return this. - -Expression* -Expression::deref() -{ - if (this->classification_ == EXPRESSION_UNARY) - { - Unary_expression* ue = static_cast(this); - if (ue->op() == OPERATOR_MULT) - return ue->operand(); - } - return this; -} - -// Class Binary_expression. - -// Traversal. - -int -Binary_expression::do_traverse(Traverse* traverse) -{ - int t = Expression::traverse(&this->left_, traverse); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return Expression::traverse(&this->right_, traverse); -} - -// Compare integer constants according to OP. - -bool -Binary_expression::compare_integer(Operator op, mpz_t left_val, - mpz_t right_val) -{ - int i = mpz_cmp(left_val, right_val); - switch (op) - { - case OPERATOR_EQEQ: - return i == 0; - case OPERATOR_NOTEQ: - return i != 0; - case OPERATOR_LT: - return i < 0; - case OPERATOR_LE: - return i <= 0; - case OPERATOR_GT: - return i > 0; - case OPERATOR_GE: - return i >= 0; - default: - gcc_unreachable(); - } -} - -// Compare floating point constants according to OP. - -bool -Binary_expression::compare_float(Operator op, Type* type, mpfr_t left_val, - mpfr_t right_val) -{ - int i; - if (type == NULL) - i = mpfr_cmp(left_val, right_val); - else - { - mpfr_t lv; - mpfr_init_set(lv, left_val, GMP_RNDN); - mpfr_t rv; - mpfr_init_set(rv, right_val, GMP_RNDN); - Float_expression::constrain_float(lv, type); - Float_expression::constrain_float(rv, type); - i = mpfr_cmp(lv, rv); - mpfr_clear(lv); - mpfr_clear(rv); - } - switch (op) - { - case OPERATOR_EQEQ: - return i == 0; - case OPERATOR_NOTEQ: - return i != 0; - case OPERATOR_LT: - return i < 0; - case OPERATOR_LE: - return i <= 0; - case OPERATOR_GT: - return i > 0; - case OPERATOR_GE: - return i >= 0; - default: - gcc_unreachable(); - } -} - -// Compare complex constants according to OP. Complex numbers may -// only be compared for equality. - -bool -Binary_expression::compare_complex(Operator op, Type* type, - mpfr_t left_real, mpfr_t left_imag, - mpfr_t right_real, mpfr_t right_imag) -{ - bool is_equal; - if (type == NULL) - is_equal = (mpfr_cmp(left_real, right_real) == 0 - && mpfr_cmp(left_imag, right_imag) == 0); - else - { - mpfr_t lr; - mpfr_t li; - mpfr_init_set(lr, left_real, GMP_RNDN); - mpfr_init_set(li, left_imag, GMP_RNDN); - mpfr_t rr; - mpfr_t ri; - mpfr_init_set(rr, right_real, GMP_RNDN); - mpfr_init_set(ri, right_imag, GMP_RNDN); - Complex_expression::constrain_complex(lr, li, type); - Complex_expression::constrain_complex(rr, ri, type); - is_equal = mpfr_cmp(lr, rr) == 0 && mpfr_cmp(li, ri) == 0; - mpfr_clear(lr); - mpfr_clear(li); - mpfr_clear(rr); - mpfr_clear(ri); - } - switch (op) - { - case OPERATOR_EQEQ: - return is_equal; - case OPERATOR_NOTEQ: - return !is_equal; - default: - gcc_unreachable(); - } -} - -// Apply binary opcode OP to LEFT_VAL and RIGHT_VAL, setting VAL. -// LEFT_TYPE is the type of LEFT_VAL, RIGHT_TYPE is the type of -// RIGHT_VAL; LEFT_TYPE and/or RIGHT_TYPE may be NULL. Return true if -// this could be done, false if not. - -bool -Binary_expression::eval_integer(Operator op, Type* left_type, mpz_t left_val, - Type* right_type, mpz_t right_val, - source_location location, mpz_t val) -{ - bool is_shift_op = false; - switch (op) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - // These return boolean values. We should probably handle them - // anyhow in case a type conversion is used on the result. - return false; - case OPERATOR_PLUS: - mpz_add(val, left_val, right_val); - break; - case OPERATOR_MINUS: - mpz_sub(val, left_val, right_val); - break; - case OPERATOR_OR: - mpz_ior(val, left_val, right_val); - break; - case OPERATOR_XOR: - mpz_xor(val, left_val, right_val); - break; - case OPERATOR_MULT: - mpz_mul(val, left_val, right_val); - break; - case OPERATOR_DIV: - if (mpz_sgn(right_val) != 0) - mpz_tdiv_q(val, left_val, right_val); - else - { - error_at(location, "division by zero"); - mpz_set_ui(val, 0); - return true; - } - break; - case OPERATOR_MOD: - if (mpz_sgn(right_val) != 0) - mpz_tdiv_r(val, left_val, right_val); - else - { - error_at(location, "division by zero"); - mpz_set_ui(val, 0); - return true; - } - break; - case OPERATOR_LSHIFT: - { - unsigned long shift = mpz_get_ui(right_val); - if (mpz_cmp_ui(right_val, shift) != 0) - { - error_at(location, "shift count overflow"); - mpz_set_ui(val, 0); - return true; - } - mpz_mul_2exp(val, left_val, shift); - is_shift_op = true; - break; - } - break; - case OPERATOR_RSHIFT: - { - unsigned long shift = mpz_get_ui(right_val); - if (mpz_cmp_ui(right_val, shift) != 0) - { - error_at(location, "shift count overflow"); - mpz_set_ui(val, 0); - return true; - } - if (mpz_cmp_ui(left_val, 0) >= 0) - mpz_tdiv_q_2exp(val, left_val, shift); - else - mpz_fdiv_q_2exp(val, left_val, shift); - is_shift_op = true; - break; - } - break; - case OPERATOR_AND: - mpz_and(val, left_val, right_val); - break; - case OPERATOR_BITCLEAR: - { - mpz_t tval; - mpz_init(tval); - mpz_com(tval, right_val); - mpz_and(val, left_val, tval); - mpz_clear(tval); - } - break; - default: - gcc_unreachable(); - } - - Type* type = left_type; - if (!is_shift_op) - { - if (type == NULL) - type = right_type; - else if (type != right_type && right_type != NULL) - { - if (type->is_abstract()) - type = right_type; - else if (!right_type->is_abstract()) - { - // This look like a type error which should be diagnosed - // elsewhere. Don't do anything here, to avoid an - // unhelpful chain of error messages. - return true; - } - } - } - - if (type != NULL && !type->is_abstract()) - { - // We have to check the operands too, as we have implicitly - // coerced them to TYPE. - if ((type != left_type - && !Integer_expression::check_constant(left_val, type, location)) - || (!is_shift_op - && type != right_type - && !Integer_expression::check_constant(right_val, type, - location)) - || !Integer_expression::check_constant(val, type, location)) - mpz_set_ui(val, 0); - } - - return true; -} - -// Apply binary opcode OP to LEFT_VAL and RIGHT_VAL, setting VAL. -// Return true if this could be done, false if not. - -bool -Binary_expression::eval_float(Operator op, Type* left_type, mpfr_t left_val, - Type* right_type, mpfr_t right_val, - mpfr_t val, source_location location) -{ - switch (op) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - // These return boolean values. We should probably handle them - // anyhow in case a type conversion is used on the result. - return false; - case OPERATOR_PLUS: - mpfr_add(val, left_val, right_val, GMP_RNDN); - break; - case OPERATOR_MINUS: - mpfr_sub(val, left_val, right_val, GMP_RNDN); - break; - case OPERATOR_OR: - case OPERATOR_XOR: - case OPERATOR_AND: - case OPERATOR_BITCLEAR: - return false; - case OPERATOR_MULT: - mpfr_mul(val, left_val, right_val, GMP_RNDN); - break; - case OPERATOR_DIV: - if (mpfr_zero_p(right_val)) - error_at(location, "division by zero"); - mpfr_div(val, left_val, right_val, GMP_RNDN); - break; - case OPERATOR_MOD: - return false; - case OPERATOR_LSHIFT: - case OPERATOR_RSHIFT: - return false; - default: - gcc_unreachable(); - } - - Type* type = left_type; - if (type == NULL) - type = right_type; - else if (type != right_type && right_type != NULL) - { - if (type->is_abstract()) - type = right_type; - else if (!right_type->is_abstract()) - { - // This looks like a type error which should be diagnosed - // elsewhere. Don't do anything here, to avoid an unhelpful - // chain of error messages. - return true; - } - } - - if (type != NULL && !type->is_abstract()) - { - if ((type != left_type - && !Float_expression::check_constant(left_val, type, location)) - || (type != right_type - && !Float_expression::check_constant(right_val, type, - location)) - || !Float_expression::check_constant(val, type, location)) - mpfr_set_ui(val, 0, GMP_RNDN); - } - - return true; -} - -// Apply binary opcode OP to LEFT_REAL/LEFT_IMAG and -// RIGHT_REAL/RIGHT_IMAG, setting REAL/IMAG. Return true if this -// could be done, false if not. - -bool -Binary_expression::eval_complex(Operator op, Type* left_type, - mpfr_t left_real, mpfr_t left_imag, - Type *right_type, - mpfr_t right_real, mpfr_t right_imag, - mpfr_t real, mpfr_t imag, - source_location location) -{ - switch (op) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - // These return boolean values and must be handled differently. - return false; - case OPERATOR_PLUS: - mpfr_add(real, left_real, right_real, GMP_RNDN); - mpfr_add(imag, left_imag, right_imag, GMP_RNDN); - break; - case OPERATOR_MINUS: - mpfr_sub(real, left_real, right_real, GMP_RNDN); - mpfr_sub(imag, left_imag, right_imag, GMP_RNDN); - break; - case OPERATOR_OR: - case OPERATOR_XOR: - case OPERATOR_AND: - case OPERATOR_BITCLEAR: - return false; - case OPERATOR_MULT: - { - // You might think that multiplying two complex numbers would - // be simple, and you would be right, until you start to think - // about getting the right answer for infinity. If one - // operand here is infinity and the other is anything other - // than zero or NaN, then we are going to wind up subtracting - // two infinity values. That will give us a NaN, but the - // correct answer is infinity. - - mpfr_t lrrr; - mpfr_init(lrrr); - mpfr_mul(lrrr, left_real, right_real, GMP_RNDN); - - mpfr_t lrri; - mpfr_init(lrri); - mpfr_mul(lrri, left_real, right_imag, GMP_RNDN); - - mpfr_t lirr; - mpfr_init(lirr); - mpfr_mul(lirr, left_imag, right_real, GMP_RNDN); - - mpfr_t liri; - mpfr_init(liri); - mpfr_mul(liri, left_imag, right_imag, GMP_RNDN); - - mpfr_sub(real, lrrr, liri, GMP_RNDN); - mpfr_add(imag, lrri, lirr, GMP_RNDN); - - // If we get NaN on both sides, check whether it should really - // be infinity. The rule is that if either side of the - // complex number is infinity, then the whole value is - // infinity, even if the other side is NaN. So the only case - // we have to fix is the one in which both sides are NaN. - if (mpfr_nan_p(real) && mpfr_nan_p(imag) - && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag)) - && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag))) - { - bool is_infinity = false; - - mpfr_t lr; - mpfr_t li; - mpfr_init_set(lr, left_real, GMP_RNDN); - mpfr_init_set(li, left_imag, GMP_RNDN); - - mpfr_t rr; - mpfr_t ri; - mpfr_init_set(rr, right_real, GMP_RNDN); - mpfr_init_set(ri, right_imag, GMP_RNDN); - - // If the left side is infinity, then the result is - // infinity. - if (mpfr_inf_p(lr) || mpfr_inf_p(li)) - { - mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN); - mpfr_copysign(lr, lr, left_real, GMP_RNDN); - mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN); - mpfr_copysign(li, li, left_imag, GMP_RNDN); - if (mpfr_nan_p(rr)) - { - mpfr_set_ui(rr, 0, GMP_RNDN); - mpfr_copysign(rr, rr, right_real, GMP_RNDN); - } - if (mpfr_nan_p(ri)) - { - mpfr_set_ui(ri, 0, GMP_RNDN); - mpfr_copysign(ri, ri, right_imag, GMP_RNDN); - } - is_infinity = true; - } - - // If the right side is infinity, then the result is - // infinity. - if (mpfr_inf_p(rr) || mpfr_inf_p(ri)) - { - mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN); - mpfr_copysign(rr, rr, right_real, GMP_RNDN); - mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN); - mpfr_copysign(ri, ri, right_imag, GMP_RNDN); - if (mpfr_nan_p(lr)) - { - mpfr_set_ui(lr, 0, GMP_RNDN); - mpfr_copysign(lr, lr, left_real, GMP_RNDN); - } - if (mpfr_nan_p(li)) - { - mpfr_set_ui(li, 0, GMP_RNDN); - mpfr_copysign(li, li, left_imag, GMP_RNDN); - } - is_infinity = true; - } - - // If we got an overflow in the intermediate computations, - // then the result is infinity. - if (!is_infinity - && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri) - || mpfr_inf_p(lirr) || mpfr_inf_p(liri))) - { - if (mpfr_nan_p(lr)) - { - mpfr_set_ui(lr, 0, GMP_RNDN); - mpfr_copysign(lr, lr, left_real, GMP_RNDN); - } - if (mpfr_nan_p(li)) - { - mpfr_set_ui(li, 0, GMP_RNDN); - mpfr_copysign(li, li, left_imag, GMP_RNDN); - } - if (mpfr_nan_p(rr)) - { - mpfr_set_ui(rr, 0, GMP_RNDN); - mpfr_copysign(rr, rr, right_real, GMP_RNDN); - } - if (mpfr_nan_p(ri)) - { - mpfr_set_ui(ri, 0, GMP_RNDN); - mpfr_copysign(ri, ri, right_imag, GMP_RNDN); - } - is_infinity = true; - } - - if (is_infinity) - { - mpfr_mul(lrrr, lr, rr, GMP_RNDN); - mpfr_mul(lrri, lr, ri, GMP_RNDN); - mpfr_mul(lirr, li, rr, GMP_RNDN); - mpfr_mul(liri, li, ri, GMP_RNDN); - mpfr_sub(real, lrrr, liri, GMP_RNDN); - mpfr_add(imag, lrri, lirr, GMP_RNDN); - mpfr_set_inf(real, mpfr_sgn(real)); - mpfr_set_inf(imag, mpfr_sgn(imag)); - } - - mpfr_clear(lr); - mpfr_clear(li); - mpfr_clear(rr); - mpfr_clear(ri); - } - - mpfr_clear(lrrr); - mpfr_clear(lrri); - mpfr_clear(lirr); - mpfr_clear(liri); - } - break; - case OPERATOR_DIV: - { - // For complex division we want to avoid having an - // intermediate overflow turn the whole result in a NaN. We - // scale the values to try to avoid this. - - if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag)) - error_at(location, "division by zero"); - - mpfr_t rra; - mpfr_t ria; - mpfr_init(rra); - mpfr_init(ria); - mpfr_abs(rra, right_real, GMP_RNDN); - mpfr_abs(ria, right_imag, GMP_RNDN); - mpfr_t t; - mpfr_init(t); - mpfr_max(t, rra, ria, GMP_RNDN); - - mpfr_t rr; - mpfr_t ri; - mpfr_init_set(rr, right_real, GMP_RNDN); - mpfr_init_set(ri, right_imag, GMP_RNDN); - long ilogbw = 0; - if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t)) - { - ilogbw = mpfr_get_exp(t); - mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN); - mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN); - } - - mpfr_t denom; - mpfr_init(denom); - mpfr_mul(denom, rr, rr, GMP_RNDN); - mpfr_mul(t, ri, ri, GMP_RNDN); - mpfr_add(denom, denom, t, GMP_RNDN); - - mpfr_mul(real, left_real, rr, GMP_RNDN); - mpfr_mul(t, left_imag, ri, GMP_RNDN); - mpfr_add(real, real, t, GMP_RNDN); - mpfr_div(real, real, denom, GMP_RNDN); - mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN); - - mpfr_mul(imag, left_imag, rr, GMP_RNDN); - mpfr_mul(t, left_real, ri, GMP_RNDN); - mpfr_sub(imag, imag, t, GMP_RNDN); - mpfr_div(imag, imag, denom, GMP_RNDN); - mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN); - - // If we wind up with NaN on both sides, check whether we - // should really have infinity. The rule is that if either - // side of the complex number is infinity, then the whole - // value is infinity, even if the other side is NaN. So the - // only case we have to fix is the one in which both sides are - // NaN. - if (mpfr_nan_p(real) && mpfr_nan_p(imag) - && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag)) - && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag))) - { - if (mpfr_zero_p(denom)) - { - mpfr_set_inf(real, mpfr_sgn(rr)); - mpfr_mul(real, real, left_real, GMP_RNDN); - mpfr_set_inf(imag, mpfr_sgn(rr)); - mpfr_mul(imag, imag, left_imag, GMP_RNDN); - } - else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag)) - && mpfr_number_p(rr) && mpfr_number_p(ri)) - { - mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN); - mpfr_copysign(t, t, left_real, GMP_RNDN); - - mpfr_t t2; - mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN); - mpfr_copysign(t2, t2, left_imag, GMP_RNDN); - - mpfr_t t3; - mpfr_init(t3); - mpfr_mul(t3, t, rr, GMP_RNDN); - - mpfr_t t4; - mpfr_init(t4); - mpfr_mul(t4, t2, ri, GMP_RNDN); - - mpfr_add(t3, t3, t4, GMP_RNDN); - mpfr_set_inf(real, mpfr_sgn(t3)); - - mpfr_mul(t3, t2, rr, GMP_RNDN); - mpfr_mul(t4, t, ri, GMP_RNDN); - mpfr_sub(t3, t3, t4, GMP_RNDN); - mpfr_set_inf(imag, mpfr_sgn(t3)); - - mpfr_clear(t2); - mpfr_clear(t3); - mpfr_clear(t4); - } - else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag)) - && mpfr_number_p(left_real) && mpfr_number_p(left_imag)) - { - mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN); - mpfr_copysign(t, t, rr, GMP_RNDN); - - mpfr_t t2; - mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN); - mpfr_copysign(t2, t2, ri, GMP_RNDN); - - mpfr_t t3; - mpfr_init(t3); - mpfr_mul(t3, left_real, t, GMP_RNDN); - - mpfr_t t4; - mpfr_init(t4); - mpfr_mul(t4, left_imag, t2, GMP_RNDN); - - mpfr_add(t3, t3, t4, GMP_RNDN); - mpfr_set_ui(real, 0, GMP_RNDN); - mpfr_mul(real, real, t3, GMP_RNDN); - - mpfr_mul(t3, left_imag, t, GMP_RNDN); - mpfr_mul(t4, left_real, t2, GMP_RNDN); - mpfr_sub(t3, t3, t4, GMP_RNDN); - mpfr_set_ui(imag, 0, GMP_RNDN); - mpfr_mul(imag, imag, t3, GMP_RNDN); - - mpfr_clear(t2); - mpfr_clear(t3); - mpfr_clear(t4); - } - } - - mpfr_clear(denom); - mpfr_clear(rr); - mpfr_clear(ri); - mpfr_clear(t); - mpfr_clear(rra); - mpfr_clear(ria); - } - break; - case OPERATOR_MOD: - return false; - case OPERATOR_LSHIFT: - case OPERATOR_RSHIFT: - return false; - default: - gcc_unreachable(); - } - - Type* type = left_type; - if (type == NULL) - type = right_type; - else if (type != right_type && right_type != NULL) - { - if (type->is_abstract()) - type = right_type; - else if (!right_type->is_abstract()) - { - // This looks like a type error which should be diagnosed - // elsewhere. Don't do anything here, to avoid an unhelpful - // chain of error messages. - return true; - } - } - - if (type != NULL && !type->is_abstract()) - { - if ((type != left_type - && !Complex_expression::check_constant(left_real, left_imag, - type, location)) - || (type != right_type - && !Complex_expression::check_constant(right_real, right_imag, - type, location)) - || !Complex_expression::check_constant(real, imag, type, - location)) - { - mpfr_set_ui(real, 0, GMP_RNDN); - mpfr_set_ui(imag, 0, GMP_RNDN); - } - } - - return true; -} - -// Lower a binary expression. We have to evaluate constant -// expressions now, in order to implement Go's unlimited precision -// constants. - -Expression* -Binary_expression::do_lower(Gogo*, Named_object*, int) -{ - source_location location = this->location(); - Operator op = this->op_; - Expression* left = this->left_; - Expression* right = this->right_; - - const bool is_comparison = (op == OPERATOR_EQEQ - || op == OPERATOR_NOTEQ - || op == OPERATOR_LT - || op == OPERATOR_LE - || op == OPERATOR_GT - || op == OPERATOR_GE); - - // Integer constant expressions. - { - mpz_t left_val; - mpz_init(left_val); - Type* left_type; - mpz_t right_val; - mpz_init(right_val); - Type* right_type; - if (left->integer_constant_value(false, left_val, &left_type) - && right->integer_constant_value(false, right_val, &right_type)) - { - Expression* ret = NULL; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base() - && op != OPERATOR_LSHIFT - && op != OPERATOR_RSHIFT) - { - // May be a type error--let it be diagnosed later. - } - else if (is_comparison) - { - bool b = Binary_expression::compare_integer(op, left_val, - right_val); - ret = Expression::make_cast(Type::lookup_bool_type(), - Expression::make_boolean(b, location), - location); - } - else - { - mpz_t val; - mpz_init(val); - - if (Binary_expression::eval_integer(op, left_type, left_val, - right_type, right_val, - location, val)) - { - gcc_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND); - Type* type; - if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT) - type = left_type; - else if (left_type == NULL) - type = right_type; - else if (right_type == NULL) - type = left_type; - else if (!left_type->is_abstract() - && left_type->named_type() != NULL) - type = left_type; - else if (!right_type->is_abstract() - && right_type->named_type() != NULL) - type = right_type; - else if (!left_type->is_abstract()) - type = left_type; - else if (!right_type->is_abstract()) - type = right_type; - else if (left_type->float_type() != NULL) - type = left_type; - else if (right_type->float_type() != NULL) - type = right_type; - else if (left_type->complex_type() != NULL) - type = left_type; - else if (right_type->complex_type() != NULL) - type = right_type; - else - type = left_type; - ret = Expression::make_integer(&val, type, location); - } - - mpz_clear(val); - } - - if (ret != NULL) - { - mpz_clear(right_val); - mpz_clear(left_val); - return ret; - } - } - mpz_clear(right_val); - mpz_clear(left_val); - } - - // Floating point constant expressions. - { - mpfr_t left_val; - mpfr_init(left_val); - Type* left_type; - mpfr_t right_val; - mpfr_init(right_val); - Type* right_type; - if (left->float_constant_value(left_val, &left_type) - && right->float_constant_value(right_val, &right_type)) - { - Expression* ret = NULL; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base() - && op != OPERATOR_LSHIFT - && op != OPERATOR_RSHIFT) - { - // May be a type error--let it be diagnosed later. - } - else if (is_comparison) - { - bool b = Binary_expression::compare_float(op, - (left_type != NULL - ? left_type - : right_type), - left_val, right_val); - ret = Expression::make_boolean(b, location); - } - else - { - mpfr_t val; - mpfr_init(val); - - if (Binary_expression::eval_float(op, left_type, left_val, - right_type, right_val, val, - location)) - { - gcc_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND - && op != OPERATOR_LSHIFT && op != OPERATOR_RSHIFT); - Type* type; - if (left_type == NULL) - type = right_type; - else if (right_type == NULL) - type = left_type; - else if (!left_type->is_abstract() - && left_type->named_type() != NULL) - type = left_type; - else if (!right_type->is_abstract() - && right_type->named_type() != NULL) - type = right_type; - else if (!left_type->is_abstract()) - type = left_type; - else if (!right_type->is_abstract()) - type = right_type; - else if (left_type->float_type() != NULL) - type = left_type; - else if (right_type->float_type() != NULL) - type = right_type; - else - type = left_type; - ret = Expression::make_float(&val, type, location); - } - - mpfr_clear(val); - } - - if (ret != NULL) - { - mpfr_clear(right_val); - mpfr_clear(left_val); - return ret; - } - } - mpfr_clear(right_val); - mpfr_clear(left_val); - } - - // Complex constant expressions. - { - mpfr_t left_real; - mpfr_t left_imag; - mpfr_init(left_real); - mpfr_init(left_imag); - Type* left_type; - - mpfr_t right_real; - mpfr_t right_imag; - mpfr_init(right_real); - mpfr_init(right_imag); - Type* right_type; - - if (left->complex_constant_value(left_real, left_imag, &left_type) - && right->complex_constant_value(right_real, right_imag, &right_type)) - { - Expression* ret = NULL; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base()) - { - // May be a type error--let it be diagnosed later. - } - else if (is_comparison) - { - bool b = Binary_expression::compare_complex(op, - (left_type != NULL - ? left_type - : right_type), - left_real, - left_imag, - right_real, - right_imag); - ret = Expression::make_boolean(b, location); - } - else - { - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - - if (Binary_expression::eval_complex(op, left_type, - left_real, left_imag, - right_type, - right_real, right_imag, - real, imag, - location)) - { - gcc_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND - && op != OPERATOR_LSHIFT && op != OPERATOR_RSHIFT); - Type* type; - if (left_type == NULL) - type = right_type; - else if (right_type == NULL) - type = left_type; - else if (!left_type->is_abstract() - && left_type->named_type() != NULL) - type = left_type; - else if (!right_type->is_abstract() - && right_type->named_type() != NULL) - type = right_type; - else if (!left_type->is_abstract()) - type = left_type; - else if (!right_type->is_abstract()) - type = right_type; - else if (left_type->complex_type() != NULL) - type = left_type; - else if (right_type->complex_type() != NULL) - type = right_type; - else - type = left_type; - ret = Expression::make_complex(&real, &imag, type, - location); - } - mpfr_clear(real); - mpfr_clear(imag); - } - - if (ret != NULL) - { - mpfr_clear(left_real); - mpfr_clear(left_imag); - mpfr_clear(right_real); - mpfr_clear(right_imag); - return ret; - } - } - - mpfr_clear(left_real); - mpfr_clear(left_imag); - mpfr_clear(right_real); - mpfr_clear(right_imag); - } - - // String constant expressions. - if (op == OPERATOR_PLUS - && left->type()->is_string_type() - && right->type()->is_string_type()) - { - std::string left_string; - std::string right_string; - if (left->string_constant_value(&left_string) - && right->string_constant_value(&right_string)) - return Expression::make_string(left_string + right_string, location); - } - - return this; -} - -// Return the integer constant value, if it has one. - -bool -Binary_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val, - Type** ptype) const -{ - mpz_t left_val; - mpz_init(left_val); - Type* left_type; - if (!this->left_->integer_constant_value(iota_is_constant, left_val, - &left_type)) - { - mpz_clear(left_val); - return false; - } - - mpz_t right_val; - mpz_init(right_val); - Type* right_type; - if (!this->right_->integer_constant_value(iota_is_constant, right_val, - &right_type)) - { - mpz_clear(right_val); - mpz_clear(left_val); - return false; - } - - bool ret; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base() - && this->op_ != OPERATOR_RSHIFT - && this->op_ != OPERATOR_LSHIFT) - ret = false; - else - ret = Binary_expression::eval_integer(this->op_, left_type, left_val, - right_type, right_val, - this->location(), val); - - mpz_clear(right_val); - mpz_clear(left_val); - - if (ret) - *ptype = left_type; - - return ret; -} - -// Return the floating point constant value, if it has one. - -bool -Binary_expression::do_float_constant_value(mpfr_t val, Type** ptype) const -{ - mpfr_t left_val; - mpfr_init(left_val); - Type* left_type; - if (!this->left_->float_constant_value(left_val, &left_type)) - { - mpfr_clear(left_val); - return false; - } - - mpfr_t right_val; - mpfr_init(right_val); - Type* right_type; - if (!this->right_->float_constant_value(right_val, &right_type)) - { - mpfr_clear(right_val); - mpfr_clear(left_val); - return false; - } - - bool ret; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base()) - ret = false; - else - ret = Binary_expression::eval_float(this->op_, left_type, left_val, - right_type, right_val, - val, this->location()); - - mpfr_clear(left_val); - mpfr_clear(right_val); - - if (ret) - *ptype = left_type; - - return ret; -} - -// Return the complex constant value, if it has one. - -bool -Binary_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - mpfr_t left_real; - mpfr_t left_imag; - mpfr_init(left_real); - mpfr_init(left_imag); - Type* left_type; - if (!this->left_->complex_constant_value(left_real, left_imag, &left_type)) - { - mpfr_clear(left_real); - mpfr_clear(left_imag); - return false; - } - - mpfr_t right_real; - mpfr_t right_imag; - mpfr_init(right_real); - mpfr_init(right_imag); - Type* right_type; - if (!this->right_->complex_constant_value(right_real, right_imag, - &right_type)) - { - mpfr_clear(left_real); - mpfr_clear(left_imag); - mpfr_clear(right_real); - mpfr_clear(right_imag); - return false; - } - - bool ret; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base()) - ret = false; - else - ret = Binary_expression::eval_complex(this->op_, left_type, - left_real, left_imag, - right_type, - right_real, right_imag, - real, imag, - this->location()); - mpfr_clear(left_real); - mpfr_clear(left_imag); - mpfr_clear(right_real); - mpfr_clear(right_imag); - - if (ret) - *ptype = left_type; - - return ret; -} - -// Note that the value is being discarded. - -void -Binary_expression::do_discarding_value() -{ - if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND) - this->right_->discarding_value(); - else - this->warn_about_unused_value(); -} - -// Get type. - -Type* -Binary_expression::do_type() -{ - switch (this->op_) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - return Type::lookup_bool_type(); - - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_OR: - case OPERATOR_XOR: - case OPERATOR_MULT: - case OPERATOR_DIV: - case OPERATOR_MOD: - case OPERATOR_AND: - case OPERATOR_BITCLEAR: - { - Type* left_type = this->left_->type(); - Type* right_type = this->right_->type(); - if (!left_type->is_abstract() && left_type->named_type() != NULL) - return left_type; - else if (!right_type->is_abstract() && right_type->named_type() != NULL) - return right_type; - else if (!left_type->is_abstract()) - return left_type; - else if (!right_type->is_abstract()) - return right_type; - else if (left_type->complex_type() != NULL) - return left_type; - else if (right_type->complex_type() != NULL) - return right_type; - else if (left_type->float_type() != NULL) - return left_type; - else if (right_type->float_type() != NULL) - return right_type; - else - return left_type; - } - - case OPERATOR_LSHIFT: - case OPERATOR_RSHIFT: - return this->left_->type(); - - default: - gcc_unreachable(); - } -} - -// Set type for a binary expression. - -void -Binary_expression::do_determine_type(const Type_context* context) -{ - Type* tleft = this->left_->type(); - Type* tright = this->right_->type(); - - // Both sides should have the same type, except for the shift - // operations. For a comparison, we should ignore the incoming - // type. - - bool is_shift_op = (this->op_ == OPERATOR_LSHIFT - || this->op_ == OPERATOR_RSHIFT); - - bool is_comparison = (this->op_ == OPERATOR_EQEQ - || this->op_ == OPERATOR_NOTEQ - || this->op_ == OPERATOR_LT - || this->op_ == OPERATOR_LE - || this->op_ == OPERATOR_GT - || this->op_ == OPERATOR_GE); - - Type_context subcontext(*context); - - if (is_comparison) - { - // In a comparison, the context does not determine the types of - // the operands. - subcontext.type = NULL; - } - - // Set the context for the left hand operand. - if (is_shift_op) - { - // The right hand operand plays no role in determining the type - // of the left hand operand. A shift of an abstract integer in - // a string context gets special treatment, which may be a - // language bug. - if (subcontext.type != NULL - && subcontext.type->is_string_type() - && tleft->is_abstract()) - error_at(this->location(), "shift of non-integer operand"); - } - else if (!tleft->is_abstract()) - subcontext.type = tleft; - else if (!tright->is_abstract()) - subcontext.type = tright; - else if (subcontext.type == NULL) - { - if ((tleft->integer_type() != NULL && tright->integer_type() != NULL) - || (tleft->float_type() != NULL && tright->float_type() != NULL) - || (tleft->complex_type() != NULL && tright->complex_type() != NULL)) - { - // Both sides have an abstract integer, abstract float, or - // abstract complex type. Just let CONTEXT determine - // whether they may remain abstract or not. - } - else if (tleft->complex_type() != NULL) - subcontext.type = tleft; - else if (tright->complex_type() != NULL) - subcontext.type = tright; - else if (tleft->float_type() != NULL) - subcontext.type = tleft; - else if (tright->float_type() != NULL) - subcontext.type = tright; - else - subcontext.type = tleft; - } - - this->left_->determine_type(&subcontext); - - // The context for the right hand operand is the same as for the - // left hand operand, except for a shift operator. - if (is_shift_op) - { - subcontext.type = Type::lookup_integer_type("uint"); - subcontext.may_be_abstract = false; - } - - this->right_->determine_type(&subcontext); -} - -// Report an error if the binary operator OP does not support TYPE. -// Return whether the operation is OK. This should not be used for -// shift. - -bool -Binary_expression::check_operator_type(Operator op, Type* type, - source_location location) -{ - switch (op) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - if (!type->is_boolean_type()) - { - error_at(location, "expected boolean type"); - return false; - } - break; - - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - if (type->integer_type() == NULL - && type->float_type() == NULL - && type->complex_type() == NULL - && !type->is_string_type() - && type->points_to() == NULL - && !type->is_nil_type() - && !type->is_boolean_type() - && type->interface_type() == NULL - && (type->array_type() == NULL - || type->array_type()->length() != NULL) - && type->map_type() == NULL - && type->channel_type() == NULL - && type->function_type() == NULL) - { - error_at(location, - ("expected integer, floating, complex, string, pointer, " - "boolean, interface, slice, map, channel, " - "or function type")); - return false; - } - break; - - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - if (type->integer_type() == NULL - && type->float_type() == NULL - && !type->is_string_type()) - { - error_at(location, "expected integer, floating, or string type"); - return false; - } - break; - - case OPERATOR_PLUS: - case OPERATOR_PLUSEQ: - if (type->integer_type() == NULL - && type->float_type() == NULL - && type->complex_type() == NULL - && !type->is_string_type()) - { - error_at(location, - "expected integer, floating, complex, or string type"); - return false; - } - break; - - case OPERATOR_MINUS: - case OPERATOR_MINUSEQ: - case OPERATOR_MULT: - case OPERATOR_MULTEQ: - case OPERATOR_DIV: - case OPERATOR_DIVEQ: - if (type->integer_type() == NULL - && type->float_type() == NULL - && type->complex_type() == NULL) - { - error_at(location, "expected integer, floating, or complex type"); - return false; - } - break; - - case OPERATOR_MOD: - case OPERATOR_MODEQ: - case OPERATOR_OR: - case OPERATOR_OREQ: - case OPERATOR_AND: - case OPERATOR_ANDEQ: - case OPERATOR_XOR: - case OPERATOR_XOREQ: - case OPERATOR_BITCLEAR: - case OPERATOR_BITCLEAREQ: - if (type->integer_type() == NULL) - { - error_at(location, "expected integer type"); - return false; - } - break; - - default: - gcc_unreachable(); - } - - return true; -} - -// Check types. - -void -Binary_expression::do_check_types(Gogo*) -{ - Type* left_type = this->left_->type(); - Type* right_type = this->right_->type(); - if (left_type->is_error_type() || right_type->is_error_type()) - return; - - if (this->op_ == OPERATOR_EQEQ - || this->op_ == OPERATOR_NOTEQ - || this->op_ == OPERATOR_LT - || this->op_ == OPERATOR_LE - || this->op_ == OPERATOR_GT - || this->op_ == OPERATOR_GE) - { - if (!Type::are_assignable(left_type, right_type, NULL) - && !Type::are_assignable(right_type, left_type, NULL)) - { - this->report_error(_("incompatible types in binary expression")); - return; - } - if (!Binary_expression::check_operator_type(this->op_, left_type, - this->location()) - || !Binary_expression::check_operator_type(this->op_, right_type, - this->location())) - { - this->set_is_error(); - return; - } - } - else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT) - { - if (!Type::are_compatible_for_binop(left_type, right_type)) - { - this->report_error(_("incompatible types in binary expression")); - return; - } - if (!Binary_expression::check_operator_type(this->op_, left_type, - this->location())) - { - this->set_is_error(); - return; - } - } - else - { - if (left_type->integer_type() == NULL) - this->report_error(_("shift of non-integer operand")); - - if (!right_type->is_abstract() - && (right_type->integer_type() == NULL - || !right_type->integer_type()->is_unsigned())) - this->report_error(_("shift count not unsigned integer")); - else - { - mpz_t val; - mpz_init(val); - Type* type; - if (this->right_->integer_constant_value(true, val, &type)) - { - if (mpz_sgn(val) < 0) - this->report_error(_("negative shift count")); - } - mpz_clear(val); - } - } -} - -// Get a tree for a binary expression. - -tree -Binary_expression::do_get_tree(Translate_context* context) -{ - tree left = this->left_->get_tree(context); - tree right = this->right_->get_tree(context); - - if (left == error_mark_node || right == error_mark_node) - return error_mark_node; - - enum tree_code code; - bool use_left_type = true; - bool is_shift_op = false; - switch (this->op_) - { - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - return Expression::comparison_tree(context, this->op_, - this->left_->type(), left, - this->right_->type(), right, - this->location()); - - case OPERATOR_OROR: - code = TRUTH_ORIF_EXPR; - use_left_type = false; - break; - case OPERATOR_ANDAND: - code = TRUTH_ANDIF_EXPR; - use_left_type = false; - break; - case OPERATOR_PLUS: - code = PLUS_EXPR; - break; - case OPERATOR_MINUS: - code = MINUS_EXPR; - break; - case OPERATOR_OR: - code = BIT_IOR_EXPR; - break; - case OPERATOR_XOR: - code = BIT_XOR_EXPR; - break; - case OPERATOR_MULT: - code = MULT_EXPR; - break; - case OPERATOR_DIV: - { - Type *t = this->left_->type(); - if (t->float_type() != NULL || t->complex_type() != NULL) - code = RDIV_EXPR; - else - code = TRUNC_DIV_EXPR; - } - break; - case OPERATOR_MOD: - code = TRUNC_MOD_EXPR; - break; - case OPERATOR_LSHIFT: - code = LSHIFT_EXPR; - is_shift_op = true; - break; - case OPERATOR_RSHIFT: - code = RSHIFT_EXPR; - is_shift_op = true; - break; - case OPERATOR_AND: - code = BIT_AND_EXPR; - break; - case OPERATOR_BITCLEAR: - right = fold_build1(BIT_NOT_EXPR, TREE_TYPE(right), right); - code = BIT_AND_EXPR; - break; - default: - gcc_unreachable(); - } - - tree type = use_left_type ? TREE_TYPE(left) : TREE_TYPE(right); - - if (this->left_->type()->is_string_type()) - { - gcc_assert(this->op_ == OPERATOR_PLUS); - tree string_type = Type::make_string_type()->get_tree(context->gogo()); - static tree string_plus_decl; - return Gogo::call_builtin(&string_plus_decl, - this->location(), - "__go_string_plus", - 2, - string_type, - string_type, - left, - string_type, - right); - } - - tree compute_type = excess_precision_type(type); - if (compute_type != NULL_TREE) - { - left = ::convert(compute_type, left); - right = ::convert(compute_type, right); - } - - tree eval_saved = NULL_TREE; - if (is_shift_op) - { - if (!DECL_P(left)) - left = save_expr(left); - if (!DECL_P(right)) - right = save_expr(right); - // Make sure the values are evaluated. - eval_saved = fold_build2_loc(this->location(), COMPOUND_EXPR, - void_type_node, left, right); - } - - tree ret = fold_build2_loc(this->location(), - code, - compute_type != NULL_TREE ? compute_type : type, - left, right); - - if (compute_type != NULL_TREE) - ret = ::convert(type, ret); - - // In Go, a shift larger than the size of the type is well-defined. - // This is not true in GENERIC, so we need to insert a conditional. - if (is_shift_op) - { - gcc_assert(INTEGRAL_TYPE_P(TREE_TYPE(left))); - gcc_assert(this->left_->type()->integer_type() != NULL); - int bits = TYPE_PRECISION(TREE_TYPE(left)); - - tree compare = fold_build2(LT_EXPR, boolean_type_node, right, - build_int_cst_type(TREE_TYPE(right), bits)); - - tree overflow_result = fold_convert_loc(this->location(), - TREE_TYPE(left), - integer_zero_node); - if (this->op_ == OPERATOR_RSHIFT - && !this->left_->type()->integer_type()->is_unsigned()) - { - tree neg = fold_build2_loc(this->location(), LT_EXPR, - boolean_type_node, left, - fold_convert_loc(this->location(), - TREE_TYPE(left), - integer_zero_node)); - tree neg_one = fold_build2_loc(this->location(), - MINUS_EXPR, TREE_TYPE(left), - fold_convert_loc(this->location(), - TREE_TYPE(left), - integer_zero_node), - fold_convert_loc(this->location(), - TREE_TYPE(left), - integer_one_node)); - overflow_result = fold_build3_loc(this->location(), COND_EXPR, - TREE_TYPE(left), neg, neg_one, - overflow_result); - } - - ret = fold_build3_loc(this->location(), COND_EXPR, TREE_TYPE(left), - compare, ret, overflow_result); - - ret = fold_build2_loc(this->location(), COMPOUND_EXPR, - TREE_TYPE(ret), eval_saved, ret); - } - - return ret; -} - -// Export a binary expression. - -void -Binary_expression::do_export(Export* exp) const -{ - exp->write_c_string("("); - this->left_->export_expression(exp); - switch (this->op_) - { - case OPERATOR_OROR: - exp->write_c_string(" || "); - break; - case OPERATOR_ANDAND: - exp->write_c_string(" && "); - break; - case OPERATOR_EQEQ: - exp->write_c_string(" == "); - break; - case OPERATOR_NOTEQ: - exp->write_c_string(" != "); - break; - case OPERATOR_LT: - exp->write_c_string(" < "); - break; - case OPERATOR_LE: - exp->write_c_string(" <= "); - break; - case OPERATOR_GT: - exp->write_c_string(" > "); - break; - case OPERATOR_GE: - exp->write_c_string(" >= "); - break; - case OPERATOR_PLUS: - exp->write_c_string(" + "); - break; - case OPERATOR_MINUS: - exp->write_c_string(" - "); - break; - case OPERATOR_OR: - exp->write_c_string(" | "); - break; - case OPERATOR_XOR: - exp->write_c_string(" ^ "); - break; - case OPERATOR_MULT: - exp->write_c_string(" * "); - break; - case OPERATOR_DIV: - exp->write_c_string(" / "); - break; - case OPERATOR_MOD: - exp->write_c_string(" % "); - break; - case OPERATOR_LSHIFT: - exp->write_c_string(" << "); - break; - case OPERATOR_RSHIFT: - exp->write_c_string(" >> "); - break; - case OPERATOR_AND: - exp->write_c_string(" & "); - break; - case OPERATOR_BITCLEAR: - exp->write_c_string(" &^ "); - break; - default: - gcc_unreachable(); - } - this->right_->export_expression(exp); - exp->write_c_string(")"); -} - -// Import a binary expression. - -Expression* -Binary_expression::do_import(Import* imp) -{ - imp->require_c_string("("); - - Expression* left = Expression::import_expression(imp); - - Operator op; - if (imp->match_c_string(" || ")) - { - op = OPERATOR_OROR; - imp->advance(4); - } - else if (imp->match_c_string(" && ")) - { - op = OPERATOR_ANDAND; - imp->advance(4); - } - else if (imp->match_c_string(" == ")) - { - op = OPERATOR_EQEQ; - imp->advance(4); - } - else if (imp->match_c_string(" != ")) - { - op = OPERATOR_NOTEQ; - imp->advance(4); - } - else if (imp->match_c_string(" < ")) - { - op = OPERATOR_LT; - imp->advance(3); - } - else if (imp->match_c_string(" <= ")) - { - op = OPERATOR_LE; - imp->advance(4); - } - else if (imp->match_c_string(" > ")) - { - op = OPERATOR_GT; - imp->advance(3); - } - else if (imp->match_c_string(" >= ")) - { - op = OPERATOR_GE; - imp->advance(4); - } - else if (imp->match_c_string(" + ")) - { - op = OPERATOR_PLUS; - imp->advance(3); - } - else if (imp->match_c_string(" - ")) - { - op = OPERATOR_MINUS; - imp->advance(3); - } - else if (imp->match_c_string(" | ")) - { - op = OPERATOR_OR; - imp->advance(3); - } - else if (imp->match_c_string(" ^ ")) - { - op = OPERATOR_XOR; - imp->advance(3); - } - else if (imp->match_c_string(" * ")) - { - op = OPERATOR_MULT; - imp->advance(3); - } - else if (imp->match_c_string(" / ")) - { - op = OPERATOR_DIV; - imp->advance(3); - } - else if (imp->match_c_string(" % ")) - { - op = OPERATOR_MOD; - imp->advance(3); - } - else if (imp->match_c_string(" << ")) - { - op = OPERATOR_LSHIFT; - imp->advance(4); - } - else if (imp->match_c_string(" >> ")) - { - op = OPERATOR_RSHIFT; - imp->advance(4); - } - else if (imp->match_c_string(" & ")) - { - op = OPERATOR_AND; - imp->advance(3); - } - else if (imp->match_c_string(" &^ ")) - { - op = OPERATOR_BITCLEAR; - imp->advance(4); - } - else - { - error_at(imp->location(), "unrecognized binary operator"); - return Expression::make_error(imp->location()); - } - - Expression* right = Expression::import_expression(imp); - - imp->require_c_string(")"); - - return Expression::make_binary(op, left, right, imp->location()); -} - -// Make a binary expression. - -Expression* -Expression::make_binary(Operator op, Expression* left, Expression* right, - source_location location) -{ - return new Binary_expression(op, left, right, location); -} - -// Implement a comparison. - -tree -Expression::comparison_tree(Translate_context* context, Operator op, - Type* left_type, tree left_tree, - Type* right_type, tree right_tree, - source_location location) -{ - enum tree_code code; - switch (op) - { - case OPERATOR_EQEQ: - code = EQ_EXPR; - break; - case OPERATOR_NOTEQ: - code = NE_EXPR; - break; - case OPERATOR_LT: - code = LT_EXPR; - break; - case OPERATOR_LE: - code = LE_EXPR; - break; - case OPERATOR_GT: - code = GT_EXPR; - break; - case OPERATOR_GE: - code = GE_EXPR; - break; - default: - gcc_unreachable(); - } - - if (left_type->is_string_type()) - { - gcc_assert(right_type->is_string_type()); - tree string_type = Type::make_string_type()->get_tree(context->gogo()); - static tree string_compare_decl; - left_tree = Gogo::call_builtin(&string_compare_decl, - location, - "__go_strcmp", - 2, - integer_type_node, - string_type, - left_tree, - string_type, - right_tree); - right_tree = build_int_cst_type(integer_type_node, 0); - } - - if ((left_type->interface_type() != NULL - && right_type->interface_type() == NULL - && !right_type->is_nil_type()) - || (left_type->interface_type() == NULL - && !left_type->is_nil_type() - && right_type->interface_type() != NULL)) - { - // Comparing an interface value to a non-interface value. - if (left_type->interface_type() == NULL) - { - std::swap(left_type, right_type); - std::swap(left_tree, right_tree); - } - - // The right operand is not an interface. We need to take its - // address if it is not a pointer. - tree make_tmp; - tree arg; - if (right_type->points_to() != NULL) - { - make_tmp = NULL_TREE; - arg = right_tree; - } - else if (TREE_ADDRESSABLE(TREE_TYPE(right_tree)) || DECL_P(right_tree)) - { - make_tmp = NULL_TREE; - arg = build_fold_addr_expr_loc(location, right_tree); - if (DECL_P(right_tree)) - TREE_ADDRESSABLE(right_tree) = 1; - } - else - { - tree tmp = create_tmp_var(TREE_TYPE(right_tree), - get_name(right_tree)); - DECL_IGNORED_P(tmp) = 0; - DECL_INITIAL(tmp) = right_tree; - TREE_ADDRESSABLE(tmp) = 1; - make_tmp = build1(DECL_EXPR, void_type_node, tmp); - SET_EXPR_LOCATION(make_tmp, location); - arg = build_fold_addr_expr_loc(location, tmp); - } - arg = fold_convert_loc(location, ptr_type_node, arg); - - tree descriptor = right_type->type_descriptor_pointer(context->gogo()); - - if (left_type->interface_type()->is_empty()) - { - static tree empty_interface_value_compare_decl; - left_tree = Gogo::call_builtin(&empty_interface_value_compare_decl, - location, - "__go_empty_interface_value_compare", - 3, - integer_type_node, - TREE_TYPE(left_tree), - left_tree, - TREE_TYPE(descriptor), - descriptor, - ptr_type_node, - arg); - // This can panic if the type is not comparable. - TREE_NOTHROW(empty_interface_value_compare_decl) = 0; - } - else - { - static tree interface_value_compare_decl; - left_tree = Gogo::call_builtin(&interface_value_compare_decl, - location, - "__go_interface_value_compare", - 3, - integer_type_node, - TREE_TYPE(left_tree), - left_tree, - TREE_TYPE(descriptor), - descriptor, - ptr_type_node, - arg); - // This can panic if the type is not comparable. - TREE_NOTHROW(interface_value_compare_decl) = 0; - } - right_tree = build_int_cst_type(integer_type_node, 0); - - if (make_tmp != NULL_TREE) - left_tree = build2(COMPOUND_EXPR, TREE_TYPE(left_tree), make_tmp, - left_tree); - } - else if (left_type->interface_type() != NULL - && right_type->interface_type() != NULL) - { - if (left_type->interface_type()->is_empty()) - { - gcc_assert(right_type->interface_type()->is_empty()); - static tree empty_interface_compare_decl; - left_tree = Gogo::call_builtin(&empty_interface_compare_decl, - location, - "__go_empty_interface_compare", - 2, - integer_type_node, - TREE_TYPE(left_tree), - left_tree, - TREE_TYPE(right_tree), - right_tree); - // This can panic if the type is uncomparable. - TREE_NOTHROW(empty_interface_compare_decl) = 0; - } - else - { - gcc_assert(!right_type->interface_type()->is_empty()); - static tree interface_compare_decl; - left_tree = Gogo::call_builtin(&interface_compare_decl, - location, - "__go_interface_compare", - 2, - integer_type_node, - TREE_TYPE(left_tree), - left_tree, - TREE_TYPE(right_tree), - right_tree); - // This can panic if the type is uncomparable. - TREE_NOTHROW(interface_compare_decl) = 0; - } - right_tree = build_int_cst_type(integer_type_node, 0); - } - - if (left_type->is_nil_type() - && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)) - { - std::swap(left_type, right_type); - std::swap(left_tree, right_tree); - } - - if (right_type->is_nil_type()) - { - if (left_type->array_type() != NULL - && left_type->array_type()->length() == NULL) - { - Array_type* at = left_type->array_type(); - left_tree = at->value_pointer_tree(context->gogo(), left_tree); - right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node); - } - else if (left_type->interface_type() != NULL) - { - // An interface is nil if the first field is nil. - tree left_type_tree = TREE_TYPE(left_tree); - gcc_assert(TREE_CODE(left_type_tree) == RECORD_TYPE); - tree field = TYPE_FIELDS(left_type_tree); - left_tree = build3(COMPONENT_REF, TREE_TYPE(field), left_tree, - field, NULL_TREE); - right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node); - } - else - { - gcc_assert(POINTER_TYPE_P(TREE_TYPE(left_tree))); - right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node); - } - } - - tree ret = fold_build2(code, boolean_type_node, left_tree, right_tree); - if (CAN_HAVE_LOCATION_P(ret)) - SET_EXPR_LOCATION(ret, location); - return ret; -} - -// Class Bound_method_expression. - -// Traversal. - -int -Bound_method_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return Expression::traverse(&this->method_, traverse); -} - -// Return the type of a bound method expression. The type of this -// object is really the type of the method with no receiver. We -// should be able to get away with just returning the type of the -// method. - -Type* -Bound_method_expression::do_type() -{ - return this->method_->type(); -} - -// Determine the types of a method expression. - -void -Bound_method_expression::do_determine_type(const Type_context*) -{ - this->method_->determine_type_no_context(); - Type* mtype = this->method_->type(); - Function_type* fntype = mtype == NULL ? NULL : mtype->function_type(); - if (fntype == NULL || !fntype->is_method()) - this->expr_->determine_type_no_context(); - else - { - Type_context subcontext(fntype->receiver()->type(), false); - this->expr_->determine_type(&subcontext); - } -} - -// Check the types of a method expression. - -void -Bound_method_expression::do_check_types(Gogo*) -{ - Type* type = this->method_->type()->deref(); - if (type == NULL - || type->function_type() == NULL - || !type->function_type()->is_method()) - this->report_error(_("object is not a method")); - else - { - Type* rtype = type->function_type()->receiver()->type()->deref(); - Type* etype = (this->expr_type_ != NULL - ? this->expr_type_ - : this->expr_->type()); - etype = etype->deref(); - if (!Type::are_identical(rtype, etype, NULL)) - this->report_error(_("method type does not match object type")); - } -} - -// Get the tree for a method expression. There is no standard tree -// representation for this. The only places it may currently be used -// are in a Call_expression or a Go_statement, which will take it -// apart directly. So this has nothing to do at present. - -tree -Bound_method_expression::do_get_tree(Translate_context*) -{ - gcc_unreachable(); -} - -// Make a method expression. - -Bound_method_expression* -Expression::make_bound_method(Expression* expr, Expression* method, - source_location location) -{ - return new Bound_method_expression(expr, method, location); -} - -// Class Builtin_call_expression. This is used for a call to a -// builtin function. - -class Builtin_call_expression : public Call_expression -{ - public: - Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args, - bool is_varargs, source_location location); - - protected: - // This overrides Call_expression::do_lower. - Expression* - do_lower(Gogo*, Named_object*, int); - - bool - do_is_constant() const; - - bool - do_integer_constant_value(bool, mpz_t, Type**) const; - - bool - do_float_constant_value(mpfr_t, Type**) const; - - bool - do_complex_constant_value(mpfr_t, mpfr_t, Type**) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Builtin_call_expression(this->gogo_, this->fn()->copy(), - this->args()->copy(), - this->is_varargs(), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - virtual bool - do_is_recover_call() const; - - virtual void - do_set_recover_arg(Expression*); - - private: - // The builtin functions. - enum Builtin_function_code - { - BUILTIN_INVALID, - - // Predeclared builtin functions. - BUILTIN_APPEND, - BUILTIN_CAP, - BUILTIN_CLOSE, - BUILTIN_CLOSED, - BUILTIN_CMPLX, - BUILTIN_COPY, - BUILTIN_IMAG, - BUILTIN_LEN, - BUILTIN_MAKE, - BUILTIN_NEW, - BUILTIN_PANIC, - BUILTIN_PRINT, - BUILTIN_PRINTLN, - BUILTIN_REAL, - BUILTIN_RECOVER, - - // Builtin functions from the unsafe package. - BUILTIN_ALIGNOF, - BUILTIN_OFFSETOF, - BUILTIN_SIZEOF - }; - - Expression* - one_arg() const; - - bool - check_one_arg(); - - static Type* - real_imag_type(Type*); - - static Type* - cmplx_type(Type*); - - // A pointer back to the general IR structure. This avoids a global - // variable, or passing it around everywhere. - Gogo* gogo_; - // The builtin function being called. - Builtin_function_code code_; -}; - -Builtin_call_expression::Builtin_call_expression(Gogo* gogo, - Expression* fn, - Expression_list* args, - bool is_varargs, - source_location location) - : Call_expression(fn, args, is_varargs, location), - gogo_(gogo), code_(BUILTIN_INVALID) -{ - Func_expression* fnexp = this->fn()->func_expression(); - gcc_assert(fnexp != NULL); - const std::string& name(fnexp->named_object()->name()); - if (name == "append") - this->code_ = BUILTIN_APPEND; - else if (name == "cap") - this->code_ = BUILTIN_CAP; - else if (name == "close") - this->code_ = BUILTIN_CLOSE; - else if (name == "closed") - this->code_ = BUILTIN_CLOSED; - else if (name == "cmplx") - this->code_ = BUILTIN_CMPLX; - else if (name == "copy") - this->code_ = BUILTIN_COPY; - else if (name == "imag") - this->code_ = BUILTIN_IMAG; - else if (name == "len") - this->code_ = BUILTIN_LEN; - else if (name == "make") - this->code_ = BUILTIN_MAKE; - else if (name == "new") - this->code_ = BUILTIN_NEW; - else if (name == "panic") - this->code_ = BUILTIN_PANIC; - else if (name == "print") - this->code_ = BUILTIN_PRINT; - else if (name == "println") - this->code_ = BUILTIN_PRINTLN; - else if (name == "real") - this->code_ = BUILTIN_REAL; - else if (name == "recover") - this->code_ = BUILTIN_RECOVER; - else if (name == "Alignof") - this->code_ = BUILTIN_ALIGNOF; - else if (name == "Offsetof") - this->code_ = BUILTIN_OFFSETOF; - else if (name == "Sizeof") - this->code_ = BUILTIN_SIZEOF; - else - gcc_unreachable(); -} - -// Return whether this is a call to recover. This is a virtual -// function called from the parent class. - -bool -Builtin_call_expression::do_is_recover_call() const -{ - if (this->classification() == EXPRESSION_ERROR) - return false; - return this->code_ == BUILTIN_RECOVER; -} - -// Set the argument for a call to recover. - -void -Builtin_call_expression::do_set_recover_arg(Expression* arg) -{ - const Expression_list* args = this->args(); - gcc_assert(args == NULL || args->empty()); - Expression_list* new_args = new Expression_list(); - new_args->push_back(arg); - this->set_args(new_args); -} - -// A traversal class which looks for a call expression. - -class Find_call_expression : public Traverse -{ - public: - Find_call_expression() - : Traverse(traverse_expressions), - found_(false) - { } - - int - expression(Expression**); - - bool - found() - { return this->found_; } - - private: - bool found_; -}; - -int -Find_call_expression::expression(Expression** pexpr) -{ - if ((*pexpr)->call_expression() != NULL) - { - this->found_ = true; - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lower a builtin call expression. This turns new and make into -// specific expressions. We also convert to a constant if we can. - -Expression* -Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function, int) -{ - if (this->code_ == BUILTIN_NEW) - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 1) - this->report_error(_("not enough arguments")); - else if (args->size() > 1) - this->report_error(_("too many arguments")); - else - { - Expression* arg = args->front(); - if (!arg->is_type_expression()) - { - error_at(arg->location(), "expected type"); - this->set_is_error(); - } - else - return Expression::make_allocation(arg->type(), this->location()); - } - } - else if (this->code_ == BUILTIN_MAKE) - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 1) - this->report_error(_("not enough arguments")); - else - { - Expression* arg = args->front(); - if (!arg->is_type_expression()) - { - error_at(arg->location(), "expected type"); - this->set_is_error(); - } - else - { - Expression_list* newargs; - if (args->size() == 1) - newargs = NULL; - else - { - newargs = new Expression_list(); - Expression_list::const_iterator p = args->begin(); - ++p; - for (; p != args->end(); ++p) - newargs->push_back(*p); - } - return Expression::make_make(arg->type(), newargs, - this->location()); - } - } - } - else if (this->is_constant()) - { - // We can only lower len and cap if there are no function calls - // in the arguments. Otherwise we have to make the call. - if (this->code_ == BUILTIN_LEN || this->code_ == BUILTIN_CAP) - { - Expression* arg = this->one_arg(); - if (!arg->is_constant()) - { - Find_call_expression find_call; - Expression::traverse(&arg, &find_call); - if (find_call.found()) - return this; - } - } - - mpz_t ival; - mpz_init(ival); - Type* type; - if (this->integer_constant_value(true, ival, &type)) - { - Expression* ret = Expression::make_integer(&ival, type, - this->location()); - mpz_clear(ival); - return ret; - } - mpz_clear(ival); - - mpfr_t rval; - mpfr_init(rval); - if (this->float_constant_value(rval, &type)) - { - Expression* ret = Expression::make_float(&rval, type, - this->location()); - mpfr_clear(rval); - return ret; - } - - mpfr_t imag; - mpfr_init(imag); - if (this->complex_constant_value(rval, imag, &type)) - { - Expression* ret = Expression::make_complex(&rval, &imag, type, - this->location()); - mpfr_clear(rval); - mpfr_clear(imag); - return ret; - } - mpfr_clear(rval); - mpfr_clear(imag); - } - else if (this->code_ == BUILTIN_RECOVER) - { - if (function != NULL) - function->func_value()->set_calls_recover(); - else - { - // Calling recover outside of a function always returns the - // nil empty interface. - Type* eface = Type::make_interface_type(NULL, this->location()); - return Expression::make_cast(eface, - Expression::make_nil(this->location()), - this->location()); - } - } - else if (this->code_ == BUILTIN_APPEND) - { - // Lower the varargs. - const Expression_list* args = this->args(); - if (args == NULL || args->empty()) - return this; - Type* slice_type = args->front()->type(); - if (!slice_type->is_open_array_type()) - { - error_at(args->front()->location(), "argument 1 must be a slice"); - this->set_is_error(); - return this; - } - return this->lower_varargs(gogo, function, slice_type, 2); - } - - return this; -} - -// Return the type of the real or imag functions, given the type of -// the argument. We need to map complex to float, complex64 to -// float32, and complex128 to float64, so it has to be done by name. -// This returns NULL if it can't figure out the type. - -Type* -Builtin_call_expression::real_imag_type(Type* arg_type) -{ - if (arg_type == NULL || arg_type->is_abstract()) - return NULL; - Named_type* nt = arg_type->named_type(); - if (nt == NULL) - return NULL; - while (nt->real_type()->named_type() != NULL) - nt = nt->real_type()->named_type(); - if (nt->name() == "complex") - return Type::lookup_float_type("float"); - else if (nt->name() == "complex64") - return Type::lookup_float_type("float32"); - else if (nt->name() == "complex128") - return Type::lookup_float_type("float64"); - else - return NULL; -} - -// Return the type of the cmplx function, given the type of one of the -// argments. Like real_imag_type, we have to map by name. - -Type* -Builtin_call_expression::cmplx_type(Type* arg_type) -{ - if (arg_type == NULL || arg_type->is_abstract()) - return NULL; - Named_type* nt = arg_type->named_type(); - if (nt == NULL) - return NULL; - while (nt->real_type()->named_type() != NULL) - nt = nt->real_type()->named_type(); - if (nt->name() == "float") - return Type::lookup_complex_type("complex"); - else if (nt->name() == "float32") - return Type::lookup_complex_type("complex64"); - else if (nt->name() == "float64") - return Type::lookup_complex_type("complex128"); - else - return NULL; -} - -// Return a single argument, or NULL if there isn't one. - -Expression* -Builtin_call_expression::one_arg() const -{ - const Expression_list* args = this->args(); - if (args->size() != 1) - return NULL; - return args->front(); -} - -// Return whether this is constant: len of a string, or len or cap of -// a fixed array, or unsafe.Sizeof, unsafe.Offsetof, unsafe.Alignof. - -bool -Builtin_call_expression::do_is_constant() const -{ - switch (this->code_) - { - case BUILTIN_LEN: - case BUILTIN_CAP: - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - Type* arg_type = arg->type(); - - if (arg_type->points_to() != NULL - && arg_type->points_to()->array_type() != NULL - && !arg_type->points_to()->is_open_array_type()) - arg_type = arg_type->points_to(); - - if (arg_type->array_type() != NULL - && arg_type->array_type()->length() != NULL) - return arg_type->array_type()->length()->is_constant(); - - if (this->code_ == BUILTIN_LEN && arg_type->is_string_type()) - return arg->is_constant(); - } - break; - - case BUILTIN_SIZEOF: - case BUILTIN_ALIGNOF: - return this->one_arg() != NULL; - - case BUILTIN_OFFSETOF: - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - return arg->field_reference_expression() != NULL; - } - - case BUILTIN_CMPLX: - { - const Expression_list* args = this->args(); - if (args != NULL && args->size() == 2) - return args->front()->is_constant() && args->back()->is_constant(); - } - break; - - case BUILTIN_REAL: - case BUILTIN_IMAG: - { - Expression* arg = this->one_arg(); - return arg != NULL && arg->is_constant(); - } - - default: - break; - } - - return false; -} - -// Return an integer constant value if possible. - -bool -Builtin_call_expression::do_integer_constant_value(bool iota_is_constant, - mpz_t val, - Type** ptype) const -{ - if (this->code_ == BUILTIN_LEN - || this->code_ == BUILTIN_CAP) - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - Type* arg_type = arg->type(); - - if (this->code_ == BUILTIN_LEN && arg_type->is_string_type()) - { - std::string sval; - if (arg->string_constant_value(&sval)) - { - mpz_set_ui(val, sval.length()); - *ptype = Type::lookup_integer_type("int"); - return true; - } - } - - if (arg_type->points_to() != NULL - && arg_type->points_to()->array_type() != NULL - && !arg_type->points_to()->is_open_array_type()) - arg_type = arg_type->points_to(); - - if (arg_type->array_type() != NULL - && arg_type->array_type()->length() != NULL) - { - Expression* e = arg_type->array_type()->length(); - if (e->integer_constant_value(iota_is_constant, val, ptype)) - { - *ptype = Type::lookup_integer_type("int"); - return true; - } - } - } - else if (this->code_ == BUILTIN_SIZEOF - || this->code_ == BUILTIN_ALIGNOF) - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - Type* arg_type = arg->type(); - if (arg_type->is_error_type()) - return false; - if (arg_type->is_abstract()) - return false; - tree arg_type_tree = arg_type->get_tree(this->gogo_); - unsigned long val_long; - if (this->code_ == BUILTIN_SIZEOF) - { - tree type_size = TYPE_SIZE_UNIT(arg_type_tree); - gcc_assert(TREE_CODE(type_size) == INTEGER_CST); - if (TREE_INT_CST_HIGH(type_size) != 0) - return false; - unsigned HOST_WIDE_INT val_wide = TREE_INT_CST_LOW(type_size); - val_long = static_cast(val_wide); - if (val_long != val_wide) - return false; - } - else if (this->code_ == BUILTIN_ALIGNOF) - { - val_long = TYPE_ALIGN(arg_type_tree); - if (arg->field_reference_expression() != NULL) - { - // Calling unsafe.Alignof(s.f) returns the alignment of - // the type of f when it is used as a field in a struct. -#ifdef BIGGEST_FIELD_ALIGNMENT - if (val_long > BIGGEST_FIELD_ALIGNMENT) - val_long = BIGGEST_FIELD_ALIGNMENT; -#endif -#ifdef ADJUST_FIELD_ALIGN - // A separate declaration avoids a warning promoted to - // an error if ADJUST_FIELD_ALIGN ignores FIELD. - tree field; - field = build_decl(UNKNOWN_LOCATION, FIELD_DECL, NULL, - arg_type_tree); - val_long = ADJUST_FIELD_ALIGN(field, val_long); -#endif - } - val_long /= BITS_PER_UNIT; - } - else - gcc_unreachable(); - mpz_set_ui(val, val_long); - *ptype = NULL; - return true; - } - else if (this->code_ == BUILTIN_OFFSETOF) - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - Field_reference_expression* farg = arg->field_reference_expression(); - if (farg == NULL) - return false; - Expression* struct_expr = farg->expr(); - Type* st = struct_expr->type(); - if (st->struct_type() == NULL) - return false; - tree struct_tree = st->get_tree(this->gogo_); - gcc_assert(TREE_CODE(struct_tree) == RECORD_TYPE); - tree field = TYPE_FIELDS(struct_tree); - for (unsigned int index = farg->field_index(); index > 0; --index) - { - field = DECL_CHAIN(field); - gcc_assert(field != NULL_TREE); - } - HOST_WIDE_INT offset_wide = int_byte_position (field); - if (offset_wide < 0) - return false; - unsigned long offset_long = static_cast(offset_wide); - if (offset_long != static_cast(offset_wide)) - return false; - mpz_set_ui(val, offset_long); - return true; - } - return false; -} - -// Return a floating point constant value if possible. - -bool -Builtin_call_expression::do_float_constant_value(mpfr_t val, - Type** ptype) const -{ - if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG) - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - - bool ret = false; - Type* type; - if (arg->complex_constant_value(real, imag, &type)) - { - if (this->code_ == BUILTIN_REAL) - mpfr_set(val, real, GMP_RNDN); - else - mpfr_set(val, imag, GMP_RNDN); - *ptype = Builtin_call_expression::real_imag_type(type); - ret = true; - } - - mpfr_clear(real); - mpfr_clear(imag); - return ret; - } - - return false; -} - -// Return a complex constant value if possible. - -bool -Builtin_call_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - if (this->code_ == BUILTIN_CMPLX) - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() != 2) - return false; - - mpfr_t r; - mpfr_init(r); - Type* rtype; - if (!args->front()->float_constant_value(r, &rtype)) - { - mpfr_clear(r); - return false; - } - - mpfr_t i; - mpfr_init(i); - - bool ret = false; - Type* itype; - if (args->back()->float_constant_value(i, &itype) - && Type::are_identical(rtype, itype, NULL)) - { - mpfr_set(real, r, GMP_RNDN); - mpfr_set(imag, i, GMP_RNDN); - *ptype = Builtin_call_expression::cmplx_type(rtype); - ret = true; - } - - mpfr_clear(r); - mpfr_clear(i); - - return ret; - } - - return false; -} - -// Return the type. - -Type* -Builtin_call_expression::do_type() -{ - switch (this->code_) - { - case BUILTIN_INVALID: - default: - gcc_unreachable(); - - case BUILTIN_NEW: - case BUILTIN_MAKE: - { - const Expression_list* args = this->args(); - if (args == NULL || args->empty()) - return Type::make_error_type(); - return Type::make_pointer_type(args->front()->type()); - } - - case BUILTIN_CAP: - case BUILTIN_COPY: - case BUILTIN_LEN: - case BUILTIN_ALIGNOF: - case BUILTIN_OFFSETOF: - case BUILTIN_SIZEOF: - return Type::lookup_integer_type("int"); - - case BUILTIN_CLOSE: - case BUILTIN_PANIC: - case BUILTIN_PRINT: - case BUILTIN_PRINTLN: - return Type::make_void_type(); - - case BUILTIN_CLOSED: - return Type::lookup_bool_type(); - - case BUILTIN_RECOVER: - return Type::make_interface_type(NULL, BUILTINS_LOCATION); - - case BUILTIN_APPEND: - { - const Expression_list* args = this->args(); - if (args == NULL || args->empty()) - return Type::make_error_type(); - return args->front()->type(); - } - - case BUILTIN_REAL: - case BUILTIN_IMAG: - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return Type::make_error_type(); - Type* t = arg->type(); - if (t->is_abstract()) - t = t->make_non_abstract_type(); - t = Builtin_call_expression::real_imag_type(t); - if (t == NULL) - t = Type::make_error_type(); - return t; - } - - case BUILTIN_CMPLX: - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() != 2) - return Type::make_error_type(); - Type* t = args->front()->type(); - if (t->is_abstract()) - { - t = args->back()->type(); - if (t->is_abstract()) - t = t->make_non_abstract_type(); - } - t = Builtin_call_expression::cmplx_type(t); - if (t == NULL) - t = Type::make_error_type(); - return t; - } - } -} - -// Determine the type. - -void -Builtin_call_expression::do_determine_type(const Type_context* context) -{ - this->fn()->determine_type_no_context(); - - const Expression_list* args = this->args(); - - bool is_print; - Type* arg_type = NULL; - switch (this->code_) - { - case BUILTIN_PRINT: - case BUILTIN_PRINTLN: - // Do not force a large integer constant to "int". - is_print = true; - break; - - case BUILTIN_REAL: - case BUILTIN_IMAG: - arg_type = Builtin_call_expression::cmplx_type(context->type); - is_print = false; - break; - - case BUILTIN_CMPLX: - { - // For the cmplx function the type of one operand can - // determine the type of the other, as in a binary expression. - arg_type = Builtin_call_expression::real_imag_type(context->type); - if (args != NULL && args->size() == 2) - { - Type* t1 = args->front()->type(); - Type* t2 = args->front()->type(); - if (!t1->is_abstract()) - arg_type = t1; - else if (!t2->is_abstract()) - arg_type = t2; - } - is_print = false; - } - break; - - default: - is_print = false; - break; - } - - if (args != NULL) - { - for (Expression_list::const_iterator pa = args->begin(); - pa != args->end(); - ++pa) - { - Type_context subcontext; - subcontext.type = arg_type; - - if (is_print) - { - // We want to print large constants, we so can't just - // use the appropriate nonabstract type. Use uint64 for - // an integer if we know it is nonnegative, otherwise - // use int64 for a integer, otherwise use float64 for a - // float or complex128 for a complex. - Type* want_type = NULL; - Type* atype = (*pa)->type(); - if (atype->is_abstract()) - { - if (atype->integer_type() != NULL) - { - mpz_t val; - mpz_init(val); - Type* dummy; - if (this->integer_constant_value(true, val, &dummy) - && mpz_sgn(val) >= 0) - want_type = Type::lookup_integer_type("uint64"); - else - want_type = Type::lookup_integer_type("int64"); - mpz_clear(val); - } - else if (atype->float_type() != NULL) - want_type = Type::lookup_float_type("float64"); - else if (atype->complex_type() != NULL) - want_type = Type::lookup_complex_type("complex128"); - else if (atype->is_abstract_string_type()) - want_type = Type::lookup_string_type(); - else if (atype->is_abstract_boolean_type()) - want_type = Type::lookup_bool_type(); - else - gcc_unreachable(); - subcontext.type = want_type; - } - } - - (*pa)->determine_type(&subcontext); - } - } -} - -// If there is exactly one argument, return true. Otherwise give an -// error message and return false. - -bool -Builtin_call_expression::check_one_arg() -{ - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 1) - { - this->report_error(_("not enough arguments")); - return false; - } - else if (args->size() > 1) - { - this->report_error(_("too many arguments")); - return false; - } - if (args->front()->is_error_expression() - || args->front()->type()->is_error_type()) - { - this->set_is_error(); - return false; - } - return true; -} - -// Check argument types for a builtin function. - -void -Builtin_call_expression::do_check_types(Gogo*) -{ - switch (this->code_) - { - case BUILTIN_INVALID: - case BUILTIN_NEW: - case BUILTIN_MAKE: - return; - - case BUILTIN_LEN: - case BUILTIN_CAP: - { - // The single argument may be either a string or an array or a - // map or a channel, or a pointer to a closed array. - if (this->check_one_arg()) - { - Type* arg_type = this->one_arg()->type(); - if (arg_type->points_to() != NULL - && arg_type->points_to()->array_type() != NULL - && !arg_type->points_to()->is_open_array_type()) - arg_type = arg_type->points_to(); - if (this->code_ == BUILTIN_CAP) - { - if (!arg_type->is_error_type() - && arg_type->array_type() == NULL - && arg_type->channel_type() == NULL) - this->report_error(_("argument must be array or slice " - "or channel")); - } - else - { - if (!arg_type->is_error_type() - && !arg_type->is_string_type() - && arg_type->array_type() == NULL - && arg_type->map_type() == NULL - && arg_type->channel_type() == NULL) - this->report_error(_("argument must be string or " - "array or slice or map or channel")); - } - } - } - break; - - case BUILTIN_PRINT: - case BUILTIN_PRINTLN: - { - const Expression_list* args = this->args(); - if (args == NULL) - { - if (this->code_ == BUILTIN_PRINT) - warning_at(this->location(), 0, - "no arguments for builtin function %<%s%>", - (this->code_ == BUILTIN_PRINT - ? "print" - : "println")); - } - else - { - for (Expression_list::const_iterator p = args->begin(); - p != args->end(); - ++p) - { - Type* type = (*p)->type(); - if (type->is_error_type() - || type->is_string_type() - || type->integer_type() != NULL - || type->float_type() != NULL - || type->complex_type() != NULL - || type->is_boolean_type() - || type->points_to() != NULL - || type->interface_type() != NULL - || type->channel_type() != NULL - || type->map_type() != NULL - || type->function_type() != NULL - || type->is_open_array_type()) - ; - else - this->report_error(_("unsupported argument type to " - "builtin function")); - } - } - } - break; - - case BUILTIN_CLOSE: - case BUILTIN_CLOSED: - if (this->check_one_arg()) - { - if (this->one_arg()->type()->channel_type() == NULL) - this->report_error(_("argument must be channel")); - } - break; - - case BUILTIN_PANIC: - case BUILTIN_SIZEOF: - case BUILTIN_ALIGNOF: - this->check_one_arg(); - break; - - case BUILTIN_RECOVER: - if (this->args() != NULL && !this->args()->empty()) - this->report_error(_("too many arguments")); - break; - - case BUILTIN_OFFSETOF: - if (this->check_one_arg()) - { - Expression* arg = this->one_arg(); - if (arg->field_reference_expression() == NULL) - this->report_error(_("argument must be a field reference")); - } - break; - - case BUILTIN_COPY: - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 2) - { - this->report_error(_("not enough arguments")); - break; - } - else if (args->size() > 2) - { - this->report_error(_("too many arguments")); - break; - } - Type* arg1_type = args->front()->type(); - Type* arg2_type = args->back()->type(); - if (arg1_type->is_error_type() || arg2_type->is_error_type()) - break; - - Type* e1; - if (arg1_type->is_open_array_type()) - e1 = arg1_type->array_type()->element_type(); - else - { - this->report_error(_("left argument must be a slice")); - break; - } - - Type* e2; - if (arg2_type->is_open_array_type()) - e2 = arg2_type->array_type()->element_type(); - else if (arg2_type->is_string_type()) - e2 = Type::lookup_integer_type("uint8"); - else - { - this->report_error(_("right argument must be a slice or a string")); - break; - } - - if (!Type::are_identical(e1, e2, NULL)) - this->report_error(_("element types must be the same")); - } - break; - - case BUILTIN_APPEND: - { - const Expression_list* args = this->args(); - if (args == NULL || args->empty()) - { - this->report_error(_("not enough arguments")); - break; - } - /* Lowering varargs should have left us with 2 arguments. */ - gcc_assert(args->size() == 2); - std::string reason; - if (!Type::are_assignable(args->front()->type(), args->back()->type(), - &reason)) - { - if (reason.empty()) - this->report_error(_("arguments 1 and 2 have different types")); - else - { - error_at(this->location(), - "arguments 1 and 2 have different types (%s)", - reason.c_str()); - this->set_is_error(); - } - } - break; - } - - case BUILTIN_REAL: - case BUILTIN_IMAG: - if (this->check_one_arg()) - { - if (this->one_arg()->type()->complex_type() == NULL) - this->report_error(_("argument must have complex type")); - } - break; - - case BUILTIN_CMPLX: - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 2) - this->report_error(_("not enough arguments")); - else if (args->size() > 2) - this->report_error(_("too many arguments")); - else if (args->front()->is_error_expression() - || args->front()->type()->is_error_type() - || args->back()->is_error_expression() - || args->back()->type()->is_error_type()) - this->set_is_error(); - else if (!Type::are_identical(args->front()->type(), - args->back()->type(), NULL)) - this->report_error(_("cmplx arguments must have identical types")); - else if (args->front()->type()->float_type() == NULL) - this->report_error(_("cmplx arguments must have " - "floating-point type")); - } - break; - - default: - gcc_unreachable(); - } -} - -// Return the tree for a builtin function. - -tree -Builtin_call_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - source_location location = this->location(); - switch (this->code_) - { - case BUILTIN_INVALID: - case BUILTIN_NEW: - case BUILTIN_MAKE: - gcc_unreachable(); - - case BUILTIN_LEN: - case BUILTIN_CAP: - { - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 1); - Expression* arg = *args->begin(); - Type* arg_type = arg->type(); - tree arg_tree = arg->get_tree(context); - if (arg_tree == error_mark_node) - return error_mark_node; - - if (arg_type->points_to() != NULL) - { - arg_type = arg_type->points_to(); - gcc_assert(arg_type->array_type() != NULL - && !arg_type->is_open_array_type()); - gcc_assert(POINTER_TYPE_P(TREE_TYPE(arg_tree))); - arg_tree = build_fold_indirect_ref(arg_tree); - } - - tree val_tree; - if (this->code_ == BUILTIN_LEN) - { - if (arg_type->is_string_type()) - val_tree = String_type::length_tree(gogo, arg_tree); - else if (arg_type->array_type() != NULL) - val_tree = arg_type->array_type()->length_tree(gogo, arg_tree); - else if (arg_type->map_type() != NULL) - { - static tree map_len_fndecl; - val_tree = Gogo::call_builtin(&map_len_fndecl, - location, - "__go_map_len", - 1, - sizetype, - arg_type->get_tree(gogo), - arg_tree); - } - else if (arg_type->channel_type() != NULL) - { - static tree chan_len_fndecl; - val_tree = Gogo::call_builtin(&chan_len_fndecl, - location, - "__go_chan_len", - 1, - sizetype, - arg_type->get_tree(gogo), - arg_tree); - } - else - gcc_unreachable(); - } - else - { - if (arg_type->array_type() != NULL) - val_tree = arg_type->array_type()->capacity_tree(gogo, arg_tree); - else if (arg_type->channel_type() != NULL) - { - static tree chan_cap_fndecl; - val_tree = Gogo::call_builtin(&chan_cap_fndecl, - location, - "__go_chan_cap", - 1, - sizetype, - arg_type->get_tree(gogo), - arg_tree); - } - else - gcc_unreachable(); - } - - tree type_tree = Type::lookup_integer_type("int")->get_tree(gogo); - if (type_tree == TREE_TYPE(val_tree)) - return val_tree; - else - return fold(convert_to_integer(type_tree, val_tree)); - } - - case BUILTIN_PRINT: - case BUILTIN_PRINTLN: - { - const bool is_ln = this->code_ == BUILTIN_PRINTLN; - tree stmt_list = NULL_TREE; - - const Expression_list* call_args = this->args(); - if (call_args != NULL) - { - for (Expression_list::const_iterator p = call_args->begin(); - p != call_args->end(); - ++p) - { - if (is_ln && p != call_args->begin()) - { - static tree print_space_fndecl; - tree call = Gogo::call_builtin(&print_space_fndecl, - location, - "__go_print_space", - 0, - void_type_node); - append_to_statement_list(call, &stmt_list); - } - - Type* type = (*p)->type(); - - tree arg = (*p)->get_tree(context); - if (arg == error_mark_node) - return error_mark_node; - - tree* pfndecl; - const char* fnname; - if (type->is_string_type()) - { - static tree print_string_fndecl; - pfndecl = &print_string_fndecl; - fnname = "__go_print_string"; - } - else if (type->integer_type() != NULL - && type->integer_type()->is_unsigned()) - { - static tree print_uint64_fndecl; - pfndecl = &print_uint64_fndecl; - fnname = "__go_print_uint64"; - Type* itype = Type::lookup_integer_type("uint64"); - arg = fold_convert_loc(location, itype->get_tree(gogo), - arg); - } - else if (type->integer_type() != NULL) - { - static tree print_int64_fndecl; - pfndecl = &print_int64_fndecl; - fnname = "__go_print_int64"; - Type* itype = Type::lookup_integer_type("int64"); - arg = fold_convert_loc(location, itype->get_tree(gogo), - arg); - } - else if (type->float_type() != NULL) - { - static tree print_double_fndecl; - pfndecl = &print_double_fndecl; - fnname = "__go_print_double"; - arg = fold_convert_loc(location, double_type_node, arg); - } - else if (type->complex_type() != NULL) - { - static tree print_complex_fndecl; - pfndecl = &print_complex_fndecl; - fnname = "__go_print_complex"; - arg = fold_convert_loc(location, complex_double_type_node, - arg); - } - else if (type->is_boolean_type()) - { - static tree print_bool_fndecl; - pfndecl = &print_bool_fndecl; - fnname = "__go_print_bool"; - } - else if (type->points_to() != NULL - || type->channel_type() != NULL - || type->map_type() != NULL - || type->function_type() != NULL) - { - static tree print_pointer_fndecl; - pfndecl = &print_pointer_fndecl; - fnname = "__go_print_pointer"; - arg = fold_convert_loc(location, ptr_type_node, arg); - } - else if (type->interface_type() != NULL) - { - if (type->interface_type()->is_empty()) - { - static tree print_empty_interface_fndecl; - pfndecl = &print_empty_interface_fndecl; - fnname = "__go_print_empty_interface"; - } - else - { - static tree print_interface_fndecl; - pfndecl = &print_interface_fndecl; - fnname = "__go_print_interface"; - } - } - else if (type->is_open_array_type()) - { - static tree print_slice_fndecl; - pfndecl = &print_slice_fndecl; - fnname = "__go_print_slice"; - } - else - gcc_unreachable(); - - tree call = Gogo::call_builtin(pfndecl, - location, - fnname, - 1, - void_type_node, - TREE_TYPE(arg), - arg); - append_to_statement_list(call, &stmt_list); - } - } - - if (is_ln) - { - static tree print_nl_fndecl; - tree call = Gogo::call_builtin(&print_nl_fndecl, - location, - "__go_print_nl", - 0, - void_type_node); - append_to_statement_list(call, &stmt_list); - } - - return stmt_list; - } - - case BUILTIN_PANIC: - { - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 1); - Expression* arg = args->front(); - tree arg_tree = arg->get_tree(context); - if (arg_tree == error_mark_node) - return error_mark_node; - Type *empty = Type::make_interface_type(NULL, BUILTINS_LOCATION); - arg_tree = Expression::convert_for_assignment(context, empty, - arg->type(), - arg_tree, location); - static tree panic_fndecl; - tree call = Gogo::call_builtin(&panic_fndecl, - location, - "__go_panic", - 1, - void_type_node, - TREE_TYPE(arg_tree), - arg_tree); - // This function will throw an exception. - TREE_NOTHROW(panic_fndecl) = 0; - // This function will not return. - TREE_THIS_VOLATILE(panic_fndecl) = 1; - return call; - } - - case BUILTIN_RECOVER: - { - // The argument is set when building recover thunks. It's a - // boolean value which is true if we can recover a value now. - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 1); - Expression* arg = args->front(); - tree arg_tree = arg->get_tree(context); - if (arg_tree == error_mark_node) - return error_mark_node; - - Type *empty = Type::make_interface_type(NULL, BUILTINS_LOCATION); - tree empty_tree = empty->get_tree(context->gogo()); - - Type* nil_type = Type::make_nil_type(); - Expression* nil = Expression::make_nil(location); - tree nil_tree = nil->get_tree(context); - tree empty_nil_tree = Expression::convert_for_assignment(context, - empty, - nil_type, - nil_tree, - location); - - // We need to handle a deferred call to recover specially, - // because it changes whether it can recover a panic or not. - // See test7 in test/recover1.go. - tree call; - if (this->is_deferred()) - { - static tree deferred_recover_fndecl; - call = Gogo::call_builtin(&deferred_recover_fndecl, - location, - "__go_deferred_recover", - 0, - empty_tree); - } - else - { - static tree recover_fndecl; - call = Gogo::call_builtin(&recover_fndecl, - location, - "__go_recover", - 0, - empty_tree); - } - return fold_build3_loc(location, COND_EXPR, empty_tree, arg_tree, - call, empty_nil_tree); - } - - case BUILTIN_CLOSE: - case BUILTIN_CLOSED: - { - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 1); - Expression* arg = args->front(); - tree arg_tree = arg->get_tree(context); - if (arg_tree == error_mark_node) - return error_mark_node; - if (this->code_ == BUILTIN_CLOSE) - { - static tree close_fndecl; - return Gogo::call_builtin(&close_fndecl, - location, - "__go_builtin_close", - 1, - void_type_node, - TREE_TYPE(arg_tree), - arg_tree); - } - else - { - static tree closed_fndecl; - return Gogo::call_builtin(&closed_fndecl, - location, - "__go_builtin_closed", - 1, - boolean_type_node, - TREE_TYPE(arg_tree), - arg_tree); - } - } - - case BUILTIN_SIZEOF: - case BUILTIN_OFFSETOF: - case BUILTIN_ALIGNOF: - { - mpz_t val; - mpz_init(val); - Type* dummy; - bool b = this->integer_constant_value(true, val, &dummy); - gcc_assert(b); - tree type = Type::lookup_integer_type("int")->get_tree(gogo); - tree ret = Expression::integer_constant_tree(val, type); - mpz_clear(val); - return ret; - } - - case BUILTIN_COPY: - { - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 2); - Expression* arg1 = args->front(); - Expression* arg2 = args->back(); - - tree arg1_tree = arg1->get_tree(context); - tree arg2_tree = arg2->get_tree(context); - if (arg1_tree == error_mark_node || arg2_tree == error_mark_node) - return error_mark_node; - - Type* arg1_type = arg1->type(); - Array_type* at = arg1_type->array_type(); - arg1_tree = save_expr(arg1_tree); - tree arg1_val = at->value_pointer_tree(gogo, arg1_tree); - tree arg1_len = at->length_tree(gogo, arg1_tree); - - Type* arg2_type = arg2->type(); - tree arg2_val; - tree arg2_len; - if (arg2_type->is_open_array_type()) - { - at = arg2_type->array_type(); - arg2_tree = save_expr(arg2_tree); - arg2_val = at->value_pointer_tree(gogo, arg2_tree); - arg2_len = at->length_tree(gogo, arg2_tree); - } - else - { - arg2_tree = save_expr(arg2_tree); - arg2_val = String_type::bytes_tree(gogo, arg2_tree); - arg2_len = String_type::length_tree(gogo, arg2_tree); - } - - arg1_len = save_expr(arg1_len); - arg2_len = save_expr(arg2_len); - tree len = fold_build3_loc(location, COND_EXPR, TREE_TYPE(arg1_len), - fold_build2_loc(location, LT_EXPR, - boolean_type_node, - arg1_len, arg2_len), - arg1_len, arg2_len); - len = save_expr(len); - - Type* element_type = at->element_type(); - tree element_type_tree = element_type->get_tree(gogo); - tree element_size = TYPE_SIZE_UNIT(element_type_tree); - tree bytecount = fold_convert_loc(location, TREE_TYPE(element_size), - len); - bytecount = fold_build2_loc(location, MULT_EXPR, - TREE_TYPE(element_size), - bytecount, element_size); - bytecount = fold_convert_loc(location, size_type_node, bytecount); - - tree call = build_call_expr_loc(location, - built_in_decls[BUILT_IN_MEMMOVE], - 3, arg1_val, arg2_val, bytecount); - - return fold_build2_loc(location, COMPOUND_EXPR, TREE_TYPE(len), - call, len); - } - - case BUILTIN_APPEND: - { - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 2); - Expression* arg1 = args->front(); - Expression* arg2 = args->back(); - - tree arg1_tree = arg1->get_tree(context); - tree arg2_tree = arg2->get_tree(context); - if (arg1_tree == error_mark_node || arg2_tree == error_mark_node) - return error_mark_node; - - tree descriptor_tree = arg1->type()->type_descriptor_pointer(gogo); - - // We rebuild the decl each time since the slice types may - // change. - tree append_fndecl = NULL_TREE; - return Gogo::call_builtin(&append_fndecl, - location, - "__go_append", - 3, - TREE_TYPE(arg1_tree), - TREE_TYPE(descriptor_tree), - descriptor_tree, - TREE_TYPE(arg1_tree), - arg1_tree, - TREE_TYPE(arg2_tree), - arg2_tree); - } - - case BUILTIN_REAL: - case BUILTIN_IMAG: - { - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 1); - Expression* arg = args->front(); - tree arg_tree = arg->get_tree(context); - if (arg_tree == error_mark_node) - return error_mark_node; - gcc_assert(COMPLEX_FLOAT_TYPE_P(TREE_TYPE(arg_tree))); - if (this->code_ == BUILTIN_REAL) - return fold_build1_loc(location, REALPART_EXPR, - TREE_TYPE(TREE_TYPE(arg_tree)), - arg_tree); - else - return fold_build1_loc(location, IMAGPART_EXPR, - TREE_TYPE(TREE_TYPE(arg_tree)), - arg_tree); - } - - case BUILTIN_CMPLX: - { - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 2); - tree r = args->front()->get_tree(context); - tree i = args->back()->get_tree(context); - if (r == error_mark_node || i == error_mark_node) - return error_mark_node; - gcc_assert(TYPE_MAIN_VARIANT(TREE_TYPE(r)) - == TYPE_MAIN_VARIANT(TREE_TYPE(i))); - gcc_assert(SCALAR_FLOAT_TYPE_P(TREE_TYPE(r))); - return fold_build2_loc(location, COMPLEX_EXPR, - build_complex_type(TREE_TYPE(r)), - r, i); - } - - default: - gcc_unreachable(); - } -} - -// We have to support exporting a builtin call expression, because -// code can set a constant to the result of a builtin expression. - -void -Builtin_call_expression::do_export(Export* exp) const -{ - bool ok = false; - - mpz_t val; - mpz_init(val); - Type* dummy; - if (this->integer_constant_value(true, val, &dummy)) - { - Integer_expression::export_integer(exp, val); - ok = true; - } - mpz_clear(val); - - if (!ok) - { - mpfr_t fval; - mpfr_init(fval); - if (this->float_constant_value(fval, &dummy)) - { - Float_expression::export_float(exp, fval); - ok = true; - } - mpfr_clear(fval); - } - - if (!ok) - { - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - if (this->complex_constant_value(real, imag, &dummy)) - { - Complex_expression::export_complex(exp, real, imag); - ok = true; - } - mpfr_clear(real); - mpfr_clear(imag); - } - - if (!ok) - { - error_at(this->location(), "value is not constant"); - return; - } - - // A trailing space lets us reliably identify the end of the number. - exp->write_c_string(" "); -} - -// Class Call_expression. - -// Traversal. - -int -Call_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->args_ != NULL) - { - if (this->args_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lower a call statement. - -Expression* -Call_expression::do_lower(Gogo* gogo, Named_object* function, int) -{ - // A type case can look like a function call. - if (this->fn_->is_type_expression() - && this->args_ != NULL - && this->args_->size() == 1) - return Expression::make_cast(this->fn_->type(), this->args_->front(), - this->location()); - - // Recognize a call to a builtin function. - Func_expression* fne = this->fn_->func_expression(); - if (fne != NULL - && fne->named_object()->is_function_declaration() - && fne->named_object()->func_declaration_value()->type()->is_builtin()) - return new Builtin_call_expression(gogo, this->fn_, this->args_, - this->is_varargs_, this->location()); - - // Handle an argument which is a call to a function which returns - // multiple results. - if (this->args_ != NULL - && this->args_->size() == 1 - && this->args_->front()->call_expression() != NULL - && this->fn_->type()->function_type() != NULL) - { - Function_type* fntype = this->fn_->type()->function_type(); - size_t rc = this->args_->front()->call_expression()->result_count(); - if (rc > 1 - && fntype->parameters() != NULL - && (fntype->parameters()->size() == rc - || (fntype->is_varargs() - && fntype->parameters()->size() - 1 <= rc))) - { - Call_expression* call = this->args_->front()->call_expression(); - Expression_list* args = new Expression_list; - for (size_t i = 0; i < rc; ++i) - args->push_back(Expression::make_call_result(call, i)); - // We can't return a new call expression here, because this - // one may be referenced by Call_result expressions. FIXME. - delete this->args_; - this->args_ = args; - } - } - - // Handle a call to a varargs function by packaging up the extra - // parameters. - if (this->fn_->type()->function_type() != NULL - && this->fn_->type()->function_type()->is_varargs()) - { - Function_type* fntype = this->fn_->type()->function_type(); - const Typed_identifier_list* parameters = fntype->parameters(); - gcc_assert(parameters != NULL && !parameters->empty()); - Type* varargs_type = parameters->back().type(); - return this->lower_varargs(gogo, function, varargs_type, - parameters->size()); - } - - return this; -} - -// Lower a call to a varargs function. FUNCTION is the function in -// which the call occurs--it's not the function we are calling. -// VARARGS_TYPE is the type of the varargs parameter, a slice type. -// PARAM_COUNT is the number of parameters of the function we are -// calling; the last of these parameters will be the varargs -// parameter. - -Expression* -Call_expression::lower_varargs(Gogo* gogo, Named_object* function, - Type* varargs_type, size_t param_count) -{ - if (this->varargs_are_lowered_) - return this; - - source_location loc = this->location(); - - gcc_assert(param_count > 0); - gcc_assert(varargs_type->is_open_array_type()); - - size_t arg_count = this->args_ == NULL ? 0 : this->args_->size(); - if (arg_count < param_count - 1) - { - // Not enough arguments; will be caught in check_types. - return this; - } - - Expression_list* old_args = this->args_; - Expression_list* new_args = new Expression_list(); - bool push_empty_arg = false; - if (old_args == NULL || old_args->empty()) - { - gcc_assert(param_count == 1); - push_empty_arg = true; - } - else - { - Expression_list::const_iterator pa; - int i = 1; - for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i) - { - if (static_cast(i) == param_count) - break; - new_args->push_back(*pa); - } - - // We have reached the varargs parameter. - - bool issued_error = false; - if (pa == old_args->end()) - push_empty_arg = true; - else if (pa + 1 == old_args->end() && this->is_varargs_) - new_args->push_back(*pa); - else if (this->is_varargs_) - { - this->report_error(_("too many arguments")); - return this; - } - else if (pa + 1 == old_args->end() - && this->is_compatible_varargs_argument(function, *pa, - varargs_type, - &issued_error)) - new_args->push_back(*pa); - else - { - Type* element_type = varargs_type->array_type()->element_type(); - Expression_list* vals = new Expression_list; - for (; pa != old_args->end(); ++pa, ++i) - { - // Check types here so that we get a better message. - Type* patype = (*pa)->type(); - source_location paloc = (*pa)->location(); - if (!this->check_argument_type(i, element_type, patype, - paloc, issued_error)) - continue; - vals->push_back(*pa); - } - Expression* val = - Expression::make_slice_composite_literal(varargs_type, vals, loc); - new_args->push_back(val); - } - } - - if (push_empty_arg) - new_args->push_back(Expression::make_nil(loc)); - - // We can't return a new call expression here, because this one may - // be referenced by Call_result expressions. FIXME. - if (old_args != NULL) - delete old_args; - this->args_ = new_args; - this->varargs_are_lowered_ = true; - - // Lower all the new subexpressions. - Expression* ret = this; - gogo->lower_expression(function, &ret); - gcc_assert(ret == this); - return ret; -} - -// Return true if ARG is a varargs argment which should be passed to -// the varargs parameter of type PARAM_TYPE without wrapping. ARG -// will be the last argument passed in the call, and PARAM_TYPE will -// be the type of the last parameter of the varargs function being -// called. - -bool -Call_expression::is_compatible_varargs_argument(Named_object* function, - Expression* arg, - Type* param_type, - bool* issued_error) -{ - *issued_error = false; - - Type* var_type = NULL; - - // The simple case is passing the varargs parameter of the caller. - Var_expression* ve = arg->var_expression(); - if (ve != NULL && ve->named_object()->is_variable()) - { - Variable* var = ve->named_object()->var_value(); - if (var->is_varargs_parameter()) - var_type = var->type(); - } - - // The complex case is passing the varargs parameter of some - // enclosing function. This will look like passing down *c.f where - // c is the closure variable and f is a field in the closure. - if (function != NULL - && function->func_value()->needs_closure() - && arg->classification() == EXPRESSION_UNARY) - { - Unary_expression* ue = static_cast(arg); - if (ue->op() == OPERATOR_MULT) - { - Field_reference_expression* fre = - ue->operand()->deref()->field_reference_expression(); - if (fre != NULL) - { - Var_expression* ve = fre->expr()->deref()->var_expression(); - if (ve != NULL) - { - Named_object* no = ve->named_object(); - Function* f = function->func_value(); - if (no == f->closure_var()) - { - // At this point we know that this indeed a - // reference to some enclosing variable. Now we - // need to figure out whether that variable is a - // varargs parameter. - Named_object* enclosing = - f->enclosing_var(fre->field_index()); - Variable* var = enclosing->var_value(); - if (var->is_varargs_parameter()) - var_type = var->type(); - } - } - } - } - } - - if (var_type == NULL) - return false; - - // We only match if the parameter is the same, with an identical - // type. - Array_type* var_at = var_type->array_type(); - gcc_assert(var_at != NULL); - Array_type* param_at = param_type->array_type(); - if (param_at != NULL - && Type::are_identical(var_at->element_type(), - param_at->element_type(), NULL)) - return true; - error_at(arg->location(), "... mismatch: passing ...T as ..."); - *issued_error = true; - return false; -} - -// Get the function type. Returns NULL if we don't know the type. If -// this returns NULL, and if_ERROR is true, issues an error. - -Function_type* -Call_expression::get_function_type() const -{ - return this->fn_->type()->function_type(); -} - -// Return the number of values which this call will return. - -size_t -Call_expression::result_count() const -{ - const Function_type* fntype = this->get_function_type(); - if (fntype == NULL) - return 0; - if (fntype->results() == NULL) - return 0; - return fntype->results()->size(); -} - -// Return whether this is a call to the predeclared function recover. - -bool -Call_expression::is_recover_call() const -{ - return this->do_is_recover_call(); -} - -// Set the argument to the recover function. - -void -Call_expression::set_recover_arg(Expression* arg) -{ - this->do_set_recover_arg(arg); -} - -// Virtual functions also implemented by Builtin_call_expression. - -bool -Call_expression::do_is_recover_call() const -{ - return false; -} - -void -Call_expression::do_set_recover_arg(Expression*) -{ - gcc_unreachable(); -} - -// Get the type. - -Type* -Call_expression::do_type() -{ - if (this->type_ != NULL) - return this->type_; - - Type* ret; - Function_type* fntype = this->get_function_type(); - if (fntype == NULL) - return Type::make_error_type(); - - const Typed_identifier_list* results = fntype->results(); - if (results == NULL) - ret = Type::make_void_type(); - else if (results->size() == 1) - ret = results->begin()->type(); - else - ret = Type::make_call_multiple_result_type(this); - - this->type_ = ret; - - return this->type_; -} - -// Determine types for a call expression. We can use the function -// parameter types to set the types of the arguments. - -void -Call_expression::do_determine_type(const Type_context*) -{ - this->fn_->determine_type_no_context(); - Function_type* fntype = this->get_function_type(); - const Typed_identifier_list* parameters = NULL; - if (fntype != NULL) - parameters = fntype->parameters(); - if (this->args_ != NULL) - { - Typed_identifier_list::const_iterator pt; - if (parameters != NULL) - pt = parameters->begin(); - for (Expression_list::const_iterator pa = this->args_->begin(); - pa != this->args_->end(); - ++pa) - { - if (parameters != NULL && pt != parameters->end()) - { - Type_context subcontext(pt->type(), false); - (*pa)->determine_type(&subcontext); - ++pt; - } - else - (*pa)->determine_type_no_context(); - } - } -} - -// Check types for parameter I. - -bool -Call_expression::check_argument_type(int i, const Type* parameter_type, - const Type* argument_type, - source_location argument_location, - bool issued_error) -{ - std::string reason; - if (!Type::are_assignable(parameter_type, argument_type, &reason)) - { - if (!issued_error) - { - if (reason.empty()) - error_at(argument_location, "argument %d has incompatible type", i); - else - error_at(argument_location, - "argument %d has incompatible type (%s)", - i, reason.c_str()); - } - this->set_is_error(); - return false; - } - return true; -} - -// Check types. - -void -Call_expression::do_check_types(Gogo*) -{ - Function_type* fntype = this->get_function_type(); - if (fntype == NULL) - { - if (!this->fn_->type()->is_error_type()) - this->report_error(_("expected function")); - return; - } - - if (fntype->is_method()) - { - // We don't support pointers to methods, so the function has to - // be a bound method expression. - Bound_method_expression* bme = this->fn_->bound_method_expression(); - if (bme == NULL) - { - this->report_error(_("method call without object")); - return; - } - Type* first_arg_type = bme->first_argument()->type(); - if (first_arg_type->points_to() == NULL) - { - // When passing a value, we need to check that we are - // permitted to copy it. - std::string reason; - if (!Type::are_assignable(fntype->receiver()->type(), - first_arg_type, &reason)) - { - if (reason.empty()) - this->report_error(_("incompatible type for receiver")); - else - { - error_at(this->location(), - "incompatible type for receiver (%s)", - reason.c_str()); - this->set_is_error(); - } - } - } - } - - // Note that varargs was handled by the lower_varargs() method, so - // we don't have to worry about it here. - - const Typed_identifier_list* parameters = fntype->parameters(); - if (this->args_ == NULL) - { - if (parameters != NULL && !parameters->empty()) - this->report_error(_("not enough arguments")); - } - else if (parameters == NULL) - this->report_error(_("too many arguments")); - else - { - int i = 0; - Typed_identifier_list::const_iterator pt = parameters->begin(); - for (Expression_list::const_iterator pa = this->args_->begin(); - pa != this->args_->end(); - ++pa, ++pt, ++i) - { - if (pt == parameters->end()) - { - this->report_error(_("too many arguments")); - return; - } - this->check_argument_type(i + 1, pt->type(), (*pa)->type(), - (*pa)->location(), false); - } - if (pt != parameters->end()) - this->report_error(_("not enough arguments")); - } -} - -// Return whether we have to use a temporary variable to ensure that -// we evaluate this call expression in order. If the call returns no -// results then it will inevitably be executed last. If the call -// returns more than one result then it will be used with Call_result -// expressions. So we only have to use a temporary variable if the -// call returns exactly one result. - -bool -Call_expression::do_must_eval_in_order() const -{ - return this->result_count() == 1; -} - -// Get the function and the first argument to use when calling a bound -// method. - -tree -Call_expression::bound_method_function(Translate_context* context, - Bound_method_expression* bound_method, - tree* first_arg_ptr) -{ - Expression* first_argument = bound_method->first_argument(); - tree first_arg = first_argument->get_tree(context); - if (first_arg == error_mark_node) - return error_mark_node; - - // We always pass a pointer to the first argument when calling a - // method. - if (first_argument->type()->points_to() == NULL) - { - tree pointer_to_arg_type = build_pointer_type(TREE_TYPE(first_arg)); - if (TREE_ADDRESSABLE(TREE_TYPE(first_arg)) - || DECL_P(first_arg) - || TREE_CODE(first_arg) == INDIRECT_REF - || TREE_CODE(first_arg) == COMPONENT_REF) - { - first_arg = build_fold_addr_expr(first_arg); - if (DECL_P(first_arg)) - TREE_ADDRESSABLE(first_arg) = 1; - } - else - { - tree tmp = create_tmp_var(TREE_TYPE(first_arg), - get_name(first_arg)); - DECL_IGNORED_P(tmp) = 0; - DECL_INITIAL(tmp) = first_arg; - first_arg = build2(COMPOUND_EXPR, pointer_to_arg_type, - build1(DECL_EXPR, void_type_node, tmp), - build_fold_addr_expr(tmp)); - TREE_ADDRESSABLE(tmp) = 1; - } - if (first_arg == error_mark_node) - return error_mark_node; - } - - Type* fatype = bound_method->first_argument_type(); - if (fatype != NULL) - { - if (fatype->points_to() == NULL) - fatype = Type::make_pointer_type(fatype); - first_arg = fold_convert(fatype->get_tree(context->gogo()), first_arg); - if (first_arg == error_mark_node - || TREE_TYPE(first_arg) == error_mark_node) - return error_mark_node; - } - - *first_arg_ptr = first_arg; - - return bound_method->method()->get_tree(context); -} - -// Get the function and the first argument to use when calling an -// interface method. - -tree -Call_expression::interface_method_function( - Translate_context* context, - Interface_field_reference_expression* interface_method, - tree* first_arg_ptr) -{ - tree expr = interface_method->expr()->get_tree(context); - if (expr == error_mark_node) - return error_mark_node; - expr = save_expr(expr); - tree first_arg = interface_method->get_underlying_object_tree(context, expr); - if (first_arg == error_mark_node) - return error_mark_node; - *first_arg_ptr = first_arg; - return interface_method->get_function_tree(context, expr); -} - -// Build the call expression. - -tree -Call_expression::do_get_tree(Translate_context* context) -{ - if (this->tree_ != NULL_TREE) - return this->tree_; - - Function_type* fntype = this->get_function_type(); - if (fntype == NULL) - return error_mark_node; - - if (this->fn_->is_error_expression()) - return error_mark_node; - - Gogo* gogo = context->gogo(); - source_location location = this->location(); - - Func_expression* func = this->fn_->func_expression(); - Bound_method_expression* bound_method = this->fn_->bound_method_expression(); - Interface_field_reference_expression* interface_method = - this->fn_->interface_field_reference_expression(); - const bool has_closure = func != NULL && func->closure() != NULL; - const bool is_method = bound_method != NULL || interface_method != NULL; - gcc_assert(!fntype->is_method() || is_method); - - int nargs; - tree* args; - if (this->args_ == NULL || this->args_->empty()) - { - nargs = is_method ? 1 : 0; - args = nargs == 0 ? NULL : new tree[nargs]; - } - else - { - const Typed_identifier_list* params = fntype->parameters(); - gcc_assert(params != NULL); - - nargs = this->args_->size(); - int i = is_method ? 1 : 0; - nargs += i; - args = new tree[nargs]; - - Typed_identifier_list::const_iterator pp = params->begin(); - Expression_list::const_iterator pe; - for (pe = this->args_->begin(); - pe != this->args_->end(); - ++pe, ++pp, ++i) - { - tree arg_val = (*pe)->get_tree(context); - args[i] = Expression::convert_for_assignment(context, - pp->type(), - (*pe)->type(), - arg_val, - location); - if (args[i] == error_mark_node) - return error_mark_node; - } - gcc_assert(pp == params->end()); - gcc_assert(i == nargs); - } - - tree rettype = TREE_TYPE(TREE_TYPE(fntype->get_tree(gogo))); - if (rettype == error_mark_node) - return error_mark_node; - - tree fn; - if (has_closure) - fn = func->get_tree_without_closure(gogo); - else if (!is_method) - fn = this->fn_->get_tree(context); - else if (bound_method != NULL) - fn = this->bound_method_function(context, bound_method, &args[0]); - else if (interface_method != NULL) - fn = this->interface_method_function(context, interface_method, &args[0]); - else - gcc_unreachable(); - - if (fn == error_mark_node || TREE_TYPE(fn) == error_mark_node) - return error_mark_node; - - // This is to support builtin math functions when using 80387 math. - tree fndecl = fn; - if (TREE_CODE(fndecl) == ADDR_EXPR) - fndecl = TREE_OPERAND(fndecl, 0); - tree excess_type = NULL_TREE; - if (DECL_P(fndecl) - && DECL_IS_BUILTIN(fndecl) - && DECL_BUILT_IN_CLASS(fndecl) == BUILT_IN_NORMAL - && nargs > 0 - && ((SCALAR_FLOAT_TYPE_P(rettype) - && SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[0]))) - || (COMPLEX_FLOAT_TYPE_P(rettype) - && COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[0]))))) - { - excess_type = excess_precision_type(TREE_TYPE(args[0])); - if (excess_type != NULL_TREE) - { - tree excess_fndecl = mathfn_built_in(excess_type, - DECL_FUNCTION_CODE(fndecl)); - if (excess_fndecl == NULL_TREE) - excess_type = NULL_TREE; - else - { - fn = build_fold_addr_expr_loc(location, excess_fndecl); - for (int i = 0; i < nargs; ++i) - args[i] = ::convert(excess_type, args[i]); - } - } - } - - tree ret = build_call_array(excess_type != NULL_TREE ? excess_type : rettype, - fn, nargs, args); - delete[] args; - - SET_EXPR_LOCATION(ret, location); - - if (has_closure) - { - tree closure_tree = func->closure()->get_tree(context); - if (closure_tree != error_mark_node) - CALL_EXPR_STATIC_CHAIN(ret) = closure_tree; - } - - // If this is a recursive function type which returns itself, as in - // type F func() F - // we have used ptr_type_node for the return type. Add a cast here - // to the correct type. - if (TREE_TYPE(ret) == ptr_type_node) - { - tree t = this->type()->get_tree(gogo); - ret = fold_convert_loc(location, t, ret); - } - - if (excess_type != NULL_TREE) - { - // Calling convert here can undo our excess precision change. - // That may or may not be a bug in convert_to_real. - ret = build1(NOP_EXPR, rettype, ret); - } - - // If there is more than one result, we will refer to the call - // multiple times. - if (fntype->results() != NULL && fntype->results()->size() > 1) - ret = save_expr(ret); - - this->tree_ = ret; - - return ret; -} - -// Make a call expression. - -Call_expression* -Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs, - source_location location) -{ - return new Call_expression(fn, args, is_varargs, location); -} - -// A single result from a call which returns multiple results. - -class Call_result_expression : public Expression -{ - public: - Call_result_expression(Call_expression* call, unsigned int index) - : Expression(EXPRESSION_CALL_RESULT, call->location()), - call_(call), index_(index) - { } - - protected: - int - do_traverse(Traverse*); - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Call_result_expression(this->call_->call_expression(), - this->index_); - } - - bool - do_must_eval_in_order() const - { return true; } - - tree - do_get_tree(Translate_context*); - - private: - // The underlying call expression. - Expression* call_; - // Which result we want. - unsigned int index_; -}; - -// Traverse a call result. - -int -Call_result_expression::do_traverse(Traverse* traverse) -{ - if (traverse->remember_expression(this->call_)) - { - // We have already traversed the call expression. - return TRAVERSE_CONTINUE; - } - return Expression::traverse(&this->call_, traverse); -} - -// Get the type. - -Type* -Call_result_expression::do_type() -{ - // THIS->CALL_ can be replaced with a temporary reference due to - // Call_expression::do_must_eval_in_order when there is an error. - Call_expression* ce = this->call_->call_expression(); - if (ce == NULL) - return Type::make_error_type(); - Function_type* fntype = ce->get_function_type(); - if (fntype == NULL) - return Type::make_error_type(); - const Typed_identifier_list* results = fntype->results(); - Typed_identifier_list::const_iterator pr = results->begin(); - for (unsigned int i = 0; i < this->index_; ++i) - { - if (pr == results->end()) - return Type::make_error_type(); - ++pr; - } - if (pr == results->end()) - return Type::make_error_type(); - return pr->type(); -} - -// Check the type. This is where we give an error if we're trying to -// extract too many values from a call. - -void -Call_result_expression::do_check_types(Gogo*) -{ - bool ok = true; - Call_expression* ce = this->call_->call_expression(); - if (ce != NULL) - ok = this->index_ < ce->result_count(); - else - { - // This can happen when the call returns a single value but we - // are asking for the second result. - if (this->call_->is_error_expression()) - return; - ok = false; - } - if (!ok) - error_at(this->location(), - "number of results does not match number of values"); -} - -// Determine the type. We have nothing to do here, but the 0 result -// needs to pass down to the caller. - -void -Call_result_expression::do_determine_type(const Type_context*) -{ - if (this->index_ == 0) - this->call_->determine_type_no_context(); -} - -// Return the tree. - -tree -Call_result_expression::do_get_tree(Translate_context* context) -{ - tree call_tree = this->call_->get_tree(context); - if (call_tree == error_mark_node) - return error_mark_node; - gcc_assert(TREE_CODE(TREE_TYPE(call_tree)) == RECORD_TYPE); - tree field = TYPE_FIELDS(TREE_TYPE(call_tree)); - for (unsigned int i = 0; i < this->index_; ++i) - { - gcc_assert(field != NULL_TREE); - field = DECL_CHAIN(field); - } - gcc_assert(field != NULL_TREE); - return build3(COMPONENT_REF, TREE_TYPE(field), call_tree, field, NULL_TREE); -} - -// Make a reference to a single result of a call which returns -// multiple results. - -Expression* -Expression::make_call_result(Call_expression* call, unsigned int index) -{ - return new Call_result_expression(call, index); -} - -// Class Index_expression. - -// Traversal. - -int -Index_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT - || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT - || (this->end_ != NULL - && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Lower an index expression. This converts the generic index -// expression into an array index, a string index, or a map index. - -Expression* -Index_expression::do_lower(Gogo*, Named_object*, int) -{ - source_location location = this->location(); - Expression* left = this->left_; - Expression* start = this->start_; - Expression* end = this->end_; - - Type* type = left->type(); - if (type->is_error_type()) - return Expression::make_error(location); - else if (type->array_type() != NULL) - return Expression::make_array_index(left, start, end, location); - else if (type->points_to() != NULL - && type->points_to()->array_type() != NULL - && !type->points_to()->is_open_array_type()) - { - Expression* deref = Expression::make_unary(OPERATOR_MULT, left, - location); - return Expression::make_array_index(deref, start, end, location); - } - else if (type->is_string_type()) - return Expression::make_string_index(left, start, end, location); - else if (type->map_type() != NULL) - { - if (end != NULL) - { - error_at(location, "invalid slice of map"); - return Expression::make_error(location); - } - Map_index_expression* ret= Expression::make_map_index(left, start, - location); - if (this->is_lvalue_) - ret->set_is_lvalue(); - return ret; - } - else - { - error_at(location, - "attempt to index object which is not array, string, or map"); - return Expression::make_error(location); - } -} - -// Make an index expression. - -Expression* -Expression::make_index(Expression* left, Expression* start, Expression* end, - source_location location) -{ - return new Index_expression(left, start, end, location); -} - -// An array index. This is used for both indexing and slicing. - -class Array_index_expression : public Expression -{ - public: - Array_index_expression(Expression* array, Expression* start, - Expression* end, source_location location) - : Expression(EXPRESSION_ARRAY_INDEX, location), - array_(array), start_(start), end_(end), type_(NULL) - { } - - protected: - int - do_traverse(Traverse*); - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return Expression::make_array_index(this->array_->copy(), - this->start_->copy(), - (this->end_ == NULL - ? NULL - : this->end_->copy()), - this->location()); - } - - bool - do_is_addressable() const; - - void - do_address_taken(bool escapes) - { this->array_->address_taken(escapes); } - - tree - do_get_tree(Translate_context*); - - private: - // The array we are getting a value from. - Expression* array_; - // The start or only index. - Expression* start_; - // The end index of a slice. This may be NULL for a simple array - // index, or it may be a nil expression for the length of the array. - Expression* end_; - // The type of the expression. - Type* type_; -}; - -// Array index traversal. - -int -Array_index_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->end_ != NULL) - { - if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Return the type of an array index. - -Type* -Array_index_expression::do_type() -{ - if (this->type_ == NULL) - { - Array_type* type = this->array_->type()->array_type(); - if (type == NULL) - this->type_ = Type::make_error_type(); - else if (this->end_ == NULL) - this->type_ = type->element_type(); - else if (type->is_open_array_type()) - { - // A slice of a slice has the same type as the original - // slice. - this->type_ = this->array_->type()->deref(); - } - else - { - // A slice of an array is a slice. - this->type_ = Type::make_array_type(type->element_type(), NULL); - } - } - return this->type_; -} - -// Set the type of an array index. - -void -Array_index_expression::do_determine_type(const Type_context*) -{ - this->array_->determine_type_no_context(); - Type_context subcontext(NULL, true); - this->start_->determine_type(&subcontext); - if (this->end_ != NULL) - this->end_->determine_type(&subcontext); -} - -// Check types of an array index. - -void -Array_index_expression::do_check_types(Gogo*) -{ - if (this->start_->type()->integer_type() == NULL) - this->report_error(_("index must be integer")); - if (this->end_ != NULL - && this->end_->type()->integer_type() == NULL - && !this->end_->is_nil_expression()) - this->report_error(_("slice end must be integer")); - - Array_type* array_type = this->array_->type()->array_type(); - gcc_assert(array_type != NULL); - - unsigned int int_bits = - Type::lookup_integer_type("int")->integer_type()->bits(); - - Type* dummy; - mpz_t lval; - mpz_init(lval); - bool lval_valid = (array_type->length() != NULL - && array_type->length()->integer_constant_value(true, - lval, - &dummy)); - mpz_t ival; - mpz_init(ival); - if (this->start_->integer_constant_value(true, ival, &dummy)) - { - if (mpz_sgn(ival) < 0 - || mpz_sizeinbase(ival, 2) >= int_bits - || (lval_valid - && (this->end_ == NULL - ? mpz_cmp(ival, lval) >= 0 - : mpz_cmp(ival, lval) > 0))) - { - error_at(this->start_->location(), "array index out of bounds"); - this->set_is_error(); - } - } - if (this->end_ != NULL && !this->end_->is_nil_expression()) - { - if (this->end_->integer_constant_value(true, ival, &dummy)) - { - if (mpz_sgn(ival) < 0 - || mpz_sizeinbase(ival, 2) >= int_bits - || (lval_valid && mpz_cmp(ival, lval) > 0)) - { - error_at(this->end_->location(), "array index out of bounds"); - this->set_is_error(); - } - } - } - mpz_clear(ival); - mpz_clear(lval); - - // A slice of an array requires an addressable array. A slice of a - // slice is always possible. - if (this->end_ != NULL - && !array_type->is_open_array_type() - && !this->array_->is_addressable()) - this->report_error(_("array is not addressable")); -} - -// Return whether this expression is addressable. - -bool -Array_index_expression::do_is_addressable() const -{ - // A slice expression is not addressable. - if (this->end_ != NULL) - return false; - - // An index into a slice is addressable. - if (this->array_->type()->is_open_array_type()) - return true; - - // An index into an array is addressable if the array is - // addressable. - return this->array_->is_addressable(); -} - -// Get a tree for an array index. - -tree -Array_index_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - source_location loc = this->location(); - - Array_type* array_type = this->array_->type()->array_type(); - gcc_assert(array_type != NULL); - - tree type_tree = array_type->get_tree(gogo); - - tree array_tree = this->array_->get_tree(context); - if (array_tree == error_mark_node) - return error_mark_node; - - if (array_type->length() == NULL && !DECL_P(array_tree)) - array_tree = save_expr(array_tree); - tree length_tree = array_type->length_tree(gogo, array_tree); - length_tree = save_expr(length_tree); - tree length_type = TREE_TYPE(length_tree); - - tree bad_index = boolean_false_node; - - tree start_tree = this->start_->get_tree(context); - if (start_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(start_tree)) - start_tree = save_expr(start_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree))) - start_tree = convert_to_integer(length_type, start_tree); - - bad_index = Expression::check_bounds(start_tree, length_type, bad_index, - loc); - - start_tree = fold_convert_loc(loc, length_type, start_tree); - bad_index = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, bad_index, - fold_build2_loc(loc, - (this->end_ == NULL - ? GE_EXPR - : GT_EXPR), - boolean_type_node, start_tree, - length_tree)); - - int code = (array_type->length() != NULL - ? (this->end_ == NULL - ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS - : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS) - : (this->end_ == NULL - ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS - : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS)); - tree crash = Gogo::runtime_error(code, loc); - - if (this->end_ == NULL) - { - // Simple array indexing. This has to return an l-value, so - // wrap the index check into START_TREE. - start_tree = build2(COMPOUND_EXPR, TREE_TYPE(start_tree), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - start_tree); - start_tree = fold_convert_loc(loc, sizetype, start_tree); - - if (array_type->length() != NULL) - { - // Fixed array. - return build4(ARRAY_REF, TREE_TYPE(type_tree), array_tree, - start_tree, NULL_TREE, NULL_TREE); - } - else - { - // Open array. - tree values = array_type->value_pointer_tree(gogo, array_tree); - tree element_type_tree = array_type->element_type()->get_tree(gogo); - tree element_size = TYPE_SIZE_UNIT(element_type_tree); - tree offset = fold_build2_loc(loc, MULT_EXPR, sizetype, - start_tree, element_size); - tree ptr = fold_build2_loc(loc, POINTER_PLUS_EXPR, - TREE_TYPE(values), values, offset); - return build_fold_indirect_ref(ptr); - } - } - - // Array slice. - - tree capacity_tree = array_type->capacity_tree(gogo, array_tree); - capacity_tree = fold_convert_loc(loc, length_type, capacity_tree); - - tree end_tree; - if (this->end_->is_nil_expression()) - end_tree = length_tree; - else - { - end_tree = this->end_->get_tree(context); - if (end_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(end_tree)) - end_tree = save_expr(end_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree))) - end_tree = convert_to_integer(length_type, end_tree); - - bad_index = Expression::check_bounds(end_tree, length_type, bad_index, - loc); - - end_tree = fold_convert_loc(loc, length_type, end_tree); - - capacity_tree = save_expr(capacity_tree); - tree bad_end = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - fold_build2_loc(loc, LT_EXPR, - boolean_type_node, - end_tree, start_tree), - fold_build2_loc(loc, GT_EXPR, - boolean_type_node, - end_tree, capacity_tree)); - bad_index = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - bad_index, bad_end); - } - - tree element_type_tree = array_type->element_type()->get_tree(gogo); - tree element_size = TYPE_SIZE_UNIT(element_type_tree); - - tree offset = fold_build2_loc(loc, MULT_EXPR, sizetype, - fold_convert_loc(loc, sizetype, start_tree), - element_size); - - tree value_pointer = array_type->value_pointer_tree(gogo, array_tree); - - value_pointer = fold_build2_loc(loc, POINTER_PLUS_EXPR, - TREE_TYPE(value_pointer), - value_pointer, offset); - - tree result_length_tree = fold_build2_loc(loc, MINUS_EXPR, length_type, - end_tree, start_tree); - - tree result_capacity_tree = fold_build2_loc(loc, MINUS_EXPR, length_type, - capacity_tree, start_tree); - - tree struct_tree = this->type()->get_tree(gogo); - gcc_assert(TREE_CODE(struct_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(struct_tree); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0); - elt->index = field; - elt->value = value_pointer; - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0); - elt->index = field; - elt->value = fold_convert_loc(loc, TREE_TYPE(field), result_length_tree); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0); - elt->index = field; - elt->value = fold_convert_loc(loc, TREE_TYPE(field), result_capacity_tree); - - tree constructor = build_constructor(struct_tree, init); - - if (TREE_CONSTANT(value_pointer) - && TREE_CONSTANT(result_length_tree) - && TREE_CONSTANT(result_capacity_tree)) - TREE_CONSTANT(constructor) = 1; - - return fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(constructor), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - constructor); -} - -// Make an array index expression. END may be NULL. - -Expression* -Expression::make_array_index(Expression* array, Expression* start, - Expression* end, source_location location) -{ - // Taking a slice of a composite literal requires moving the literal - // onto the heap. - if (end != NULL && array->is_composite_literal()) - { - array = Expression::make_heap_composite(array, location); - array = Expression::make_unary(OPERATOR_MULT, array, location); - } - return new Array_index_expression(array, start, end, location); -} - -// A string index. This is used for both indexing and slicing. - -class String_index_expression : public Expression -{ - public: - String_index_expression(Expression* string, Expression* start, - Expression* end, source_location location) - : Expression(EXPRESSION_STRING_INDEX, location), - string_(string), start_(start), end_(end) - { } - - protected: - int - do_traverse(Traverse*); - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return Expression::make_string_index(this->string_->copy(), - this->start_->copy(), - (this->end_ == NULL - ? NULL - : this->end_->copy()), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - private: - // The string we are getting a value from. - Expression* string_; - // The start or only index. - Expression* start_; - // The end index of a slice. This may be NULL for a single index, - // or it may be a nil expression for the length of the string. - Expression* end_; -}; - -// String index traversal. - -int -String_index_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->end_ != NULL) - { - if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Return the type of a string index. - -Type* -String_index_expression::do_type() -{ - if (this->end_ == NULL) - return Type::lookup_integer_type("uint8"); - else - return Type::make_string_type(); -} - -// Determine the type of a string index. - -void -String_index_expression::do_determine_type(const Type_context*) -{ - this->string_->determine_type_no_context(); - Type_context subcontext(NULL, true); - this->start_->determine_type(&subcontext); - if (this->end_ != NULL) - this->end_->determine_type(&subcontext); -} - -// Check types of a string index. - -void -String_index_expression::do_check_types(Gogo*) -{ - if (this->start_->type()->integer_type() == NULL) - this->report_error(_("index must be integer")); - if (this->end_ != NULL - && this->end_->type()->integer_type() == NULL - && !this->end_->is_nil_expression()) - this->report_error(_("slice end must be integer")); - - std::string sval; - bool sval_valid = this->string_->string_constant_value(&sval); - - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (this->start_->integer_constant_value(true, ival, &dummy)) - { - if (mpz_sgn(ival) < 0 - || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0)) - { - error_at(this->start_->location(), "string index out of bounds"); - this->set_is_error(); - } - } - if (this->end_ != NULL && !this->end_->is_nil_expression()) - { - if (this->end_->integer_constant_value(true, ival, &dummy)) - { - if (mpz_sgn(ival) < 0 - || (sval_valid && mpz_cmp_ui(ival, sval.length()) > 0)) - { - error_at(this->end_->location(), "string index out of bounds"); - this->set_is_error(); - } - } - } - mpz_clear(ival); -} - -// Get a tree for a string index. - -tree -String_index_expression::do_get_tree(Translate_context* context) -{ - source_location loc = this->location(); - - tree string_tree = this->string_->get_tree(context); - if (string_tree == error_mark_node) - return error_mark_node; - - if (this->string_->type()->points_to() != NULL) - string_tree = build_fold_indirect_ref(string_tree); - if (!DECL_P(string_tree)) - string_tree = save_expr(string_tree); - tree string_type = TREE_TYPE(string_tree); - - tree length_tree = String_type::length_tree(context->gogo(), string_tree); - length_tree = save_expr(length_tree); - tree length_type = TREE_TYPE(length_tree); - - tree bad_index = boolean_false_node; - - tree start_tree = this->start_->get_tree(context); - if (start_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(start_tree)) - start_tree = save_expr(start_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree))) - start_tree = convert_to_integer(length_type, start_tree); - - bad_index = Expression::check_bounds(start_tree, length_type, bad_index, - loc); - - start_tree = fold_convert_loc(loc, length_type, start_tree); - - int code = (this->end_ == NULL - ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS - : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS); - tree crash = Gogo::runtime_error(code, loc); - - if (this->end_ == NULL) - { - bad_index = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - bad_index, - fold_build2_loc(loc, GE_EXPR, - boolean_type_node, - start_tree, length_tree)); - - tree bytes_tree = String_type::bytes_tree(context->gogo(), string_tree); - tree ptr = fold_build2_loc(loc, POINTER_PLUS_EXPR, TREE_TYPE(bytes_tree), - bytes_tree, - fold_convert_loc(loc, sizetype, start_tree)); - tree index = build_fold_indirect_ref_loc(loc, ptr); - - return build2(COMPOUND_EXPR, TREE_TYPE(index), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - index); - } - else - { - tree end_tree; - if (this->end_->is_nil_expression()) - end_tree = build_int_cst(length_type, -1); - else - { - end_tree = this->end_->get_tree(context); - if (end_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(end_tree)) - end_tree = save_expr(end_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree))) - end_tree = convert_to_integer(length_type, end_tree); - - bad_index = Expression::check_bounds(end_tree, length_type, - bad_index, loc); - - end_tree = fold_convert_loc(loc, length_type, end_tree); - } - - static tree strslice_fndecl; - tree ret = Gogo::call_builtin(&strslice_fndecl, - loc, - "__go_string_slice", - 3, - string_type, - string_type, - string_tree, - length_type, - start_tree, - length_type, - end_tree); - // This will panic if the bounds are out of range for the - // string. - TREE_NOTHROW(strslice_fndecl) = 0; - - if (bad_index == boolean_false_node) - return ret; - else - return build2(COMPOUND_EXPR, TREE_TYPE(ret), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - ret); - } -} - -// Make a string index expression. END may be NULL. - -Expression* -Expression::make_string_index(Expression* string, Expression* start, - Expression* end, source_location location) -{ - return new String_index_expression(string, start, end, location); -} - -// Class Map_index. - -// Get the type of the map. - -Map_type* -Map_index_expression::get_map_type() const -{ - Map_type* mt = this->map_->type()->deref()->map_type(); - gcc_assert(mt != NULL); - return mt; -} - -// Map index traversal. - -int -Map_index_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return Expression::traverse(&this->index_, traverse); -} - -// Return the type of a map index. - -Type* -Map_index_expression::do_type() -{ - Type* type = this->get_map_type()->val_type(); - // If this map index is in a tuple assignment, we actually return a - // pointer to the value type. Tuple_map_assignment_statement is - // responsible for handling this correctly. We need to get the type - // right in case this gets assigned to a temporary variable. - if (this->is_in_tuple_assignment_) - type = Type::make_pointer_type(type); - return type; -} - -// Fix the type of a map index. - -void -Map_index_expression::do_determine_type(const Type_context*) -{ - this->map_->determine_type_no_context(); - Type_context subcontext(this->get_map_type()->key_type(), false); - this->index_->determine_type(&subcontext); -} - -// Check types of a map index. - -void -Map_index_expression::do_check_types(Gogo*) -{ - std::string reason; - if (!Type::are_assignable(this->get_map_type()->key_type(), - this->index_->type(), &reason)) - { - if (reason.empty()) - this->report_error(_("incompatible type for map index")); - else - { - error_at(this->location(), "incompatible type for map index (%s)", - reason.c_str()); - this->set_is_error(); - } - } -} - -// Get a tree for a map index. - -tree -Map_index_expression::do_get_tree(Translate_context* context) -{ - Map_type* type = this->get_map_type(); - - tree valptr = this->get_value_pointer(context, this->is_lvalue_); - if (valptr == error_mark_node) - return error_mark_node; - valptr = save_expr(valptr); - - tree val_type_tree = TREE_TYPE(TREE_TYPE(valptr)); - - if (this->is_lvalue_) - return build_fold_indirect_ref(valptr); - else if (this->is_in_tuple_assignment_) - { - // Tuple_map_assignment_statement is responsible for using this - // appropriately. - return valptr; - } - else - { - return fold_build3(COND_EXPR, val_type_tree, - fold_build2(EQ_EXPR, boolean_type_node, valptr, - fold_convert(TREE_TYPE(valptr), - null_pointer_node)), - type->val_type()->get_init_tree(context->gogo(), - false), - build_fold_indirect_ref(valptr)); - } -} - -// Get a tree for the map index. This returns a tree which evaluates -// to a pointer to a value. The pointer will be NULL if the key is -// not in the map. - -tree -Map_index_expression::get_value_pointer(Translate_context* context, - bool insert) -{ - Map_type* type = this->get_map_type(); - - tree map_tree = this->map_->get_tree(context); - tree index_tree = this->index_->get_tree(context); - index_tree = Expression::convert_for_assignment(context, type->key_type(), - this->index_->type(), - index_tree, - this->location()); - if (map_tree == error_mark_node || index_tree == error_mark_node) - return error_mark_node; - - if (this->map_->type()->points_to() != NULL) - map_tree = build_fold_indirect_ref(map_tree); - - // We need to pass in a pointer to the key, so stuff it into a - // variable. - tree tmp = create_tmp_var(TREE_TYPE(index_tree), get_name(index_tree)); - DECL_IGNORED_P(tmp) = 0; - DECL_INITIAL(tmp) = index_tree; - tree make_tmp = build1(DECL_EXPR, void_type_node, tmp); - tree tmpref = fold_convert(const_ptr_type_node, build_fold_addr_expr(tmp)); - TREE_ADDRESSABLE(tmp) = 1; - - static tree map_index_fndecl; - tree call = Gogo::call_builtin(&map_index_fndecl, - this->location(), - "__go_map_index", - 3, - const_ptr_type_node, - TREE_TYPE(map_tree), - map_tree, - const_ptr_type_node, - tmpref, - boolean_type_node, - (insert - ? boolean_true_node - : boolean_false_node)); - // This can panic on a map of interface type if the interface holds - // an uncomparable or unhashable type. - TREE_NOTHROW(map_index_fndecl) = 0; - - tree val_type_tree = type->val_type()->get_tree(context->gogo()); - if (val_type_tree == error_mark_node) - return error_mark_node; - tree ptr_val_type_tree = build_pointer_type(val_type_tree); - - return build2(COMPOUND_EXPR, ptr_val_type_tree, - make_tmp, - fold_convert(ptr_val_type_tree, call)); -} - -// Make a map index expression. - -Map_index_expression* -Expression::make_map_index(Expression* map, Expression* index, - source_location location) -{ - return new Map_index_expression(map, index, location); -} - -// Class Field_reference_expression. - -// Return the type of a field reference. - -Type* -Field_reference_expression::do_type() -{ - Struct_type* struct_type = this->expr_->type()->struct_type(); - gcc_assert(struct_type != NULL); - return struct_type->field(this->field_index_)->type(); -} - -// Check the types for a field reference. - -void -Field_reference_expression::do_check_types(Gogo*) -{ - Struct_type* struct_type = this->expr_->type()->struct_type(); - gcc_assert(struct_type != NULL); - gcc_assert(struct_type->field(this->field_index_) != NULL); -} - -// Get a tree for a field reference. - -tree -Field_reference_expression::do_get_tree(Translate_context* context) -{ - tree struct_tree = this->expr_->get_tree(context); - if (struct_tree == error_mark_node - || TREE_TYPE(struct_tree) == error_mark_node) - return error_mark_node; - gcc_assert(TREE_CODE(TREE_TYPE(struct_tree)) == RECORD_TYPE); - tree field = TYPE_FIELDS(TREE_TYPE(struct_tree)); - gcc_assert(field != NULL_TREE); - for (unsigned int i = this->field_index_; i > 0; --i) - { - field = DECL_CHAIN(field); - gcc_assert(field != NULL_TREE); - } - return build3(COMPONENT_REF, TREE_TYPE(field), struct_tree, field, - NULL_TREE); -} - -// Make a reference to a qualified identifier in an expression. - -Field_reference_expression* -Expression::make_field_reference(Expression* expr, unsigned int field_index, - source_location location) -{ - return new Field_reference_expression(expr, field_index, location); -} - -// Class Interface_field_reference_expression. - -// Return a tree for the pointer to the function to call. - -tree -Interface_field_reference_expression::get_function_tree(Translate_context*, - tree expr) -{ - if (this->expr_->type()->points_to() != NULL) - expr = build_fold_indirect_ref(expr); - - tree expr_type = TREE_TYPE(expr); - gcc_assert(TREE_CODE(expr_type) == RECORD_TYPE); - - tree field = TYPE_FIELDS(expr_type); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0); - - tree table = build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE); - gcc_assert(POINTER_TYPE_P(TREE_TYPE(table))); - - table = build_fold_indirect_ref(table); - gcc_assert(TREE_CODE(TREE_TYPE(table)) == RECORD_TYPE); - - std::string name = Gogo::unpack_hidden_name(this->name_); - for (field = DECL_CHAIN(TYPE_FIELDS(TREE_TYPE(table))); - field != NULL_TREE; - field = DECL_CHAIN(field)) - { - if (name == IDENTIFIER_POINTER(DECL_NAME(field))) - break; - } - gcc_assert(field != NULL_TREE); - - return build3(COMPONENT_REF, TREE_TYPE(field), table, field, NULL_TREE); -} - -// Return a tree for the first argument to pass to the interface -// function. - -tree -Interface_field_reference_expression::get_underlying_object_tree( - Translate_context*, - tree expr) -{ - if (this->expr_->type()->points_to() != NULL) - expr = build_fold_indirect_ref(expr); - - tree expr_type = TREE_TYPE(expr); - gcc_assert(TREE_CODE(expr_type) == RECORD_TYPE); - - tree field = DECL_CHAIN(TYPE_FIELDS(expr_type)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0); - - return build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE); -} - -// Traversal. - -int -Interface_field_reference_expression::do_traverse(Traverse* traverse) -{ - return Expression::traverse(&this->expr_, traverse); -} - -// Return the type of an interface field reference. - -Type* -Interface_field_reference_expression::do_type() -{ - Type* expr_type = this->expr_->type(); - - Type* points_to = expr_type->points_to(); - if (points_to != NULL) - expr_type = points_to; - - Interface_type* interface_type = expr_type->interface_type(); - if (interface_type == NULL) - return Type::make_error_type(); - - const Typed_identifier* method = interface_type->find_method(this->name_); - if (method == NULL) - return Type::make_error_type(); - - return method->type(); -} - -// Determine types. - -void -Interface_field_reference_expression::do_determine_type(const Type_context*) -{ - this->expr_->determine_type_no_context(); -} - -// Check the types for an interface field reference. - -void -Interface_field_reference_expression::do_check_types(Gogo*) -{ - Type* type = this->expr_->type(); - - Type* points_to = type->points_to(); - if (points_to != NULL) - type = points_to; - - Interface_type* interface_type = type->interface_type(); - if (interface_type == NULL) - this->report_error(_("expected interface or pointer to interface")); - else - { - const Typed_identifier* method = - interface_type->find_method(this->name_); - if (method == NULL) - { - error_at(this->location(), "method %qs not in interface", - Gogo::message_name(this->name_).c_str()); - this->set_is_error(); - } - } -} - -// Get a tree for a reference to a field in an interface. There is no -// standard tree type representation for this: it's a function -// attached to its first argument, like a Bound_method_expression. -// The only places it may currently be used are in a Call_expression -// or a Go_statement, which will take it apart directly. So this has -// nothing to do at present. - -tree -Interface_field_reference_expression::do_get_tree(Translate_context*) -{ - gcc_unreachable(); -} - -// Make a reference to a field in an interface. - -Expression* -Expression::make_interface_field_reference(Expression* expr, - const std::string& field, - source_location location) -{ - return new Interface_field_reference_expression(expr, field, location); -} - -// A general selector. This is a Parser_expression for LEFT.NAME. It -// is lowered after we know the type of the left hand side. - -class Selector_expression : public Parser_expression -{ - public: - Selector_expression(Expression* left, const std::string& name, - source_location location) - : Parser_expression(EXPRESSION_SELECTOR, location), - left_(left), name_(name) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return Expression::traverse(&this->left_, traverse); } - - Expression* - do_lower(Gogo*, Named_object*, int); - - Expression* - do_copy() - { - return new Selector_expression(this->left_->copy(), this->name_, - this->location()); - } - - private: - Expression* - lower_method_expression(Gogo*); - - // The expression on the left hand side. - Expression* left_; - // The name on the right hand side. - std::string name_; -}; - -// Lower a selector expression once we know the real type of the left -// hand side. - -Expression* -Selector_expression::do_lower(Gogo* gogo, Named_object*, int) -{ - Expression* left = this->left_; - if (left->is_type_expression()) - return this->lower_method_expression(gogo); - return Type::bind_field_or_method(gogo, left->type(), left, this->name_, - this->location()); -} - -// Lower a method expression T.M or (*T).M. We turn this into a -// function literal. - -Expression* -Selector_expression::lower_method_expression(Gogo* gogo) -{ - source_location location = this->location(); - Type* type = this->left_->type(); - const std::string& name(this->name_); - - bool is_pointer; - if (type->points_to() == NULL) - is_pointer = false; - else - { - is_pointer = true; - type = type->points_to(); - } - Named_type* nt = type->named_type(); - if (nt == NULL) - { - error_at(location, - ("method expression requires named type or " - "pointer to named type")); - return Expression::make_error(location); - } - - bool is_ambiguous; - Method* method = nt->method_function(name, &is_ambiguous); - if (method == NULL) - { - if (!is_ambiguous) - error_at(location, "type %<%s%> has no method %<%s%>", - nt->message_name().c_str(), - Gogo::message_name(name).c_str()); - else - error_at(location, "method %<%s%> is ambiguous in type %<%s%>", - Gogo::message_name(name).c_str(), - nt->message_name().c_str()); - return Expression::make_error(location); - } - - if (!is_pointer && !method->is_value_method()) - { - error_at(location, "method requires pointer (use %<(*%s).%s)%>", - nt->message_name().c_str(), - Gogo::message_name(name).c_str()); - return Expression::make_error(location); - } - - // Build a new function type in which the receiver becomes the first - // argument. - Function_type* method_type = method->type(); - gcc_assert(method_type->is_method()); - - const char* const receiver_name = "$this"; - Typed_identifier_list* parameters = new Typed_identifier_list(); - parameters->push_back(Typed_identifier(receiver_name, this->left_->type(), - location)); - - const Typed_identifier_list* method_parameters = method_type->parameters(); - if (method_parameters != NULL) - { - for (Typed_identifier_list::const_iterator p = method_parameters->begin(); - p != method_parameters->end(); - ++p) - parameters->push_back(*p); - } - - const Typed_identifier_list* method_results = method_type->results(); - Typed_identifier_list* results; - if (method_results == NULL) - results = NULL; - else - { - results = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator p = method_results->begin(); - p != method_results->end(); - ++p) - results->push_back(*p); - } - - Function_type* fntype = Type::make_function_type(NULL, parameters, results, - location); - if (method_type->is_varargs()) - fntype->set_is_varargs(); - - // We generate methods which always takes a pointer to the receiver - // as their first argument. If this is for a pointer type, we can - // simply reuse the existing function. We use an internal hack to - // get the right type. - - if (is_pointer) - { - Named_object* mno = (method->needs_stub_method() - ? method->stub_object() - : method->named_object()); - Expression* f = Expression::make_func_reference(mno, NULL, location); - f = Expression::make_cast(fntype, f, location); - Type_conversion_expression* tce = - static_cast(f); - tce->set_may_convert_function_types(); - return f; - } - - Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false, - location); - - Named_object* vno = gogo->lookup(receiver_name, NULL); - gcc_assert(vno != NULL); - Expression* ve = Expression::make_var_reference(vno, location); - Expression* bm = Type::bind_field_or_method(gogo, nt, ve, name, location); - gcc_assert(bm != NULL && !bm->is_error_expression()); - - Expression_list* args; - if (method_parameters == NULL) - args = NULL; - else - { - args = new Expression_list(); - for (Typed_identifier_list::const_iterator p = method_parameters->begin(); - p != method_parameters->end(); - ++p) - { - vno = gogo->lookup(p->name(), NULL); - gcc_assert(vno != NULL); - args->push_back(Expression::make_var_reference(vno, location)); - } - } - - Call_expression* call = Expression::make_call(bm, args, - method_type->is_varargs(), - location); - - size_t count = call->result_count(); - Statement* s; - if (count == 0) - s = Statement::make_statement(call); - else - { - Expression_list* retvals = new Expression_list(); - if (count <= 1) - retvals->push_back(call); - else - { - for (size_t i = 0; i < count; ++i) - retvals->push_back(Expression::make_call_result(call, i)); - } - s = Statement::make_return_statement(no->func_value()->type()->results(), - retvals, location); - } - gogo->add_statement(s); - - gogo->finish_function(location); - - return Expression::make_func_reference(no, NULL, location); -} - -// Make a selector expression. - -Expression* -Expression::make_selector(Expression* left, const std::string& name, - source_location location) -{ - return new Selector_expression(left, name, location); -} - -// Implement the builtin function new. - -class Allocation_expression : public Expression -{ - public: - Allocation_expression(Type* type, source_location location) - : Expression(EXPRESSION_ALLOCATION, location), - type_(type) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return Type::traverse(this->type_, traverse); } - - Type* - do_type() - { return Type::make_pointer_type(this->type_); } - - void - do_determine_type(const Type_context*) - { } - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { return new Allocation_expression(this->type_, this->location()); } - - tree - do_get_tree(Translate_context*); - - private: - // The type we are allocating. - Type* type_; -}; - -// Check the type of an allocation expression. - -void -Allocation_expression::do_check_types(Gogo*) -{ - if (this->type_->function_type() != NULL) - this->report_error(_("invalid new of function type")); -} - -// Return a tree for an allocation expression. - -tree -Allocation_expression::do_get_tree(Translate_context* context) -{ - tree type_tree = this->type_->get_tree(context->gogo()); - tree size_tree = TYPE_SIZE_UNIT(type_tree); - tree space = context->gogo()->allocate_memory(this->type_, size_tree, - this->location()); - return fold_convert(build_pointer_type(type_tree), space); -} - -// Make an allocation expression. - -Expression* -Expression::make_allocation(Type* type, source_location location) -{ - return new Allocation_expression(type, location); -} - -// Implement the builtin function make. - -class Make_expression : public Expression -{ - public: - Make_expression(Type* type, Expression_list* args, source_location location) - : Expression(EXPRESSION_MAKE, location), - type_(type), args_(args) - { } - - protected: - int - do_traverse(Traverse* traverse); - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Make_expression(this->type_, this->args_->copy(), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - private: - // The type we are making. - Type* type_; - // The arguments to pass to the make routine. - Expression_list* args_; -}; - -// Traversal. - -int -Make_expression::do_traverse(Traverse* traverse) -{ - if (this->args_ != NULL - && this->args_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Set types of arguments. - -void -Make_expression::do_determine_type(const Type_context*) -{ - if (this->args_ != NULL) - { - Type_context context(Type::lookup_integer_type("int"), false); - for (Expression_list::const_iterator pe = this->args_->begin(); - pe != this->args_->end(); - ++pe) - (*pe)->determine_type(&context); - } -} - -// Check types for a make expression. - -void -Make_expression::do_check_types(Gogo*) -{ - if (this->type_->channel_type() == NULL - && this->type_->map_type() == NULL - && (this->type_->array_type() == NULL - || this->type_->array_type()->length() != NULL)) - this->report_error(_("invalid type for make function")); - else if (!this->type_->check_make_expression(this->args_, this->location())) - this->set_is_error(); -} - -// Return a tree for a make expression. - -tree -Make_expression::do_get_tree(Translate_context* context) -{ - return this->type_->make_expression_tree(context, this->args_, - this->location()); -} - -// Make a make expression. - -Expression* -Expression::make_make(Type* type, Expression_list* args, - source_location location) -{ - return new Make_expression(type, args, location); -} - -// Construct a struct. - -class Struct_construction_expression : public Expression -{ - public: - Struct_construction_expression(Type* type, Expression_list* vals, - source_location location) - : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location), - type_(type), vals_(vals) - { } - - // Return whether this is a constant initializer. - bool - is_constant_struct() const; - - protected: - int - do_traverse(Traverse* traverse); - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Struct_construction_expression(this->type_, this->vals_->copy(), - this->location()); - } - - bool - do_is_addressable() const - { return true; } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The type of the struct to construct. - Type* type_; - // The list of values, in order of the fields in the struct. A NULL - // entry means that the field should be zero-initialized. - Expression_list* vals_; -}; - -// Traversal. - -int -Struct_construction_expression::do_traverse(Traverse* traverse) -{ - if (this->vals_ != NULL - && this->vals_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Return whether this is a constant initializer. - -bool -Struct_construction_expression::is_constant_struct() const -{ - if (this->vals_ == NULL) - return true; - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - if (*pv != NULL - && !(*pv)->is_constant() - && (!(*pv)->is_composite_literal() - || (*pv)->is_nonconstant_composite_literal())) - return false; - } - - const Struct_field_list* fields = this->type_->struct_type()->fields(); - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - // There are no constant constructors for interfaces. - if (pf->type()->interface_type() != NULL) - return false; - } - - return true; -} - -// Final type determination. - -void -Struct_construction_expression::do_determine_type(const Type_context*) -{ - if (this->vals_ == NULL) - return; - const Struct_field_list* fields = this->type_->struct_type()->fields(); - Expression_list::const_iterator pv = this->vals_->begin(); - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++pv) - { - if (pv == this->vals_->end()) - return; - if (*pv != NULL) - { - Type_context subcontext(pf->type(), false); - (*pv)->determine_type(&subcontext); - } - } -} - -// Check types. - -void -Struct_construction_expression::do_check_types(Gogo*) -{ - if (this->vals_ == NULL) - return; - - Struct_type* st = this->type_->struct_type(); - if (this->vals_->size() > st->field_count()) - { - this->report_error(_("too many expressions for struct")); - return; - } - - const Struct_field_list* fields = st->fields(); - Expression_list::const_iterator pv = this->vals_->begin(); - int i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++pv, ++i) - { - if (pv == this->vals_->end()) - { - this->report_error(_("too few expressions for struct")); - break; - } - - if (*pv == NULL) - continue; - - std::string reason; - if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason)) - { - if (reason.empty()) - error_at((*pv)->location(), - "incompatible type for field %d in struct construction", - i + 1); - else - error_at((*pv)->location(), - ("incompatible type for field %d in " - "struct construction (%s)"), - i + 1, reason.c_str()); - this->set_is_error(); - } - } - gcc_assert(pv == this->vals_->end()); -} - -// Return a tree for constructing a struct. - -tree -Struct_construction_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - - if (this->vals_ == NULL) - return this->type_->get_init_tree(gogo, false); - - tree type_tree = this->type_->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - gcc_assert(TREE_CODE(type_tree) == RECORD_TYPE); - - bool is_constant = true; - const Struct_field_list* fields = this->type_->struct_type()->fields(); - VEC(constructor_elt,gc)* elts = VEC_alloc(constructor_elt, gc, - fields->size()); - Struct_field_list::const_iterator pf = fields->begin(); - Expression_list::const_iterator pv = this->vals_->begin(); - for (tree field = TYPE_FIELDS(type_tree); - field != NULL_TREE; - field = DECL_CHAIN(field), ++pf) - { - gcc_assert(pf != fields->end()); - - tree val; - if (pv == this->vals_->end()) - val = pf->type()->get_init_tree(gogo, false); - else if (*pv == NULL) - { - val = pf->type()->get_init_tree(gogo, false); - ++pv; - } - else - { - val = Expression::convert_for_assignment(context, pf->type(), - (*pv)->type(), - (*pv)->get_tree(context), - this->location()); - ++pv; - } - - if (val == error_mark_node || TREE_TYPE(val) == error_mark_node) - return error_mark_node; - - constructor_elt* elt = VEC_quick_push(constructor_elt, elts, NULL); - elt->index = field; - elt->value = val; - if (!TREE_CONSTANT(val)) - is_constant = false; - } - gcc_assert(pf == fields->end()); - - tree ret = build_constructor(type_tree, elts); - if (is_constant) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Export a struct construction. - -void -Struct_construction_expression::do_export(Export* exp) const -{ - exp->write_c_string("convert("); - exp->write_type(this->type_); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - exp->write_c_string(", "); - if (*pv != NULL) - (*pv)->export_expression(exp); - } - exp->write_c_string(")"); -} - -// Make a struct composite literal. This used by the thunk code. - -Expression* -Expression::make_struct_composite_literal(Type* type, Expression_list* vals, - source_location location) -{ - gcc_assert(type->struct_type() != NULL); - return new Struct_construction_expression(type, vals, location); -} - -// Construct an array. This class is not used directly; instead we -// use the child classes, Fixed_array_construction_expression and -// Open_array_construction_expression. - -class Array_construction_expression : public Expression -{ - protected: - Array_construction_expression(Expression_classification classification, - Type* type, Expression_list* vals, - source_location location) - : Expression(classification, location), - type_(type), vals_(vals) - { } - - public: - // Return whether this is a constant initializer. - bool - is_constant_array() const; - - // Return the number of elements. - size_t - element_count() const - { return this->vals_ == NULL ? 0 : this->vals_->size(); } - -protected: - int - do_traverse(Traverse* traverse); - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - bool - do_is_addressable() const - { return true; } - - void - do_export(Export*) const; - - // The list of values. - Expression_list* - vals() - { return this->vals_; } - - // Get a constructor tree for the array values. - tree - get_constructor_tree(Translate_context* context, tree type_tree); - - private: - // The type of the array to construct. - Type* type_; - // The list of values. - Expression_list* vals_; -}; - -// Traversal. - -int -Array_construction_expression::do_traverse(Traverse* traverse) -{ - if (this->vals_ != NULL - && this->vals_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Return whether this is a constant initializer. - -bool -Array_construction_expression::is_constant_array() const -{ - if (this->vals_ == NULL) - return true; - - // There are no constant constructors for interfaces. - if (this->type_->array_type()->element_type()->interface_type() != NULL) - return false; - - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - if (*pv != NULL - && !(*pv)->is_constant() - && (!(*pv)->is_composite_literal() - || (*pv)->is_nonconstant_composite_literal())) - return false; - } - return true; -} - -// Final type determination. - -void -Array_construction_expression::do_determine_type(const Type_context*) -{ - if (this->vals_ == NULL) - return; - Type_context subcontext(this->type_->array_type()->element_type(), false); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - if (*pv != NULL) - (*pv)->determine_type(&subcontext); - } -} - -// Check types. - -void -Array_construction_expression::do_check_types(Gogo*) -{ - if (this->vals_ == NULL) - return; - - Array_type* at = this->type_->array_type(); - int i = 0; - Type* element_type = at->element_type(); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv, ++i) - { - if (*pv != NULL - && !Type::are_assignable(element_type, (*pv)->type(), NULL)) - { - error_at((*pv)->location(), - "incompatible type for element %d in composite literal", - i + 1); - this->set_is_error(); - } - } - - Expression* length = at->length(); - if (length != NULL) - { - mpz_t val; - mpz_init(val); - Type* type; - if (at->length()->integer_constant_value(true, val, &type)) - { - if (this->vals_->size() > mpz_get_ui(val)) - this->report_error(_("too many elements in composite literal")); - } - mpz_clear(val); - } -} - -// Get a constructor tree for the array values. - -tree -Array_construction_expression::get_constructor_tree(Translate_context* context, - tree type_tree) -{ - VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc, - (this->vals_ == NULL - ? 0 - : this->vals_->size())); - Type* element_type = this->type_->array_type()->element_type(); - bool is_constant = true; - if (this->vals_ != NULL) - { - size_t i = 0; - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv, ++i) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, values, NULL); - elt->index = size_int(i); - if (*pv == NULL) - elt->value = element_type->get_init_tree(context->gogo(), false); - else - { - tree value_tree = (*pv)->get_tree(context); - elt->value = Expression::convert_for_assignment(context, - element_type, - (*pv)->type(), - value_tree, - this->location()); - } - if (elt->value == error_mark_node) - return error_mark_node; - if (!TREE_CONSTANT(elt->value)) - is_constant = false; - } - } - - tree ret = build_constructor(type_tree, values); - if (is_constant) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Export an array construction. - -void -Array_construction_expression::do_export(Export* exp) const -{ - exp->write_c_string("convert("); - exp->write_type(this->type_); - if (this->vals_ != NULL) - { - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - exp->write_c_string(", "); - if (*pv != NULL) - (*pv)->export_expression(exp); - } - } - exp->write_c_string(")"); -} - -// Construct a fixed array. - -class Fixed_array_construction_expression : - public Array_construction_expression -{ - public: - Fixed_array_construction_expression(Type* type, Expression_list* vals, - source_location location) - : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION, - type, vals, location) - { - gcc_assert(type->array_type() != NULL - && type->array_type()->length() != NULL); - } - - protected: - Expression* - do_copy() - { - return new Fixed_array_construction_expression(this->type(), - (this->vals() == NULL - ? NULL - : this->vals()->copy()), - this->location()); - } - - tree - do_get_tree(Translate_context*); -}; - -// Return a tree for constructing a fixed array. - -tree -Fixed_array_construction_expression::do_get_tree(Translate_context* context) -{ - return this->get_constructor_tree(context, - this->type()->get_tree(context->gogo())); -} - -// Construct an open array. - -class Open_array_construction_expression : public Array_construction_expression -{ - public: - Open_array_construction_expression(Type* type, Expression_list* vals, - source_location location) - : Array_construction_expression(EXPRESSION_OPEN_ARRAY_CONSTRUCTION, - type, vals, location) - { - gcc_assert(type->array_type() != NULL - && type->array_type()->length() == NULL); - } - - protected: - // Note that taking the address of an open array literal is invalid. - - Expression* - do_copy() - { - return new Open_array_construction_expression(this->type(), - (this->vals() == NULL - ? NULL - : this->vals()->copy()), - this->location()); - } - - tree - do_get_tree(Translate_context*); -}; - -// Return a tree for constructing an open array. - -tree -Open_array_construction_expression::do_get_tree(Translate_context* context) -{ - Type* element_type = this->type()->array_type()->element_type(); - tree element_type_tree = element_type->get_tree(context->gogo()); - tree values; - tree length_tree; - if (this->vals() == NULL || this->vals()->empty()) - { - // We need to create a unique value. - tree max = size_int(0); - tree constructor_type = build_array_type(element_type_tree, - build_index_type(max)); - if (constructor_type == error_mark_node) - return error_mark_node; - VEC(constructor_elt,gc)* vec = VEC_alloc(constructor_elt, gc, 1); - constructor_elt* elt = VEC_quick_push(constructor_elt, vec, NULL); - elt->index = size_int(0); - elt->value = element_type->get_init_tree(context->gogo(), false); - values = build_constructor(constructor_type, vec); - if (TREE_CONSTANT(elt->value)) - TREE_CONSTANT(values) = 1; - length_tree = size_int(0); - } - else - { - tree max = size_int(this->vals()->size() - 1); - tree constructor_type = build_array_type(element_type_tree, - build_index_type(max)); - if (constructor_type == error_mark_node) - return error_mark_node; - values = this->get_constructor_tree(context, constructor_type); - length_tree = size_int(this->vals()->size()); - } - - if (values == error_mark_node) - return error_mark_node; - - bool is_constant_initializer = TREE_CONSTANT(values); - bool is_in_function = context->function() != NULL; - - if (is_constant_initializer) - { - tree tmp = build_decl(this->location(), VAR_DECL, - create_tmp_var_name("C"), TREE_TYPE(values)); - DECL_EXTERNAL(tmp) = 0; - TREE_PUBLIC(tmp) = 0; - TREE_STATIC(tmp) = 1; - DECL_ARTIFICIAL(tmp) = 1; - if (is_in_function) - { - // If this is not a function, we will only initialize the - // value once, so we can use this directly rather than - // copying it. In that case we can't make it read-only, - // because the program is permitted to change it. - TREE_READONLY(tmp) = 1; - TREE_CONSTANT(tmp) = 1; - } - DECL_INITIAL(tmp) = values; - rest_of_decl_compilation(tmp, 1, 0); - values = tmp; - } - - tree space; - tree set; - if (!is_in_function && is_constant_initializer) - { - // Outside of a function, we know the initializer will only run - // once. - space = build_fold_addr_expr(values); - set = NULL_TREE; - } - else - { - tree memsize = TYPE_SIZE_UNIT(TREE_TYPE(values)); - space = context->gogo()->allocate_memory(element_type, memsize, - this->location()); - space = save_expr(space); - - tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space); - tree ref = build_fold_indirect_ref_loc(this->location(), s); - TREE_THIS_NOTRAP(ref) = 1; - set = build2(MODIFY_EXPR, void_type_node, ref, values); - } - - // Build a constructor for the open array. - - tree type_tree = this->type()->get_tree(context->gogo()); - gcc_assert(TREE_CODE(type_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(type_tree); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), space); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), length_tree); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), length_tree); - - tree constructor = build_constructor(type_tree, init); - if (!is_in_function && is_constant_initializer) - TREE_CONSTANT(constructor) = 1; - - if (set == NULL_TREE) - return constructor; - else - return build2(COMPOUND_EXPR, type_tree, set, constructor); -} - -// Make a slice composite literal. This is used by the type -// descriptor code. - -Expression* -Expression::make_slice_composite_literal(Type* type, Expression_list* vals, - source_location location) -{ - gcc_assert(type->is_open_array_type()); - return new Open_array_construction_expression(type, vals, location); -} - -// Construct a map. - -class Map_construction_expression : public Expression -{ - public: - Map_construction_expression(Type* type, Expression_list* vals, - source_location location) - : Expression(EXPRESSION_MAP_CONSTRUCTION, location), - type_(type), vals_(vals) - { gcc_assert(vals == NULL || vals->size() % 2 == 0); } - - protected: - int - do_traverse(Traverse* traverse); - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Map_construction_expression(this->type_, this->vals_->copy(), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The type of the map to construct. - Type* type_; - // The list of values. - Expression_list* vals_; -}; - -// Traversal. - -int -Map_construction_expression::do_traverse(Traverse* traverse) -{ - if (this->vals_ != NULL - && this->vals_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Final type determination. - -void -Map_construction_expression::do_determine_type(const Type_context*) -{ - if (this->vals_ == NULL) - return; - - Map_type* mt = this->type_->map_type(); - Type_context key_context(mt->key_type(), false); - Type_context val_context(mt->val_type(), false); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - (*pv)->determine_type(&key_context); - ++pv; - (*pv)->determine_type(&val_context); - } -} - -// Check types. - -void -Map_construction_expression::do_check_types(Gogo*) -{ - if (this->vals_ == NULL) - return; - - Map_type* mt = this->type_->map_type(); - int i = 0; - Type* key_type = mt->key_type(); - Type* val_type = mt->val_type(); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv, ++i) - { - if (!Type::are_assignable(key_type, (*pv)->type(), NULL)) - { - error_at((*pv)->location(), - "incompatible type for element %d key in map construction", - i + 1); - this->set_is_error(); - } - ++pv; - if (!Type::are_assignable(val_type, (*pv)->type(), NULL)) - { - error_at((*pv)->location(), - ("incompatible type for element %d value " - "in map construction"), - i + 1); - this->set_is_error(); - } - } -} - -// Return a tree for constructing a map. - -tree -Map_construction_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - source_location loc = this->location(); - - Map_type* mt = this->type_->map_type(); - - // Build a struct to hold the key and value. - tree struct_type = make_node(RECORD_TYPE); - - Type* key_type = mt->key_type(); - tree id = get_identifier("__key"); - tree key_field = build_decl(loc, FIELD_DECL, id, key_type->get_tree(gogo)); - DECL_CONTEXT(key_field) = struct_type; - TYPE_FIELDS(struct_type) = key_field; - - Type* val_type = mt->val_type(); - id = get_identifier("__val"); - tree val_field = build_decl(loc, FIELD_DECL, id, val_type->get_tree(gogo)); - DECL_CONTEXT(val_field) = struct_type; - DECL_CHAIN(key_field) = val_field; - - layout_type(struct_type); - - bool is_constant = true; - size_t i = 0; - tree valaddr; - tree make_tmp; - - if (this->vals_ == NULL || this->vals_->empty()) - { - valaddr = null_pointer_node; - make_tmp = NULL_TREE; - } - else - { - VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc, - this->vals_->size() / 2); - - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv, ++i) - { - bool one_is_constant = true; - - VEC(constructor_elt,gc)* one = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, one, NULL); - elt->index = key_field; - tree val_tree = (*pv)->get_tree(context); - elt->value = Expression::convert_for_assignment(context, key_type, - (*pv)->type(), - val_tree, loc); - if (elt->value == error_mark_node) - return error_mark_node; - if (!TREE_CONSTANT(elt->value)) - one_is_constant = false; - - ++pv; - - elt = VEC_quick_push(constructor_elt, one, NULL); - elt->index = val_field; - val_tree = (*pv)->get_tree(context); - elt->value = Expression::convert_for_assignment(context, val_type, - (*pv)->type(), - val_tree, loc); - if (elt->value == error_mark_node) - return error_mark_node; - if (!TREE_CONSTANT(elt->value)) - one_is_constant = false; - - elt = VEC_quick_push(constructor_elt, values, NULL); - elt->index = size_int(i); - elt->value = build_constructor(struct_type, one); - if (one_is_constant) - TREE_CONSTANT(elt->value) = 1; - else - is_constant = false; - } - - tree index_type = build_index_type(size_int(i - 1)); - tree array_type = build_array_type(struct_type, index_type); - tree init = build_constructor(array_type, values); - if (is_constant) - TREE_CONSTANT(init) = 1; - tree tmp; - if (current_function_decl != NULL) - { - tmp = create_tmp_var(array_type, get_name(array_type)); - DECL_INITIAL(tmp) = init; - make_tmp = fold_build1_loc(loc, DECL_EXPR, void_type_node, tmp); - TREE_ADDRESSABLE(tmp) = 1; - } - else - { - tmp = build_decl(loc, VAR_DECL, create_tmp_var_name("M"), array_type); - DECL_EXTERNAL(tmp) = 0; - TREE_PUBLIC(tmp) = 0; - TREE_STATIC(tmp) = 1; - DECL_ARTIFICIAL(tmp) = 1; - if (!TREE_CONSTANT(init)) - make_tmp = fold_build2_loc(loc, INIT_EXPR, void_type_node, tmp, - init); - else - { - TREE_READONLY(tmp) = 1; - TREE_CONSTANT(tmp) = 1; - DECL_INITIAL(tmp) = init; - make_tmp = NULL_TREE; - } - rest_of_decl_compilation(tmp, 1, 0); - } - - valaddr = build_fold_addr_expr(tmp); - } - - tree descriptor = gogo->map_descriptor(mt); - - tree type_tree = this->type_->get_tree(gogo); - - static tree construct_map_fndecl; - tree call = Gogo::call_builtin(&construct_map_fndecl, - loc, - "__go_construct_map", - 6, - type_tree, - TREE_TYPE(descriptor), - descriptor, - sizetype, - size_int(i), - sizetype, - TYPE_SIZE_UNIT(struct_type), - sizetype, - byte_position(val_field), - sizetype, - TYPE_SIZE_UNIT(TREE_TYPE(val_field)), - const_ptr_type_node, - fold_convert(const_ptr_type_node, valaddr)); - - tree ret; - if (make_tmp == NULL) - ret = call; - else - ret = fold_build2_loc(loc, COMPOUND_EXPR, type_tree, make_tmp, call); - return ret; -} - -// Export an array construction. - -void -Map_construction_expression::do_export(Export* exp) const -{ - exp->write_c_string("convert("); - exp->write_type(this->type_); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - exp->write_c_string(", "); - (*pv)->export_expression(exp); - } - exp->write_c_string(")"); -} - -// A general composite literal. This is lowered to a type specific -// version. - -class Composite_literal_expression : public Parser_expression -{ - public: - Composite_literal_expression(Type* type, int depth, bool has_keys, - Expression_list* vals, source_location location) - : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location), - type_(type), depth_(depth), vals_(vals), has_keys_(has_keys) - { } - - protected: - int - do_traverse(Traverse* traverse); - - Expression* - do_lower(Gogo*, Named_object*, int); - - Expression* - do_copy() - { - return new Composite_literal_expression(this->type_, this->depth_, - this->has_keys_, - (this->vals_ == NULL - ? NULL - : this->vals_->copy()), - this->location()); - } - - private: - Expression* - lower_struct(Type*); - - Expression* - lower_array(Type*); - - Expression* - make_array(Type*, Expression_list*); - - Expression* - lower_map(Type*); - - // The type of the composite literal. - Type* type_; - // The depth within a list of composite literals within a composite - // literal, when the type is omitted. - int depth_; - // The values to put in the composite literal. - Expression_list* vals_; - // If this is true, then VALS_ is a list of pairs: a key and a - // value. In an array initializer, a missing key will be NULL. - bool has_keys_; -}; - -// Traversal. - -int -Composite_literal_expression::do_traverse(Traverse* traverse) -{ - if (this->vals_ != NULL - && this->vals_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return Type::traverse(this->type_, traverse); -} - -// Lower a generic composite literal into a specific version based on -// the type. - -Expression* -Composite_literal_expression::do_lower(Gogo*, Named_object*, int) -{ - Type* type = this->type_; - - for (int depth = this->depth_; depth > 0; --depth) - { - if (type->array_type() != NULL) - type = type->array_type()->element_type(); - else if (type->map_type() != NULL) - type = type->map_type()->val_type(); - else - { - if (!type->is_error_type()) - error_at(this->location(), - ("may only omit types within composite literals " - "of slice, array, or map type")); - return Expression::make_error(this->location()); - } - } - - if (type->is_error_type()) - return Expression::make_error(this->location()); - else if (type->struct_type() != NULL) - return this->lower_struct(type); - else if (type->array_type() != NULL) - return this->lower_array(type); - else if (type->map_type() != NULL) - return this->lower_map(type); - else - { - error_at(this->location(), - ("expected struct, slice, array, or map type " - "for composite literal")); - return Expression::make_error(this->location()); - } -} - -// Lower a struct composite literal. - -Expression* -Composite_literal_expression::lower_struct(Type* type) -{ - source_location location = this->location(); - Struct_type* st = type->struct_type(); - if (this->vals_ == NULL || !this->has_keys_) - return new Struct_construction_expression(type, this->vals_, location); - - size_t field_count = st->field_count(); - std::vector vals(field_count); - Expression_list::const_iterator p = this->vals_->begin(); - while (p != this->vals_->end()) - { - Expression* name_expr = *p; - - ++p; - gcc_assert(p != this->vals_->end()); - Expression* val = *p; - - ++p; - - if (name_expr == NULL) - { - error_at(val->location(), "mixture of field and value initializers"); - return Expression::make_error(location); - } - - bool bad_key = false; - std::string name; - switch (name_expr->classification()) - { - case EXPRESSION_UNKNOWN_REFERENCE: - name = name_expr->unknown_expression()->name(); - break; - - case EXPRESSION_CONST_REFERENCE: - name = static_cast(name_expr)->name(); - break; - - case EXPRESSION_TYPE: - { - Type* t = name_expr->type(); - Named_type* nt = t->named_type(); - if (nt == NULL) - bad_key = true; - else - name = nt->name(); - } - break; - - case EXPRESSION_VAR_REFERENCE: - name = name_expr->var_expression()->name(); - break; - - case EXPRESSION_FUNC_REFERENCE: - name = name_expr->func_expression()->name(); - break; - - case EXPRESSION_UNARY: - // If there is a local variable around with the same name as - // the field, and this occurs in the closure, then the - // parser may turn the field reference into an indirection - // through the closure. FIXME: This is a mess. - { - bad_key = true; - Unary_expression* ue = static_cast(name_expr); - if (ue->op() == OPERATOR_MULT) - { - Field_reference_expression* fre = - ue->operand()->field_reference_expression(); - if (fre != NULL) - { - Struct_type* st = - fre->expr()->type()->deref()->struct_type(); - if (st != NULL) - { - const Struct_field* sf = st->field(fre->field_index()); - name = sf->field_name(); - char buf[20]; - snprintf(buf, sizeof buf, "%u", fre->field_index()); - size_t buflen = strlen(buf); - if (name.compare(name.length() - buflen, buflen, buf) - == 0) - { - name = name.substr(0, name.length() - buflen); - bad_key = false; - } - } - } - } - } - break; - - default: - bad_key = true; - break; - } - if (bad_key) - { - error_at(name_expr->location(), "expected struct field name"); - return Expression::make_error(location); - } - - unsigned int index; - const Struct_field* sf = st->find_local_field(name, &index); - if (sf == NULL) - { - error_at(name_expr->location(), "unknown field %qs in %qs", - Gogo::message_name(name).c_str(), - (type->named_type() != NULL - ? type->named_type()->message_name().c_str() - : "unnamed struct")); - return Expression::make_error(location); - } - if (vals[index] != NULL) - { - error_at(name_expr->location(), - "duplicate value for field %qs in %qs", - Gogo::message_name(name).c_str(), - (type->named_type() != NULL - ? type->named_type()->message_name().c_str() - : "unnamed struct")); - return Expression::make_error(location); - } - - vals[index] = val; - } - - Expression_list* list = new Expression_list; - list->reserve(field_count); - for (size_t i = 0; i < field_count; ++i) - list->push_back(vals[i]); - - return new Struct_construction_expression(type, list, location); -} - -// Lower an array composite literal. - -Expression* -Composite_literal_expression::lower_array(Type* type) -{ - source_location location = this->location(); - if (this->vals_ == NULL || !this->has_keys_) - return this->make_array(type, this->vals_); - - std::vector vals; - vals.reserve(this->vals_->size()); - unsigned long index = 0; - Expression_list::const_iterator p = this->vals_->begin(); - while (p != this->vals_->end()) - { - Expression* index_expr = *p; - - ++p; - gcc_assert(p != this->vals_->end()); - Expression* val = *p; - - ++p; - - if (index_expr != NULL) - { - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (!index_expr->integer_constant_value(true, ival, &dummy)) - { - mpz_clear(ival); - error_at(index_expr->location(), - "index expression is not integer constant"); - return Expression::make_error(location); - } - if (mpz_sgn(ival) < 0) - { - mpz_clear(ival); - error_at(index_expr->location(), "index expression is negative"); - return Expression::make_error(location); - } - index = mpz_get_ui(ival); - if (mpz_cmp_ui(ival, index) != 0) - { - mpz_clear(ival); - error_at(index_expr->location(), "index value overflow"); - return Expression::make_error(location); - } - mpz_clear(ival); - } - - if (index == vals.size()) - vals.push_back(val); - else - { - if (index > vals.size()) - { - vals.reserve(index + 32); - vals.resize(index + 1, static_cast(NULL)); - } - if (vals[index] != NULL) - { - error_at((index_expr != NULL - ? index_expr->location() - : val->location()), - "duplicate value for index %lu", - index); - return Expression::make_error(location); - } - vals[index] = val; - } - - ++index; - } - - size_t size = vals.size(); - Expression_list* list = new Expression_list; - list->reserve(size); - for (size_t i = 0; i < size; ++i) - list->push_back(vals[i]); - - return this->make_array(type, list); -} - -// Actually build the array composite literal. This handles -// [...]{...}. - -Expression* -Composite_literal_expression::make_array(Type* type, Expression_list* vals) -{ - source_location location = this->location(); - Array_type* at = type->array_type(); - if (at->length() != NULL && at->length()->is_nil_expression()) - { - size_t size = vals == NULL ? 0 : vals->size(); - mpz_t vlen; - mpz_init_set_ui(vlen, size); - Expression* elen = Expression::make_integer(&vlen, NULL, location); - mpz_clear(vlen); - at = Type::make_array_type(at->element_type(), elen); - type = at; - } - if (at->length() != NULL) - return new Fixed_array_construction_expression(type, vals, location); - else - return new Open_array_construction_expression(type, vals, location); -} - -// Lower a map composite literal. - -Expression* -Composite_literal_expression::lower_map(Type* type) -{ - source_location location = this->location(); - if (this->vals_ != NULL) - { - if (!this->has_keys_) - { - error_at(location, "map composite literal must have keys"); - return Expression::make_error(location); - } - - for (Expression_list::const_iterator p = this->vals_->begin(); - p != this->vals_->end(); - p += 2) - { - if (*p == NULL) - { - ++p; - error_at((*p)->location(), - "map composite literal must have keys for every value"); - return Expression::make_error(location); - } - } - } - - return new Map_construction_expression(type, this->vals_, location); -} - -// Make a composite literal expression. - -Expression* -Expression::make_composite_literal(Type* type, int depth, bool has_keys, - Expression_list* vals, - source_location location) -{ - return new Composite_literal_expression(type, depth, has_keys, vals, - location); -} - -// Return whether this expression is a composite literal. - -bool -Expression::is_composite_literal() const -{ - switch (this->classification_) - { - case EXPRESSION_COMPOSITE_LITERAL: - case EXPRESSION_STRUCT_CONSTRUCTION: - case EXPRESSION_FIXED_ARRAY_CONSTRUCTION: - case EXPRESSION_OPEN_ARRAY_CONSTRUCTION: - case EXPRESSION_MAP_CONSTRUCTION: - return true; - default: - return false; - } -} - -// Return whether this expression is a composite literal which is not -// constant. - -bool -Expression::is_nonconstant_composite_literal() const -{ - switch (this->classification_) - { - case EXPRESSION_STRUCT_CONSTRUCTION: - { - const Struct_construction_expression *psce = - static_cast(this); - return !psce->is_constant_struct(); - } - case EXPRESSION_FIXED_ARRAY_CONSTRUCTION: - { - const Fixed_array_construction_expression *pace = - static_cast(this); - return !pace->is_constant_array(); - } - case EXPRESSION_OPEN_ARRAY_CONSTRUCTION: - { - const Open_array_construction_expression *pace = - static_cast(this); - return !pace->is_constant_array(); - } - case EXPRESSION_MAP_CONSTRUCTION: - return true; - default: - return false; - } -} - -// Return true if this is a reference to a local variable. - -bool -Expression::is_local_variable() const -{ - const Var_expression* ve = this->var_expression(); - if (ve == NULL) - return false; - const Named_object* no = ve->named_object(); - return (no->is_result_variable() - || (no->is_variable() && !no->var_value()->is_global())); -} - -// Class Type_guard_expression. - -// Traversal. - -int -Type_guard_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT - || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Check types of a type guard expression. The expression must have -// an interface type, but the actual type conversion is checked at run -// time. - -void -Type_guard_expression::do_check_types(Gogo*) -{ - // 6g permits using a type guard with unsafe.pointer; we are - // compatible. - Type* expr_type = this->expr_->type(); - if (expr_type->is_unsafe_pointer_type()) - { - if (this->type_->points_to() == NULL - && (this->type_->integer_type() == NULL - || (this->type_->forwarded() - != Type::lookup_integer_type("uintptr")))) - this->report_error(_("invalid unsafe.Pointer conversion")); - } - else if (this->type_->is_unsafe_pointer_type()) - { - if (expr_type->points_to() == NULL - && (expr_type->integer_type() == NULL - || (expr_type->forwarded() - != Type::lookup_integer_type("uintptr")))) - this->report_error(_("invalid unsafe.Pointer conversion")); - } - else if (expr_type->interface_type() == NULL) - this->report_error(_("type assertion only valid for interface types")); - else if (this->type_->interface_type() == NULL) - { - std::string reason; - if (!expr_type->interface_type()->implements_interface(this->type_, - &reason)) - { - if (reason.empty()) - this->report_error(_("impossible type assertion: " - "type does not implement interface")); - else - { - error_at(this->location(), - ("impossible type assertion: " - "type does not implement interface (%s)"), - reason.c_str()); - this->set_is_error(); - } - } - } -} - -// Return a tree for a type guard expression. - -tree -Type_guard_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree expr_tree = this->expr_->get_tree(context); - if (expr_tree == error_mark_node) - return error_mark_node; - Type* expr_type = this->expr_->type(); - if ((this->type_->is_unsafe_pointer_type() - && (expr_type->points_to() != NULL - || expr_type->integer_type() != NULL)) - || (expr_type->is_unsafe_pointer_type() - && this->type_->points_to() != NULL)) - return convert_to_pointer(this->type_->get_tree(gogo), expr_tree); - else if (expr_type->is_unsafe_pointer_type() - && this->type_->integer_type() != NULL) - return convert_to_integer(this->type_->get_tree(gogo), expr_tree); - else if (this->type_->interface_type() != NULL) - return Expression::convert_interface_to_interface(context, this->type_, - this->expr_->type(), - expr_tree, true, - this->location()); - else - return Expression::convert_for_assignment(context, this->type_, - this->expr_->type(), expr_tree, - this->location()); -} - -// Make a type guard expression. - -Expression* -Expression::make_type_guard(Expression* expr, Type* type, - source_location location) -{ - return new Type_guard_expression(expr, type, location); -} - -// Class Heap_composite_expression. - -// When you take the address of a composite literal, it is allocated -// on the heap. This class implements that. - -class Heap_composite_expression : public Expression -{ - public: - Heap_composite_expression(Expression* expr, source_location location) - : Expression(EXPRESSION_HEAP_COMPOSITE, location), - expr_(expr) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return Expression::traverse(&this->expr_, traverse); } - - Type* - do_type() - { return Type::make_pointer_type(this->expr_->type()); } - - void - do_determine_type(const Type_context*) - { this->expr_->determine_type_no_context(); } - - Expression* - do_copy() - { - return Expression::make_heap_composite(this->expr_->copy(), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - // We only export global objects, and the parser does not generate - // this in global scope. - void - do_export(Export*) const - { gcc_unreachable(); } - - private: - // The composite literal which is being put on the heap. - Expression* expr_; -}; - -// Return a tree which allocates a composite literal on the heap. - -tree -Heap_composite_expression::do_get_tree(Translate_context* context) -{ - tree expr_tree = this->expr_->get_tree(context); - if (expr_tree == error_mark_node) - return error_mark_node; - tree expr_size = TYPE_SIZE_UNIT(TREE_TYPE(expr_tree)); - gcc_assert(TREE_CODE(expr_size) == INTEGER_CST); - tree space = context->gogo()->allocate_memory(this->expr_->type(), - expr_size, this->location()); - space = fold_convert(build_pointer_type(TREE_TYPE(expr_tree)), space); - space = save_expr(space); - tree ref = build_fold_indirect_ref_loc(this->location(), space); - TREE_THIS_NOTRAP(ref) = 1; - tree ret = build2(COMPOUND_EXPR, TREE_TYPE(space), - build2(MODIFY_EXPR, void_type_node, ref, expr_tree), - space); - SET_EXPR_LOCATION(ret, this->location()); - return ret; -} - -// Allocate a composite literal on the heap. - -Expression* -Expression::make_heap_composite(Expression* expr, source_location location) -{ - return new Heap_composite_expression(expr, location); -} - -// Class Receive_expression. - -// Return the type of a receive expression. - -Type* -Receive_expression::do_type() -{ - Channel_type* channel_type = this->channel_->type()->channel_type(); - if (channel_type == NULL) - return Type::make_error_type(); - return channel_type->element_type(); -} - -// Check types for a receive expression. - -void -Receive_expression::do_check_types(Gogo*) -{ - Type* type = this->channel_->type(); - if (type->is_error_type()) - { - this->set_is_error(); - return; - } - if (type->channel_type() == NULL) - { - this->report_error(_("expected channel")); - return; - } - if (!type->channel_type()->may_receive()) - { - this->report_error(_("invalid receive on send-only channel")); - return; - } -} - -// Get a tree for a receive expression. - -tree -Receive_expression::do_get_tree(Translate_context* context) -{ - Channel_type* channel_type = this->channel_->type()->channel_type(); - gcc_assert(channel_type != NULL); - Type* element_type = channel_type->element_type(); - tree element_type_tree = element_type->get_tree(context->gogo()); - - tree channel = this->channel_->get_tree(context); - if (element_type_tree == error_mark_node || channel == error_mark_node) - return error_mark_node; - - return Gogo::receive_from_channel(element_type_tree, channel, - this->for_select_, this->location()); -} - -// Make a receive expression. - -Receive_expression* -Expression::make_receive(Expression* channel, source_location location) -{ - return new Receive_expression(channel, location); -} - -// Class Send_expression. - -// Traversal. - -int -Send_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->channel_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return Expression::traverse(&this->val_, traverse); -} - -// Get the type. - -Type* -Send_expression::do_type() -{ - return Type::lookup_bool_type(); -} - -// Set types. - -void -Send_expression::do_determine_type(const Type_context*) -{ - this->channel_->determine_type_no_context(); - - Type* type = this->channel_->type(); - Type_context subcontext; - if (type->channel_type() != NULL) - subcontext.type = type->channel_type()->element_type(); - this->val_->determine_type(&subcontext); -} - -// Check types. - -void -Send_expression::do_check_types(Gogo*) -{ - Type* type = this->channel_->type(); - if (type->is_error_type()) - { - this->set_is_error(); - return; - } - Channel_type* channel_type = type->channel_type(); - if (channel_type == NULL) - { - error_at(this->location(), "left operand of %<<-%> must be channel"); - this->set_is_error(); - return; - } - Type* element_type = channel_type->element_type(); - if (element_type != NULL - && !Type::are_assignable(element_type, this->val_->type(), NULL)) - { - this->report_error(_("incompatible types in send")); - return; - } - if (!channel_type->may_send()) - { - this->report_error(_("invalid send on receive-only channel")); - return; - } -} - -// Get a tree for a send expression. - -tree -Send_expression::do_get_tree(Translate_context* context) -{ - tree channel = this->channel_->get_tree(context); - tree val = this->val_->get_tree(context); - if (channel == error_mark_node || val == error_mark_node) - return error_mark_node; - Channel_type* channel_type = this->channel_->type()->channel_type(); - val = Expression::convert_for_assignment(context, - channel_type->element_type(), - this->val_->type(), - val, - this->location()); - return Gogo::send_on_channel(channel, val, this->is_value_discarded_, - this->for_select_, this->location()); -} - -// Make a send expression - -Send_expression* -Expression::make_send(Expression* channel, Expression* val, - source_location location) -{ - return new Send_expression(channel, val, location); -} - -// An expression which evaluates to a pointer to the type descriptor -// of a type. - -class Type_descriptor_expression : public Expression -{ - public: - Type_descriptor_expression(Type* type, source_location location) - : Expression(EXPRESSION_TYPE_DESCRIPTOR, location), - type_(type) - { } - - protected: - Type* - do_type() - { return Type::make_type_descriptor_ptr_type(); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context* context) - { return this->type_->type_descriptor_pointer(context->gogo()); } - - private: - // The type for which this is the descriptor. - Type* type_; -}; - -// Make a type descriptor expression. - -Expression* -Expression::make_type_descriptor(Type* type, source_location location) -{ - return new Type_descriptor_expression(type, location); -} - -// An expression which evaluates to some characteristic of a type. -// This is only used to initialize fields of a type descriptor. Using -// a new expression class is slightly inefficient but gives us a good -// separation between the frontend and the middle-end with regard to -// how types are laid out. - -class Type_info_expression : public Expression -{ - public: - Type_info_expression(Type* type, Type_info type_info) - : Expression(EXPRESSION_TYPE_INFO, BUILTINS_LOCATION), - type_(type), type_info_(type_info) - { } - - protected: - Type* - do_type(); - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context* context); - - private: - // The type for which we are getting information. - Type* type_; - // What information we want. - Type_info type_info_; -}; - -// The type is chosen to match what the type descriptor struct -// expects. - -Type* -Type_info_expression::do_type() -{ - switch (this->type_info_) - { - case TYPE_INFO_SIZE: - return Type::lookup_integer_type("uintptr"); - case TYPE_INFO_ALIGNMENT: - case TYPE_INFO_FIELD_ALIGNMENT: - return Type::lookup_integer_type("uint8"); - default: - gcc_unreachable(); - } -} - -// Return type information in GENERIC. - -tree -Type_info_expression::do_get_tree(Translate_context* context) -{ - tree type_tree = this->type_->get_tree(context->gogo()); - if (type_tree == error_mark_node) - return error_mark_node; - - tree val_type_tree = this->type()->get_tree(context->gogo()); - gcc_assert(val_type_tree != error_mark_node); - - if (this->type_info_ == TYPE_INFO_SIZE) - return fold_convert_loc(BUILTINS_LOCATION, val_type_tree, - TYPE_SIZE_UNIT(type_tree)); - else - { - unsigned HOST_WIDE_INT val; - if (this->type_info_ == TYPE_INFO_ALIGNMENT) - val = TYPE_ALIGN_UNIT(type_tree); - else - { - gcc_assert(this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT); - val = TYPE_ALIGN(type_tree); -#ifdef BIGGEST_FIELD_ALIGMENT - if (val > BIGGEST_FIELD_ALIGNMENT) - val = BIGGEST_FIELD_ALIGNMENT; -#endif -#ifdef ADJUST_FIELD_ALIGN - { - tree f = build_decl(UNKNOWN_LOCATION, FIELD_DECL, NULL, type_tree); - val = ADJUST_FIELD_ALIGN(f, val); - } -#endif - val /= BITS_PER_UNIT; - } - - return build_int_cstu(val_type_tree, val); - } -} - -// Make a type info expression. - -Expression* -Expression::make_type_info(Type* type, Type_info type_info) -{ - return new Type_info_expression(type, type_info); -} - -// An expression which evaluates to the offset of a field within a -// struct. This, like Type_info_expression, q.v., is only used to -// initialize fields of a type descriptor. - -class Struct_field_offset_expression : public Expression -{ - public: - Struct_field_offset_expression(Struct_type* type, const Struct_field* field) - : Expression(EXPRESSION_STRUCT_FIELD_OFFSET, BUILTINS_LOCATION), - type_(type), field_(field) - { } - - protected: - Type* - do_type() - { return Type::lookup_integer_type("uintptr"); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context* context); - - private: - // The type of the struct. - Struct_type* type_; - // The field. - const Struct_field* field_; -}; - -// Return a struct field offset in GENERIC. - -tree -Struct_field_offset_expression::do_get_tree(Translate_context* context) -{ - tree type_tree = this->type_->get_tree(context->gogo()); - if (type_tree == error_mark_node) - return error_mark_node; - - tree val_type_tree = this->type()->get_tree(context->gogo()); - gcc_assert(val_type_tree != error_mark_node); - - const Struct_field_list* fields = this->type_->fields(); - tree struct_field_tree = TYPE_FIELDS(type_tree); - Struct_field_list::const_iterator p; - for (p = fields->begin(); - p != fields->end(); - ++p, struct_field_tree = DECL_CHAIN(struct_field_tree)) - { - gcc_assert(struct_field_tree != NULL_TREE); - if (&*p == this->field_) - break; - } - gcc_assert(&*p == this->field_); - - return fold_convert_loc(BUILTINS_LOCATION, val_type_tree, - byte_position(struct_field_tree)); -} - -// Make an expression for a struct field offset. - -Expression* -Expression::make_struct_field_offset(Struct_type* type, - const Struct_field* field) -{ - return new Struct_field_offset_expression(type, field); -} - -// An expression which evaluates to the address of an unnamed label. - -class Label_addr_expression : public Expression -{ - public: - Label_addr_expression(Label* label, source_location location) - : Expression(EXPRESSION_LABEL_ADDR, location), - label_(label) - { } - - protected: - Type* - do_type() - { return Type::make_pointer_type(Type::make_void_type()); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return new Label_addr_expression(this->label_, this->location()); } - - tree - do_get_tree(Translate_context*) - { return this->label_->get_addr(this->location()); } - - private: - // The label whose address we are taking. - Label* label_; -}; - -// Make an expression for the address of an unnamed label. - -Expression* -Expression::make_label_addr(Label* label, source_location location) -{ - return new Label_addr_expression(label, location); -} - -// Import an expression. This comes at the end in order to see the -// various class definitions. - -Expression* -Expression::import_expression(Import* imp) -{ - int c = imp->peek_char(); - if (imp->match_c_string("- ") - || imp->match_c_string("! ") - || imp->match_c_string("^ ")) - return Unary_expression::do_import(imp); - else if (c == '(') - return Binary_expression::do_import(imp); - else if (imp->match_c_string("true") - || imp->match_c_string("false")) - return Boolean_expression::do_import(imp); - else if (c == '"') - return String_expression::do_import(imp); - else if (c == '-' || (c >= '0' && c <= '9')) - { - // This handles integers, floats and complex constants. - return Integer_expression::do_import(imp); - } - else if (imp->match_c_string("nil")) - return Nil_expression::do_import(imp); - else if (imp->match_c_string("convert")) - return Type_conversion_expression::do_import(imp); - else - { - error_at(imp->location(), "import error: expected expression"); - return Expression::make_error(imp->location()); - } -} - -// Class Expression_list. - -// Traverse the list. - -int -Expression_list::traverse(Traverse* traverse) -{ - for (Expression_list::iterator p = this->begin(); - p != this->end(); - ++p) - { - if (*p != NULL) - { - if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - return TRAVERSE_CONTINUE; -} - -// Copy the list. - -Expression_list* -Expression_list::copy() -{ - Expression_list* ret = new Expression_list(); - for (Expression_list::iterator p = this->begin(); - p != this->end(); - ++p) - { - if (*p == NULL) - ret->push_back(NULL); - else - ret->push_back((*p)->copy()); - } - return ret; -} - -// Return whether an expression list has an error expression. - -bool -Expression_list::contains_error() const -{ - for (Expression_list::const_iterator p = this->begin(); - p != this->end(); - ++p) - if (*p != NULL && (*p)->is_error_expression()) - return true; - return false; -} diff --git a/gcc/go/gofrontend/expressions.cc.merge-right.r172891 b/gcc/go/gofrontend/expressions.cc.merge-right.r172891 deleted file mode 100644 index 2c330ef2e46..00000000000 --- a/gcc/go/gofrontend/expressions.cc.merge-right.r172891 +++ /dev/null @@ -1,12843 +0,0 @@ -// expressions.cc -- Go frontend expression handling. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include - -#ifndef ENABLE_BUILD_WITH_CXX -extern "C" -{ -#endif - -#include "toplev.h" -#include "intl.h" -#include "tree.h" -#include "gimple.h" -#include "tree-iterator.h" -#include "convert.h" -#include "real.h" -#include "realmpfr.h" - -#ifndef ENABLE_BUILD_WITH_CXX -} -#endif - -#include "go-c.h" -#include "gogo.h" -#include "types.h" -#include "export.h" -#include "import.h" -#include "statements.h" -#include "lex.h" -#include "backend.h" -#include "expressions.h" - -// Class Expression. - -Expression::Expression(Expression_classification classification, - source_location location) - : classification_(classification), location_(location) -{ -} - -Expression::~Expression() -{ -} - -// If this expression has a constant integer value, return it. - -bool -Expression::integer_constant_value(bool iota_is_constant, mpz_t val, - Type** ptype) const -{ - *ptype = NULL; - return this->do_integer_constant_value(iota_is_constant, val, ptype); -} - -// If this expression has a constant floating point value, return it. - -bool -Expression::float_constant_value(mpfr_t val, Type** ptype) const -{ - *ptype = NULL; - if (this->do_float_constant_value(val, ptype)) - return true; - mpz_t ival; - mpz_init(ival); - Type* t; - bool ret; - if (!this->do_integer_constant_value(false, ival, &t)) - ret = false; - else - { - mpfr_set_z(val, ival, GMP_RNDN); - ret = true; - } - mpz_clear(ival); - return ret; -} - -// If this expression has a constant complex value, return it. - -bool -Expression::complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - *ptype = NULL; - if (this->do_complex_constant_value(real, imag, ptype)) - return true; - Type *t; - if (this->float_constant_value(real, &t)) - { - mpfr_set_ui(imag, 0, GMP_RNDN); - return true; - } - return false; -} - -// Traverse the expressions. - -int -Expression::traverse(Expression** pexpr, Traverse* traverse) -{ - Expression* expr = *pexpr; - if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0) - { - int t = traverse->expression(pexpr); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - return TRAVERSE_CONTINUE; - } - return expr->do_traverse(traverse); -} - -// Traverse subexpressions of this expression. - -int -Expression::traverse_subexpressions(Traverse* traverse) -{ - return this->do_traverse(traverse); -} - -// Default implementation for do_traverse for child classes. - -int -Expression::do_traverse(Traverse*) -{ - return TRAVERSE_CONTINUE; -} - -// This virtual function is called by the parser if the value of this -// expression is being discarded. By default, we warn. Expressions -// with side effects override. - -void -Expression::do_discarding_value() -{ - this->warn_about_unused_value(); -} - -// This virtual function is called to export expressions. This will -// only be used by expressions which may be constant. - -void -Expression::do_export(Export*) const -{ - go_unreachable(); -} - -// Warn that the value of the expression is not used. - -void -Expression::warn_about_unused_value() -{ - warning_at(this->location(), OPT_Wunused_value, "value computed is not used"); -} - -// Note that this expression is an error. This is called by children -// when they discover an error. - -void -Expression::set_is_error() -{ - this->classification_ = EXPRESSION_ERROR; -} - -// For children to call to report an error conveniently. - -void -Expression::report_error(const char* msg) -{ - error_at(this->location_, "%s", msg); - this->set_is_error(); -} - -// Set types of variables and constants. This is implemented by the -// child class. - -void -Expression::determine_type(const Type_context* context) -{ - this->do_determine_type(context); -} - -// Set types when there is no context. - -void -Expression::determine_type_no_context() -{ - Type_context context; - this->do_determine_type(&context); -} - -// Return a tree handling any conversions which must be done during -// assignment. - -tree -Expression::convert_for_assignment(Translate_context* context, Type* lhs_type, - Type* rhs_type, tree rhs_tree, - source_location location) -{ - if (lhs_type == rhs_type) - return rhs_tree; - - if (lhs_type->is_error() || rhs_type->is_error()) - return error_mark_node; - - if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node) - return error_mark_node; - - Gogo* gogo = context->gogo(); - - tree lhs_type_tree = lhs_type->get_tree(gogo); - if (lhs_type_tree == error_mark_node) - return error_mark_node; - - if (lhs_type->interface_type() != NULL) - { - if (rhs_type->interface_type() == NULL) - return Expression::convert_type_to_interface(context, lhs_type, - rhs_type, rhs_tree, - location); - else - return Expression::convert_interface_to_interface(context, lhs_type, - rhs_type, rhs_tree, - false, location); - } - else if (rhs_type->interface_type() != NULL) - return Expression::convert_interface_to_type(context, lhs_type, rhs_type, - rhs_tree, location); - else if (lhs_type->is_open_array_type() - && rhs_type->is_nil_type()) - { - // Assigning nil to an open array. - go_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(lhs_type_tree); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__values") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), null_pointer_node); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__count") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), integer_zero_node); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__capacity") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), integer_zero_node); - - tree val = build_constructor(lhs_type_tree, init); - TREE_CONSTANT(val) = 1; - - return val; - } - else if (rhs_type->is_nil_type()) - { - // The left hand side should be a pointer type at the tree - // level. - go_assert(POINTER_TYPE_P(lhs_type_tree)); - return fold_convert(lhs_type_tree, null_pointer_node); - } - else if (lhs_type_tree == TREE_TYPE(rhs_tree)) - { - // No conversion is needed. - return rhs_tree; - } - else if (POINTER_TYPE_P(lhs_type_tree) - || INTEGRAL_TYPE_P(lhs_type_tree) - || SCALAR_FLOAT_TYPE_P(lhs_type_tree) - || COMPLEX_FLOAT_TYPE_P(lhs_type_tree)) - return fold_convert_loc(location, lhs_type_tree, rhs_tree); - else if (TREE_CODE(lhs_type_tree) == RECORD_TYPE - && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE) - { - // This conversion must be permitted by Go, or we wouldn't have - // gotten here. - go_assert(int_size_in_bytes(lhs_type_tree) - == int_size_in_bytes(TREE_TYPE(rhs_tree))); - return fold_build1_loc(location, VIEW_CONVERT_EXPR, lhs_type_tree, - rhs_tree); - } - else - { - go_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree))); - return rhs_tree; - } -} - -// Return a tree for a conversion from a non-interface type to an -// interface type. - -tree -Expression::convert_type_to_interface(Translate_context* context, - Type* lhs_type, Type* rhs_type, - tree rhs_tree, source_location location) -{ - Gogo* gogo = context->gogo(); - Interface_type* lhs_interface_type = lhs_type->interface_type(); - bool lhs_is_empty = lhs_interface_type->is_empty(); - - // Since RHS_TYPE is a static type, we can create the interface - // method table at compile time. - - // When setting an interface to nil, we just set both fields to - // NULL. - if (rhs_type->is_nil_type()) - return lhs_type->get_init_tree(gogo, false); - - // This should have been checked already. - go_assert(lhs_interface_type->implements_interface(rhs_type, NULL)); - - tree lhs_type_tree = lhs_type->get_tree(gogo); - if (lhs_type_tree == error_mark_node) - return error_mark_node; - - // An interface is a tuple. If LHS_TYPE is an empty interface type, - // then the first field is the type descriptor for RHS_TYPE. - // Otherwise it is the interface method table for RHS_TYPE. - tree first_field_value; - if (lhs_is_empty) - first_field_value = rhs_type->type_descriptor_pointer(gogo); - else - { - // Build the interface method table for this interface and this - // object type: a list of function pointers for each interface - // method. - Named_type* rhs_named_type = rhs_type->named_type(); - bool is_pointer = false; - if (rhs_named_type == NULL) - { - rhs_named_type = rhs_type->deref()->named_type(); - is_pointer = true; - } - tree method_table; - if (rhs_named_type == NULL) - method_table = null_pointer_node; - else - method_table = - rhs_named_type->interface_method_table(gogo, lhs_interface_type, - is_pointer); - first_field_value = fold_convert_loc(location, const_ptr_type_node, - method_table); - } - if (first_field_value == error_mark_node) - return error_mark_node; - - // Start building a constructor for the value we will return. - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(lhs_type_tree); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0); - elt->index = field; - elt->value = fold_convert_loc(location, TREE_TYPE(field), first_field_value); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0); - elt->index = field; - - if (rhs_type->points_to() != NULL) - { - // We are assigning a pointer to the interface; the interface - // holds the pointer itself. - elt->value = rhs_tree; - return build_constructor(lhs_type_tree, init); - } - - // We are assigning a non-pointer value to the interface; the - // interface gets a copy of the value in the heap. - - tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree)); - - tree space = gogo->allocate_memory(rhs_type, object_size, location); - space = fold_convert_loc(location, build_pointer_type(TREE_TYPE(rhs_tree)), - space); - space = save_expr(space); - - tree ref = build_fold_indirect_ref_loc(location, space); - TREE_THIS_NOTRAP(ref) = 1; - tree set = fold_build2_loc(location, MODIFY_EXPR, void_type_node, - ref, rhs_tree); - - elt->value = fold_convert_loc(location, TREE_TYPE(field), space); - - return build2(COMPOUND_EXPR, lhs_type_tree, set, - build_constructor(lhs_type_tree, init)); -} - -// Return a tree for the type descriptor of RHS_TREE, which has -// interface type RHS_TYPE. If RHS_TREE is nil the result will be -// NULL. - -tree -Expression::get_interface_type_descriptor(Translate_context*, - Type* rhs_type, tree rhs_tree, - source_location location) -{ - tree rhs_type_tree = TREE_TYPE(rhs_tree); - go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE); - tree rhs_field = TYPE_FIELDS(rhs_type_tree); - tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field, - NULL_TREE); - if (rhs_type->interface_type()->is_empty()) - { - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), - "__type_descriptor") == 0); - return v; - } - - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods") - == 0); - go_assert(POINTER_TYPE_P(TREE_TYPE(v))); - v = save_expr(v); - tree v1 = build_fold_indirect_ref_loc(location, v); - go_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE); - tree f = TYPE_FIELDS(TREE_TYPE(v1)); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor") - == 0); - v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE); - - tree eq = fold_build2_loc(location, EQ_EXPR, boolean_type_node, v, - fold_convert_loc(location, TREE_TYPE(v), - null_pointer_node)); - tree n = fold_convert_loc(location, TREE_TYPE(v1), null_pointer_node); - return fold_build3_loc(location, COND_EXPR, TREE_TYPE(v1), - eq, n, v1); -} - -// Return a tree for the conversion of an interface type to an -// interface type. - -tree -Expression::convert_interface_to_interface(Translate_context* context, - Type *lhs_type, Type *rhs_type, - tree rhs_tree, bool for_type_guard, - source_location location) -{ - Gogo* gogo = context->gogo(); - Interface_type* lhs_interface_type = lhs_type->interface_type(); - bool lhs_is_empty = lhs_interface_type->is_empty(); - - tree lhs_type_tree = lhs_type->get_tree(gogo); - if (lhs_type_tree == error_mark_node) - return error_mark_node; - - // In the general case this requires runtime examination of the type - // method table to match it up with the interface methods. - - // FIXME: If all of the methods in the right hand side interface - // also appear in the left hand side interface, then we don't need - // to do a runtime check, although we still need to build a new - // method table. - - // Get the type descriptor for the right hand side. This will be - // NULL for a nil interface. - - if (!DECL_P(rhs_tree)) - rhs_tree = save_expr(rhs_tree); - - tree rhs_type_descriptor = - Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree, - location); - - // The result is going to be a two element constructor. - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(lhs_type_tree); - elt->index = field; - - if (for_type_guard) - { - // A type assertion fails when converting a nil interface. - tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo); - static tree assert_interface_decl; - tree call = Gogo::call_builtin(&assert_interface_decl, - location, - "__go_assert_interface", - 2, - ptr_type_node, - TREE_TYPE(lhs_type_descriptor), - lhs_type_descriptor, - TREE_TYPE(rhs_type_descriptor), - rhs_type_descriptor); - if (call == error_mark_node) - return error_mark_node; - // This will panic if the interface conversion fails. - TREE_NOTHROW(assert_interface_decl) = 0; - elt->value = fold_convert_loc(location, TREE_TYPE(field), call); - } - else if (lhs_is_empty) - { - // A convertion to an empty interface always succeeds, and the - // first field is just the type descriptor of the object. - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__type_descriptor") == 0); - go_assert(TREE_TYPE(field) == TREE_TYPE(rhs_type_descriptor)); - elt->value = rhs_type_descriptor; - } - else - { - // A conversion to a non-empty interface may fail, but unlike a - // type assertion converting nil will always succeed. - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") - == 0); - tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo); - static tree convert_interface_decl; - tree call = Gogo::call_builtin(&convert_interface_decl, - location, - "__go_convert_interface", - 2, - ptr_type_node, - TREE_TYPE(lhs_type_descriptor), - lhs_type_descriptor, - TREE_TYPE(rhs_type_descriptor), - rhs_type_descriptor); - if (call == error_mark_node) - return error_mark_node; - // This will panic if the interface conversion fails. - TREE_NOTHROW(convert_interface_decl) = 0; - elt->value = fold_convert_loc(location, TREE_TYPE(field), call); - } - - // The second field is simply the object pointer. - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0); - elt->index = field; - - tree rhs_type_tree = TREE_TYPE(rhs_tree); - go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE); - tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree)); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0); - elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field, - NULL_TREE); - - return build_constructor(lhs_type_tree, init); -} - -// Return a tree for the conversion of an interface type to a -// non-interface type. - -tree -Expression::convert_interface_to_type(Translate_context* context, - Type *lhs_type, Type* rhs_type, - tree rhs_tree, source_location location) -{ - Gogo* gogo = context->gogo(); - tree rhs_type_tree = TREE_TYPE(rhs_tree); - - tree lhs_type_tree = lhs_type->get_tree(gogo); - if (lhs_type_tree == error_mark_node) - return error_mark_node; - - // Call a function to check that the type is valid. The function - // will panic with an appropriate runtime type error if the type is - // not valid. - - tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo); - - if (!DECL_P(rhs_tree)) - rhs_tree = save_expr(rhs_tree); - - tree rhs_type_descriptor = - Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree, - location); - - tree rhs_inter_descriptor = rhs_type->type_descriptor_pointer(gogo); - - static tree check_interface_type_decl; - tree call = Gogo::call_builtin(&check_interface_type_decl, - location, - "__go_check_interface_type", - 3, - void_type_node, - TREE_TYPE(lhs_type_descriptor), - lhs_type_descriptor, - TREE_TYPE(rhs_type_descriptor), - rhs_type_descriptor, - TREE_TYPE(rhs_inter_descriptor), - rhs_inter_descriptor); - if (call == error_mark_node) - return error_mark_node; - // This call will panic if the conversion is invalid. - TREE_NOTHROW(check_interface_type_decl) = 0; - - // If the call succeeds, pull out the value. - go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE); - tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree)); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0); - tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field, - NULL_TREE); - - // If the value is a pointer, then it is the value we want. - // Otherwise it points to the value. - if (lhs_type->points_to() == NULL) - { - val = fold_convert_loc(location, build_pointer_type(lhs_type_tree), val); - val = build_fold_indirect_ref_loc(location, val); - } - - return build2(COMPOUND_EXPR, lhs_type_tree, call, - fold_convert_loc(location, lhs_type_tree, val)); -} - -// Convert an expression to a tree. This is implemented by the child -// class. Not that it is not in general safe to call this multiple -// times for a single expression, but that we don't catch such errors. - -tree -Expression::get_tree(Translate_context* context) -{ - // The child may have marked this expression as having an error. - if (this->classification_ == EXPRESSION_ERROR) - return error_mark_node; - - return this->do_get_tree(context); -} - -// Return a tree for VAL in TYPE. - -tree -Expression::integer_constant_tree(mpz_t val, tree type) -{ - if (type == error_mark_node) - return error_mark_node; - else if (TREE_CODE(type) == INTEGER_TYPE) - return double_int_to_tree(type, - mpz_get_double_int(type, val, true)); - else if (TREE_CODE(type) == REAL_TYPE) - { - mpfr_t fval; - mpfr_init_set_z(fval, val, GMP_RNDN); - tree ret = Expression::float_constant_tree(fval, type); - mpfr_clear(fval); - return ret; - } - else if (TREE_CODE(type) == COMPLEX_TYPE) - { - mpfr_t fval; - mpfr_init_set_z(fval, val, GMP_RNDN); - tree real = Expression::float_constant_tree(fval, TREE_TYPE(type)); - mpfr_clear(fval); - tree imag = build_real_from_int_cst(TREE_TYPE(type), - integer_zero_node); - return build_complex(type, real, imag); - } - else - go_unreachable(); -} - -// Return a tree for VAL in TYPE. - -tree -Expression::float_constant_tree(mpfr_t val, tree type) -{ - if (type == error_mark_node) - return error_mark_node; - else if (TREE_CODE(type) == INTEGER_TYPE) - { - mpz_t ival; - mpz_init(ival); - mpfr_get_z(ival, val, GMP_RNDN); - tree ret = Expression::integer_constant_tree(ival, type); - mpz_clear(ival); - return ret; - } - else if (TREE_CODE(type) == REAL_TYPE) - { - REAL_VALUE_TYPE r1; - real_from_mpfr(&r1, val, type, GMP_RNDN); - REAL_VALUE_TYPE r2; - real_convert(&r2, TYPE_MODE(type), &r1); - return build_real(type, r2); - } - else if (TREE_CODE(type) == COMPLEX_TYPE) - { - REAL_VALUE_TYPE r1; - real_from_mpfr(&r1, val, TREE_TYPE(type), GMP_RNDN); - REAL_VALUE_TYPE r2; - real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1); - tree imag = build_real_from_int_cst(TREE_TYPE(type), - integer_zero_node); - return build_complex(type, build_real(TREE_TYPE(type), r2), imag); - } - else - go_unreachable(); -} - -// Return a tree for REAL/IMAG in TYPE. - -tree -Expression::complex_constant_tree(mpfr_t real, mpfr_t imag, tree type) -{ - if (type == error_mark_node) - return error_mark_node; - else if (TREE_CODE(type) == INTEGER_TYPE || TREE_CODE(type) == REAL_TYPE) - return Expression::float_constant_tree(real, type); - else if (TREE_CODE(type) == COMPLEX_TYPE) - { - REAL_VALUE_TYPE r1; - real_from_mpfr(&r1, real, TREE_TYPE(type), GMP_RNDN); - REAL_VALUE_TYPE r2; - real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1); - - REAL_VALUE_TYPE r3; - real_from_mpfr(&r3, imag, TREE_TYPE(type), GMP_RNDN); - REAL_VALUE_TYPE r4; - real_convert(&r4, TYPE_MODE(TREE_TYPE(type)), &r3); - - return build_complex(type, build_real(TREE_TYPE(type), r2), - build_real(TREE_TYPE(type), r4)); - } - else - go_unreachable(); -} - -// Return a tree which evaluates to true if VAL, of arbitrary integer -// type, is negative or is more than the maximum value of BOUND_TYPE. -// If SOFAR is not NULL, it is or'red into the result. The return -// value may be NULL if SOFAR is NULL. - -tree -Expression::check_bounds(tree val, tree bound_type, tree sofar, - source_location loc) -{ - tree val_type = TREE_TYPE(val); - tree ret = NULL_TREE; - - if (!TYPE_UNSIGNED(val_type)) - { - ret = fold_build2_loc(loc, LT_EXPR, boolean_type_node, val, - build_int_cst(val_type, 0)); - if (ret == boolean_false_node) - ret = NULL_TREE; - } - - if ((TYPE_UNSIGNED(val_type) && !TYPE_UNSIGNED(bound_type)) - || TYPE_SIZE(val_type) > TYPE_SIZE(bound_type)) - { - tree max = TYPE_MAX_VALUE(bound_type); - tree big = fold_build2_loc(loc, GT_EXPR, boolean_type_node, val, - fold_convert_loc(loc, val_type, max)); - if (big == boolean_false_node) - ; - else if (ret == NULL_TREE) - ret = big; - else - ret = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - ret, big); - } - - if (ret == NULL_TREE) - return sofar; - else if (sofar == NULL_TREE) - return ret; - else - return fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - sofar, ret); -} - -// Error expressions. This are used to avoid cascading errors. - -class Error_expression : public Expression -{ - public: - Error_expression(source_location location) - : Expression(EXPRESSION_ERROR, location) - { } - - protected: - bool - do_is_constant() const - { return true; } - - bool - do_integer_constant_value(bool, mpz_t val, Type**) const - { - mpz_set_ui(val, 0); - return true; - } - - bool - do_float_constant_value(mpfr_t val, Type**) const - { - mpfr_set_ui(val, 0, GMP_RNDN); - return true; - } - - bool - do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const - { - mpfr_set_ui(real, 0, GMP_RNDN); - mpfr_set_ui(imag, 0, GMP_RNDN); - return true; - } - - void - do_discarding_value() - { } - - Type* - do_type() - { return Type::make_error_type(); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - bool - do_is_addressable() const - { return true; } - - tree - do_get_tree(Translate_context*) - { return error_mark_node; } -}; - -Expression* -Expression::make_error(source_location location) -{ - return new Error_expression(location); -} - -// An expression which is really a type. This is used during parsing. -// It is an error if these survive after lowering. - -class -Type_expression : public Expression -{ - public: - Type_expression(Type* type, source_location location) - : Expression(EXPRESSION_TYPE, location), - type_(type) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return Type::traverse(this->type_, traverse); } - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*) - { } - - void - do_check_types(Gogo*) - { this->report_error(_("invalid use of type")); } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context*) - { go_unreachable(); } - - private: - // The type which we are representing as an expression. - Type* type_; -}; - -Expression* -Expression::make_type(Type* type, source_location location) -{ - return new Type_expression(type, location); -} - -// Class Parser_expression. - -Type* -Parser_expression::do_type() -{ - // We should never really ask for the type of a Parser_expression. - // However, it can happen, at least when we have an invalid const - // whose initializer refers to the const itself. In that case we - // may ask for the type when lowering the const itself. - go_assert(saw_errors()); - return Type::make_error_type(); -} - -// Class Var_expression. - -// Lower a variable expression. Here we just make sure that the -// initialization expression of the variable has been lowered. This -// ensures that we will be able to determine the type of the variable -// if necessary. - -Expression* -Var_expression::do_lower(Gogo* gogo, Named_object* function, int) -{ - if (this->variable_->is_variable()) - { - Variable* var = this->variable_->var_value(); - // This is either a local variable or a global variable. A - // reference to a variable which is local to an enclosing - // function will be a reference to a field in a closure. - if (var->is_global()) - function = NULL; - var->lower_init_expression(gogo, function); - } - return this; -} - -// Return the type of a reference to a variable. - -Type* -Var_expression::do_type() -{ - if (this->variable_->is_variable()) - return this->variable_->var_value()->type(); - else if (this->variable_->is_result_variable()) - return this->variable_->result_var_value()->type(); - else - go_unreachable(); -} - -// Determine the type of a reference to a variable. - -void -Var_expression::do_determine_type(const Type_context*) -{ - if (this->variable_->is_variable()) - this->variable_->var_value()->determine_type(); -} - -// Something takes the address of this variable. This means that we -// may want to move the variable onto the heap. - -void -Var_expression::do_address_taken(bool escapes) -{ - if (!escapes) - ; - else if (this->variable_->is_variable()) - this->variable_->var_value()->set_address_taken(); - else if (this->variable_->is_result_variable()) - this->variable_->result_var_value()->set_address_taken(); - else - go_unreachable(); -} - -// Get the tree for a reference to a variable. - -tree -Var_expression::do_get_tree(Translate_context* context) -{ - Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(), - context->function()); - tree ret = var_to_tree(bvar); - if (ret == error_mark_node) - return error_mark_node; - bool is_in_heap; - if (this->variable_->is_variable()) - is_in_heap = this->variable_->var_value()->is_in_heap(); - else if (this->variable_->is_result_variable()) - is_in_heap = this->variable_->result_var_value()->is_in_heap(); - else - go_unreachable(); - if (is_in_heap) - { - ret = build_fold_indirect_ref_loc(this->location(), ret); - TREE_THIS_NOTRAP(ret) = 1; - } - return ret; -} - -// Make a reference to a variable in an expression. - -Expression* -Expression::make_var_reference(Named_object* var, source_location location) -{ - if (var->is_sink()) - return Expression::make_sink(location); - - // FIXME: Creating a new object for each reference to a variable is - // wasteful. - return new Var_expression(var, location); -} - -// Class Temporary_reference_expression. - -// The type. - -Type* -Temporary_reference_expression::do_type() -{ - return this->statement_->type(); -} - -// Called if something takes the address of this temporary variable. -// We never have to move temporary variables to the heap, but we do -// need to know that they must live in the stack rather than in a -// register. - -void -Temporary_reference_expression::do_address_taken(bool) -{ - this->statement_->set_is_address_taken(); -} - -// Get a tree referring to the variable. - -tree -Temporary_reference_expression::do_get_tree(Translate_context* context) -{ - Bvariable* bvar = this->statement_->get_backend_variable(context); - - // The gcc backend can't represent the same set of recursive types - // that the Go frontend can. In some cases this means that a - // temporary variable won't have the right backend type. Correct - // that here by adding a type cast. We need to use base() to push - // the circularity down one level. - tree ret = var_to_tree(bvar); - if (POINTER_TYPE_P(TREE_TYPE(ret)) && VOID_TYPE_P(TREE_TYPE(TREE_TYPE(ret)))) - { - tree type_tree = this->type()->base()->get_tree(context->gogo()); - ret = fold_convert_loc(this->location(), type_tree, ret); - } - return ret; -} - -// Make a reference to a temporary variable. - -Expression* -Expression::make_temporary_reference(Temporary_statement* statement, - source_location location) -{ - return new Temporary_reference_expression(statement, location); -} - -// A sink expression--a use of the blank identifier _. - -class Sink_expression : public Expression -{ - public: - Sink_expression(source_location location) - : Expression(EXPRESSION_SINK, location), - type_(NULL), var_(NULL_TREE) - { } - - protected: - void - do_discarding_value() - { } - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - Expression* - do_copy() - { return new Sink_expression(this->location()); } - - tree - do_get_tree(Translate_context*); - - private: - // The type of this sink variable. - Type* type_; - // The temporary variable we generate. - tree var_; -}; - -// Return the type of a sink expression. - -Type* -Sink_expression::do_type() -{ - if (this->type_ == NULL) - return Type::make_sink_type(); - return this->type_; -} - -// Determine the type of a sink expression. - -void -Sink_expression::do_determine_type(const Type_context* context) -{ - if (context->type != NULL) - this->type_ = context->type; -} - -// Return a temporary variable for a sink expression. This will -// presumably be a write-only variable which the middle-end will drop. - -tree -Sink_expression::do_get_tree(Translate_context* context) -{ - if (this->var_ == NULL_TREE) - { - go_assert(this->type_ != NULL && !this->type_->is_sink_type()); - this->var_ = create_tmp_var(this->type_->get_tree(context->gogo()), - "blank"); - } - return this->var_; -} - -// Make a sink expression. - -Expression* -Expression::make_sink(source_location location) -{ - return new Sink_expression(location); -} - -// Class Func_expression. - -// FIXME: Can a function expression appear in a constant expression? -// The value is unchanging. Initializing a constant to the address of -// a function seems like it could work, though there might be little -// point to it. - -// Traversal. - -int -Func_expression::do_traverse(Traverse* traverse) -{ - return (this->closure_ == NULL - ? TRAVERSE_CONTINUE - : Expression::traverse(&this->closure_, traverse)); -} - -// Return the type of a function expression. - -Type* -Func_expression::do_type() -{ - if (this->function_->is_function()) - return this->function_->func_value()->type(); - else if (this->function_->is_function_declaration()) - return this->function_->func_declaration_value()->type(); - else - go_unreachable(); -} - -// Get the tree for a function expression without evaluating the -// closure. - -tree -Func_expression::get_tree_without_closure(Gogo* gogo) -{ - Function_type* fntype; - if (this->function_->is_function()) - fntype = this->function_->func_value()->type(); - else if (this->function_->is_function_declaration()) - fntype = this->function_->func_declaration_value()->type(); - else - go_unreachable(); - - // Builtin functions are handled specially by Call_expression. We - // can't take their address. - if (fntype->is_builtin()) - { - error_at(this->location(), "invalid use of special builtin function %qs", - this->function_->name().c_str()); - return error_mark_node; - } - - Named_object* no = this->function_; - - tree id = no->get_id(gogo); - if (id == error_mark_node) - return error_mark_node; - - tree fndecl; - if (no->is_function()) - fndecl = no->func_value()->get_or_make_decl(gogo, no, id); - else if (no->is_function_declaration()) - fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no, id); - else - go_unreachable(); - - if (fndecl == error_mark_node) - return error_mark_node; - - return build_fold_addr_expr_loc(this->location(), fndecl); -} - -// Get the tree for a function expression. This is used when we take -// the address of a function rather than simply calling it. If the -// function has a closure, we must use a trampoline. - -tree -Func_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - - tree fnaddr = this->get_tree_without_closure(gogo); - if (fnaddr == error_mark_node) - return error_mark_node; - - go_assert(TREE_CODE(fnaddr) == ADDR_EXPR - && TREE_CODE(TREE_OPERAND(fnaddr, 0)) == FUNCTION_DECL); - TREE_ADDRESSABLE(TREE_OPERAND(fnaddr, 0)) = 1; - - // For a normal non-nested function call, that is all we have to do. - if (!this->function_->is_function() - || this->function_->func_value()->enclosing() == NULL) - { - go_assert(this->closure_ == NULL); - return fnaddr; - } - - // For a nested function call, we have to always allocate a - // trampoline. If we don't always allocate, then closures will not - // be reliably distinct. - Expression* closure = this->closure_; - tree closure_tree; - if (closure == NULL) - closure_tree = null_pointer_node; - else - { - // Get the value of the closure. This will be a pointer to - // space allocated on the heap. - closure_tree = closure->get_tree(context); - if (closure_tree == error_mark_node) - return error_mark_node; - go_assert(POINTER_TYPE_P(TREE_TYPE(closure_tree))); - } - - // Now we need to build some code on the heap. This code will load - // the static chain pointer with the closure and then jump to the - // body of the function. The normal gcc approach is to build the - // code on the stack. Unfortunately we can not do that, as Go - // permits us to return the function pointer. - - return gogo->make_trampoline(fnaddr, closure_tree, this->location()); -} - -// Make a reference to a function in an expression. - -Expression* -Expression::make_func_reference(Named_object* function, Expression* closure, - source_location location) -{ - return new Func_expression(function, closure, location); -} - -// Class Unknown_expression. - -// Return the name of an unknown expression. - -const std::string& -Unknown_expression::name() const -{ - return this->named_object_->name(); -} - -// Lower a reference to an unknown name. - -Expression* -Unknown_expression::do_lower(Gogo*, Named_object*, int) -{ - source_location location = this->location(); - Named_object* no = this->named_object_; - Named_object* real; - if (!no->is_unknown()) - real = no; - else - { - real = no->unknown_value()->real_named_object(); - if (real == NULL) - { - if (this->is_composite_literal_key_) - return this; - error_at(location, "reference to undefined name %qs", - this->named_object_->message_name().c_str()); - return Expression::make_error(location); - } - } - switch (real->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - return Expression::make_const_reference(real, location); - case Named_object::NAMED_OBJECT_TYPE: - return Expression::make_type(real->type_value(), location); - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - if (this->is_composite_literal_key_) - return this; - error_at(location, "reference to undefined type %qs", - real->message_name().c_str()); - return Expression::make_error(location); - case Named_object::NAMED_OBJECT_VAR: - return Expression::make_var_reference(real, location); - case Named_object::NAMED_OBJECT_FUNC: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - return Expression::make_func_reference(real, NULL, location); - case Named_object::NAMED_OBJECT_PACKAGE: - if (this->is_composite_literal_key_) - return this; - error_at(location, "unexpected reference to package"); - return Expression::make_error(location); - default: - go_unreachable(); - } -} - -// Make a reference to an unknown name. - -Expression* -Expression::make_unknown_reference(Named_object* no, source_location location) -{ - go_assert(no->resolve()->is_unknown()); - return new Unknown_expression(no, location); -} - -// A boolean expression. - -class Boolean_expression : public Expression -{ - public: - Boolean_expression(bool val, source_location location) - : Expression(EXPRESSION_BOOLEAN, location), - val_(val), type_(NULL) - { } - - static Expression* - do_import(Import*); - - protected: - bool - do_is_constant() const - { return true; } - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context*) - { return this->val_ ? boolean_true_node : boolean_false_node; } - - void - do_export(Export* exp) const - { exp->write_c_string(this->val_ ? "true" : "false"); } - - private: - // The constant. - bool val_; - // The type as determined by context. - Type* type_; -}; - -// Get the type. - -Type* -Boolean_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_boolean_type(); - return this->type_; -} - -// Set the type from the context. - -void -Boolean_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL && context->type->is_boolean_type()) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_bool_type(); -} - -// Import a boolean constant. - -Expression* -Boolean_expression::do_import(Import* imp) -{ - if (imp->peek_char() == 't') - { - imp->require_c_string("true"); - return Expression::make_boolean(true, imp->location()); - } - else - { - imp->require_c_string("false"); - return Expression::make_boolean(false, imp->location()); - } -} - -// Make a boolean expression. - -Expression* -Expression::make_boolean(bool val, source_location location) -{ - return new Boolean_expression(val, location); -} - -// Class String_expression. - -// Get the type. - -Type* -String_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_string_type(); - return this->type_; -} - -// Set the type from the context. - -void -String_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL && context->type->is_string_type()) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_string_type(); -} - -// Build a string constant. - -tree -String_expression::do_get_tree(Translate_context* context) -{ - return context->gogo()->go_string_constant_tree(this->val_); -} - -// Export a string expression. - -void -String_expression::do_export(Export* exp) const -{ - std::string s; - s.reserve(this->val_.length() * 4 + 2); - s += '"'; - for (std::string::const_iterator p = this->val_.begin(); - p != this->val_.end(); - ++p) - { - if (*p == '\\' || *p == '"') - { - s += '\\'; - s += *p; - } - else if (*p >= 0x20 && *p < 0x7f) - s += *p; - else if (*p == '\n') - s += "\\n"; - else if (*p == '\t') - s += "\\t"; - else - { - s += "\\x"; - unsigned char c = *p; - unsigned int dig = c >> 4; - s += dig < 10 ? '0' + dig : 'A' + dig - 10; - dig = c & 0xf; - s += dig < 10 ? '0' + dig : 'A' + dig - 10; - } - } - s += '"'; - exp->write_string(s); -} - -// Import a string expression. - -Expression* -String_expression::do_import(Import* imp) -{ - imp->require_c_string("\""); - std::string val; - while (true) - { - int c = imp->get_char(); - if (c == '"' || c == -1) - break; - if (c != '\\') - val += static_cast(c); - else - { - c = imp->get_char(); - if (c == '\\' || c == '"') - val += static_cast(c); - else if (c == 'n') - val += '\n'; - else if (c == 't') - val += '\t'; - else if (c == 'x') - { - c = imp->get_char(); - unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10; - c = imp->get_char(); - unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10; - char v = (vh << 4) | vl; - val += v; - } - else - { - error_at(imp->location(), "bad string constant"); - return Expression::make_error(imp->location()); - } - } - } - return Expression::make_string(val, imp->location()); -} - -// Make a string expression. - -Expression* -Expression::make_string(const std::string& val, source_location location) -{ - return new String_expression(val, location); -} - -// Make an integer expression. - -class Integer_expression : public Expression -{ - public: - Integer_expression(const mpz_t* val, Type* type, source_location location) - : Expression(EXPRESSION_INTEGER, location), - type_(type) - { mpz_init_set(this->val_, *val); } - - static Expression* - do_import(Import*); - - // Return whether VAL fits in the type. - static bool - check_constant(mpz_t val, Type*, source_location); - - // Write VAL to export data. - static void - export_integer(Export* exp, const mpz_t val); - - protected: - bool - do_is_constant() const - { return true; } - - bool - do_integer_constant_value(bool, mpz_t val, Type** ptype) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context* context); - - void - do_check_types(Gogo*); - - tree - do_get_tree(Translate_context*); - - Expression* - do_copy() - { return Expression::make_integer(&this->val_, this->type_, - this->location()); } - - void - do_export(Export*) const; - - private: - // The integer value. - mpz_t val_; - // The type so far. - Type* type_; -}; - -// Return an integer constant value. - -bool -Integer_expression::do_integer_constant_value(bool, mpz_t val, - Type** ptype) const -{ - if (this->type_ != NULL) - *ptype = this->type_; - mpz_set(val, this->val_); - return true; -} - -// Return the current type. If we haven't set the type yet, we return -// an abstract integer type. - -Type* -Integer_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_abstract_integer_type(); - return this->type_; -} - -// Set the type of the integer value. Here we may switch from an -// abstract type to a real type. - -void -Integer_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL - && (context->type->integer_type() != NULL - || context->type->float_type() != NULL - || context->type->complex_type() != NULL)) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_integer_type("int"); -} - -// Return true if the integer VAL fits in the range of the type TYPE. -// Otherwise give an error and return false. TYPE may be NULL. - -bool -Integer_expression::check_constant(mpz_t val, Type* type, - source_location location) -{ - if (type == NULL) - return true; - Integer_type* itype = type->integer_type(); - if (itype == NULL || itype->is_abstract()) - return true; - - int bits = mpz_sizeinbase(val, 2); - - if (itype->is_unsigned()) - { - // For an unsigned type we can only accept a nonnegative number, - // and we must be able to represent at least BITS. - if (mpz_sgn(val) >= 0 - && bits <= itype->bits()) - return true; - } - else - { - // For a signed type we need an extra bit to indicate the sign. - // We have to handle the most negative integer specially. - if (bits + 1 <= itype->bits() - || (bits <= itype->bits() - && mpz_sgn(val) < 0 - && (mpz_scan1(val, 0) - == static_cast(itype->bits() - 1)) - && mpz_scan0(val, itype->bits()) == ULONG_MAX)) - return true; - } - - error_at(location, "integer constant overflow"); - return false; -} - -// Check the type of an integer constant. - -void -Integer_expression::do_check_types(Gogo*) -{ - if (this->type_ == NULL) - return; - if (!Integer_expression::check_constant(this->val_, this->type_, - this->location())) - this->set_is_error(); -} - -// Get a tree for an integer constant. - -tree -Integer_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type; - if (this->type_ != NULL && !this->type_->is_abstract()) - type = this->type_->get_tree(gogo); - else if (this->type_ != NULL && this->type_->float_type() != NULL) - { - // We are converting to an abstract floating point type. - type = Type::lookup_float_type("float64")->get_tree(gogo); - } - else if (this->type_ != NULL && this->type_->complex_type() != NULL) - { - // We are converting to an abstract complex type. - type = Type::lookup_complex_type("complex128")->get_tree(gogo); - } - else - { - // If we still have an abstract type here, then this is being - // used in a constant expression which didn't get reduced for - // some reason. Use a type which will fit the value. We use <, - // not <=, because we need an extra bit for the sign bit. - int bits = mpz_sizeinbase(this->val_, 2); - if (bits < INT_TYPE_SIZE) - type = Type::lookup_integer_type("int")->get_tree(gogo); - else if (bits < 64) - type = Type::lookup_integer_type("int64")->get_tree(gogo); - else - type = long_long_integer_type_node; - } - return Expression::integer_constant_tree(this->val_, type); -} - -// Write VAL to export data. - -void -Integer_expression::export_integer(Export* exp, const mpz_t val) -{ - char* s = mpz_get_str(NULL, 10, val); - exp->write_c_string(s); - free(s); -} - -// Export an integer in a constant expression. - -void -Integer_expression::do_export(Export* exp) const -{ - Integer_expression::export_integer(exp, this->val_); - // A trailing space lets us reliably identify the end of the number. - exp->write_c_string(" "); -} - -// Import an integer, floating point, or complex value. This handles -// all these types because they all start with digits. - -Expression* -Integer_expression::do_import(Import* imp) -{ - std::string num = imp->read_identifier(); - imp->require_c_string(" "); - if (!num.empty() && num[num.length() - 1] == 'i') - { - mpfr_t real; - size_t plus_pos = num.find('+', 1); - size_t minus_pos = num.find('-', 1); - size_t pos; - if (plus_pos == std::string::npos) - pos = minus_pos; - else if (minus_pos == std::string::npos) - pos = plus_pos; - else - { - error_at(imp->location(), "bad number in import data: %qs", - num.c_str()); - return Expression::make_error(imp->location()); - } - if (pos == std::string::npos) - mpfr_set_ui(real, 0, GMP_RNDN); - else - { - std::string real_str = num.substr(0, pos); - if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0) - { - error_at(imp->location(), "bad number in import data: %qs", - real_str.c_str()); - return Expression::make_error(imp->location()); - } - } - - std::string imag_str; - if (pos == std::string::npos) - imag_str = num; - else - imag_str = num.substr(pos); - imag_str = imag_str.substr(0, imag_str.size() - 1); - mpfr_t imag; - if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0) - { - error_at(imp->location(), "bad number in import data: %qs", - imag_str.c_str()); - return Expression::make_error(imp->location()); - } - Expression* ret = Expression::make_complex(&real, &imag, NULL, - imp->location()); - mpfr_clear(real); - mpfr_clear(imag); - return ret; - } - else if (num.find('.') == std::string::npos - && num.find('E') == std::string::npos) - { - mpz_t val; - if (mpz_init_set_str(val, num.c_str(), 10) != 0) - { - error_at(imp->location(), "bad number in import data: %qs", - num.c_str()); - return Expression::make_error(imp->location()); - } - Expression* ret = Expression::make_integer(&val, NULL, imp->location()); - mpz_clear(val); - return ret; - } - else - { - mpfr_t val; - if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0) - { - error_at(imp->location(), "bad number in import data: %qs", - num.c_str()); - return Expression::make_error(imp->location()); - } - Expression* ret = Expression::make_float(&val, NULL, imp->location()); - mpfr_clear(val); - return ret; - } -} - -// Build a new integer value. - -Expression* -Expression::make_integer(const mpz_t* val, Type* type, - source_location location) -{ - return new Integer_expression(val, type, location); -} - -// Floats. - -class Float_expression : public Expression -{ - public: - Float_expression(const mpfr_t* val, Type* type, source_location location) - : Expression(EXPRESSION_FLOAT, location), - type_(type) - { - mpfr_init_set(this->val_, *val, GMP_RNDN); - } - - // Constrain VAL to fit into TYPE. - static void - constrain_float(mpfr_t val, Type* type); - - // Return whether VAL fits in the type. - static bool - check_constant(mpfr_t val, Type*, source_location); - - // Write VAL to export data. - static void - export_float(Export* exp, const mpfr_t val); - - protected: - bool - do_is_constant() const - { return true; } - - bool - do_float_constant_value(mpfr_t val, Type**) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { return Expression::make_float(&this->val_, this->type_, - this->location()); } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The floating point value. - mpfr_t val_; - // The type so far. - Type* type_; -}; - -// Constrain VAL to fit into TYPE. - -void -Float_expression::constrain_float(mpfr_t val, Type* type) -{ - Float_type* ftype = type->float_type(); - if (ftype != NULL && !ftype->is_abstract()) - mpfr_prec_round(val, ftype->bits(), GMP_RNDN); -} - -// Return a floating point constant value. - -bool -Float_expression::do_float_constant_value(mpfr_t val, Type** ptype) const -{ - if (this->type_ != NULL) - *ptype = this->type_; - mpfr_set(val, this->val_, GMP_RNDN); - return true; -} - -// Return the current type. If we haven't set the type yet, we return -// an abstract float type. - -Type* -Float_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_abstract_float_type(); - return this->type_; -} - -// Set the type of the float value. Here we may switch from an -// abstract type to a real type. - -void -Float_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL - && (context->type->integer_type() != NULL - || context->type->float_type() != NULL - || context->type->complex_type() != NULL)) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_float_type("float64"); -} - -// Return true if the floating point value VAL fits in the range of -// the type TYPE. Otherwise give an error and return false. TYPE may -// be NULL. - -bool -Float_expression::check_constant(mpfr_t val, Type* type, - source_location location) -{ - if (type == NULL) - return true; - Float_type* ftype = type->float_type(); - if (ftype == NULL || ftype->is_abstract()) - return true; - - // A NaN or Infinity always fits in the range of the type. - if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val)) - return true; - - mp_exp_t exp = mpfr_get_exp(val); - mp_exp_t max_exp; - switch (ftype->bits()) - { - case 32: - max_exp = 128; - break; - case 64: - max_exp = 1024; - break; - default: - go_unreachable(); - } - if (exp > max_exp) - { - error_at(location, "floating point constant overflow"); - return false; - } - return true; -} - -// Check the type of a float value. - -void -Float_expression::do_check_types(Gogo*) -{ - if (this->type_ == NULL) - return; - - if (!Float_expression::check_constant(this->val_, this->type_, - this->location())) - this->set_is_error(); - - Integer_type* integer_type = this->type_->integer_type(); - if (integer_type != NULL) - { - if (!mpfr_integer_p(this->val_)) - this->report_error(_("floating point constant truncated to integer")); - else - { - go_assert(!integer_type->is_abstract()); - mpz_t ival; - mpz_init(ival); - mpfr_get_z(ival, this->val_, GMP_RNDN); - Integer_expression::check_constant(ival, integer_type, - this->location()); - mpz_clear(ival); - } - } -} - -// Get a tree for a float constant. - -tree -Float_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type; - if (this->type_ != NULL && !this->type_->is_abstract()) - type = this->type_->get_tree(gogo); - else if (this->type_ != NULL && this->type_->integer_type() != NULL) - { - // We have an abstract integer type. We just hope for the best. - type = Type::lookup_integer_type("int")->get_tree(gogo); - } - else - { - // If we still have an abstract type here, then this is being - // used in a constant expression which didn't get reduced. We - // just use float64 and hope for the best. - type = Type::lookup_float_type("float64")->get_tree(gogo); - } - return Expression::float_constant_tree(this->val_, type); -} - -// Write a floating point number to export data. - -void -Float_expression::export_float(Export *exp, const mpfr_t val) -{ - mp_exp_t exponent; - char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN); - if (*s == '-') - exp->write_c_string("-"); - exp->write_c_string("0."); - exp->write_c_string(*s == '-' ? s + 1 : s); - mpfr_free_str(s); - char buf[30]; - snprintf(buf, sizeof buf, "E%ld", exponent); - exp->write_c_string(buf); -} - -// Export a floating point number in a constant expression. - -void -Float_expression::do_export(Export* exp) const -{ - Float_expression::export_float(exp, this->val_); - // A trailing space lets us reliably identify the end of the number. - exp->write_c_string(" "); -} - -// Make a float expression. - -Expression* -Expression::make_float(const mpfr_t* val, Type* type, source_location location) -{ - return new Float_expression(val, type, location); -} - -// Complex numbers. - -class Complex_expression : public Expression -{ - public: - Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type, - source_location location) - : Expression(EXPRESSION_COMPLEX, location), - type_(type) - { - mpfr_init_set(this->real_, *real, GMP_RNDN); - mpfr_init_set(this->imag_, *imag, GMP_RNDN); - } - - // Constrain REAL/IMAG to fit into TYPE. - static void - constrain_complex(mpfr_t real, mpfr_t imag, Type* type); - - // Return whether REAL/IMAG fits in the type. - static bool - check_constant(mpfr_t real, mpfr_t imag, Type*, source_location); - - // Write REAL/IMAG to export data. - static void - export_complex(Export* exp, const mpfr_t real, const mpfr_t val); - - protected: - bool - do_is_constant() const - { return true; } - - bool - do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return Expression::make_complex(&this->real_, &this->imag_, this->type_, - this->location()); - } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The real part. - mpfr_t real_; - // The imaginary part; - mpfr_t imag_; - // The type if known. - Type* type_; -}; - -// Constrain REAL/IMAG to fit into TYPE. - -void -Complex_expression::constrain_complex(mpfr_t real, mpfr_t imag, Type* type) -{ - Complex_type* ctype = type->complex_type(); - if (ctype != NULL && !ctype->is_abstract()) - { - mpfr_prec_round(real, ctype->bits() / 2, GMP_RNDN); - mpfr_prec_round(imag, ctype->bits() / 2, GMP_RNDN); - } -} - -// Return a complex constant value. - -bool -Complex_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - if (this->type_ != NULL) - *ptype = this->type_; - mpfr_set(real, this->real_, GMP_RNDN); - mpfr_set(imag, this->imag_, GMP_RNDN); - return true; -} - -// Return the current type. If we haven't set the type yet, we return -// an abstract complex type. - -Type* -Complex_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_abstract_complex_type(); - return this->type_; -} - -// Set the type of the complex value. Here we may switch from an -// abstract type to a real type. - -void -Complex_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL - && context->type->complex_type() != NULL) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_complex_type("complex128"); -} - -// Return true if the complex value REAL/IMAG fits in the range of the -// type TYPE. Otherwise give an error and return false. TYPE may be -// NULL. - -bool -Complex_expression::check_constant(mpfr_t real, mpfr_t imag, Type* type, - source_location location) -{ - if (type == NULL) - return true; - Complex_type* ctype = type->complex_type(); - if (ctype == NULL || ctype->is_abstract()) - return true; - - mp_exp_t max_exp; - switch (ctype->bits()) - { - case 64: - max_exp = 128; - break; - case 128: - max_exp = 1024; - break; - default: - go_unreachable(); - } - - // A NaN or Infinity always fits in the range of the type. - if (!mpfr_nan_p(real) && !mpfr_inf_p(real) && !mpfr_zero_p(real)) - { - if (mpfr_get_exp(real) > max_exp) - { - error_at(location, "complex real part constant overflow"); - return false; - } - } - - if (!mpfr_nan_p(imag) && !mpfr_inf_p(imag) && !mpfr_zero_p(imag)) - { - if (mpfr_get_exp(imag) > max_exp) - { - error_at(location, "complex imaginary part constant overflow"); - return false; - } - } - - return true; -} - -// Check the type of a complex value. - -void -Complex_expression::do_check_types(Gogo*) -{ - if (this->type_ == NULL) - return; - - if (!Complex_expression::check_constant(this->real_, this->imag_, - this->type_, this->location())) - this->set_is_error(); -} - -// Get a tree for a complex constant. - -tree -Complex_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type; - if (this->type_ != NULL && !this->type_->is_abstract()) - type = this->type_->get_tree(gogo); - else - { - // If we still have an abstract type here, this this is being - // used in a constant expression which didn't get reduced. We - // just use complex128 and hope for the best. - type = Type::lookup_complex_type("complex128")->get_tree(gogo); - } - return Expression::complex_constant_tree(this->real_, this->imag_, type); -} - -// Write REAL/IMAG to export data. - -void -Complex_expression::export_complex(Export* exp, const mpfr_t real, - const mpfr_t imag) -{ - if (!mpfr_zero_p(real)) - { - Float_expression::export_float(exp, real); - if (mpfr_sgn(imag) > 0) - exp->write_c_string("+"); - } - Float_expression::export_float(exp, imag); - exp->write_c_string("i"); -} - -// Export a complex number in a constant expression. - -void -Complex_expression::do_export(Export* exp) const -{ - Complex_expression::export_complex(exp, this->real_, this->imag_); - // A trailing space lets us reliably identify the end of the number. - exp->write_c_string(" "); -} - -// Make a complex expression. - -Expression* -Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type, - source_location location) -{ - return new Complex_expression(real, imag, type, location); -} - -// Find a named object in an expression. - -class Find_named_object : public Traverse -{ - public: - Find_named_object(Named_object* no) - : Traverse(traverse_expressions), - no_(no), found_(false) - { } - - // Whether we found the object. - bool - found() const - { return this->found_; } - - protected: - int - expression(Expression**); - - private: - // The object we are looking for. - Named_object* no_; - // Whether we found it. - bool found_; -}; - -// A reference to a const in an expression. - -class Const_expression : public Expression -{ - public: - Const_expression(Named_object* constant, source_location location) - : Expression(EXPRESSION_CONST_REFERENCE, location), - constant_(constant), type_(NULL), seen_(false) - { } - - Named_object* - named_object() - { return this->constant_; } - - // Check that the initializer does not refer to the constant itself. - void - check_for_init_loop(); - - protected: - int - do_traverse(Traverse*); - - Expression* - do_lower(Gogo*, Named_object*, int); - - bool - do_is_constant() const - { return true; } - - bool - do_integer_constant_value(bool, mpz_t val, Type**) const; - - bool - do_float_constant_value(mpfr_t val, Type**) const; - - bool - do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const; - - bool - do_string_constant_value(std::string* val) const - { return this->constant_->const_value()->expr()->string_constant_value(val); } - - Type* - do_type(); - - // The type of a const is set by the declaration, not the use. - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context* context); - - // When exporting a reference to a const as part of a const - // expression, we export the value. We ignore the fact that it has - // a name. - void - do_export(Export* exp) const - { this->constant_->const_value()->expr()->export_expression(exp); } - - private: - // The constant. - Named_object* constant_; - // The type of this reference. This is used if the constant has an - // abstract type. - Type* type_; - // Used to prevent infinite recursion when a constant incorrectly - // refers to itself. - mutable bool seen_; -}; - -// Traversal. - -int -Const_expression::do_traverse(Traverse* traverse) -{ - if (this->type_ != NULL) - return Type::traverse(this->type_, traverse); - return TRAVERSE_CONTINUE; -} - -// Lower a constant expression. This is where we convert the -// predeclared constant iota into an integer value. - -Expression* -Const_expression::do_lower(Gogo* gogo, Named_object*, int iota_value) -{ - if (this->constant_->const_value()->expr()->classification() - == EXPRESSION_IOTA) - { - if (iota_value == -1) - { - error_at(this->location(), - "iota is only defined in const declarations"); - iota_value = 0; - } - mpz_t val; - mpz_init_set_ui(val, static_cast(iota_value)); - Expression* ret = Expression::make_integer(&val, NULL, - this->location()); - mpz_clear(val); - return ret; - } - - // Make sure that the constant itself has been lowered. - gogo->lower_constant(this->constant_); - - return this; -} - -// Return an integer constant value. - -bool -Const_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val, - Type** ptype) const -{ - if (this->seen_) - return false; - - Type* ctype; - if (this->type_ != NULL) - ctype = this->type_; - else - ctype = this->constant_->const_value()->type(); - if (ctype != NULL && ctype->integer_type() == NULL) - return false; - - Expression* e = this->constant_->const_value()->expr(); - - this->seen_ = true; - - Type* t; - bool r = e->integer_constant_value(iota_is_constant, val, &t); - - this->seen_ = false; - - if (r - && ctype != NULL - && !Integer_expression::check_constant(val, ctype, this->location())) - return false; - - *ptype = ctype != NULL ? ctype : t; - return r; -} - -// Return a floating point constant value. - -bool -Const_expression::do_float_constant_value(mpfr_t val, Type** ptype) const -{ - if (this->seen_) - return false; - - Type* ctype; - if (this->type_ != NULL) - ctype = this->type_; - else - ctype = this->constant_->const_value()->type(); - if (ctype != NULL && ctype->float_type() == NULL) - return false; - - this->seen_ = true; - - Type* t; - bool r = this->constant_->const_value()->expr()->float_constant_value(val, - &t); - - this->seen_ = false; - - if (r && ctype != NULL) - { - if (!Float_expression::check_constant(val, ctype, this->location())) - return false; - Float_expression::constrain_float(val, ctype); - } - *ptype = ctype != NULL ? ctype : t; - return r; -} - -// Return a complex constant value. - -bool -Const_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type **ptype) const -{ - if (this->seen_) - return false; - - Type* ctype; - if (this->type_ != NULL) - ctype = this->type_; - else - ctype = this->constant_->const_value()->type(); - if (ctype != NULL && ctype->complex_type() == NULL) - return false; - - this->seen_ = true; - - Type *t; - bool r = this->constant_->const_value()->expr()->complex_constant_value(real, - imag, - &t); - - this->seen_ = false; - - if (r && ctype != NULL) - { - if (!Complex_expression::check_constant(real, imag, ctype, - this->location())) - return false; - Complex_expression::constrain_complex(real, imag, ctype); - } - *ptype = ctype != NULL ? ctype : t; - return r; -} - -// Return the type of the const reference. - -Type* -Const_expression::do_type() -{ - if (this->type_ != NULL) - return this->type_; - - Named_constant* nc = this->constant_->const_value(); - - if (this->seen_ || nc->lowering()) - { - this->report_error(_("constant refers to itself")); - this->type_ = Type::make_error_type(); - return this->type_; - } - - this->seen_ = true; - - Type* ret = nc->type(); - - if (ret != NULL) - { - this->seen_ = false; - return ret; - } - - // During parsing, a named constant may have a NULL type, but we - // must not return a NULL type here. - ret = nc->expr()->type(); - - this->seen_ = false; - - return ret; -} - -// Set the type of the const reference. - -void -Const_expression::do_determine_type(const Type_context* context) -{ - Type* ctype = this->constant_->const_value()->type(); - Type* cetype = (ctype != NULL - ? ctype - : this->constant_->const_value()->expr()->type()); - if (ctype != NULL && !ctype->is_abstract()) - ; - else if (context->type != NULL - && (context->type->integer_type() != NULL - || context->type->float_type() != NULL - || context->type->complex_type() != NULL) - && (cetype->integer_type() != NULL - || cetype->float_type() != NULL - || cetype->complex_type() != NULL)) - this->type_ = context->type; - else if (context->type != NULL - && context->type->is_string_type() - && cetype->is_string_type()) - this->type_ = context->type; - else if (context->type != NULL - && context->type->is_boolean_type() - && cetype->is_boolean_type()) - this->type_ = context->type; - else if (!context->may_be_abstract) - { - if (cetype->is_abstract()) - cetype = cetype->make_non_abstract_type(); - this->type_ = cetype; - } -} - -// Check for a loop in which the initializer of a constant refers to -// the constant itself. - -void -Const_expression::check_for_init_loop() -{ - if (this->type_ != NULL && this->type_->is_error()) - return; - - if (this->seen_) - { - this->report_error(_("constant refers to itself")); - this->type_ = Type::make_error_type(); - return; - } - - Expression* init = this->constant_->const_value()->expr(); - Find_named_object find_named_object(this->constant_); - - this->seen_ = true; - Expression::traverse(&init, &find_named_object); - this->seen_ = false; - - if (find_named_object.found()) - { - if (this->type_ == NULL || !this->type_->is_error()) - { - this->report_error(_("constant refers to itself")); - this->type_ = Type::make_error_type(); - } - return; - } -} - -// Check types of a const reference. - -void -Const_expression::do_check_types(Gogo*) -{ - if (this->type_ != NULL && this->type_->is_error()) - return; - - this->check_for_init_loop(); - - if (this->type_ == NULL || this->type_->is_abstract()) - return; - - // Check for integer overflow. - if (this->type_->integer_type() != NULL) - { - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (!this->integer_constant_value(true, ival, &dummy)) - { - mpfr_t fval; - mpfr_init(fval); - Expression* cexpr = this->constant_->const_value()->expr(); - if (cexpr->float_constant_value(fval, &dummy)) - { - if (!mpfr_integer_p(fval)) - this->report_error(_("floating point constant " - "truncated to integer")); - else - { - mpfr_get_z(ival, fval, GMP_RNDN); - Integer_expression::check_constant(ival, this->type_, - this->location()); - } - } - mpfr_clear(fval); - } - mpz_clear(ival); - } -} - -// Return a tree for the const reference. - -tree -Const_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type_tree; - if (this->type_ == NULL) - type_tree = NULL_TREE; - else - { - type_tree = this->type_->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - } - - // If the type has been set for this expression, but the underlying - // object is an abstract int or float, we try to get the abstract - // value. Otherwise we may lose something in the conversion. - if (this->type_ != NULL - && (this->constant_->const_value()->type() == NULL - || this->constant_->const_value()->type()->is_abstract())) - { - Expression* expr = this->constant_->const_value()->expr(); - mpz_t ival; - mpz_init(ival); - Type* t; - if (expr->integer_constant_value(true, ival, &t)) - { - tree ret = Expression::integer_constant_tree(ival, type_tree); - mpz_clear(ival); - return ret; - } - mpz_clear(ival); - - mpfr_t fval; - mpfr_init(fval); - if (expr->float_constant_value(fval, &t)) - { - tree ret = Expression::float_constant_tree(fval, type_tree); - mpfr_clear(fval); - return ret; - } - - mpfr_t imag; - mpfr_init(imag); - if (expr->complex_constant_value(fval, imag, &t)) - { - tree ret = Expression::complex_constant_tree(fval, imag, type_tree); - mpfr_clear(fval); - mpfr_clear(imag); - return ret; - } - mpfr_clear(imag); - mpfr_clear(fval); - } - - tree const_tree = this->constant_->get_tree(gogo, context->function()); - if (this->type_ == NULL - || const_tree == error_mark_node - || TREE_TYPE(const_tree) == error_mark_node) - return const_tree; - - tree ret; - if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree))) - ret = fold_convert(type_tree, const_tree); - else if (TREE_CODE(type_tree) == INTEGER_TYPE) - ret = fold(convert_to_integer(type_tree, const_tree)); - else if (TREE_CODE(type_tree) == REAL_TYPE) - ret = fold(convert_to_real(type_tree, const_tree)); - else if (TREE_CODE(type_tree) == COMPLEX_TYPE) - ret = fold(convert_to_complex(type_tree, const_tree)); - else - go_unreachable(); - return ret; -} - -// Make a reference to a constant in an expression. - -Expression* -Expression::make_const_reference(Named_object* constant, - source_location location) -{ - return new Const_expression(constant, location); -} - -// Find a named object in an expression. - -int -Find_named_object::expression(Expression** pexpr) -{ - switch ((*pexpr)->classification()) - { - case Expression::EXPRESSION_CONST_REFERENCE: - { - Const_expression* ce = static_cast(*pexpr); - if (ce->named_object() == this->no_) - break; - - // We need to check a constant initializer explicitly, as - // loops here will not be caught by the loop checking for - // variable initializers. - ce->check_for_init_loop(); - - return TRAVERSE_CONTINUE; - } - - case Expression::EXPRESSION_VAR_REFERENCE: - if ((*pexpr)->var_expression()->named_object() == this->no_) - break; - return TRAVERSE_CONTINUE; - case Expression::EXPRESSION_FUNC_REFERENCE: - if ((*pexpr)->func_expression()->named_object() == this->no_) - break; - return TRAVERSE_CONTINUE; - default: - return TRAVERSE_CONTINUE; - } - this->found_ = true; - return TRAVERSE_EXIT; -} - -// The nil value. - -class Nil_expression : public Expression -{ - public: - Nil_expression(source_location location) - : Expression(EXPRESSION_NIL, location) - { } - - static Expression* - do_import(Import*); - - protected: - bool - do_is_constant() const - { return true; } - - Type* - do_type() - { return Type::make_nil_type(); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context*) - { return null_pointer_node; } - - void - do_export(Export* exp) const - { exp->write_c_string("nil"); } -}; - -// Import a nil expression. - -Expression* -Nil_expression::do_import(Import* imp) -{ - imp->require_c_string("nil"); - return Expression::make_nil(imp->location()); -} - -// Make a nil expression. - -Expression* -Expression::make_nil(source_location location) -{ - return new Nil_expression(location); -} - -// The value of the predeclared constant iota. This is little more -// than a marker. This will be lowered to an integer in -// Const_expression::do_lower, which is where we know the value that -// it should have. - -class Iota_expression : public Parser_expression -{ - public: - Iota_expression(source_location location) - : Parser_expression(EXPRESSION_IOTA, location) - { } - - protected: - Expression* - do_lower(Gogo*, Named_object*, int) - { go_unreachable(); } - - // There should only ever be one of these. - Expression* - do_copy() - { go_unreachable(); } -}; - -// Make an iota expression. This is only called for one case: the -// value of the predeclared constant iota. - -Expression* -Expression::make_iota() -{ - static Iota_expression iota_expression(UNKNOWN_LOCATION); - return &iota_expression; -} - -// A type conversion expression. - -class Type_conversion_expression : public Expression -{ - public: - Type_conversion_expression(Type* type, Expression* expr, - source_location location) - : Expression(EXPRESSION_CONVERSION, location), - type_(type), expr_(expr), may_convert_function_types_(false) - { } - - // Return the type to which we are converting. - Type* - type() const - { return this->type_; } - - // Return the expression which we are converting. - Expression* - expr() const - { return this->expr_; } - - // Permit converting from one function type to another. This is - // used internally for method expressions. - void - set_may_convert_function_types() - { - this->may_convert_function_types_ = true; - } - - // Import a type conversion expression. - static Expression* - do_import(Import*); - - protected: - int - do_traverse(Traverse* traverse); - - Expression* - do_lower(Gogo*, Named_object*, int); - - bool - do_is_constant() const - { return this->expr_->is_constant(); } - - bool - do_integer_constant_value(bool, mpz_t, Type**) const; - - bool - do_float_constant_value(mpfr_t, Type**) const; - - bool - do_complex_constant_value(mpfr_t, mpfr_t, Type**) const; - - bool - do_string_constant_value(std::string*) const; - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*) - { - Type_context subcontext(this->type_, false); - this->expr_->determine_type(&subcontext); - } - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Type_conversion_expression(this->type_, this->expr_->copy(), - this->location()); - } - - tree - do_get_tree(Translate_context* context); - - void - do_export(Export*) const; - - private: - // The type to convert to. - Type* type_; - // The expression to convert. - Expression* expr_; - // True if this is permitted to convert function types. This is - // used internally for method expressions. - bool may_convert_function_types_; -}; - -// Traversal. - -int -Type_conversion_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT - || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Convert to a constant at lowering time. - -Expression* -Type_conversion_expression::do_lower(Gogo*, Named_object*, int) -{ - Type* type = this->type_; - Expression* val = this->expr_; - source_location location = this->location(); - - if (type->integer_type() != NULL) - { - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (val->integer_constant_value(false, ival, &dummy)) - { - if (!Integer_expression::check_constant(ival, type, location)) - mpz_set_ui(ival, 0); - Expression* ret = Expression::make_integer(&ival, type, location); - mpz_clear(ival); - return ret; - } - - mpfr_t fval; - mpfr_init(fval); - if (val->float_constant_value(fval, &dummy)) - { - if (!mpfr_integer_p(fval)) - { - error_at(location, - "floating point constant truncated to integer"); - return Expression::make_error(location); - } - mpfr_get_z(ival, fval, GMP_RNDN); - if (!Integer_expression::check_constant(ival, type, location)) - mpz_set_ui(ival, 0); - Expression* ret = Expression::make_integer(&ival, type, location); - mpfr_clear(fval); - mpz_clear(ival); - return ret; - } - mpfr_clear(fval); - mpz_clear(ival); - } - - if (type->float_type() != NULL) - { - mpfr_t fval; - mpfr_init(fval); - Type* dummy; - if (val->float_constant_value(fval, &dummy)) - { - if (!Float_expression::check_constant(fval, type, location)) - mpfr_set_ui(fval, 0, GMP_RNDN); - Float_expression::constrain_float(fval, type); - Expression *ret = Expression::make_float(&fval, type, location); - mpfr_clear(fval); - return ret; - } - mpfr_clear(fval); - } - - if (type->complex_type() != NULL) - { - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - Type* dummy; - if (val->complex_constant_value(real, imag, &dummy)) - { - if (!Complex_expression::check_constant(real, imag, type, location)) - { - mpfr_set_ui(real, 0, GMP_RNDN); - mpfr_set_ui(imag, 0, GMP_RNDN); - } - Complex_expression::constrain_complex(real, imag, type); - Expression* ret = Expression::make_complex(&real, &imag, type, - location); - mpfr_clear(real); - mpfr_clear(imag); - return ret; - } - mpfr_clear(real); - mpfr_clear(imag); - } - - if (type->is_open_array_type() && type->named_type() == NULL) - { - Type* element_type = type->array_type()->element_type()->forwarded(); - bool is_byte = element_type == Type::lookup_integer_type("uint8"); - bool is_int = element_type == Type::lookup_integer_type("int"); - if (is_byte || is_int) - { - std::string s; - if (val->string_constant_value(&s)) - { - Expression_list* vals = new Expression_list(); - if (is_byte) - { - for (std::string::const_iterator p = s.begin(); - p != s.end(); - p++) - { - mpz_t val; - mpz_init_set_ui(val, static_cast(*p)); - Expression* v = Expression::make_integer(&val, - element_type, - location); - vals->push_back(v); - mpz_clear(val); - } - } - else - { - const char *p = s.data(); - const char *pend = s.data() + s.length(); - while (p < pend) - { - unsigned int c; - int adv = Lex::fetch_char(p, &c); - if (adv == 0) - { - warning_at(this->location(), 0, - "invalid UTF-8 encoding"); - adv = 1; - } - p += adv; - mpz_t val; - mpz_init_set_ui(val, c); - Expression* v = Expression::make_integer(&val, - element_type, - location); - vals->push_back(v); - mpz_clear(val); - } - } - - return Expression::make_slice_composite_literal(type, vals, - location); - } - } - } - - return this; -} - -// Return the constant integer value if there is one. - -bool -Type_conversion_expression::do_integer_constant_value(bool iota_is_constant, - mpz_t val, - Type** ptype) const -{ - if (this->type_->integer_type() == NULL) - return false; - - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (this->expr_->integer_constant_value(iota_is_constant, ival, &dummy)) - { - if (!Integer_expression::check_constant(ival, this->type_, - this->location())) - { - mpz_clear(ival); - return false; - } - mpz_set(val, ival); - mpz_clear(ival); - *ptype = this->type_; - return true; - } - mpz_clear(ival); - - mpfr_t fval; - mpfr_init(fval); - if (this->expr_->float_constant_value(fval, &dummy)) - { - mpfr_get_z(val, fval, GMP_RNDN); - mpfr_clear(fval); - if (!Integer_expression::check_constant(val, this->type_, - this->location())) - return false; - *ptype = this->type_; - return true; - } - mpfr_clear(fval); - - return false; -} - -// Return the constant floating point value if there is one. - -bool -Type_conversion_expression::do_float_constant_value(mpfr_t val, - Type** ptype) const -{ - if (this->type_->float_type() == NULL) - return false; - - mpfr_t fval; - mpfr_init(fval); - Type* dummy; - if (this->expr_->float_constant_value(fval, &dummy)) - { - if (!Float_expression::check_constant(fval, this->type_, - this->location())) - { - mpfr_clear(fval); - return false; - } - mpfr_set(val, fval, GMP_RNDN); - mpfr_clear(fval); - Float_expression::constrain_float(val, this->type_); - *ptype = this->type_; - return true; - } - mpfr_clear(fval); - - return false; -} - -// Return the constant complex value if there is one. - -bool -Type_conversion_expression::do_complex_constant_value(mpfr_t real, - mpfr_t imag, - Type **ptype) const -{ - if (this->type_->complex_type() == NULL) - return false; - - mpfr_t rval; - mpfr_t ival; - mpfr_init(rval); - mpfr_init(ival); - Type* dummy; - if (this->expr_->complex_constant_value(rval, ival, &dummy)) - { - if (!Complex_expression::check_constant(rval, ival, this->type_, - this->location())) - { - mpfr_clear(rval); - mpfr_clear(ival); - return false; - } - mpfr_set(real, rval, GMP_RNDN); - mpfr_set(imag, ival, GMP_RNDN); - mpfr_clear(rval); - mpfr_clear(ival); - Complex_expression::constrain_complex(real, imag, this->type_); - *ptype = this->type_; - return true; - } - mpfr_clear(rval); - mpfr_clear(ival); - - return false; -} - -// Return the constant string value if there is one. - -bool -Type_conversion_expression::do_string_constant_value(std::string* val) const -{ - if (this->type_->is_string_type() - && this->expr_->type()->integer_type() != NULL) - { - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (this->expr_->integer_constant_value(false, ival, &dummy)) - { - unsigned long ulval = mpz_get_ui(ival); - if (mpz_cmp_ui(ival, ulval) == 0) - { - Lex::append_char(ulval, true, val, this->location()); - mpz_clear(ival); - return true; - } - } - mpz_clear(ival); - } - - // FIXME: Could handle conversion from const []int here. - - return false; -} - -// Check that types are convertible. - -void -Type_conversion_expression::do_check_types(Gogo*) -{ - Type* type = this->type_; - Type* expr_type = this->expr_->type(); - std::string reason; - - if (type->is_error() || expr_type->is_error()) - { - this->set_is_error(); - return; - } - - if (this->may_convert_function_types_ - && type->function_type() != NULL - && expr_type->function_type() != NULL) - return; - - if (Type::are_convertible(type, expr_type, &reason)) - return; - - error_at(this->location(), "%s", reason.c_str()); - this->set_is_error(); -} - -// Get a tree for a type conversion. - -tree -Type_conversion_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type_tree = this->type_->get_tree(gogo); - tree expr_tree = this->expr_->get_tree(context); - - if (type_tree == error_mark_node - || expr_tree == error_mark_node - || TREE_TYPE(expr_tree) == error_mark_node) - return error_mark_node; - - if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree))) - return fold_convert(type_tree, expr_tree); - - Type* type = this->type_; - Type* expr_type = this->expr_->type(); - tree ret; - if (type->interface_type() != NULL || expr_type->interface_type() != NULL) - ret = Expression::convert_for_assignment(context, type, expr_type, - expr_tree, this->location()); - else if (type->integer_type() != NULL) - { - if (expr_type->integer_type() != NULL - || expr_type->float_type() != NULL - || expr_type->is_unsafe_pointer_type()) - ret = fold(convert_to_integer(type_tree, expr_tree)); - else - go_unreachable(); - } - else if (type->float_type() != NULL) - { - if (expr_type->integer_type() != NULL - || expr_type->float_type() != NULL) - ret = fold(convert_to_real(type_tree, expr_tree)); - else - go_unreachable(); - } - else if (type->complex_type() != NULL) - { - if (expr_type->complex_type() != NULL) - ret = fold(convert_to_complex(type_tree, expr_tree)); - else - go_unreachable(); - } - else if (type->is_string_type() - && expr_type->integer_type() != NULL) - { - expr_tree = fold_convert(integer_type_node, expr_tree); - if (host_integerp(expr_tree, 0)) - { - HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0); - std::string s; - Lex::append_char(intval, true, &s, this->location()); - Expression* se = Expression::make_string(s, this->location()); - return se->get_tree(context); - } - - static tree int_to_string_fndecl; - ret = Gogo::call_builtin(&int_to_string_fndecl, - this->location(), - "__go_int_to_string", - 1, - type_tree, - integer_type_node, - fold_convert(integer_type_node, expr_tree)); - } - else if (type->is_string_type() - && (expr_type->array_type() != NULL - || (expr_type->points_to() != NULL - && expr_type->points_to()->array_type() != NULL))) - { - Type* t = expr_type; - if (t->points_to() != NULL) - { - t = t->points_to(); - expr_tree = build_fold_indirect_ref(expr_tree); - } - if (!DECL_P(expr_tree)) - expr_tree = save_expr(expr_tree); - Array_type* a = t->array_type(); - Type* e = a->element_type()->forwarded(); - go_assert(e->integer_type() != NULL); - tree valptr = fold_convert(const_ptr_type_node, - a->value_pointer_tree(gogo, expr_tree)); - tree len = a->length_tree(gogo, expr_tree); - len = fold_convert_loc(this->location(), integer_type_node, len); - if (e->integer_type()->is_unsigned() - && e->integer_type()->bits() == 8) - { - static tree byte_array_to_string_fndecl; - ret = Gogo::call_builtin(&byte_array_to_string_fndecl, - this->location(), - "__go_byte_array_to_string", - 2, - type_tree, - const_ptr_type_node, - valptr, - integer_type_node, - len); - } - else - { - go_assert(e == Type::lookup_integer_type("int")); - static tree int_array_to_string_fndecl; - ret = Gogo::call_builtin(&int_array_to_string_fndecl, - this->location(), - "__go_int_array_to_string", - 2, - type_tree, - const_ptr_type_node, - valptr, - integer_type_node, - len); - } - } - else if (type->is_open_array_type() && expr_type->is_string_type()) - { - Type* e = type->array_type()->element_type()->forwarded(); - go_assert(e->integer_type() != NULL); - if (e->integer_type()->is_unsigned() - && e->integer_type()->bits() == 8) - { - static tree string_to_byte_array_fndecl; - ret = Gogo::call_builtin(&string_to_byte_array_fndecl, - this->location(), - "__go_string_to_byte_array", - 1, - type_tree, - TREE_TYPE(expr_tree), - expr_tree); - } - else - { - go_assert(e == Type::lookup_integer_type("int")); - static tree string_to_int_array_fndecl; - ret = Gogo::call_builtin(&string_to_int_array_fndecl, - this->location(), - "__go_string_to_int_array", - 1, - type_tree, - TREE_TYPE(expr_tree), - expr_tree); - } - } - else if ((type->is_unsafe_pointer_type() - && expr_type->points_to() != NULL) - || (expr_type->is_unsafe_pointer_type() - && type->points_to() != NULL)) - ret = fold_convert(type_tree, expr_tree); - else if (type->is_unsafe_pointer_type() - && expr_type->integer_type() != NULL) - ret = convert_to_pointer(type_tree, expr_tree); - else if (this->may_convert_function_types_ - && type->function_type() != NULL - && expr_type->function_type() != NULL) - ret = fold_convert_loc(this->location(), type_tree, expr_tree); - else - ret = Expression::convert_for_assignment(context, type, expr_type, - expr_tree, this->location()); - - return ret; -} - -// Output a type conversion in a constant expression. - -void -Type_conversion_expression::do_export(Export* exp) const -{ - exp->write_c_string("convert("); - exp->write_type(this->type_); - exp->write_c_string(", "); - this->expr_->export_expression(exp); - exp->write_c_string(")"); -} - -// Import a type conversion or a struct construction. - -Expression* -Type_conversion_expression::do_import(Import* imp) -{ - imp->require_c_string("convert("); - Type* type = imp->read_type(); - imp->require_c_string(", "); - Expression* val = Expression::import_expression(imp); - imp->require_c_string(")"); - return Expression::make_cast(type, val, imp->location()); -} - -// Make a type cast expression. - -Expression* -Expression::make_cast(Type* type, Expression* val, source_location location) -{ - if (type->is_error_type() || val->is_error_expression()) - return Expression::make_error(location); - return new Type_conversion_expression(type, val, location); -} - -// An unsafe type conversion, used to pass values to builtin functions. - -class Unsafe_type_conversion_expression : public Expression -{ - public: - Unsafe_type_conversion_expression(Type* type, Expression* expr, - source_location location) - : Expression(EXPRESSION_UNSAFE_CONVERSION, location), - type_(type), expr_(expr) - { } - - protected: - int - do_traverse(Traverse* traverse); - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { - return new Unsafe_type_conversion_expression(this->type_, - this->expr_->copy(), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - private: - // The type to convert to. - Type* type_; - // The expression to convert. - Expression* expr_; -}; - -// Traversal. - -int -Unsafe_type_conversion_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT - || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Convert to backend representation. - -tree -Unsafe_type_conversion_expression::do_get_tree(Translate_context* context) -{ - // We are only called for a limited number of cases. - - Type* t = this->type_; - Type* et = this->expr_->type(); - - tree type_tree = this->type_->get_tree(context->gogo()); - tree expr_tree = this->expr_->get_tree(context); - if (type_tree == error_mark_node || expr_tree == error_mark_node) - return error_mark_node; - - source_location loc = this->location(); - - bool use_view_convert = false; - if (t->is_open_array_type()) - { - go_assert(et->is_open_array_type()); - use_view_convert = true; - } - else if (t->map_type() != NULL) - go_assert(et->map_type() != NULL); - else if (t->channel_type() != NULL) - go_assert(et->channel_type() != NULL); - else if (t->points_to() != NULL && t->points_to()->channel_type() != NULL) - go_assert((et->points_to() != NULL - && et->points_to()->channel_type() != NULL) - || et->is_nil_type()); - else if (t->is_unsafe_pointer_type()) - go_assert(et->points_to() != NULL || et->is_nil_type()); - else if (et->is_unsafe_pointer_type()) - go_assert(t->points_to() != NULL); - else if (t->interface_type() != NULL && !t->interface_type()->is_empty()) - { - go_assert(et->interface_type() != NULL - && !et->interface_type()->is_empty()); - use_view_convert = true; - } - else if (t->interface_type() != NULL && t->interface_type()->is_empty()) - { - go_assert(et->interface_type() != NULL - && et->interface_type()->is_empty()); - use_view_convert = true; - } - else if (t->integer_type() != NULL) - { - go_assert(et->is_boolean_type() - || et->integer_type() != NULL - || et->function_type() != NULL - || et->points_to() != NULL - || et->map_type() != NULL - || et->channel_type() != NULL); - return convert_to_integer(type_tree, expr_tree); - } - else - go_unreachable(); - - if (use_view_convert) - return fold_build1_loc(loc, VIEW_CONVERT_EXPR, type_tree, expr_tree); - else - return fold_convert_loc(loc, type_tree, expr_tree); -} - -// Make an unsafe type conversion expression. - -Expression* -Expression::make_unsafe_cast(Type* type, Expression* expr, - source_location location) -{ - return new Unsafe_type_conversion_expression(type, expr, location); -} - -// Unary expressions. - -class Unary_expression : public Expression -{ - public: - Unary_expression(Operator op, Expression* expr, source_location location) - : Expression(EXPRESSION_UNARY, location), - op_(op), escapes_(true), expr_(expr) - { } - - // Return the operator. - Operator - op() const - { return this->op_; } - - // Return the operand. - Expression* - operand() const - { return this->expr_; } - - // Record that an address expression does not escape. - void - set_does_not_escape() - { - go_assert(this->op_ == OPERATOR_AND); - this->escapes_ = false; - } - - // Apply unary opcode OP to UVAL, setting VAL. Return true if this - // could be done, false if not. - static bool - eval_integer(Operator op, Type* utype, mpz_t uval, mpz_t val, - source_location); - - // Apply unary opcode OP to UVAL, setting VAL. Return true if this - // could be done, false if not. - static bool - eval_float(Operator op, mpfr_t uval, mpfr_t val); - - // Apply unary opcode OP to UREAL/UIMAG, setting REAL/IMAG. Return - // true if this could be done, false if not. - static bool - eval_complex(Operator op, mpfr_t ureal, mpfr_t uimag, mpfr_t real, - mpfr_t imag); - - static Expression* - do_import(Import*); - - protected: - int - do_traverse(Traverse* traverse) - { return Expression::traverse(&this->expr_, traverse); } - - Expression* - do_lower(Gogo*, Named_object*, int); - - bool - do_is_constant() const; - - bool - do_integer_constant_value(bool, mpz_t, Type**) const; - - bool - do_float_constant_value(mpfr_t, Type**) const; - - bool - do_complex_constant_value(mpfr_t, mpfr_t, Type**) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return Expression::make_unary(this->op_, this->expr_->copy(), - this->location()); - } - - bool - do_is_addressable() const - { return this->op_ == OPERATOR_MULT; } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The unary operator to apply. - Operator op_; - // Normally true. False if this is an address expression which does - // not escape the current function. - bool escapes_; - // The operand. - Expression* expr_; -}; - -// If we are taking the address of a composite literal, and the -// contents are not constant, then we want to make a heap composite -// instead. - -Expression* -Unary_expression::do_lower(Gogo*, Named_object*, int) -{ - source_location loc = this->location(); - Operator op = this->op_; - Expression* expr = this->expr_; - - if (op == OPERATOR_MULT && expr->is_type_expression()) - return Expression::make_type(Type::make_pointer_type(expr->type()), loc); - - // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require - // moving x to the heap. FIXME: Is it worth doing a real escape - // analysis here? This case is found in math/unsafe.go and is - // therefore worth special casing. - if (op == OPERATOR_MULT) - { - Expression* e = expr; - while (e->classification() == EXPRESSION_CONVERSION) - { - Type_conversion_expression* te - = static_cast(e); - e = te->expr(); - } - - if (e->classification() == EXPRESSION_UNARY) - { - Unary_expression* ue = static_cast(e); - if (ue->op_ == OPERATOR_AND) - { - if (e == expr) - { - // *&x == x. - return ue->expr_; - } - ue->set_does_not_escape(); - } - } - } - - // Catching an invalid indirection of unsafe.Pointer here avoid - // having to deal with TYPE_VOID in other places. - if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type()) - { - error_at(this->location(), "invalid indirect of %"); - return Expression::make_error(this->location()); - } - - if (op == OPERATOR_PLUS || op == OPERATOR_MINUS - || op == OPERATOR_NOT || op == OPERATOR_XOR) - { - Expression* ret = NULL; - - mpz_t eval; - mpz_init(eval); - Type* etype; - if (expr->integer_constant_value(false, eval, &etype)) - { - mpz_t val; - mpz_init(val); - if (Unary_expression::eval_integer(op, etype, eval, val, loc)) - ret = Expression::make_integer(&val, etype, loc); - mpz_clear(val); - } - mpz_clear(eval); - if (ret != NULL) - return ret; - - if (op == OPERATOR_PLUS || op == OPERATOR_MINUS) - { - mpfr_t fval; - mpfr_init(fval); - Type* ftype; - if (expr->float_constant_value(fval, &ftype)) - { - mpfr_t val; - mpfr_init(val); - if (Unary_expression::eval_float(op, fval, val)) - ret = Expression::make_float(&val, ftype, loc); - mpfr_clear(val); - } - if (ret != NULL) - { - mpfr_clear(fval); - return ret; - } - - mpfr_t ival; - mpfr_init(ival); - if (expr->complex_constant_value(fval, ival, &ftype)) - { - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - if (Unary_expression::eval_complex(op, fval, ival, real, imag)) - ret = Expression::make_complex(&real, &imag, ftype, loc); - mpfr_clear(real); - mpfr_clear(imag); - } - mpfr_clear(ival); - mpfr_clear(fval); - if (ret != NULL) - return ret; - } - } - - return this; -} - -// Return whether a unary expression is a constant. - -bool -Unary_expression::do_is_constant() const -{ - if (this->op_ == OPERATOR_MULT) - { - // Indirecting through a pointer is only constant if the object - // to which the expression points is constant, but we currently - // have no way to determine that. - return false; - } - else if (this->op_ == OPERATOR_AND) - { - // Taking the address of a variable is constant if it is a - // global variable, not constant otherwise. In other cases - // taking the address is probably not a constant. - Var_expression* ve = this->expr_->var_expression(); - if (ve != NULL) - { - Named_object* no = ve->named_object(); - return no->is_variable() && no->var_value()->is_global(); - } - return false; - } - else - return this->expr_->is_constant(); -} - -// Apply unary opcode OP to UVAL, setting VAL. UTYPE is the type of -// UVAL, if known; it may be NULL. Return true if this could be done, -// false if not. - -bool -Unary_expression::eval_integer(Operator op, Type* utype, mpz_t uval, mpz_t val, - source_location location) -{ - switch (op) - { - case OPERATOR_PLUS: - mpz_set(val, uval); - return true; - case OPERATOR_MINUS: - mpz_neg(val, uval); - return Integer_expression::check_constant(val, utype, location); - case OPERATOR_NOT: - mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0); - return true; - case OPERATOR_XOR: - if (utype == NULL - || utype->integer_type() == NULL - || utype->integer_type()->is_abstract()) - mpz_com(val, uval); - else - { - // The number of HOST_WIDE_INTs that it takes to represent - // UVAL. - size_t count = ((mpz_sizeinbase(uval, 2) - + HOST_BITS_PER_WIDE_INT - - 1) - / HOST_BITS_PER_WIDE_INT); - - unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count]; - memset(phwi, 0, count * sizeof(HOST_WIDE_INT)); - - size_t ecount; - mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval); - go_assert(ecount <= count); - - // Trim down to the number of words required by the type. - size_t obits = utype->integer_type()->bits(); - if (!utype->integer_type()->is_unsigned()) - ++obits; - size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1) - / HOST_BITS_PER_WIDE_INT); - go_assert(ocount <= count); - - for (size_t i = 0; i < ocount; ++i) - phwi[i] = ~phwi[i]; - - size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits; - if (clearbits != 0) - phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1) - >> clearbits); - - mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi); - - delete[] phwi; - } - return Integer_expression::check_constant(val, utype, location); - case OPERATOR_AND: - case OPERATOR_MULT: - return false; - default: - go_unreachable(); - } -} - -// Apply unary opcode OP to UVAL, setting VAL. Return true if this -// could be done, false if not. - -bool -Unary_expression::eval_float(Operator op, mpfr_t uval, mpfr_t val) -{ - switch (op) - { - case OPERATOR_PLUS: - mpfr_set(val, uval, GMP_RNDN); - return true; - case OPERATOR_MINUS: - mpfr_neg(val, uval, GMP_RNDN); - return true; - case OPERATOR_NOT: - case OPERATOR_XOR: - case OPERATOR_AND: - case OPERATOR_MULT: - return false; - default: - go_unreachable(); - } -} - -// Apply unary opcode OP to RVAL/IVAL, setting REAL/IMAG. Return true -// if this could be done, false if not. - -bool -Unary_expression::eval_complex(Operator op, mpfr_t rval, mpfr_t ival, - mpfr_t real, mpfr_t imag) -{ - switch (op) - { - case OPERATOR_PLUS: - mpfr_set(real, rval, GMP_RNDN); - mpfr_set(imag, ival, GMP_RNDN); - return true; - case OPERATOR_MINUS: - mpfr_neg(real, rval, GMP_RNDN); - mpfr_neg(imag, ival, GMP_RNDN); - return true; - case OPERATOR_NOT: - case OPERATOR_XOR: - case OPERATOR_AND: - case OPERATOR_MULT: - return false; - default: - go_unreachable(); - } -} - -// Return the integral constant value of a unary expression, if it has one. - -bool -Unary_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val, - Type** ptype) const -{ - mpz_t uval; - mpz_init(uval); - bool ret; - if (!this->expr_->integer_constant_value(iota_is_constant, uval, ptype)) - ret = false; - else - ret = Unary_expression::eval_integer(this->op_, *ptype, uval, val, - this->location()); - mpz_clear(uval); - return ret; -} - -// Return the floating point constant value of a unary expression, if -// it has one. - -bool -Unary_expression::do_float_constant_value(mpfr_t val, Type** ptype) const -{ - mpfr_t uval; - mpfr_init(uval); - bool ret; - if (!this->expr_->float_constant_value(uval, ptype)) - ret = false; - else - ret = Unary_expression::eval_float(this->op_, uval, val); - mpfr_clear(uval); - return ret; -} - -// Return the complex constant value of a unary expression, if it has -// one. - -bool -Unary_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - mpfr_t rval; - mpfr_t ival; - mpfr_init(rval); - mpfr_init(ival); - bool ret; - if (!this->expr_->complex_constant_value(rval, ival, ptype)) - ret = false; - else - ret = Unary_expression::eval_complex(this->op_, rval, ival, real, imag); - mpfr_clear(rval); - mpfr_clear(ival); - return ret; -} - -// Return the type of a unary expression. - -Type* -Unary_expression::do_type() -{ - switch (this->op_) - { - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_NOT: - case OPERATOR_XOR: - return this->expr_->type(); - - case OPERATOR_AND: - return Type::make_pointer_type(this->expr_->type()); - - case OPERATOR_MULT: - { - Type* subtype = this->expr_->type(); - Type* points_to = subtype->points_to(); - if (points_to == NULL) - return Type::make_error_type(); - return points_to; - } - - default: - go_unreachable(); - } -} - -// Determine abstract types for a unary expression. - -void -Unary_expression::do_determine_type(const Type_context* context) -{ - switch (this->op_) - { - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_NOT: - case OPERATOR_XOR: - this->expr_->determine_type(context); - break; - - case OPERATOR_AND: - // Taking the address of something. - { - Type* subtype = (context->type == NULL - ? NULL - : context->type->points_to()); - Type_context subcontext(subtype, false); - this->expr_->determine_type(&subcontext); - } - break; - - case OPERATOR_MULT: - // Indirecting through a pointer. - { - Type* subtype = (context->type == NULL - ? NULL - : Type::make_pointer_type(context->type)); - Type_context subcontext(subtype, false); - this->expr_->determine_type(&subcontext); - } - break; - - default: - go_unreachable(); - } -} - -// Check types for a unary expression. - -void -Unary_expression::do_check_types(Gogo*) -{ - Type* type = this->expr_->type(); - if (type->is_error()) - { - this->set_is_error(); - return; - } - - switch (this->op_) - { - case OPERATOR_PLUS: - case OPERATOR_MINUS: - if (type->integer_type() == NULL - && type->float_type() == NULL - && type->complex_type() == NULL) - this->report_error(_("expected numeric type")); - break; - - case OPERATOR_NOT: - case OPERATOR_XOR: - if (type->integer_type() == NULL - && !type->is_boolean_type()) - this->report_error(_("expected integer or boolean type")); - break; - - case OPERATOR_AND: - if (!this->expr_->is_addressable()) - this->report_error(_("invalid operand for unary %<&%>")); - else - this->expr_->address_taken(this->escapes_); - break; - - case OPERATOR_MULT: - // Indirecting through a pointer. - if (type->points_to() == NULL) - this->report_error(_("expected pointer")); - break; - - default: - go_unreachable(); - } -} - -// Get a tree for a unary expression. - -tree -Unary_expression::do_get_tree(Translate_context* context) -{ - tree expr = this->expr_->get_tree(context); - if (expr == error_mark_node) - return error_mark_node; - - source_location loc = this->location(); - switch (this->op_) - { - case OPERATOR_PLUS: - return expr; - - case OPERATOR_MINUS: - { - tree type = TREE_TYPE(expr); - tree compute_type = excess_precision_type(type); - if (compute_type != NULL_TREE) - expr = ::convert(compute_type, expr); - tree ret = fold_build1_loc(loc, NEGATE_EXPR, - (compute_type != NULL_TREE - ? compute_type - : type), - expr); - if (compute_type != NULL_TREE) - ret = ::convert(type, ret); - return ret; - } - - case OPERATOR_NOT: - if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE) - return fold_build1_loc(loc, TRUTH_NOT_EXPR, TREE_TYPE(expr), expr); - else - return fold_build2_loc(loc, NE_EXPR, boolean_type_node, expr, - build_int_cst(TREE_TYPE(expr), 0)); - - case OPERATOR_XOR: - return fold_build1_loc(loc, BIT_NOT_EXPR, TREE_TYPE(expr), expr); - - case OPERATOR_AND: - // We should not see a non-constant constructor here; cases - // where we would see one should have been moved onto the heap - // at parse time. Taking the address of a nonconstant - // constructor will not do what the programmer expects. - go_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr)); - go_assert(TREE_CODE(expr) != ADDR_EXPR); - - // Build a decl for a constant constructor. - if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr)) - { - tree decl = build_decl(this->location(), VAR_DECL, - create_tmp_var_name("C"), TREE_TYPE(expr)); - DECL_EXTERNAL(decl) = 0; - TREE_PUBLIC(decl) = 0; - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - TREE_STATIC(decl) = 1; - TREE_ADDRESSABLE(decl) = 1; - DECL_ARTIFICIAL(decl) = 1; - DECL_INITIAL(decl) = expr; - rest_of_decl_compilation(decl, 1, 0); - expr = decl; - } - - return build_fold_addr_expr_loc(loc, expr); - - case OPERATOR_MULT: - { - go_assert(POINTER_TYPE_P(TREE_TYPE(expr))); - - // If we are dereferencing the pointer to a large struct, we - // need to check for nil. We don't bother to check for small - // structs because we expect the system to crash on a nil - // pointer dereference. - HOST_WIDE_INT s = int_size_in_bytes(TREE_TYPE(TREE_TYPE(expr))); - if (s == -1 || s >= 4096) - { - if (!DECL_P(expr)) - expr = save_expr(expr); - tree compare = fold_build2_loc(loc, EQ_EXPR, boolean_type_node, - expr, - fold_convert(TREE_TYPE(expr), - null_pointer_node)); - tree crash = Gogo::runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, - loc); - expr = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(expr), - build3(COND_EXPR, void_type_node, - compare, crash, NULL_TREE), - expr); - } - - // If the type of EXPR is a recursive pointer type, then we - // need to insert a cast before indirecting. - if (TREE_TYPE(TREE_TYPE(expr)) == ptr_type_node) - { - Type* pt = this->expr_->type()->points_to(); - tree ind = pt->get_tree(context->gogo()); - expr = fold_convert_loc(loc, build_pointer_type(ind), expr); - } - - return build_fold_indirect_ref_loc(loc, expr); - } - - default: - go_unreachable(); - } -} - -// Export a unary expression. - -void -Unary_expression::do_export(Export* exp) const -{ - switch (this->op_) - { - case OPERATOR_PLUS: - exp->write_c_string("+ "); - break; - case OPERATOR_MINUS: - exp->write_c_string("- "); - break; - case OPERATOR_NOT: - exp->write_c_string("! "); - break; - case OPERATOR_XOR: - exp->write_c_string("^ "); - break; - case OPERATOR_AND: - case OPERATOR_MULT: - default: - go_unreachable(); - } - this->expr_->export_expression(exp); -} - -// Import a unary expression. - -Expression* -Unary_expression::do_import(Import* imp) -{ - Operator op; - switch (imp->get_char()) - { - case '+': - op = OPERATOR_PLUS; - break; - case '-': - op = OPERATOR_MINUS; - break; - case '!': - op = OPERATOR_NOT; - break; - case '^': - op = OPERATOR_XOR; - break; - default: - go_unreachable(); - } - imp->require_c_string(" "); - Expression* expr = Expression::import_expression(imp); - return Expression::make_unary(op, expr, imp->location()); -} - -// Make a unary expression. - -Expression* -Expression::make_unary(Operator op, Expression* expr, source_location location) -{ - return new Unary_expression(op, expr, location); -} - -// If this is an indirection through a pointer, return the expression -// being pointed through. Otherwise return this. - -Expression* -Expression::deref() -{ - if (this->classification_ == EXPRESSION_UNARY) - { - Unary_expression* ue = static_cast(this); - if (ue->op() == OPERATOR_MULT) - return ue->operand(); - } - return this; -} - -// Class Binary_expression. - -// Traversal. - -int -Binary_expression::do_traverse(Traverse* traverse) -{ - int t = Expression::traverse(&this->left_, traverse); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return Expression::traverse(&this->right_, traverse); -} - -// Compare integer constants according to OP. - -bool -Binary_expression::compare_integer(Operator op, mpz_t left_val, - mpz_t right_val) -{ - int i = mpz_cmp(left_val, right_val); - switch (op) - { - case OPERATOR_EQEQ: - return i == 0; - case OPERATOR_NOTEQ: - return i != 0; - case OPERATOR_LT: - return i < 0; - case OPERATOR_LE: - return i <= 0; - case OPERATOR_GT: - return i > 0; - case OPERATOR_GE: - return i >= 0; - default: - go_unreachable(); - } -} - -// Compare floating point constants according to OP. - -bool -Binary_expression::compare_float(Operator op, Type* type, mpfr_t left_val, - mpfr_t right_val) -{ - int i; - if (type == NULL) - i = mpfr_cmp(left_val, right_val); - else - { - mpfr_t lv; - mpfr_init_set(lv, left_val, GMP_RNDN); - mpfr_t rv; - mpfr_init_set(rv, right_val, GMP_RNDN); - Float_expression::constrain_float(lv, type); - Float_expression::constrain_float(rv, type); - i = mpfr_cmp(lv, rv); - mpfr_clear(lv); - mpfr_clear(rv); - } - switch (op) - { - case OPERATOR_EQEQ: - return i == 0; - case OPERATOR_NOTEQ: - return i != 0; - case OPERATOR_LT: - return i < 0; - case OPERATOR_LE: - return i <= 0; - case OPERATOR_GT: - return i > 0; - case OPERATOR_GE: - return i >= 0; - default: - go_unreachable(); - } -} - -// Compare complex constants according to OP. Complex numbers may -// only be compared for equality. - -bool -Binary_expression::compare_complex(Operator op, Type* type, - mpfr_t left_real, mpfr_t left_imag, - mpfr_t right_real, mpfr_t right_imag) -{ - bool is_equal; - if (type == NULL) - is_equal = (mpfr_cmp(left_real, right_real) == 0 - && mpfr_cmp(left_imag, right_imag) == 0); - else - { - mpfr_t lr; - mpfr_t li; - mpfr_init_set(lr, left_real, GMP_RNDN); - mpfr_init_set(li, left_imag, GMP_RNDN); - mpfr_t rr; - mpfr_t ri; - mpfr_init_set(rr, right_real, GMP_RNDN); - mpfr_init_set(ri, right_imag, GMP_RNDN); - Complex_expression::constrain_complex(lr, li, type); - Complex_expression::constrain_complex(rr, ri, type); - is_equal = mpfr_cmp(lr, rr) == 0 && mpfr_cmp(li, ri) == 0; - mpfr_clear(lr); - mpfr_clear(li); - mpfr_clear(rr); - mpfr_clear(ri); - } - switch (op) - { - case OPERATOR_EQEQ: - return is_equal; - case OPERATOR_NOTEQ: - return !is_equal; - default: - go_unreachable(); - } -} - -// Apply binary opcode OP to LEFT_VAL and RIGHT_VAL, setting VAL. -// LEFT_TYPE is the type of LEFT_VAL, RIGHT_TYPE is the type of -// RIGHT_VAL; LEFT_TYPE and/or RIGHT_TYPE may be NULL. Return true if -// this could be done, false if not. - -bool -Binary_expression::eval_integer(Operator op, Type* left_type, mpz_t left_val, - Type* right_type, mpz_t right_val, - source_location location, mpz_t val) -{ - bool is_shift_op = false; - switch (op) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - // These return boolean values. We should probably handle them - // anyhow in case a type conversion is used on the result. - return false; - case OPERATOR_PLUS: - mpz_add(val, left_val, right_val); - break; - case OPERATOR_MINUS: - mpz_sub(val, left_val, right_val); - break; - case OPERATOR_OR: - mpz_ior(val, left_val, right_val); - break; - case OPERATOR_XOR: - mpz_xor(val, left_val, right_val); - break; - case OPERATOR_MULT: - mpz_mul(val, left_val, right_val); - break; - case OPERATOR_DIV: - if (mpz_sgn(right_val) != 0) - mpz_tdiv_q(val, left_val, right_val); - else - { - error_at(location, "division by zero"); - mpz_set_ui(val, 0); - return true; - } - break; - case OPERATOR_MOD: - if (mpz_sgn(right_val) != 0) - mpz_tdiv_r(val, left_val, right_val); - else - { - error_at(location, "division by zero"); - mpz_set_ui(val, 0); - return true; - } - break; - case OPERATOR_LSHIFT: - { - unsigned long shift = mpz_get_ui(right_val); - if (mpz_cmp_ui(right_val, shift) != 0 || shift > 0x100000) - { - error_at(location, "shift count overflow"); - mpz_set_ui(val, 0); - return true; - } - mpz_mul_2exp(val, left_val, shift); - is_shift_op = true; - break; - } - break; - case OPERATOR_RSHIFT: - { - unsigned long shift = mpz_get_ui(right_val); - if (mpz_cmp_ui(right_val, shift) != 0) - { - error_at(location, "shift count overflow"); - mpz_set_ui(val, 0); - return true; - } - if (mpz_cmp_ui(left_val, 0) >= 0) - mpz_tdiv_q_2exp(val, left_val, shift); - else - mpz_fdiv_q_2exp(val, left_val, shift); - is_shift_op = true; - break; - } - break; - case OPERATOR_AND: - mpz_and(val, left_val, right_val); - break; - case OPERATOR_BITCLEAR: - { - mpz_t tval; - mpz_init(tval); - mpz_com(tval, right_val); - mpz_and(val, left_val, tval); - mpz_clear(tval); - } - break; - default: - go_unreachable(); - } - - Type* type = left_type; - if (!is_shift_op) - { - if (type == NULL) - type = right_type; - else if (type != right_type && right_type != NULL) - { - if (type->is_abstract()) - type = right_type; - else if (!right_type->is_abstract()) - { - // This look like a type error which should be diagnosed - // elsewhere. Don't do anything here, to avoid an - // unhelpful chain of error messages. - return true; - } - } - } - - if (type != NULL && !type->is_abstract()) - { - // We have to check the operands too, as we have implicitly - // coerced them to TYPE. - if ((type != left_type - && !Integer_expression::check_constant(left_val, type, location)) - || (!is_shift_op - && type != right_type - && !Integer_expression::check_constant(right_val, type, - location)) - || !Integer_expression::check_constant(val, type, location)) - mpz_set_ui(val, 0); - } - - return true; -} - -// Apply binary opcode OP to LEFT_VAL and RIGHT_VAL, setting VAL. -// Return true if this could be done, false if not. - -bool -Binary_expression::eval_float(Operator op, Type* left_type, mpfr_t left_val, - Type* right_type, mpfr_t right_val, - mpfr_t val, source_location location) -{ - switch (op) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - // These return boolean values. We should probably handle them - // anyhow in case a type conversion is used on the result. - return false; - case OPERATOR_PLUS: - mpfr_add(val, left_val, right_val, GMP_RNDN); - break; - case OPERATOR_MINUS: - mpfr_sub(val, left_val, right_val, GMP_RNDN); - break; - case OPERATOR_OR: - case OPERATOR_XOR: - case OPERATOR_AND: - case OPERATOR_BITCLEAR: - return false; - case OPERATOR_MULT: - mpfr_mul(val, left_val, right_val, GMP_RNDN); - break; - case OPERATOR_DIV: - if (mpfr_zero_p(right_val)) - error_at(location, "division by zero"); - mpfr_div(val, left_val, right_val, GMP_RNDN); - break; - case OPERATOR_MOD: - return false; - case OPERATOR_LSHIFT: - case OPERATOR_RSHIFT: - return false; - default: - go_unreachable(); - } - - Type* type = left_type; - if (type == NULL) - type = right_type; - else if (type != right_type && right_type != NULL) - { - if (type->is_abstract()) - type = right_type; - else if (!right_type->is_abstract()) - { - // This looks like a type error which should be diagnosed - // elsewhere. Don't do anything here, to avoid an unhelpful - // chain of error messages. - return true; - } - } - - if (type != NULL && !type->is_abstract()) - { - if ((type != left_type - && !Float_expression::check_constant(left_val, type, location)) - || (type != right_type - && !Float_expression::check_constant(right_val, type, - location)) - || !Float_expression::check_constant(val, type, location)) - mpfr_set_ui(val, 0, GMP_RNDN); - } - - return true; -} - -// Apply binary opcode OP to LEFT_REAL/LEFT_IMAG and -// RIGHT_REAL/RIGHT_IMAG, setting REAL/IMAG. Return true if this -// could be done, false if not. - -bool -Binary_expression::eval_complex(Operator op, Type* left_type, - mpfr_t left_real, mpfr_t left_imag, - Type *right_type, - mpfr_t right_real, mpfr_t right_imag, - mpfr_t real, mpfr_t imag, - source_location location) -{ - switch (op) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - // These return boolean values and must be handled differently. - return false; - case OPERATOR_PLUS: - mpfr_add(real, left_real, right_real, GMP_RNDN); - mpfr_add(imag, left_imag, right_imag, GMP_RNDN); - break; - case OPERATOR_MINUS: - mpfr_sub(real, left_real, right_real, GMP_RNDN); - mpfr_sub(imag, left_imag, right_imag, GMP_RNDN); - break; - case OPERATOR_OR: - case OPERATOR_XOR: - case OPERATOR_AND: - case OPERATOR_BITCLEAR: - return false; - case OPERATOR_MULT: - { - // You might think that multiplying two complex numbers would - // be simple, and you would be right, until you start to think - // about getting the right answer for infinity. If one - // operand here is infinity and the other is anything other - // than zero or NaN, then we are going to wind up subtracting - // two infinity values. That will give us a NaN, but the - // correct answer is infinity. - - mpfr_t lrrr; - mpfr_init(lrrr); - mpfr_mul(lrrr, left_real, right_real, GMP_RNDN); - - mpfr_t lrri; - mpfr_init(lrri); - mpfr_mul(lrri, left_real, right_imag, GMP_RNDN); - - mpfr_t lirr; - mpfr_init(lirr); - mpfr_mul(lirr, left_imag, right_real, GMP_RNDN); - - mpfr_t liri; - mpfr_init(liri); - mpfr_mul(liri, left_imag, right_imag, GMP_RNDN); - - mpfr_sub(real, lrrr, liri, GMP_RNDN); - mpfr_add(imag, lrri, lirr, GMP_RNDN); - - // If we get NaN on both sides, check whether it should really - // be infinity. The rule is that if either side of the - // complex number is infinity, then the whole value is - // infinity, even if the other side is NaN. So the only case - // we have to fix is the one in which both sides are NaN. - if (mpfr_nan_p(real) && mpfr_nan_p(imag) - && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag)) - && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag))) - { - bool is_infinity = false; - - mpfr_t lr; - mpfr_t li; - mpfr_init_set(lr, left_real, GMP_RNDN); - mpfr_init_set(li, left_imag, GMP_RNDN); - - mpfr_t rr; - mpfr_t ri; - mpfr_init_set(rr, right_real, GMP_RNDN); - mpfr_init_set(ri, right_imag, GMP_RNDN); - - // If the left side is infinity, then the result is - // infinity. - if (mpfr_inf_p(lr) || mpfr_inf_p(li)) - { - mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN); - mpfr_copysign(lr, lr, left_real, GMP_RNDN); - mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN); - mpfr_copysign(li, li, left_imag, GMP_RNDN); - if (mpfr_nan_p(rr)) - { - mpfr_set_ui(rr, 0, GMP_RNDN); - mpfr_copysign(rr, rr, right_real, GMP_RNDN); - } - if (mpfr_nan_p(ri)) - { - mpfr_set_ui(ri, 0, GMP_RNDN); - mpfr_copysign(ri, ri, right_imag, GMP_RNDN); - } - is_infinity = true; - } - - // If the right side is infinity, then the result is - // infinity. - if (mpfr_inf_p(rr) || mpfr_inf_p(ri)) - { - mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN); - mpfr_copysign(rr, rr, right_real, GMP_RNDN); - mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN); - mpfr_copysign(ri, ri, right_imag, GMP_RNDN); - if (mpfr_nan_p(lr)) - { - mpfr_set_ui(lr, 0, GMP_RNDN); - mpfr_copysign(lr, lr, left_real, GMP_RNDN); - } - if (mpfr_nan_p(li)) - { - mpfr_set_ui(li, 0, GMP_RNDN); - mpfr_copysign(li, li, left_imag, GMP_RNDN); - } - is_infinity = true; - } - - // If we got an overflow in the intermediate computations, - // then the result is infinity. - if (!is_infinity - && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri) - || mpfr_inf_p(lirr) || mpfr_inf_p(liri))) - { - if (mpfr_nan_p(lr)) - { - mpfr_set_ui(lr, 0, GMP_RNDN); - mpfr_copysign(lr, lr, left_real, GMP_RNDN); - } - if (mpfr_nan_p(li)) - { - mpfr_set_ui(li, 0, GMP_RNDN); - mpfr_copysign(li, li, left_imag, GMP_RNDN); - } - if (mpfr_nan_p(rr)) - { - mpfr_set_ui(rr, 0, GMP_RNDN); - mpfr_copysign(rr, rr, right_real, GMP_RNDN); - } - if (mpfr_nan_p(ri)) - { - mpfr_set_ui(ri, 0, GMP_RNDN); - mpfr_copysign(ri, ri, right_imag, GMP_RNDN); - } - is_infinity = true; - } - - if (is_infinity) - { - mpfr_mul(lrrr, lr, rr, GMP_RNDN); - mpfr_mul(lrri, lr, ri, GMP_RNDN); - mpfr_mul(lirr, li, rr, GMP_RNDN); - mpfr_mul(liri, li, ri, GMP_RNDN); - mpfr_sub(real, lrrr, liri, GMP_RNDN); - mpfr_add(imag, lrri, lirr, GMP_RNDN); - mpfr_set_inf(real, mpfr_sgn(real)); - mpfr_set_inf(imag, mpfr_sgn(imag)); - } - - mpfr_clear(lr); - mpfr_clear(li); - mpfr_clear(rr); - mpfr_clear(ri); - } - - mpfr_clear(lrrr); - mpfr_clear(lrri); - mpfr_clear(lirr); - mpfr_clear(liri); - } - break; - case OPERATOR_DIV: - { - // For complex division we want to avoid having an - // intermediate overflow turn the whole result in a NaN. We - // scale the values to try to avoid this. - - if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag)) - error_at(location, "division by zero"); - - mpfr_t rra; - mpfr_t ria; - mpfr_init(rra); - mpfr_init(ria); - mpfr_abs(rra, right_real, GMP_RNDN); - mpfr_abs(ria, right_imag, GMP_RNDN); - mpfr_t t; - mpfr_init(t); - mpfr_max(t, rra, ria, GMP_RNDN); - - mpfr_t rr; - mpfr_t ri; - mpfr_init_set(rr, right_real, GMP_RNDN); - mpfr_init_set(ri, right_imag, GMP_RNDN); - long ilogbw = 0; - if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t)) - { - ilogbw = mpfr_get_exp(t); - mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN); - mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN); - } - - mpfr_t denom; - mpfr_init(denom); - mpfr_mul(denom, rr, rr, GMP_RNDN); - mpfr_mul(t, ri, ri, GMP_RNDN); - mpfr_add(denom, denom, t, GMP_RNDN); - - mpfr_mul(real, left_real, rr, GMP_RNDN); - mpfr_mul(t, left_imag, ri, GMP_RNDN); - mpfr_add(real, real, t, GMP_RNDN); - mpfr_div(real, real, denom, GMP_RNDN); - mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN); - - mpfr_mul(imag, left_imag, rr, GMP_RNDN); - mpfr_mul(t, left_real, ri, GMP_RNDN); - mpfr_sub(imag, imag, t, GMP_RNDN); - mpfr_div(imag, imag, denom, GMP_RNDN); - mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN); - - // If we wind up with NaN on both sides, check whether we - // should really have infinity. The rule is that if either - // side of the complex number is infinity, then the whole - // value is infinity, even if the other side is NaN. So the - // only case we have to fix is the one in which both sides are - // NaN. - if (mpfr_nan_p(real) && mpfr_nan_p(imag) - && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag)) - && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag))) - { - if (mpfr_zero_p(denom)) - { - mpfr_set_inf(real, mpfr_sgn(rr)); - mpfr_mul(real, real, left_real, GMP_RNDN); - mpfr_set_inf(imag, mpfr_sgn(rr)); - mpfr_mul(imag, imag, left_imag, GMP_RNDN); - } - else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag)) - && mpfr_number_p(rr) && mpfr_number_p(ri)) - { - mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN); - mpfr_copysign(t, t, left_real, GMP_RNDN); - - mpfr_t t2; - mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN); - mpfr_copysign(t2, t2, left_imag, GMP_RNDN); - - mpfr_t t3; - mpfr_init(t3); - mpfr_mul(t3, t, rr, GMP_RNDN); - - mpfr_t t4; - mpfr_init(t4); - mpfr_mul(t4, t2, ri, GMP_RNDN); - - mpfr_add(t3, t3, t4, GMP_RNDN); - mpfr_set_inf(real, mpfr_sgn(t3)); - - mpfr_mul(t3, t2, rr, GMP_RNDN); - mpfr_mul(t4, t, ri, GMP_RNDN); - mpfr_sub(t3, t3, t4, GMP_RNDN); - mpfr_set_inf(imag, mpfr_sgn(t3)); - - mpfr_clear(t2); - mpfr_clear(t3); - mpfr_clear(t4); - } - else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag)) - && mpfr_number_p(left_real) && mpfr_number_p(left_imag)) - { - mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN); - mpfr_copysign(t, t, rr, GMP_RNDN); - - mpfr_t t2; - mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN); - mpfr_copysign(t2, t2, ri, GMP_RNDN); - - mpfr_t t3; - mpfr_init(t3); - mpfr_mul(t3, left_real, t, GMP_RNDN); - - mpfr_t t4; - mpfr_init(t4); - mpfr_mul(t4, left_imag, t2, GMP_RNDN); - - mpfr_add(t3, t3, t4, GMP_RNDN); - mpfr_set_ui(real, 0, GMP_RNDN); - mpfr_mul(real, real, t3, GMP_RNDN); - - mpfr_mul(t3, left_imag, t, GMP_RNDN); - mpfr_mul(t4, left_real, t2, GMP_RNDN); - mpfr_sub(t3, t3, t4, GMP_RNDN); - mpfr_set_ui(imag, 0, GMP_RNDN); - mpfr_mul(imag, imag, t3, GMP_RNDN); - - mpfr_clear(t2); - mpfr_clear(t3); - mpfr_clear(t4); - } - } - - mpfr_clear(denom); - mpfr_clear(rr); - mpfr_clear(ri); - mpfr_clear(t); - mpfr_clear(rra); - mpfr_clear(ria); - } - break; - case OPERATOR_MOD: - return false; - case OPERATOR_LSHIFT: - case OPERATOR_RSHIFT: - return false; - default: - go_unreachable(); - } - - Type* type = left_type; - if (type == NULL) - type = right_type; - else if (type != right_type && right_type != NULL) - { - if (type->is_abstract()) - type = right_type; - else if (!right_type->is_abstract()) - { - // This looks like a type error which should be diagnosed - // elsewhere. Don't do anything here, to avoid an unhelpful - // chain of error messages. - return true; - } - } - - if (type != NULL && !type->is_abstract()) - { - if ((type != left_type - && !Complex_expression::check_constant(left_real, left_imag, - type, location)) - || (type != right_type - && !Complex_expression::check_constant(right_real, right_imag, - type, location)) - || !Complex_expression::check_constant(real, imag, type, - location)) - { - mpfr_set_ui(real, 0, GMP_RNDN); - mpfr_set_ui(imag, 0, GMP_RNDN); - } - } - - return true; -} - -// Lower a binary expression. We have to evaluate constant -// expressions now, in order to implement Go's unlimited precision -// constants. - -Expression* -Binary_expression::do_lower(Gogo*, Named_object*, int) -{ - source_location location = this->location(); - Operator op = this->op_; - Expression* left = this->left_; - Expression* right = this->right_; - - const bool is_comparison = (op == OPERATOR_EQEQ - || op == OPERATOR_NOTEQ - || op == OPERATOR_LT - || op == OPERATOR_LE - || op == OPERATOR_GT - || op == OPERATOR_GE); - - // Integer constant expressions. - { - mpz_t left_val; - mpz_init(left_val); - Type* left_type; - mpz_t right_val; - mpz_init(right_val); - Type* right_type; - if (left->integer_constant_value(false, left_val, &left_type) - && right->integer_constant_value(false, right_val, &right_type)) - { - Expression* ret = NULL; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base() - && op != OPERATOR_LSHIFT - && op != OPERATOR_RSHIFT) - { - // May be a type error--let it be diagnosed later. - } - else if (is_comparison) - { - bool b = Binary_expression::compare_integer(op, left_val, - right_val); - ret = Expression::make_cast(Type::lookup_bool_type(), - Expression::make_boolean(b, location), - location); - } - else - { - mpz_t val; - mpz_init(val); - - if (Binary_expression::eval_integer(op, left_type, left_val, - right_type, right_val, - location, val)) - { - go_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND); - Type* type; - if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT) - type = left_type; - else if (left_type == NULL) - type = right_type; - else if (right_type == NULL) - type = left_type; - else if (!left_type->is_abstract() - && left_type->named_type() != NULL) - type = left_type; - else if (!right_type->is_abstract() - && right_type->named_type() != NULL) - type = right_type; - else if (!left_type->is_abstract()) - type = left_type; - else if (!right_type->is_abstract()) - type = right_type; - else if (left_type->float_type() != NULL) - type = left_type; - else if (right_type->float_type() != NULL) - type = right_type; - else if (left_type->complex_type() != NULL) - type = left_type; - else if (right_type->complex_type() != NULL) - type = right_type; - else - type = left_type; - ret = Expression::make_integer(&val, type, location); - } - - mpz_clear(val); - } - - if (ret != NULL) - { - mpz_clear(right_val); - mpz_clear(left_val); - return ret; - } - } - mpz_clear(right_val); - mpz_clear(left_val); - } - - // Floating point constant expressions. - { - mpfr_t left_val; - mpfr_init(left_val); - Type* left_type; - mpfr_t right_val; - mpfr_init(right_val); - Type* right_type; - if (left->float_constant_value(left_val, &left_type) - && right->float_constant_value(right_val, &right_type)) - { - Expression* ret = NULL; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base() - && op != OPERATOR_LSHIFT - && op != OPERATOR_RSHIFT) - { - // May be a type error--let it be diagnosed later. - } - else if (is_comparison) - { - bool b = Binary_expression::compare_float(op, - (left_type != NULL - ? left_type - : right_type), - left_val, right_val); - ret = Expression::make_boolean(b, location); - } - else - { - mpfr_t val; - mpfr_init(val); - - if (Binary_expression::eval_float(op, left_type, left_val, - right_type, right_val, val, - location)) - { - go_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND - && op != OPERATOR_LSHIFT && op != OPERATOR_RSHIFT); - Type* type; - if (left_type == NULL) - type = right_type; - else if (right_type == NULL) - type = left_type; - else if (!left_type->is_abstract() - && left_type->named_type() != NULL) - type = left_type; - else if (!right_type->is_abstract() - && right_type->named_type() != NULL) - type = right_type; - else if (!left_type->is_abstract()) - type = left_type; - else if (!right_type->is_abstract()) - type = right_type; - else if (left_type->float_type() != NULL) - type = left_type; - else if (right_type->float_type() != NULL) - type = right_type; - else - type = left_type; - ret = Expression::make_float(&val, type, location); - } - - mpfr_clear(val); - } - - if (ret != NULL) - { - mpfr_clear(right_val); - mpfr_clear(left_val); - return ret; - } - } - mpfr_clear(right_val); - mpfr_clear(left_val); - } - - // Complex constant expressions. - { - mpfr_t left_real; - mpfr_t left_imag; - mpfr_init(left_real); - mpfr_init(left_imag); - Type* left_type; - - mpfr_t right_real; - mpfr_t right_imag; - mpfr_init(right_real); - mpfr_init(right_imag); - Type* right_type; - - if (left->complex_constant_value(left_real, left_imag, &left_type) - && right->complex_constant_value(right_real, right_imag, &right_type)) - { - Expression* ret = NULL; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base()) - { - // May be a type error--let it be diagnosed later. - } - else if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ) - { - bool b = Binary_expression::compare_complex(op, - (left_type != NULL - ? left_type - : right_type), - left_real, - left_imag, - right_real, - right_imag); - ret = Expression::make_boolean(b, location); - } - else - { - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - - if (Binary_expression::eval_complex(op, left_type, - left_real, left_imag, - right_type, - right_real, right_imag, - real, imag, - location)) - { - go_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND - && op != OPERATOR_LSHIFT && op != OPERATOR_RSHIFT); - Type* type; - if (left_type == NULL) - type = right_type; - else if (right_type == NULL) - type = left_type; - else if (!left_type->is_abstract() - && left_type->named_type() != NULL) - type = left_type; - else if (!right_type->is_abstract() - && right_type->named_type() != NULL) - type = right_type; - else if (!left_type->is_abstract()) - type = left_type; - else if (!right_type->is_abstract()) - type = right_type; - else if (left_type->complex_type() != NULL) - type = left_type; - else if (right_type->complex_type() != NULL) - type = right_type; - else - type = left_type; - ret = Expression::make_complex(&real, &imag, type, - location); - } - mpfr_clear(real); - mpfr_clear(imag); - } - - if (ret != NULL) - { - mpfr_clear(left_real); - mpfr_clear(left_imag); - mpfr_clear(right_real); - mpfr_clear(right_imag); - return ret; - } - } - - mpfr_clear(left_real); - mpfr_clear(left_imag); - mpfr_clear(right_real); - mpfr_clear(right_imag); - } - - // String constant expressions. - if (op == OPERATOR_PLUS - && left->type()->is_string_type() - && right->type()->is_string_type()) - { - std::string left_string; - std::string right_string; - if (left->string_constant_value(&left_string) - && right->string_constant_value(&right_string)) - return Expression::make_string(left_string + right_string, location); - } - - return this; -} - -// Return the integer constant value, if it has one. - -bool -Binary_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val, - Type** ptype) const -{ - mpz_t left_val; - mpz_init(left_val); - Type* left_type; - if (!this->left_->integer_constant_value(iota_is_constant, left_val, - &left_type)) - { - mpz_clear(left_val); - return false; - } - - mpz_t right_val; - mpz_init(right_val); - Type* right_type; - if (!this->right_->integer_constant_value(iota_is_constant, right_val, - &right_type)) - { - mpz_clear(right_val); - mpz_clear(left_val); - return false; - } - - bool ret; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base() - && this->op_ != OPERATOR_RSHIFT - && this->op_ != OPERATOR_LSHIFT) - ret = false; - else - ret = Binary_expression::eval_integer(this->op_, left_type, left_val, - right_type, right_val, - this->location(), val); - - mpz_clear(right_val); - mpz_clear(left_val); - - if (ret) - *ptype = left_type; - - return ret; -} - -// Return the floating point constant value, if it has one. - -bool -Binary_expression::do_float_constant_value(mpfr_t val, Type** ptype) const -{ - mpfr_t left_val; - mpfr_init(left_val); - Type* left_type; - if (!this->left_->float_constant_value(left_val, &left_type)) - { - mpfr_clear(left_val); - return false; - } - - mpfr_t right_val; - mpfr_init(right_val); - Type* right_type; - if (!this->right_->float_constant_value(right_val, &right_type)) - { - mpfr_clear(right_val); - mpfr_clear(left_val); - return false; - } - - bool ret; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base()) - ret = false; - else - ret = Binary_expression::eval_float(this->op_, left_type, left_val, - right_type, right_val, - val, this->location()); - - mpfr_clear(left_val); - mpfr_clear(right_val); - - if (ret) - *ptype = left_type; - - return ret; -} - -// Return the complex constant value, if it has one. - -bool -Binary_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - mpfr_t left_real; - mpfr_t left_imag; - mpfr_init(left_real); - mpfr_init(left_imag); - Type* left_type; - if (!this->left_->complex_constant_value(left_real, left_imag, &left_type)) - { - mpfr_clear(left_real); - mpfr_clear(left_imag); - return false; - } - - mpfr_t right_real; - mpfr_t right_imag; - mpfr_init(right_real); - mpfr_init(right_imag); - Type* right_type; - if (!this->right_->complex_constant_value(right_real, right_imag, - &right_type)) - { - mpfr_clear(left_real); - mpfr_clear(left_imag); - mpfr_clear(right_real); - mpfr_clear(right_imag); - return false; - } - - bool ret; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base()) - ret = false; - else - ret = Binary_expression::eval_complex(this->op_, left_type, - left_real, left_imag, - right_type, - right_real, right_imag, - real, imag, - this->location()); - mpfr_clear(left_real); - mpfr_clear(left_imag); - mpfr_clear(right_real); - mpfr_clear(right_imag); - - if (ret) - *ptype = left_type; - - return ret; -} - -// Note that the value is being discarded. - -void -Binary_expression::do_discarding_value() -{ - if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND) - this->right_->discarding_value(); - else - this->warn_about_unused_value(); -} - -// Get type. - -Type* -Binary_expression::do_type() -{ - if (this->classification() == EXPRESSION_ERROR) - return Type::make_error_type(); - - switch (this->op_) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - return Type::lookup_bool_type(); - - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_OR: - case OPERATOR_XOR: - case OPERATOR_MULT: - case OPERATOR_DIV: - case OPERATOR_MOD: - case OPERATOR_AND: - case OPERATOR_BITCLEAR: - { - Type* left_type = this->left_->type(); - Type* right_type = this->right_->type(); - if (left_type->is_error()) - return left_type; - else if (right_type->is_error()) - return right_type; - else if (!Type::are_compatible_for_binop(left_type, right_type)) - { - this->report_error(_("incompatible types in binary expression")); - return Type::make_error_type(); - } - else if (!left_type->is_abstract() && left_type->named_type() != NULL) - return left_type; - else if (!right_type->is_abstract() && right_type->named_type() != NULL) - return right_type; - else if (!left_type->is_abstract()) - return left_type; - else if (!right_type->is_abstract()) - return right_type; - else if (left_type->complex_type() != NULL) - return left_type; - else if (right_type->complex_type() != NULL) - return right_type; - else if (left_type->float_type() != NULL) - return left_type; - else if (right_type->float_type() != NULL) - return right_type; - else - return left_type; - } - - case OPERATOR_LSHIFT: - case OPERATOR_RSHIFT: - return this->left_->type(); - - default: - go_unreachable(); - } -} - -// Set type for a binary expression. - -void -Binary_expression::do_determine_type(const Type_context* context) -{ - Type* tleft = this->left_->type(); - Type* tright = this->right_->type(); - - // Both sides should have the same type, except for the shift - // operations. For a comparison, we should ignore the incoming - // type. - - bool is_shift_op = (this->op_ == OPERATOR_LSHIFT - || this->op_ == OPERATOR_RSHIFT); - - bool is_comparison = (this->op_ == OPERATOR_EQEQ - || this->op_ == OPERATOR_NOTEQ - || this->op_ == OPERATOR_LT - || this->op_ == OPERATOR_LE - || this->op_ == OPERATOR_GT - || this->op_ == OPERATOR_GE); - - Type_context subcontext(*context); - - if (is_comparison) - { - // In a comparison, the context does not determine the types of - // the operands. - subcontext.type = NULL; - } - - // Set the context for the left hand operand. - if (is_shift_op) - { - // The right hand operand plays no role in determining the type - // of the left hand operand. A shift of an abstract integer in - // a string context gets special treatment, which may be a - // language bug. - if (subcontext.type != NULL - && subcontext.type->is_string_type() - && tleft->is_abstract()) - error_at(this->location(), "shift of non-integer operand"); - } - else if (!tleft->is_abstract()) - subcontext.type = tleft; - else if (!tright->is_abstract()) - subcontext.type = tright; - else if (subcontext.type == NULL) - { - if ((tleft->integer_type() != NULL && tright->integer_type() != NULL) - || (tleft->float_type() != NULL && tright->float_type() != NULL) - || (tleft->complex_type() != NULL && tright->complex_type() != NULL)) - { - // Both sides have an abstract integer, abstract float, or - // abstract complex type. Just let CONTEXT determine - // whether they may remain abstract or not. - } - else if (tleft->complex_type() != NULL) - subcontext.type = tleft; - else if (tright->complex_type() != NULL) - subcontext.type = tright; - else if (tleft->float_type() != NULL) - subcontext.type = tleft; - else if (tright->float_type() != NULL) - subcontext.type = tright; - else - subcontext.type = tleft; - - if (subcontext.type != NULL && !context->may_be_abstract) - subcontext.type = subcontext.type->make_non_abstract_type(); - } - - this->left_->determine_type(&subcontext); - - // The context for the right hand operand is the same as for the - // left hand operand, except for a shift operator. - if (is_shift_op) - { - subcontext.type = Type::lookup_integer_type("uint"); - subcontext.may_be_abstract = false; - } - - this->right_->determine_type(&subcontext); -} - -// Report an error if the binary operator OP does not support TYPE. -// Return whether the operation is OK. This should not be used for -// shift. - -bool -Binary_expression::check_operator_type(Operator op, Type* type, - source_location location) -{ - switch (op) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - if (!type->is_boolean_type()) - { - error_at(location, "expected boolean type"); - return false; - } - break; - - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - if (type->integer_type() == NULL - && type->float_type() == NULL - && type->complex_type() == NULL - && !type->is_string_type() - && type->points_to() == NULL - && !type->is_nil_type() - && !type->is_boolean_type() - && type->interface_type() == NULL - && (type->array_type() == NULL - || type->array_type()->length() != NULL) - && type->map_type() == NULL - && type->channel_type() == NULL - && type->function_type() == NULL) - { - error_at(location, - ("expected integer, floating, complex, string, pointer, " - "boolean, interface, slice, map, channel, " - "or function type")); - return false; - } - break; - - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - if (type->integer_type() == NULL - && type->float_type() == NULL - && !type->is_string_type()) - { - error_at(location, "expected integer, floating, or string type"); - return false; - } - break; - - case OPERATOR_PLUS: - case OPERATOR_PLUSEQ: - if (type->integer_type() == NULL - && type->float_type() == NULL - && type->complex_type() == NULL - && !type->is_string_type()) - { - error_at(location, - "expected integer, floating, complex, or string type"); - return false; - } - break; - - case OPERATOR_MINUS: - case OPERATOR_MINUSEQ: - case OPERATOR_MULT: - case OPERATOR_MULTEQ: - case OPERATOR_DIV: - case OPERATOR_DIVEQ: - if (type->integer_type() == NULL - && type->float_type() == NULL - && type->complex_type() == NULL) - { - error_at(location, "expected integer, floating, or complex type"); - return false; - } - break; - - case OPERATOR_MOD: - case OPERATOR_MODEQ: - case OPERATOR_OR: - case OPERATOR_OREQ: - case OPERATOR_AND: - case OPERATOR_ANDEQ: - case OPERATOR_XOR: - case OPERATOR_XOREQ: - case OPERATOR_BITCLEAR: - case OPERATOR_BITCLEAREQ: - if (type->integer_type() == NULL) - { - error_at(location, "expected integer type"); - return false; - } - break; - - default: - go_unreachable(); - } - - return true; -} - -// Check types. - -void -Binary_expression::do_check_types(Gogo*) -{ - if (this->classification() == EXPRESSION_ERROR) - return; - - Type* left_type = this->left_->type(); - Type* right_type = this->right_->type(); - if (left_type->is_error() || right_type->is_error()) - { - this->set_is_error(); - return; - } - - if (this->op_ == OPERATOR_EQEQ - || this->op_ == OPERATOR_NOTEQ - || this->op_ == OPERATOR_LT - || this->op_ == OPERATOR_LE - || this->op_ == OPERATOR_GT - || this->op_ == OPERATOR_GE) - { - if (!Type::are_assignable(left_type, right_type, NULL) - && !Type::are_assignable(right_type, left_type, NULL)) - { - this->report_error(_("incompatible types in binary expression")); - return; - } - if (!Binary_expression::check_operator_type(this->op_, left_type, - this->location()) - || !Binary_expression::check_operator_type(this->op_, right_type, - this->location())) - { - this->set_is_error(); - return; - } - } - else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT) - { - if (!Type::are_compatible_for_binop(left_type, right_type)) - { - this->report_error(_("incompatible types in binary expression")); - return; - } - if (!Binary_expression::check_operator_type(this->op_, left_type, - this->location())) - { - this->set_is_error(); - return; - } - } - else - { - if (left_type->integer_type() == NULL) - this->report_error(_("shift of non-integer operand")); - - if (!right_type->is_abstract() - && (right_type->integer_type() == NULL - || !right_type->integer_type()->is_unsigned())) - this->report_error(_("shift count not unsigned integer")); - else - { - mpz_t val; - mpz_init(val); - Type* type; - if (this->right_->integer_constant_value(true, val, &type)) - { - if (mpz_sgn(val) < 0) - { - this->report_error(_("negative shift count")); - mpz_set_ui(val, 0); - source_location rloc = this->right_->location(); - this->right_ = Expression::make_integer(&val, right_type, - rloc); - } - } - mpz_clear(val); - } - } -} - -// Get a tree for a binary expression. - -tree -Binary_expression::do_get_tree(Translate_context* context) -{ - tree left = this->left_->get_tree(context); - tree right = this->right_->get_tree(context); - - if (left == error_mark_node || right == error_mark_node) - return error_mark_node; - - enum tree_code code; - bool use_left_type = true; - bool is_shift_op = false; - switch (this->op_) - { - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - return Expression::comparison_tree(context, this->op_, - this->left_->type(), left, - this->right_->type(), right, - this->location()); - - case OPERATOR_OROR: - code = TRUTH_ORIF_EXPR; - use_left_type = false; - break; - case OPERATOR_ANDAND: - code = TRUTH_ANDIF_EXPR; - use_left_type = false; - break; - case OPERATOR_PLUS: - code = PLUS_EXPR; - break; - case OPERATOR_MINUS: - code = MINUS_EXPR; - break; - case OPERATOR_OR: - code = BIT_IOR_EXPR; - break; - case OPERATOR_XOR: - code = BIT_XOR_EXPR; - break; - case OPERATOR_MULT: - code = MULT_EXPR; - break; - case OPERATOR_DIV: - { - Type *t = this->left_->type(); - if (t->float_type() != NULL || t->complex_type() != NULL) - code = RDIV_EXPR; - else - code = TRUNC_DIV_EXPR; - } - break; - case OPERATOR_MOD: - code = TRUNC_MOD_EXPR; - break; - case OPERATOR_LSHIFT: - code = LSHIFT_EXPR; - is_shift_op = true; - break; - case OPERATOR_RSHIFT: - code = RSHIFT_EXPR; - is_shift_op = true; - break; - case OPERATOR_AND: - code = BIT_AND_EXPR; - break; - case OPERATOR_BITCLEAR: - right = fold_build1(BIT_NOT_EXPR, TREE_TYPE(right), right); - code = BIT_AND_EXPR; - break; - default: - go_unreachable(); - } - - tree type = use_left_type ? TREE_TYPE(left) : TREE_TYPE(right); - - if (this->left_->type()->is_string_type()) - { - go_assert(this->op_ == OPERATOR_PLUS); - tree string_type = Type::make_string_type()->get_tree(context->gogo()); - static tree string_plus_decl; - return Gogo::call_builtin(&string_plus_decl, - this->location(), - "__go_string_plus", - 2, - string_type, - string_type, - left, - string_type, - right); - } - - tree compute_type = excess_precision_type(type); - if (compute_type != NULL_TREE) - { - left = ::convert(compute_type, left); - right = ::convert(compute_type, right); - } - - tree eval_saved = NULL_TREE; - if (is_shift_op) - { - // Make sure the values are evaluated. - if (!DECL_P(left) && TREE_SIDE_EFFECTS(left)) - { - left = save_expr(left); - eval_saved = left; - } - if (!DECL_P(right) && TREE_SIDE_EFFECTS(right)) - { - right = save_expr(right); - if (eval_saved == NULL_TREE) - eval_saved = right; - else - eval_saved = fold_build2_loc(this->location(), COMPOUND_EXPR, - void_type_node, eval_saved, right); - } - } - - tree ret = fold_build2_loc(this->location(), - code, - compute_type != NULL_TREE ? compute_type : type, - left, right); - - if (compute_type != NULL_TREE) - ret = ::convert(type, ret); - - // In Go, a shift larger than the size of the type is well-defined. - // This is not true in GENERIC, so we need to insert a conditional. - if (is_shift_op) - { - go_assert(INTEGRAL_TYPE_P(TREE_TYPE(left))); - go_assert(this->left_->type()->integer_type() != NULL); - int bits = TYPE_PRECISION(TREE_TYPE(left)); - - tree compare = fold_build2(LT_EXPR, boolean_type_node, right, - build_int_cst_type(TREE_TYPE(right), bits)); - - tree overflow_result = fold_convert_loc(this->location(), - TREE_TYPE(left), - integer_zero_node); - if (this->op_ == OPERATOR_RSHIFT - && !this->left_->type()->integer_type()->is_unsigned()) - { - tree neg = fold_build2_loc(this->location(), LT_EXPR, - boolean_type_node, left, - fold_convert_loc(this->location(), - TREE_TYPE(left), - integer_zero_node)); - tree neg_one = fold_build2_loc(this->location(), - MINUS_EXPR, TREE_TYPE(left), - fold_convert_loc(this->location(), - TREE_TYPE(left), - integer_zero_node), - fold_convert_loc(this->location(), - TREE_TYPE(left), - integer_one_node)); - overflow_result = fold_build3_loc(this->location(), COND_EXPR, - TREE_TYPE(left), neg, neg_one, - overflow_result); - } - - ret = fold_build3_loc(this->location(), COND_EXPR, TREE_TYPE(left), - compare, ret, overflow_result); - - if (eval_saved != NULL_TREE) - ret = fold_build2_loc(this->location(), COMPOUND_EXPR, - TREE_TYPE(ret), eval_saved, ret); - } - - return ret; -} - -// Export a binary expression. - -void -Binary_expression::do_export(Export* exp) const -{ - exp->write_c_string("("); - this->left_->export_expression(exp); - switch (this->op_) - { - case OPERATOR_OROR: - exp->write_c_string(" || "); - break; - case OPERATOR_ANDAND: - exp->write_c_string(" && "); - break; - case OPERATOR_EQEQ: - exp->write_c_string(" == "); - break; - case OPERATOR_NOTEQ: - exp->write_c_string(" != "); - break; - case OPERATOR_LT: - exp->write_c_string(" < "); - break; - case OPERATOR_LE: - exp->write_c_string(" <= "); - break; - case OPERATOR_GT: - exp->write_c_string(" > "); - break; - case OPERATOR_GE: - exp->write_c_string(" >= "); - break; - case OPERATOR_PLUS: - exp->write_c_string(" + "); - break; - case OPERATOR_MINUS: - exp->write_c_string(" - "); - break; - case OPERATOR_OR: - exp->write_c_string(" | "); - break; - case OPERATOR_XOR: - exp->write_c_string(" ^ "); - break; - case OPERATOR_MULT: - exp->write_c_string(" * "); - break; - case OPERATOR_DIV: - exp->write_c_string(" / "); - break; - case OPERATOR_MOD: - exp->write_c_string(" % "); - break; - case OPERATOR_LSHIFT: - exp->write_c_string(" << "); - break; - case OPERATOR_RSHIFT: - exp->write_c_string(" >> "); - break; - case OPERATOR_AND: - exp->write_c_string(" & "); - break; - case OPERATOR_BITCLEAR: - exp->write_c_string(" &^ "); - break; - default: - go_unreachable(); - } - this->right_->export_expression(exp); - exp->write_c_string(")"); -} - -// Import a binary expression. - -Expression* -Binary_expression::do_import(Import* imp) -{ - imp->require_c_string("("); - - Expression* left = Expression::import_expression(imp); - - Operator op; - if (imp->match_c_string(" || ")) - { - op = OPERATOR_OROR; - imp->advance(4); - } - else if (imp->match_c_string(" && ")) - { - op = OPERATOR_ANDAND; - imp->advance(4); - } - else if (imp->match_c_string(" == ")) - { - op = OPERATOR_EQEQ; - imp->advance(4); - } - else if (imp->match_c_string(" != ")) - { - op = OPERATOR_NOTEQ; - imp->advance(4); - } - else if (imp->match_c_string(" < ")) - { - op = OPERATOR_LT; - imp->advance(3); - } - else if (imp->match_c_string(" <= ")) - { - op = OPERATOR_LE; - imp->advance(4); - } - else if (imp->match_c_string(" > ")) - { - op = OPERATOR_GT; - imp->advance(3); - } - else if (imp->match_c_string(" >= ")) - { - op = OPERATOR_GE; - imp->advance(4); - } - else if (imp->match_c_string(" + ")) - { - op = OPERATOR_PLUS; - imp->advance(3); - } - else if (imp->match_c_string(" - ")) - { - op = OPERATOR_MINUS; - imp->advance(3); - } - else if (imp->match_c_string(" | ")) - { - op = OPERATOR_OR; - imp->advance(3); - } - else if (imp->match_c_string(" ^ ")) - { - op = OPERATOR_XOR; - imp->advance(3); - } - else if (imp->match_c_string(" * ")) - { - op = OPERATOR_MULT; - imp->advance(3); - } - else if (imp->match_c_string(" / ")) - { - op = OPERATOR_DIV; - imp->advance(3); - } - else if (imp->match_c_string(" % ")) - { - op = OPERATOR_MOD; - imp->advance(3); - } - else if (imp->match_c_string(" << ")) - { - op = OPERATOR_LSHIFT; - imp->advance(4); - } - else if (imp->match_c_string(" >> ")) - { - op = OPERATOR_RSHIFT; - imp->advance(4); - } - else if (imp->match_c_string(" & ")) - { - op = OPERATOR_AND; - imp->advance(3); - } - else if (imp->match_c_string(" &^ ")) - { - op = OPERATOR_BITCLEAR; - imp->advance(4); - } - else - { - error_at(imp->location(), "unrecognized binary operator"); - return Expression::make_error(imp->location()); - } - - Expression* right = Expression::import_expression(imp); - - imp->require_c_string(")"); - - return Expression::make_binary(op, left, right, imp->location()); -} - -// Make a binary expression. - -Expression* -Expression::make_binary(Operator op, Expression* left, Expression* right, - source_location location) -{ - return new Binary_expression(op, left, right, location); -} - -// Implement a comparison. - -tree -Expression::comparison_tree(Translate_context* context, Operator op, - Type* left_type, tree left_tree, - Type* right_type, tree right_tree, - source_location location) -{ - enum tree_code code; - switch (op) - { - case OPERATOR_EQEQ: - code = EQ_EXPR; - break; - case OPERATOR_NOTEQ: - code = NE_EXPR; - break; - case OPERATOR_LT: - code = LT_EXPR; - break; - case OPERATOR_LE: - code = LE_EXPR; - break; - case OPERATOR_GT: - code = GT_EXPR; - break; - case OPERATOR_GE: - code = GE_EXPR; - break; - default: - go_unreachable(); - } - - if (left_type->is_string_type() && right_type->is_string_type()) - { - tree string_type = Type::make_string_type()->get_tree(context->gogo()); - static tree string_compare_decl; - left_tree = Gogo::call_builtin(&string_compare_decl, - location, - "__go_strcmp", - 2, - integer_type_node, - string_type, - left_tree, - string_type, - right_tree); - right_tree = build_int_cst_type(integer_type_node, 0); - } - else if ((left_type->interface_type() != NULL - && right_type->interface_type() == NULL - && !right_type->is_nil_type()) - || (left_type->interface_type() == NULL - && !left_type->is_nil_type() - && right_type->interface_type() != NULL)) - { - // Comparing an interface value to a non-interface value. - if (left_type->interface_type() == NULL) - { - std::swap(left_type, right_type); - std::swap(left_tree, right_tree); - } - - // The right operand is not an interface. We need to take its - // address if it is not a pointer. - tree make_tmp; - tree arg; - if (right_type->points_to() != NULL) - { - make_tmp = NULL_TREE; - arg = right_tree; - } - else if (TREE_ADDRESSABLE(TREE_TYPE(right_tree)) || DECL_P(right_tree)) - { - make_tmp = NULL_TREE; - arg = build_fold_addr_expr_loc(location, right_tree); - if (DECL_P(right_tree)) - TREE_ADDRESSABLE(right_tree) = 1; - } - else - { - tree tmp = create_tmp_var(TREE_TYPE(right_tree), - get_name(right_tree)); - DECL_IGNORED_P(tmp) = 0; - DECL_INITIAL(tmp) = right_tree; - TREE_ADDRESSABLE(tmp) = 1; - make_tmp = build1(DECL_EXPR, void_type_node, tmp); - SET_EXPR_LOCATION(make_tmp, location); - arg = build_fold_addr_expr_loc(location, tmp); - } - arg = fold_convert_loc(location, ptr_type_node, arg); - - tree descriptor = right_type->type_descriptor_pointer(context->gogo()); - - if (left_type->interface_type()->is_empty()) - { - static tree empty_interface_value_compare_decl; - left_tree = Gogo::call_builtin(&empty_interface_value_compare_decl, - location, - "__go_empty_interface_value_compare", - 3, - integer_type_node, - TREE_TYPE(left_tree), - left_tree, - TREE_TYPE(descriptor), - descriptor, - ptr_type_node, - arg); - if (left_tree == error_mark_node) - return error_mark_node; - // This can panic if the type is not comparable. - TREE_NOTHROW(empty_interface_value_compare_decl) = 0; - } - else - { - static tree interface_value_compare_decl; - left_tree = Gogo::call_builtin(&interface_value_compare_decl, - location, - "__go_interface_value_compare", - 3, - integer_type_node, - TREE_TYPE(left_tree), - left_tree, - TREE_TYPE(descriptor), - descriptor, - ptr_type_node, - arg); - if (left_tree == error_mark_node) - return error_mark_node; - // This can panic if the type is not comparable. - TREE_NOTHROW(interface_value_compare_decl) = 0; - } - right_tree = build_int_cst_type(integer_type_node, 0); - - if (make_tmp != NULL_TREE) - left_tree = build2(COMPOUND_EXPR, TREE_TYPE(left_tree), make_tmp, - left_tree); - } - else if (left_type->interface_type() != NULL - && right_type->interface_type() != NULL) - { - if (left_type->interface_type()->is_empty() - && right_type->interface_type()->is_empty()) - { - static tree empty_interface_compare_decl; - left_tree = Gogo::call_builtin(&empty_interface_compare_decl, - location, - "__go_empty_interface_compare", - 2, - integer_type_node, - TREE_TYPE(left_tree), - left_tree, - TREE_TYPE(right_tree), - right_tree); - if (left_tree == error_mark_node) - return error_mark_node; - // This can panic if the type is uncomparable. - TREE_NOTHROW(empty_interface_compare_decl) = 0; - } - else if (!left_type->interface_type()->is_empty() - && !right_type->interface_type()->is_empty()) - { - static tree interface_compare_decl; - left_tree = Gogo::call_builtin(&interface_compare_decl, - location, - "__go_interface_compare", - 2, - integer_type_node, - TREE_TYPE(left_tree), - left_tree, - TREE_TYPE(right_tree), - right_tree); - if (left_tree == error_mark_node) - return error_mark_node; - // This can panic if the type is uncomparable. - TREE_NOTHROW(interface_compare_decl) = 0; - } - else - { - if (left_type->interface_type()->is_empty()) - { - go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ); - std::swap(left_type, right_type); - std::swap(left_tree, right_tree); - } - go_assert(!left_type->interface_type()->is_empty()); - go_assert(right_type->interface_type()->is_empty()); - static tree interface_empty_compare_decl; - left_tree = Gogo::call_builtin(&interface_empty_compare_decl, - location, - "__go_interface_empty_compare", - 2, - integer_type_node, - TREE_TYPE(left_tree), - left_tree, - TREE_TYPE(right_tree), - right_tree); - if (left_tree == error_mark_node) - return error_mark_node; - // This can panic if the type is uncomparable. - TREE_NOTHROW(interface_empty_compare_decl) = 0; - } - - right_tree = build_int_cst_type(integer_type_node, 0); - } - - if (left_type->is_nil_type() - && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)) - { - std::swap(left_type, right_type); - std::swap(left_tree, right_tree); - } - - if (right_type->is_nil_type()) - { - if (left_type->array_type() != NULL - && left_type->array_type()->length() == NULL) - { - Array_type* at = left_type->array_type(); - left_tree = at->value_pointer_tree(context->gogo(), left_tree); - right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node); - } - else if (left_type->interface_type() != NULL) - { - // An interface is nil if the first field is nil. - tree left_type_tree = TREE_TYPE(left_tree); - go_assert(TREE_CODE(left_type_tree) == RECORD_TYPE); - tree field = TYPE_FIELDS(left_type_tree); - left_tree = build3(COMPONENT_REF, TREE_TYPE(field), left_tree, - field, NULL_TREE); - right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node); - } - else - { - go_assert(POINTER_TYPE_P(TREE_TYPE(left_tree))); - right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node); - } - } - - if (left_tree == error_mark_node || right_tree == error_mark_node) - return error_mark_node; - - tree ret = fold_build2(code, boolean_type_node, left_tree, right_tree); - if (CAN_HAVE_LOCATION_P(ret)) - SET_EXPR_LOCATION(ret, location); - return ret; -} - -// Class Bound_method_expression. - -// Traversal. - -int -Bound_method_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return Expression::traverse(&this->method_, traverse); -} - -// Return the type of a bound method expression. The type of this -// object is really the type of the method with no receiver. We -// should be able to get away with just returning the type of the -// method. - -Type* -Bound_method_expression::do_type() -{ - return this->method_->type(); -} - -// Determine the types of a method expression. - -void -Bound_method_expression::do_determine_type(const Type_context*) -{ - this->method_->determine_type_no_context(); - Type* mtype = this->method_->type(); - Function_type* fntype = mtype == NULL ? NULL : mtype->function_type(); - if (fntype == NULL || !fntype->is_method()) - this->expr_->determine_type_no_context(); - else - { - Type_context subcontext(fntype->receiver()->type(), false); - this->expr_->determine_type(&subcontext); - } -} - -// Check the types of a method expression. - -void -Bound_method_expression::do_check_types(Gogo*) -{ - Type* type = this->method_->type()->deref(); - if (type == NULL - || type->function_type() == NULL - || !type->function_type()->is_method()) - this->report_error(_("object is not a method")); - else - { - Type* rtype = type->function_type()->receiver()->type()->deref(); - Type* etype = (this->expr_type_ != NULL - ? this->expr_type_ - : this->expr_->type()); - etype = etype->deref(); - if (!Type::are_identical(rtype, etype, true, NULL)) - this->report_error(_("method type does not match object type")); - } -} - -// Get the tree for a method expression. There is no standard tree -// representation for this. The only places it may currently be used -// are in a Call_expression or a Go_statement, which will take it -// apart directly. So this has nothing to do at present. - -tree -Bound_method_expression::do_get_tree(Translate_context*) -{ - error_at(this->location(), "reference to method other than calling it"); - return error_mark_node; -} - -// Make a method expression. - -Bound_method_expression* -Expression::make_bound_method(Expression* expr, Expression* method, - source_location location) -{ - return new Bound_method_expression(expr, method, location); -} - -// Class Builtin_call_expression. This is used for a call to a -// builtin function. - -class Builtin_call_expression : public Call_expression -{ - public: - Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args, - bool is_varargs, source_location location); - - protected: - // This overrides Call_expression::do_lower. - Expression* - do_lower(Gogo*, Named_object*, int); - - bool - do_is_constant() const; - - bool - do_integer_constant_value(bool, mpz_t, Type**) const; - - bool - do_float_constant_value(mpfr_t, Type**) const; - - bool - do_complex_constant_value(mpfr_t, mpfr_t, Type**) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Builtin_call_expression(this->gogo_, this->fn()->copy(), - this->args()->copy(), - this->is_varargs(), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - virtual bool - do_is_recover_call() const; - - virtual void - do_set_recover_arg(Expression*); - - private: - // The builtin functions. - enum Builtin_function_code - { - BUILTIN_INVALID, - - // Predeclared builtin functions. - BUILTIN_APPEND, - BUILTIN_CAP, - BUILTIN_CLOSE, - BUILTIN_COMPLEX, - BUILTIN_COPY, - BUILTIN_IMAG, - BUILTIN_LEN, - BUILTIN_MAKE, - BUILTIN_NEW, - BUILTIN_PANIC, - BUILTIN_PRINT, - BUILTIN_PRINTLN, - BUILTIN_REAL, - BUILTIN_RECOVER, - - // Builtin functions from the unsafe package. - BUILTIN_ALIGNOF, - BUILTIN_OFFSETOF, - BUILTIN_SIZEOF - }; - - Expression* - one_arg() const; - - bool - check_one_arg(); - - static Type* - real_imag_type(Type*); - - static Type* - complex_type(Type*); - - // A pointer back to the general IR structure. This avoids a global - // variable, or passing it around everywhere. - Gogo* gogo_; - // The builtin function being called. - Builtin_function_code code_; - // Used to stop endless loops when the length of an array uses len - // or cap of the array itself. - mutable bool seen_; -}; - -Builtin_call_expression::Builtin_call_expression(Gogo* gogo, - Expression* fn, - Expression_list* args, - bool is_varargs, - source_location location) - : Call_expression(fn, args, is_varargs, location), - gogo_(gogo), code_(BUILTIN_INVALID), seen_(false) -{ - Func_expression* fnexp = this->fn()->func_expression(); - go_assert(fnexp != NULL); - const std::string& name(fnexp->named_object()->name()); - if (name == "append") - this->code_ = BUILTIN_APPEND; - else if (name == "cap") - this->code_ = BUILTIN_CAP; - else if (name == "close") - this->code_ = BUILTIN_CLOSE; - else if (name == "complex") - this->code_ = BUILTIN_COMPLEX; - else if (name == "copy") - this->code_ = BUILTIN_COPY; - else if (name == "imag") - this->code_ = BUILTIN_IMAG; - else if (name == "len") - this->code_ = BUILTIN_LEN; - else if (name == "make") - this->code_ = BUILTIN_MAKE; - else if (name == "new") - this->code_ = BUILTIN_NEW; - else if (name == "panic") - this->code_ = BUILTIN_PANIC; - else if (name == "print") - this->code_ = BUILTIN_PRINT; - else if (name == "println") - this->code_ = BUILTIN_PRINTLN; - else if (name == "real") - this->code_ = BUILTIN_REAL; - else if (name == "recover") - this->code_ = BUILTIN_RECOVER; - else if (name == "Alignof") - this->code_ = BUILTIN_ALIGNOF; - else if (name == "Offsetof") - this->code_ = BUILTIN_OFFSETOF; - else if (name == "Sizeof") - this->code_ = BUILTIN_SIZEOF; - else - go_unreachable(); -} - -// Return whether this is a call to recover. This is a virtual -// function called from the parent class. - -bool -Builtin_call_expression::do_is_recover_call() const -{ - if (this->classification() == EXPRESSION_ERROR) - return false; - return this->code_ == BUILTIN_RECOVER; -} - -// Set the argument for a call to recover. - -void -Builtin_call_expression::do_set_recover_arg(Expression* arg) -{ - const Expression_list* args = this->args(); - go_assert(args == NULL || args->empty()); - Expression_list* new_args = new Expression_list(); - new_args->push_back(arg); - this->set_args(new_args); -} - -// A traversal class which looks for a call expression. - -class Find_call_expression : public Traverse -{ - public: - Find_call_expression() - : Traverse(traverse_expressions), - found_(false) - { } - - int - expression(Expression**); - - bool - found() - { return this->found_; } - - private: - bool found_; -}; - -int -Find_call_expression::expression(Expression** pexpr) -{ - if ((*pexpr)->call_expression() != NULL) - { - this->found_ = true; - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lower a builtin call expression. This turns new and make into -// specific expressions. We also convert to a constant if we can. - -Expression* -Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function, int) -{ - if (this->is_varargs() && this->code_ != BUILTIN_APPEND) - { - this->report_error(_("invalid use of %<...%> with builtin function")); - return Expression::make_error(this->location()); - } - - if (this->code_ == BUILTIN_NEW) - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 1) - this->report_error(_("not enough arguments")); - else if (args->size() > 1) - this->report_error(_("too many arguments")); - else - { - Expression* arg = args->front(); - if (!arg->is_type_expression()) - { - error_at(arg->location(), "expected type"); - this->set_is_error(); - } - else - return Expression::make_allocation(arg->type(), this->location()); - } - } - else if (this->code_ == BUILTIN_MAKE) - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 1) - this->report_error(_("not enough arguments")); - else - { - Expression* arg = args->front(); - if (!arg->is_type_expression()) - { - error_at(arg->location(), "expected type"); - this->set_is_error(); - } - else - { - Expression_list* newargs; - if (args->size() == 1) - newargs = NULL; - else - { - newargs = new Expression_list(); - Expression_list::const_iterator p = args->begin(); - ++p; - for (; p != args->end(); ++p) - newargs->push_back(*p); - } - return Expression::make_make(arg->type(), newargs, - this->location()); - } - } - } - else if (this->is_constant()) - { - // We can only lower len and cap if there are no function calls - // in the arguments. Otherwise we have to make the call. - if (this->code_ == BUILTIN_LEN || this->code_ == BUILTIN_CAP) - { - Expression* arg = this->one_arg(); - if (!arg->is_constant()) - { - Find_call_expression find_call; - Expression::traverse(&arg, &find_call); - if (find_call.found()) - return this; - } - } - - mpz_t ival; - mpz_init(ival); - Type* type; - if (this->integer_constant_value(true, ival, &type)) - { - Expression* ret = Expression::make_integer(&ival, type, - this->location()); - mpz_clear(ival); - return ret; - } - mpz_clear(ival); - - mpfr_t rval; - mpfr_init(rval); - if (this->float_constant_value(rval, &type)) - { - Expression* ret = Expression::make_float(&rval, type, - this->location()); - mpfr_clear(rval); - return ret; - } - - mpfr_t imag; - mpfr_init(imag); - if (this->complex_constant_value(rval, imag, &type)) - { - Expression* ret = Expression::make_complex(&rval, &imag, type, - this->location()); - mpfr_clear(rval); - mpfr_clear(imag); - return ret; - } - mpfr_clear(rval); - mpfr_clear(imag); - } - else if (this->code_ == BUILTIN_RECOVER) - { - if (function != NULL) - function->func_value()->set_calls_recover(); - else - { - // Calling recover outside of a function always returns the - // nil empty interface. - Type* eface = Type::make_interface_type(NULL, this->location()); - return Expression::make_cast(eface, - Expression::make_nil(this->location()), - this->location()); - } - } - else if (this->code_ == BUILTIN_APPEND) - { - // Lower the varargs. - const Expression_list* args = this->args(); - if (args == NULL || args->empty()) - return this; - Type* slice_type = args->front()->type(); - if (!slice_type->is_open_array_type()) - { - error_at(args->front()->location(), "argument 1 must be a slice"); - this->set_is_error(); - return this; - } - return this->lower_varargs(gogo, function, slice_type, 2); - } - - return this; -} - -// Return the type of the real or imag functions, given the type of -// the argument. We need to map complex to float, complex64 to -// float32, and complex128 to float64, so it has to be done by name. -// This returns NULL if it can't figure out the type. - -Type* -Builtin_call_expression::real_imag_type(Type* arg_type) -{ - if (arg_type == NULL || arg_type->is_abstract()) - return NULL; - Named_type* nt = arg_type->named_type(); - if (nt == NULL) - return NULL; - while (nt->real_type()->named_type() != NULL) - nt = nt->real_type()->named_type(); - if (nt->name() == "complex64") - return Type::lookup_float_type("float32"); - else if (nt->name() == "complex128") - return Type::lookup_float_type("float64"); - else - return NULL; -} - -// Return the type of the complex function, given the type of one of the -// argments. Like real_imag_type, we have to map by name. - -Type* -Builtin_call_expression::complex_type(Type* arg_type) -{ - if (arg_type == NULL || arg_type->is_abstract()) - return NULL; - Named_type* nt = arg_type->named_type(); - if (nt == NULL) - return NULL; - while (nt->real_type()->named_type() != NULL) - nt = nt->real_type()->named_type(); - if (nt->name() == "float32") - return Type::lookup_complex_type("complex64"); - else if (nt->name() == "float64") - return Type::lookup_complex_type("complex128"); - else - return NULL; -} - -// Return a single argument, or NULL if there isn't one. - -Expression* -Builtin_call_expression::one_arg() const -{ - const Expression_list* args = this->args(); - if (args->size() != 1) - return NULL; - return args->front(); -} - -// Return whether this is constant: len of a string, or len or cap of -// a fixed array, or unsafe.Sizeof, unsafe.Offsetof, unsafe.Alignof. - -bool -Builtin_call_expression::do_is_constant() const -{ - switch (this->code_) - { - case BUILTIN_LEN: - case BUILTIN_CAP: - { - if (this->seen_) - return false; - - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - Type* arg_type = arg->type(); - - if (arg_type->points_to() != NULL - && arg_type->points_to()->array_type() != NULL - && !arg_type->points_to()->is_open_array_type()) - arg_type = arg_type->points_to(); - - if (arg_type->array_type() != NULL - && arg_type->array_type()->length() != NULL) - return true; - - if (this->code_ == BUILTIN_LEN && arg_type->is_string_type()) - { - this->seen_ = true; - bool ret = arg->is_constant(); - this->seen_ = false; - return ret; - } - } - break; - - case BUILTIN_SIZEOF: - case BUILTIN_ALIGNOF: - return this->one_arg() != NULL; - - case BUILTIN_OFFSETOF: - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - return arg->field_reference_expression() != NULL; - } - - case BUILTIN_COMPLEX: - { - const Expression_list* args = this->args(); - if (args != NULL && args->size() == 2) - return args->front()->is_constant() && args->back()->is_constant(); - } - break; - - case BUILTIN_REAL: - case BUILTIN_IMAG: - { - Expression* arg = this->one_arg(); - return arg != NULL && arg->is_constant(); - } - - default: - break; - } - - return false; -} - -// Return an integer constant value if possible. - -bool -Builtin_call_expression::do_integer_constant_value(bool iota_is_constant, - mpz_t val, - Type** ptype) const -{ - if (this->code_ == BUILTIN_LEN - || this->code_ == BUILTIN_CAP) - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - Type* arg_type = arg->type(); - - if (this->code_ == BUILTIN_LEN && arg_type->is_string_type()) - { - std::string sval; - if (arg->string_constant_value(&sval)) - { - mpz_set_ui(val, sval.length()); - *ptype = Type::lookup_integer_type("int"); - return true; - } - } - - if (arg_type->points_to() != NULL - && arg_type->points_to()->array_type() != NULL - && !arg_type->points_to()->is_open_array_type()) - arg_type = arg_type->points_to(); - - if (arg_type->array_type() != NULL - && arg_type->array_type()->length() != NULL) - { - if (this->seen_) - return false; - Expression* e = arg_type->array_type()->length(); - this->seen_ = true; - bool r = e->integer_constant_value(iota_is_constant, val, ptype); - this->seen_ = false; - if (r) - { - *ptype = Type::lookup_integer_type("int"); - return true; - } - } - } - else if (this->code_ == BUILTIN_SIZEOF - || this->code_ == BUILTIN_ALIGNOF) - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - Type* arg_type = arg->type(); - if (arg_type->is_error()) - return false; - if (arg_type->is_abstract()) - return false; - if (arg_type->named_type() != NULL) - arg_type->named_type()->convert(this->gogo_); - tree arg_type_tree = arg_type->get_tree(this->gogo_); - if (arg_type_tree == error_mark_node) - return false; - unsigned long val_long; - if (this->code_ == BUILTIN_SIZEOF) - { - tree type_size = TYPE_SIZE_UNIT(arg_type_tree); - go_assert(TREE_CODE(type_size) == INTEGER_CST); - if (TREE_INT_CST_HIGH(type_size) != 0) - return false; - unsigned HOST_WIDE_INT val_wide = TREE_INT_CST_LOW(type_size); - val_long = static_cast(val_wide); - if (val_long != val_wide) - return false; - } - else if (this->code_ == BUILTIN_ALIGNOF) - { - if (arg->field_reference_expression() == NULL) - val_long = go_type_alignment(arg_type_tree); - else - { - // Calling unsafe.Alignof(s.f) returns the alignment of - // the type of f when it is used as a field in a struct. - val_long = go_field_alignment(arg_type_tree); - } - } - else - go_unreachable(); - mpz_set_ui(val, val_long); - *ptype = NULL; - return true; - } - else if (this->code_ == BUILTIN_OFFSETOF) - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - Field_reference_expression* farg = arg->field_reference_expression(); - if (farg == NULL) - return false; - Expression* struct_expr = farg->expr(); - Type* st = struct_expr->type(); - if (st->struct_type() == NULL) - return false; - if (st->named_type() != NULL) - st->named_type()->convert(this->gogo_); - tree struct_tree = st->get_tree(this->gogo_); - go_assert(TREE_CODE(struct_tree) == RECORD_TYPE); - tree field = TYPE_FIELDS(struct_tree); - for (unsigned int index = farg->field_index(); index > 0; --index) - { - field = DECL_CHAIN(field); - go_assert(field != NULL_TREE); - } - HOST_WIDE_INT offset_wide = int_byte_position (field); - if (offset_wide < 0) - return false; - unsigned long offset_long = static_cast(offset_wide); - if (offset_long != static_cast(offset_wide)) - return false; - mpz_set_ui(val, offset_long); - return true; - } - return false; -} - -// Return a floating point constant value if possible. - -bool -Builtin_call_expression::do_float_constant_value(mpfr_t val, - Type** ptype) const -{ - if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG) - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - - bool ret = false; - Type* type; - if (arg->complex_constant_value(real, imag, &type)) - { - if (this->code_ == BUILTIN_REAL) - mpfr_set(val, real, GMP_RNDN); - else - mpfr_set(val, imag, GMP_RNDN); - *ptype = Builtin_call_expression::real_imag_type(type); - ret = true; - } - - mpfr_clear(real); - mpfr_clear(imag); - return ret; - } - - return false; -} - -// Return a complex constant value if possible. - -bool -Builtin_call_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - if (this->code_ == BUILTIN_COMPLEX) - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() != 2) - return false; - - mpfr_t r; - mpfr_init(r); - Type* rtype; - if (!args->front()->float_constant_value(r, &rtype)) - { - mpfr_clear(r); - return false; - } - - mpfr_t i; - mpfr_init(i); - - bool ret = false; - Type* itype; - if (args->back()->float_constant_value(i, &itype) - && Type::are_identical(rtype, itype, false, NULL)) - { - mpfr_set(real, r, GMP_RNDN); - mpfr_set(imag, i, GMP_RNDN); - *ptype = Builtin_call_expression::complex_type(rtype); - ret = true; - } - - mpfr_clear(r); - mpfr_clear(i); - - return ret; - } - - return false; -} - -// Return the type. - -Type* -Builtin_call_expression::do_type() -{ - switch (this->code_) - { - case BUILTIN_INVALID: - default: - go_unreachable(); - - case BUILTIN_NEW: - case BUILTIN_MAKE: - { - const Expression_list* args = this->args(); - if (args == NULL || args->empty()) - return Type::make_error_type(); - return Type::make_pointer_type(args->front()->type()); - } - - case BUILTIN_CAP: - case BUILTIN_COPY: - case BUILTIN_LEN: - case BUILTIN_ALIGNOF: - case BUILTIN_OFFSETOF: - case BUILTIN_SIZEOF: - return Type::lookup_integer_type("int"); - - case BUILTIN_CLOSE: - case BUILTIN_PANIC: - case BUILTIN_PRINT: - case BUILTIN_PRINTLN: - return Type::make_void_type(); - - case BUILTIN_RECOVER: - return Type::make_interface_type(NULL, BUILTINS_LOCATION); - - case BUILTIN_APPEND: - { - const Expression_list* args = this->args(); - if (args == NULL || args->empty()) - return Type::make_error_type(); - return args->front()->type(); - } - - case BUILTIN_REAL: - case BUILTIN_IMAG: - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return Type::make_error_type(); - Type* t = arg->type(); - if (t->is_abstract()) - t = t->make_non_abstract_type(); - t = Builtin_call_expression::real_imag_type(t); - if (t == NULL) - t = Type::make_error_type(); - return t; - } - - case BUILTIN_COMPLEX: - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() != 2) - return Type::make_error_type(); - Type* t = args->front()->type(); - if (t->is_abstract()) - { - t = args->back()->type(); - if (t->is_abstract()) - t = t->make_non_abstract_type(); - } - t = Builtin_call_expression::complex_type(t); - if (t == NULL) - t = Type::make_error_type(); - return t; - } - } -} - -// Determine the type. - -void -Builtin_call_expression::do_determine_type(const Type_context* context) -{ - if (!this->determining_types()) - return; - - this->fn()->determine_type_no_context(); - - const Expression_list* args = this->args(); - - bool is_print; - Type* arg_type = NULL; - switch (this->code_) - { - case BUILTIN_PRINT: - case BUILTIN_PRINTLN: - // Do not force a large integer constant to "int". - is_print = true; - break; - - case BUILTIN_REAL: - case BUILTIN_IMAG: - arg_type = Builtin_call_expression::complex_type(context->type); - is_print = false; - break; - - case BUILTIN_COMPLEX: - { - // For the complex function the type of one operand can - // determine the type of the other, as in a binary expression. - arg_type = Builtin_call_expression::real_imag_type(context->type); - if (args != NULL && args->size() == 2) - { - Type* t1 = args->front()->type(); - Type* t2 = args->front()->type(); - if (!t1->is_abstract()) - arg_type = t1; - else if (!t2->is_abstract()) - arg_type = t2; - } - is_print = false; - } - break; - - default: - is_print = false; - break; - } - - if (args != NULL) - { - for (Expression_list::const_iterator pa = args->begin(); - pa != args->end(); - ++pa) - { - Type_context subcontext; - subcontext.type = arg_type; - - if (is_print) - { - // We want to print large constants, we so can't just - // use the appropriate nonabstract type. Use uint64 for - // an integer if we know it is nonnegative, otherwise - // use int64 for a integer, otherwise use float64 for a - // float or complex128 for a complex. - Type* want_type = NULL; - Type* atype = (*pa)->type(); - if (atype->is_abstract()) - { - if (atype->integer_type() != NULL) - { - mpz_t val; - mpz_init(val); - Type* dummy; - if (this->integer_constant_value(true, val, &dummy) - && mpz_sgn(val) >= 0) - want_type = Type::lookup_integer_type("uint64"); - else - want_type = Type::lookup_integer_type("int64"); - mpz_clear(val); - } - else if (atype->float_type() != NULL) - want_type = Type::lookup_float_type("float64"); - else if (atype->complex_type() != NULL) - want_type = Type::lookup_complex_type("complex128"); - else if (atype->is_abstract_string_type()) - want_type = Type::lookup_string_type(); - else if (atype->is_abstract_boolean_type()) - want_type = Type::lookup_bool_type(); - else - go_unreachable(); - subcontext.type = want_type; - } - } - - (*pa)->determine_type(&subcontext); - } - } -} - -// If there is exactly one argument, return true. Otherwise give an -// error message and return false. - -bool -Builtin_call_expression::check_one_arg() -{ - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 1) - { - this->report_error(_("not enough arguments")); - return false; - } - else if (args->size() > 1) - { - this->report_error(_("too many arguments")); - return false; - } - if (args->front()->is_error_expression() - || args->front()->type()->is_error()) - { - this->set_is_error(); - return false; - } - return true; -} - -// Check argument types for a builtin function. - -void -Builtin_call_expression::do_check_types(Gogo*) -{ - switch (this->code_) - { - case BUILTIN_INVALID: - case BUILTIN_NEW: - case BUILTIN_MAKE: - return; - - case BUILTIN_LEN: - case BUILTIN_CAP: - { - // The single argument may be either a string or an array or a - // map or a channel, or a pointer to a closed array. - if (this->check_one_arg()) - { - Type* arg_type = this->one_arg()->type(); - if (arg_type->points_to() != NULL - && arg_type->points_to()->array_type() != NULL - && !arg_type->points_to()->is_open_array_type()) - arg_type = arg_type->points_to(); - if (this->code_ == BUILTIN_CAP) - { - if (!arg_type->is_error() - && arg_type->array_type() == NULL - && arg_type->channel_type() == NULL) - this->report_error(_("argument must be array or slice " - "or channel")); - } - else - { - if (!arg_type->is_error() - && !arg_type->is_string_type() - && arg_type->array_type() == NULL - && arg_type->map_type() == NULL - && arg_type->channel_type() == NULL) - this->report_error(_("argument must be string or " - "array or slice or map or channel")); - } - } - } - break; - - case BUILTIN_PRINT: - case BUILTIN_PRINTLN: - { - const Expression_list* args = this->args(); - if (args == NULL) - { - if (this->code_ == BUILTIN_PRINT) - warning_at(this->location(), 0, - "no arguments for builtin function %<%s%>", - (this->code_ == BUILTIN_PRINT - ? "print" - : "println")); - } - else - { - for (Expression_list::const_iterator p = args->begin(); - p != args->end(); - ++p) - { - Type* type = (*p)->type(); - if (type->is_error() - || type->is_string_type() - || type->integer_type() != NULL - || type->float_type() != NULL - || type->complex_type() != NULL - || type->is_boolean_type() - || type->points_to() != NULL - || type->interface_type() != NULL - || type->channel_type() != NULL - || type->map_type() != NULL - || type->function_type() != NULL - || type->is_open_array_type()) - ; - else - this->report_error(_("unsupported argument type to " - "builtin function")); - } - } - } - break; - - case BUILTIN_CLOSE: - if (this->check_one_arg()) - { - if (this->one_arg()->type()->channel_type() == NULL) - this->report_error(_("argument must be channel")); - } - break; - - case BUILTIN_PANIC: - case BUILTIN_SIZEOF: - case BUILTIN_ALIGNOF: - this->check_one_arg(); - break; - - case BUILTIN_RECOVER: - if (this->args() != NULL && !this->args()->empty()) - this->report_error(_("too many arguments")); - break; - - case BUILTIN_OFFSETOF: - if (this->check_one_arg()) - { - Expression* arg = this->one_arg(); - if (arg->field_reference_expression() == NULL) - this->report_error(_("argument must be a field reference")); - } - break; - - case BUILTIN_COPY: - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 2) - { - this->report_error(_("not enough arguments")); - break; - } - else if (args->size() > 2) - { - this->report_error(_("too many arguments")); - break; - } - Type* arg1_type = args->front()->type(); - Type* arg2_type = args->back()->type(); - if (arg1_type->is_error() || arg2_type->is_error()) - break; - - Type* e1; - if (arg1_type->is_open_array_type()) - e1 = arg1_type->array_type()->element_type(); - else - { - this->report_error(_("left argument must be a slice")); - break; - } - - Type* e2; - if (arg2_type->is_open_array_type()) - e2 = arg2_type->array_type()->element_type(); - else if (arg2_type->is_string_type()) - e2 = Type::lookup_integer_type("uint8"); - else - { - this->report_error(_("right argument must be a slice or a string")); - break; - } - - if (!Type::are_identical(e1, e2, true, NULL)) - this->report_error(_("element types must be the same")); - } - break; - - case BUILTIN_APPEND: - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 2) - { - this->report_error(_("not enough arguments")); - break; - } - if (args->size() > 2) - { - this->report_error(_("too many arguments")); - break; - } - std::string reason; - if (!Type::are_assignable(args->front()->type(), args->back()->type(), - &reason)) - { - if (reason.empty()) - this->report_error(_("arguments 1 and 2 have different types")); - else - { - error_at(this->location(), - "arguments 1 and 2 have different types (%s)", - reason.c_str()); - this->set_is_error(); - } - } - break; - } - - case BUILTIN_REAL: - case BUILTIN_IMAG: - if (this->check_one_arg()) - { - if (this->one_arg()->type()->complex_type() == NULL) - this->report_error(_("argument must have complex type")); - } - break; - - case BUILTIN_COMPLEX: - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 2) - this->report_error(_("not enough arguments")); - else if (args->size() > 2) - this->report_error(_("too many arguments")); - else if (args->front()->is_error_expression() - || args->front()->type()->is_error() - || args->back()->is_error_expression() - || args->back()->type()->is_error()) - this->set_is_error(); - else if (!Type::are_identical(args->front()->type(), - args->back()->type(), true, NULL)) - this->report_error(_("complex arguments must have identical types")); - else if (args->front()->type()->float_type() == NULL) - this->report_error(_("complex arguments must have " - "floating-point type")); - } - break; - - default: - go_unreachable(); - } -} - -// Return the tree for a builtin function. - -tree -Builtin_call_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - source_location location = this->location(); - switch (this->code_) - { - case BUILTIN_INVALID: - case BUILTIN_NEW: - case BUILTIN_MAKE: - go_unreachable(); - - case BUILTIN_LEN: - case BUILTIN_CAP: - { - const Expression_list* args = this->args(); - go_assert(args != NULL && args->size() == 1); - Expression* arg = *args->begin(); - Type* arg_type = arg->type(); - - if (this->seen_) - { - go_assert(saw_errors()); - return error_mark_node; - } - this->seen_ = true; - - tree arg_tree = arg->get_tree(context); - - this->seen_ = false; - - if (arg_tree == error_mark_node) - return error_mark_node; - - if (arg_type->points_to() != NULL) - { - arg_type = arg_type->points_to(); - go_assert(arg_type->array_type() != NULL - && !arg_type->is_open_array_type()); - go_assert(POINTER_TYPE_P(TREE_TYPE(arg_tree))); - arg_tree = build_fold_indirect_ref(arg_tree); - } - - tree val_tree; - if (this->code_ == BUILTIN_LEN) - { - if (arg_type->is_string_type()) - val_tree = String_type::length_tree(gogo, arg_tree); - else if (arg_type->array_type() != NULL) - { - if (this->seen_) - { - go_assert(saw_errors()); - return error_mark_node; - } - this->seen_ = true; - val_tree = arg_type->array_type()->length_tree(gogo, arg_tree); - this->seen_ = false; - } - else if (arg_type->map_type() != NULL) - { - static tree map_len_fndecl; - val_tree = Gogo::call_builtin(&map_len_fndecl, - location, - "__go_map_len", - 1, - integer_type_node, - arg_type->get_tree(gogo), - arg_tree); - } - else if (arg_type->channel_type() != NULL) - { - static tree chan_len_fndecl; - val_tree = Gogo::call_builtin(&chan_len_fndecl, - location, - "__go_chan_len", - 1, - integer_type_node, - arg_type->get_tree(gogo), - arg_tree); - } - else - go_unreachable(); - } - else - { - if (arg_type->array_type() != NULL) - { - if (this->seen_) - { - go_assert(saw_errors()); - return error_mark_node; - } - this->seen_ = true; - val_tree = arg_type->array_type()->capacity_tree(gogo, - arg_tree); - this->seen_ = false; - } - else if (arg_type->channel_type() != NULL) - { - static tree chan_cap_fndecl; - val_tree = Gogo::call_builtin(&chan_cap_fndecl, - location, - "__go_chan_cap", - 1, - integer_type_node, - arg_type->get_tree(gogo), - arg_tree); - } - else - go_unreachable(); - } - - if (val_tree == error_mark_node) - return error_mark_node; - - tree type_tree = Type::lookup_integer_type("int")->get_tree(gogo); - if (type_tree == TREE_TYPE(val_tree)) - return val_tree; - else - return fold(convert_to_integer(type_tree, val_tree)); - } - - case BUILTIN_PRINT: - case BUILTIN_PRINTLN: - { - const bool is_ln = this->code_ == BUILTIN_PRINTLN; - tree stmt_list = NULL_TREE; - - const Expression_list* call_args = this->args(); - if (call_args != NULL) - { - for (Expression_list::const_iterator p = call_args->begin(); - p != call_args->end(); - ++p) - { - if (is_ln && p != call_args->begin()) - { - static tree print_space_fndecl; - tree call = Gogo::call_builtin(&print_space_fndecl, - location, - "__go_print_space", - 0, - void_type_node); - if (call == error_mark_node) - return error_mark_node; - append_to_statement_list(call, &stmt_list); - } - - Type* type = (*p)->type(); - - tree arg = (*p)->get_tree(context); - if (arg == error_mark_node) - return error_mark_node; - - tree* pfndecl; - const char* fnname; - if (type->is_string_type()) - { - static tree print_string_fndecl; - pfndecl = &print_string_fndecl; - fnname = "__go_print_string"; - } - else if (type->integer_type() != NULL - && type->integer_type()->is_unsigned()) - { - static tree print_uint64_fndecl; - pfndecl = &print_uint64_fndecl; - fnname = "__go_print_uint64"; - Type* itype = Type::lookup_integer_type("uint64"); - arg = fold_convert_loc(location, itype->get_tree(gogo), - arg); - } - else if (type->integer_type() != NULL) - { - static tree print_int64_fndecl; - pfndecl = &print_int64_fndecl; - fnname = "__go_print_int64"; - Type* itype = Type::lookup_integer_type("int64"); - arg = fold_convert_loc(location, itype->get_tree(gogo), - arg); - } - else if (type->float_type() != NULL) - { - static tree print_double_fndecl; - pfndecl = &print_double_fndecl; - fnname = "__go_print_double"; - arg = fold_convert_loc(location, double_type_node, arg); - } - else if (type->complex_type() != NULL) - { - static tree print_complex_fndecl; - pfndecl = &print_complex_fndecl; - fnname = "__go_print_complex"; - arg = fold_convert_loc(location, complex_double_type_node, - arg); - } - else if (type->is_boolean_type()) - { - static tree print_bool_fndecl; - pfndecl = &print_bool_fndecl; - fnname = "__go_print_bool"; - } - else if (type->points_to() != NULL - || type->channel_type() != NULL - || type->map_type() != NULL - || type->function_type() != NULL) - { - static tree print_pointer_fndecl; - pfndecl = &print_pointer_fndecl; - fnname = "__go_print_pointer"; - arg = fold_convert_loc(location, ptr_type_node, arg); - } - else if (type->interface_type() != NULL) - { - if (type->interface_type()->is_empty()) - { - static tree print_empty_interface_fndecl; - pfndecl = &print_empty_interface_fndecl; - fnname = "__go_print_empty_interface"; - } - else - { - static tree print_interface_fndecl; - pfndecl = &print_interface_fndecl; - fnname = "__go_print_interface"; - } - } - else if (type->is_open_array_type()) - { - static tree print_slice_fndecl; - pfndecl = &print_slice_fndecl; - fnname = "__go_print_slice"; - } - else - go_unreachable(); - - tree call = Gogo::call_builtin(pfndecl, - location, - fnname, - 1, - void_type_node, - TREE_TYPE(arg), - arg); - if (call == error_mark_node) - return error_mark_node; - append_to_statement_list(call, &stmt_list); - } - } - - if (is_ln) - { - static tree print_nl_fndecl; - tree call = Gogo::call_builtin(&print_nl_fndecl, - location, - "__go_print_nl", - 0, - void_type_node); - if (call == error_mark_node) - return error_mark_node; - append_to_statement_list(call, &stmt_list); - } - - return stmt_list; - } - - case BUILTIN_PANIC: - { - const Expression_list* args = this->args(); - go_assert(args != NULL && args->size() == 1); - Expression* arg = args->front(); - tree arg_tree = arg->get_tree(context); - if (arg_tree == error_mark_node) - return error_mark_node; - Type *empty = Type::make_interface_type(NULL, BUILTINS_LOCATION); - arg_tree = Expression::convert_for_assignment(context, empty, - arg->type(), - arg_tree, location); - static tree panic_fndecl; - tree call = Gogo::call_builtin(&panic_fndecl, - location, - "__go_panic", - 1, - void_type_node, - TREE_TYPE(arg_tree), - arg_tree); - if (call == error_mark_node) - return error_mark_node; - // This function will throw an exception. - TREE_NOTHROW(panic_fndecl) = 0; - // This function will not return. - TREE_THIS_VOLATILE(panic_fndecl) = 1; - return call; - } - - case BUILTIN_RECOVER: - { - // The argument is set when building recover thunks. It's a - // boolean value which is true if we can recover a value now. - const Expression_list* args = this->args(); - go_assert(args != NULL && args->size() == 1); - Expression* arg = args->front(); - tree arg_tree = arg->get_tree(context); - if (arg_tree == error_mark_node) - return error_mark_node; - - Type *empty = Type::make_interface_type(NULL, BUILTINS_LOCATION); - tree empty_tree = empty->get_tree(context->gogo()); - - Type* nil_type = Type::make_nil_type(); - Expression* nil = Expression::make_nil(location); - tree nil_tree = nil->get_tree(context); - tree empty_nil_tree = Expression::convert_for_assignment(context, - empty, - nil_type, - nil_tree, - location); - - // We need to handle a deferred call to recover specially, - // because it changes whether it can recover a panic or not. - // See test7 in test/recover1.go. - tree call; - if (this->is_deferred()) - { - static tree deferred_recover_fndecl; - call = Gogo::call_builtin(&deferred_recover_fndecl, - location, - "__go_deferred_recover", - 0, - empty_tree); - } - else - { - static tree recover_fndecl; - call = Gogo::call_builtin(&recover_fndecl, - location, - "__go_recover", - 0, - empty_tree); - } - if (call == error_mark_node) - return error_mark_node; - return fold_build3_loc(location, COND_EXPR, empty_tree, arg_tree, - call, empty_nil_tree); - } - - case BUILTIN_CLOSE: - { - const Expression_list* args = this->args(); - go_assert(args != NULL && args->size() == 1); - Expression* arg = args->front(); - tree arg_tree = arg->get_tree(context); - if (arg_tree == error_mark_node) - return error_mark_node; - static tree close_fndecl; - return Gogo::call_builtin(&close_fndecl, - location, - "__go_builtin_close", - 1, - void_type_node, - TREE_TYPE(arg_tree), - arg_tree); - } - - case BUILTIN_SIZEOF: - case BUILTIN_OFFSETOF: - case BUILTIN_ALIGNOF: - { - mpz_t val; - mpz_init(val); - Type* dummy; - bool b = this->integer_constant_value(true, val, &dummy); - if (!b) - { - go_assert(saw_errors()); - return error_mark_node; - } - tree type = Type::lookup_integer_type("int")->get_tree(gogo); - tree ret = Expression::integer_constant_tree(val, type); - mpz_clear(val); - return ret; - } - - case BUILTIN_COPY: - { - const Expression_list* args = this->args(); - go_assert(args != NULL && args->size() == 2); - Expression* arg1 = args->front(); - Expression* arg2 = args->back(); - - tree arg1_tree = arg1->get_tree(context); - tree arg2_tree = arg2->get_tree(context); - if (arg1_tree == error_mark_node || arg2_tree == error_mark_node) - return error_mark_node; - - Type* arg1_type = arg1->type(); - Array_type* at = arg1_type->array_type(); - arg1_tree = save_expr(arg1_tree); - tree arg1_val = at->value_pointer_tree(gogo, arg1_tree); - tree arg1_len = at->length_tree(gogo, arg1_tree); - if (arg1_val == error_mark_node || arg1_len == error_mark_node) - return error_mark_node; - - Type* arg2_type = arg2->type(); - tree arg2_val; - tree arg2_len; - if (arg2_type->is_open_array_type()) - { - at = arg2_type->array_type(); - arg2_tree = save_expr(arg2_tree); - arg2_val = at->value_pointer_tree(gogo, arg2_tree); - arg2_len = at->length_tree(gogo, arg2_tree); - } - else - { - arg2_tree = save_expr(arg2_tree); - arg2_val = String_type::bytes_tree(gogo, arg2_tree); - arg2_len = String_type::length_tree(gogo, arg2_tree); - } - if (arg2_val == error_mark_node || arg2_len == error_mark_node) - return error_mark_node; - - arg1_len = save_expr(arg1_len); - arg2_len = save_expr(arg2_len); - tree len = fold_build3_loc(location, COND_EXPR, TREE_TYPE(arg1_len), - fold_build2_loc(location, LT_EXPR, - boolean_type_node, - arg1_len, arg2_len), - arg1_len, arg2_len); - len = save_expr(len); - - Type* element_type = at->element_type(); - tree element_type_tree = element_type->get_tree(gogo); - if (element_type_tree == error_mark_node) - return error_mark_node; - tree element_size = TYPE_SIZE_UNIT(element_type_tree); - tree bytecount = fold_convert_loc(location, TREE_TYPE(element_size), - len); - bytecount = fold_build2_loc(location, MULT_EXPR, - TREE_TYPE(element_size), - bytecount, element_size); - bytecount = fold_convert_loc(location, size_type_node, bytecount); - - arg1_val = fold_convert_loc(location, ptr_type_node, arg1_val); - arg2_val = fold_convert_loc(location, ptr_type_node, arg2_val); - - static tree copy_fndecl; - tree call = Gogo::call_builtin(©_fndecl, - location, - "__go_copy", - 3, - void_type_node, - ptr_type_node, - arg1_val, - ptr_type_node, - arg2_val, - size_type_node, - bytecount); - if (call == error_mark_node) - return error_mark_node; - - return fold_build2_loc(location, COMPOUND_EXPR, TREE_TYPE(len), - call, len); - } - - case BUILTIN_APPEND: - { - const Expression_list* args = this->args(); - go_assert(args != NULL && args->size() == 2); - Expression* arg1 = args->front(); - Expression* arg2 = args->back(); - - tree arg1_tree = arg1->get_tree(context); - tree arg2_tree = arg2->get_tree(context); - if (arg1_tree == error_mark_node || arg2_tree == error_mark_node) - return error_mark_node; - - Array_type* at = arg1->type()->array_type(); - Type* element_type = at->element_type(); - - arg2_tree = Expression::convert_for_assignment(context, at, - arg2->type(), - arg2_tree, - location); - if (arg2_tree == error_mark_node) - return error_mark_node; - - arg2_tree = save_expr(arg2_tree); - tree arg2_val = at->value_pointer_tree(gogo, arg2_tree); - tree arg2_len = at->length_tree(gogo, arg2_tree); - if (arg2_val == error_mark_node || arg2_len == error_mark_node) - return error_mark_node; - arg2_val = fold_convert_loc(location, ptr_type_node, arg2_val); - arg2_len = fold_convert_loc(location, size_type_node, arg2_len); - - tree element_type_tree = element_type->get_tree(gogo); - if (element_type_tree == error_mark_node) - return error_mark_node; - tree element_size = TYPE_SIZE_UNIT(element_type_tree); - element_size = fold_convert_loc(location, size_type_node, - element_size); - - // We rebuild the decl each time since the slice types may - // change. - tree append_fndecl = NULL_TREE; - return Gogo::call_builtin(&append_fndecl, - location, - "__go_append", - 4, - TREE_TYPE(arg1_tree), - TREE_TYPE(arg1_tree), - arg1_tree, - ptr_type_node, - arg2_val, - size_type_node, - arg2_len, - size_type_node, - element_size); - } - - case BUILTIN_REAL: - case BUILTIN_IMAG: - { - const Expression_list* args = this->args(); - go_assert(args != NULL && args->size() == 1); - Expression* arg = args->front(); - tree arg_tree = arg->get_tree(context); - if (arg_tree == error_mark_node) - return error_mark_node; - go_assert(COMPLEX_FLOAT_TYPE_P(TREE_TYPE(arg_tree))); - if (this->code_ == BUILTIN_REAL) - return fold_build1_loc(location, REALPART_EXPR, - TREE_TYPE(TREE_TYPE(arg_tree)), - arg_tree); - else - return fold_build1_loc(location, IMAGPART_EXPR, - TREE_TYPE(TREE_TYPE(arg_tree)), - arg_tree); - } - - case BUILTIN_COMPLEX: - { - const Expression_list* args = this->args(); - go_assert(args != NULL && args->size() == 2); - tree r = args->front()->get_tree(context); - tree i = args->back()->get_tree(context); - if (r == error_mark_node || i == error_mark_node) - return error_mark_node; - go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(r)) - == TYPE_MAIN_VARIANT(TREE_TYPE(i))); - go_assert(SCALAR_FLOAT_TYPE_P(TREE_TYPE(r))); - return fold_build2_loc(location, COMPLEX_EXPR, - build_complex_type(TREE_TYPE(r)), - r, i); - } - - default: - go_unreachable(); - } -} - -// We have to support exporting a builtin call expression, because -// code can set a constant to the result of a builtin expression. - -void -Builtin_call_expression::do_export(Export* exp) const -{ - bool ok = false; - - mpz_t val; - mpz_init(val); - Type* dummy; - if (this->integer_constant_value(true, val, &dummy)) - { - Integer_expression::export_integer(exp, val); - ok = true; - } - mpz_clear(val); - - if (!ok) - { - mpfr_t fval; - mpfr_init(fval); - if (this->float_constant_value(fval, &dummy)) - { - Float_expression::export_float(exp, fval); - ok = true; - } - mpfr_clear(fval); - } - - if (!ok) - { - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - if (this->complex_constant_value(real, imag, &dummy)) - { - Complex_expression::export_complex(exp, real, imag); - ok = true; - } - mpfr_clear(real); - mpfr_clear(imag); - } - - if (!ok) - { - error_at(this->location(), "value is not constant"); - return; - } - - // A trailing space lets us reliably identify the end of the number. - exp->write_c_string(" "); -} - -// Class Call_expression. - -// Traversal. - -int -Call_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->args_ != NULL) - { - if (this->args_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lower a call statement. - -Expression* -Call_expression::do_lower(Gogo* gogo, Named_object* function, int) -{ - // A type case can look like a function call. - if (this->fn_->is_type_expression() - && this->args_ != NULL - && this->args_->size() == 1) - return Expression::make_cast(this->fn_->type(), this->args_->front(), - this->location()); - - // Recognize a call to a builtin function. - Func_expression* fne = this->fn_->func_expression(); - if (fne != NULL - && fne->named_object()->is_function_declaration() - && fne->named_object()->func_declaration_value()->type()->is_builtin()) - return new Builtin_call_expression(gogo, this->fn_, this->args_, - this->is_varargs_, this->location()); - - // Handle an argument which is a call to a function which returns - // multiple results. - if (this->args_ != NULL - && this->args_->size() == 1 - && this->args_->front()->call_expression() != NULL - && this->fn_->type()->function_type() != NULL) - { - Function_type* fntype = this->fn_->type()->function_type(); - size_t rc = this->args_->front()->call_expression()->result_count(); - if (rc > 1 - && fntype->parameters() != NULL - && (fntype->parameters()->size() == rc - || (fntype->is_varargs() - && fntype->parameters()->size() - 1 <= rc))) - { - Call_expression* call = this->args_->front()->call_expression(); - Expression_list* args = new Expression_list; - for (size_t i = 0; i < rc; ++i) - args->push_back(Expression::make_call_result(call, i)); - // We can't return a new call expression here, because this - // one may be referenced by Call_result expressions. We - // also can't delete the old arguments, because we may still - // traverse them somewhere up the call stack. FIXME. - this->args_ = args; - } - } - - // Handle a call to a varargs function by packaging up the extra - // parameters. - if (this->fn_->type()->function_type() != NULL - && this->fn_->type()->function_type()->is_varargs()) - { - Function_type* fntype = this->fn_->type()->function_type(); - const Typed_identifier_list* parameters = fntype->parameters(); - go_assert(parameters != NULL && !parameters->empty()); - Type* varargs_type = parameters->back().type(); - return this->lower_varargs(gogo, function, varargs_type, - parameters->size()); - } - - return this; -} - -// Lower a call to a varargs function. FUNCTION is the function in -// which the call occurs--it's not the function we are calling. -// VARARGS_TYPE is the type of the varargs parameter, a slice type. -// PARAM_COUNT is the number of parameters of the function we are -// calling; the last of these parameters will be the varargs -// parameter. - -Expression* -Call_expression::lower_varargs(Gogo* gogo, Named_object* function, - Type* varargs_type, size_t param_count) -{ - if (this->varargs_are_lowered_) - return this; - - source_location loc = this->location(); - - go_assert(param_count > 0); - go_assert(varargs_type->is_open_array_type()); - - size_t arg_count = this->args_ == NULL ? 0 : this->args_->size(); - if (arg_count < param_count - 1) - { - // Not enough arguments; will be caught in check_types. - return this; - } - - Expression_list* old_args = this->args_; - Expression_list* new_args = new Expression_list(); - bool push_empty_arg = false; - if (old_args == NULL || old_args->empty()) - { - go_assert(param_count == 1); - push_empty_arg = true; - } - else - { - Expression_list::const_iterator pa; - int i = 1; - for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i) - { - if (static_cast(i) == param_count) - break; - new_args->push_back(*pa); - } - - // We have reached the varargs parameter. - - bool issued_error = false; - if (pa == old_args->end()) - push_empty_arg = true; - else if (pa + 1 == old_args->end() && this->is_varargs_) - new_args->push_back(*pa); - else if (this->is_varargs_) - { - this->report_error(_("too many arguments")); - return this; - } - else - { - Type* element_type = varargs_type->array_type()->element_type(); - Expression_list* vals = new Expression_list; - for (; pa != old_args->end(); ++pa, ++i) - { - // Check types here so that we get a better message. - Type* patype = (*pa)->type(); - source_location paloc = (*pa)->location(); - if (!this->check_argument_type(i, element_type, patype, - paloc, issued_error)) - continue; - vals->push_back(*pa); - } - Expression* val = - Expression::make_slice_composite_literal(varargs_type, vals, loc); - new_args->push_back(val); - } - } - - if (push_empty_arg) - new_args->push_back(Expression::make_nil(loc)); - - // We can't return a new call expression here, because this one may - // be referenced by Call_result expressions. FIXME. - if (old_args != NULL) - delete old_args; - this->args_ = new_args; - this->varargs_are_lowered_ = true; - - // Lower all the new subexpressions. - Expression* ret = this; - gogo->lower_expression(function, &ret); - go_assert(ret == this); - return ret; -} - -// Get the function type. Returns NULL if we don't know the type. If -// this returns NULL, and if_ERROR is true, issues an error. - -Function_type* -Call_expression::get_function_type() const -{ - return this->fn_->type()->function_type(); -} - -// Return the number of values which this call will return. - -size_t -Call_expression::result_count() const -{ - const Function_type* fntype = this->get_function_type(); - if (fntype == NULL) - return 0; - if (fntype->results() == NULL) - return 0; - return fntype->results()->size(); -} - -// Return whether this is a call to the predeclared function recover. - -bool -Call_expression::is_recover_call() const -{ - return this->do_is_recover_call(); -} - -// Set the argument to the recover function. - -void -Call_expression::set_recover_arg(Expression* arg) -{ - this->do_set_recover_arg(arg); -} - -// Virtual functions also implemented by Builtin_call_expression. - -bool -Call_expression::do_is_recover_call() const -{ - return false; -} - -void -Call_expression::do_set_recover_arg(Expression*) -{ - go_unreachable(); -} - -// Get the type. - -Type* -Call_expression::do_type() -{ - if (this->type_ != NULL) - return this->type_; - - Type* ret; - Function_type* fntype = this->get_function_type(); - if (fntype == NULL) - return Type::make_error_type(); - - const Typed_identifier_list* results = fntype->results(); - if (results == NULL) - ret = Type::make_void_type(); - else if (results->size() == 1) - ret = results->begin()->type(); - else - ret = Type::make_call_multiple_result_type(this); - - this->type_ = ret; - - return this->type_; -} - -// Determine types for a call expression. We can use the function -// parameter types to set the types of the arguments. - -void -Call_expression::do_determine_type(const Type_context*) -{ - if (!this->determining_types()) - return; - - this->fn_->determine_type_no_context(); - Function_type* fntype = this->get_function_type(); - const Typed_identifier_list* parameters = NULL; - if (fntype != NULL) - parameters = fntype->parameters(); - if (this->args_ != NULL) - { - Typed_identifier_list::const_iterator pt; - if (parameters != NULL) - pt = parameters->begin(); - for (Expression_list::const_iterator pa = this->args_->begin(); - pa != this->args_->end(); - ++pa) - { - if (parameters != NULL && pt != parameters->end()) - { - Type_context subcontext(pt->type(), false); - (*pa)->determine_type(&subcontext); - ++pt; - } - else - (*pa)->determine_type_no_context(); - } - } -} - -// Called when determining types for a Call_expression. Return true -// if we should go ahead, false if they have already been determined. - -bool -Call_expression::determining_types() -{ - if (this->types_are_determined_) - return false; - else - { - this->types_are_determined_ = true; - return true; - } -} - -// Check types for parameter I. - -bool -Call_expression::check_argument_type(int i, const Type* parameter_type, - const Type* argument_type, - source_location argument_location, - bool issued_error) -{ - std::string reason; - if (!Type::are_assignable(parameter_type, argument_type, &reason)) - { - if (!issued_error) - { - if (reason.empty()) - error_at(argument_location, "argument %d has incompatible type", i); - else - error_at(argument_location, - "argument %d has incompatible type (%s)", - i, reason.c_str()); - } - this->set_is_error(); - return false; - } - return true; -} - -// Check types. - -void -Call_expression::do_check_types(Gogo*) -{ - Function_type* fntype = this->get_function_type(); - if (fntype == NULL) - { - if (!this->fn_->type()->is_error()) - this->report_error(_("expected function")); - return; - } - - if (fntype->is_method()) - { - // We don't support pointers to methods, so the function has to - // be a bound method expression. - Bound_method_expression* bme = this->fn_->bound_method_expression(); - if (bme == NULL) - { - this->report_error(_("method call without object")); - return; - } - Type* first_arg_type = bme->first_argument()->type(); - if (first_arg_type->points_to() == NULL) - { - // When passing a value, we need to check that we are - // permitted to copy it. The language permits copying - // hidden fields for a method receiver. - std::string reason; - if (!Type::are_assignable_hidden_ok(fntype->receiver()->type(), - first_arg_type, &reason)) - { - if (reason.empty()) - this->report_error(_("incompatible type for receiver")); - else - { - error_at(this->location(), - "incompatible type for receiver (%s)", - reason.c_str()); - this->set_is_error(); - } - } - } - } - - // Note that varargs was handled by the lower_varargs() method, so - // we don't have to worry about it here. - - const Typed_identifier_list* parameters = fntype->parameters(); - if (this->args_ == NULL) - { - if (parameters != NULL && !parameters->empty()) - this->report_error(_("not enough arguments")); - } - else if (parameters == NULL) - this->report_error(_("too many arguments")); - else - { - int i = 0; - Typed_identifier_list::const_iterator pt = parameters->begin(); - for (Expression_list::const_iterator pa = this->args_->begin(); - pa != this->args_->end(); - ++pa, ++pt, ++i) - { - if (pt == parameters->end()) - { - this->report_error(_("too many arguments")); - return; - } - this->check_argument_type(i + 1, pt->type(), (*pa)->type(), - (*pa)->location(), false); - } - if (pt != parameters->end()) - this->report_error(_("not enough arguments")); - } -} - -// Return whether we have to use a temporary variable to ensure that -// we evaluate this call expression in order. If the call returns no -// results then it will inevitably be executed last. If the call -// returns more than one result then it will be used with Call_result -// expressions. So we only have to use a temporary variable if the -// call returns exactly one result. - -bool -Call_expression::do_must_eval_in_order() const -{ - return this->result_count() == 1; -} - -// Get the function and the first argument to use when calling a bound -// method. - -tree -Call_expression::bound_method_function(Translate_context* context, - Bound_method_expression* bound_method, - tree* first_arg_ptr) -{ - Expression* first_argument = bound_method->first_argument(); - tree first_arg = first_argument->get_tree(context); - if (first_arg == error_mark_node) - return error_mark_node; - - // We always pass a pointer to the first argument when calling a - // method. - if (first_argument->type()->points_to() == NULL) - { - tree pointer_to_arg_type = build_pointer_type(TREE_TYPE(first_arg)); - if (TREE_ADDRESSABLE(TREE_TYPE(first_arg)) - || DECL_P(first_arg) - || TREE_CODE(first_arg) == INDIRECT_REF - || TREE_CODE(first_arg) == COMPONENT_REF) - { - first_arg = build_fold_addr_expr(first_arg); - if (DECL_P(first_arg)) - TREE_ADDRESSABLE(first_arg) = 1; - } - else - { - tree tmp = create_tmp_var(TREE_TYPE(first_arg), - get_name(first_arg)); - DECL_IGNORED_P(tmp) = 0; - DECL_INITIAL(tmp) = first_arg; - first_arg = build2(COMPOUND_EXPR, pointer_to_arg_type, - build1(DECL_EXPR, void_type_node, tmp), - build_fold_addr_expr(tmp)); - TREE_ADDRESSABLE(tmp) = 1; - } - if (first_arg == error_mark_node) - return error_mark_node; - } - - Type* fatype = bound_method->first_argument_type(); - if (fatype != NULL) - { - if (fatype->points_to() == NULL) - fatype = Type::make_pointer_type(fatype); - first_arg = fold_convert(fatype->get_tree(context->gogo()), first_arg); - if (first_arg == error_mark_node - || TREE_TYPE(first_arg) == error_mark_node) - return error_mark_node; - } - - *first_arg_ptr = first_arg; - - return bound_method->method()->get_tree(context); -} - -// Get the function and the first argument to use when calling an -// interface method. - -tree -Call_expression::interface_method_function( - Translate_context* context, - Interface_field_reference_expression* interface_method, - tree* first_arg_ptr) -{ - tree expr = interface_method->expr()->get_tree(context); - if (expr == error_mark_node) - return error_mark_node; - expr = save_expr(expr); - tree first_arg = interface_method->get_underlying_object_tree(context, expr); - if (first_arg == error_mark_node) - return error_mark_node; - *first_arg_ptr = first_arg; - return interface_method->get_function_tree(context, expr); -} - -// Build the call expression. - -tree -Call_expression::do_get_tree(Translate_context* context) -{ - if (this->tree_ != NULL_TREE) - return this->tree_; - - Function_type* fntype = this->get_function_type(); - if (fntype == NULL) - return error_mark_node; - - if (this->fn_->is_error_expression()) - return error_mark_node; - - Gogo* gogo = context->gogo(); - source_location location = this->location(); - - Func_expression* func = this->fn_->func_expression(); - Bound_method_expression* bound_method = this->fn_->bound_method_expression(); - Interface_field_reference_expression* interface_method = - this->fn_->interface_field_reference_expression(); - const bool has_closure = func != NULL && func->closure() != NULL; - const bool is_method = bound_method != NULL || interface_method != NULL; - go_assert(!fntype->is_method() || is_method); - - int nargs; - tree* args; - if (this->args_ == NULL || this->args_->empty()) - { - nargs = is_method ? 1 : 0; - args = nargs == 0 ? NULL : new tree[nargs]; - } - else - { - const Typed_identifier_list* params = fntype->parameters(); - go_assert(params != NULL); - - nargs = this->args_->size(); - int i = is_method ? 1 : 0; - nargs += i; - args = new tree[nargs]; - - Typed_identifier_list::const_iterator pp = params->begin(); - Expression_list::const_iterator pe; - for (pe = this->args_->begin(); - pe != this->args_->end(); - ++pe, ++pp, ++i) - { - go_assert(pp != params->end()); - tree arg_val = (*pe)->get_tree(context); - args[i] = Expression::convert_for_assignment(context, - pp->type(), - (*pe)->type(), - arg_val, - location); - if (args[i] == error_mark_node) - { - delete[] args; - return error_mark_node; - } - } - go_assert(pp == params->end()); - go_assert(i == nargs); - } - - tree rettype = TREE_TYPE(TREE_TYPE(fntype->get_tree(gogo))); - if (rettype == error_mark_node) - { - delete[] args; - return error_mark_node; - } - - tree fn; - if (has_closure) - fn = func->get_tree_without_closure(gogo); - else if (!is_method) - fn = this->fn_->get_tree(context); - else if (bound_method != NULL) - fn = this->bound_method_function(context, bound_method, &args[0]); - else if (interface_method != NULL) - fn = this->interface_method_function(context, interface_method, &args[0]); - else - go_unreachable(); - - if (fn == error_mark_node || TREE_TYPE(fn) == error_mark_node) - { - delete[] args; - return error_mark_node; - } - - tree fndecl = fn; - if (TREE_CODE(fndecl) == ADDR_EXPR) - fndecl = TREE_OPERAND(fndecl, 0); - - // Add a type cast in case the type of the function is a recursive - // type which refers to itself. - if (!DECL_P(fndecl) || !DECL_IS_BUILTIN(fndecl)) - { - tree fnt = fntype->get_tree(gogo); - if (fnt == error_mark_node) - return error_mark_node; - fn = fold_convert_loc(location, fnt, fn); - } - - // This is to support builtin math functions when using 80387 math. - tree excess_type = NULL_TREE; - if (TREE_CODE(fndecl) == FUNCTION_DECL - && DECL_IS_BUILTIN(fndecl) - && DECL_BUILT_IN_CLASS(fndecl) == BUILT_IN_NORMAL - && nargs > 0 - && ((SCALAR_FLOAT_TYPE_P(rettype) - && SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[0]))) - || (COMPLEX_FLOAT_TYPE_P(rettype) - && COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[0]))))) - { - excess_type = excess_precision_type(TREE_TYPE(args[0])); - if (excess_type != NULL_TREE) - { - tree excess_fndecl = mathfn_built_in(excess_type, - DECL_FUNCTION_CODE(fndecl)); - if (excess_fndecl == NULL_TREE) - excess_type = NULL_TREE; - else - { - fn = build_fold_addr_expr_loc(location, excess_fndecl); - for (int i = 0; i < nargs; ++i) - args[i] = ::convert(excess_type, args[i]); - } - } - } - - tree ret = build_call_array(excess_type != NULL_TREE ? excess_type : rettype, - fn, nargs, args); - delete[] args; - - SET_EXPR_LOCATION(ret, location); - - if (has_closure) - { - tree closure_tree = func->closure()->get_tree(context); - if (closure_tree != error_mark_node) - CALL_EXPR_STATIC_CHAIN(ret) = closure_tree; - } - - // If this is a recursive function type which returns itself, as in - // type F func() F - // we have used ptr_type_node for the return type. Add a cast here - // to the correct type. - if (TREE_TYPE(ret) == ptr_type_node) - { - tree t = this->type()->base()->get_tree(gogo); - ret = fold_convert_loc(location, t, ret); - } - - if (excess_type != NULL_TREE) - { - // Calling convert here can undo our excess precision change. - // That may or may not be a bug in convert_to_real. - ret = build1(NOP_EXPR, rettype, ret); - } - - // If there is more than one result, we will refer to the call - // multiple times. - if (fntype->results() != NULL && fntype->results()->size() > 1) - ret = save_expr(ret); - - this->tree_ = ret; - - return ret; -} - -// Make a call expression. - -Call_expression* -Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs, - source_location location) -{ - return new Call_expression(fn, args, is_varargs, location); -} - -// A single result from a call which returns multiple results. - -class Call_result_expression : public Expression -{ - public: - Call_result_expression(Call_expression* call, unsigned int index) - : Expression(EXPRESSION_CALL_RESULT, call->location()), - call_(call), index_(index) - { } - - protected: - int - do_traverse(Traverse*); - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Call_result_expression(this->call_->call_expression(), - this->index_); - } - - bool - do_must_eval_in_order() const - { return true; } - - tree - do_get_tree(Translate_context*); - - private: - // The underlying call expression. - Expression* call_; - // Which result we want. - unsigned int index_; -}; - -// Traverse a call result. - -int -Call_result_expression::do_traverse(Traverse* traverse) -{ - if (traverse->remember_expression(this->call_)) - { - // We have already traversed the call expression. - return TRAVERSE_CONTINUE; - } - return Expression::traverse(&this->call_, traverse); -} - -// Get the type. - -Type* -Call_result_expression::do_type() -{ - if (this->classification() == EXPRESSION_ERROR) - return Type::make_error_type(); - - // THIS->CALL_ can be replaced with a temporary reference due to - // Call_expression::do_must_eval_in_order when there is an error. - Call_expression* ce = this->call_->call_expression(); - if (ce == NULL) - { - this->set_is_error(); - return Type::make_error_type(); - } - Function_type* fntype = ce->get_function_type(); - if (fntype == NULL) - { - this->set_is_error(); - return Type::make_error_type(); - } - const Typed_identifier_list* results = fntype->results(); - if (results == NULL) - { - this->report_error(_("number of results does not match " - "number of values")); - return Type::make_error_type(); - } - Typed_identifier_list::const_iterator pr = results->begin(); - for (unsigned int i = 0; i < this->index_; ++i) - { - if (pr == results->end()) - break; - ++pr; - } - if (pr == results->end()) - { - this->report_error(_("number of results does not match " - "number of values")); - return Type::make_error_type(); - } - return pr->type(); -} - -// Check the type. Just make sure that we trigger the warning in -// do_type. - -void -Call_result_expression::do_check_types(Gogo*) -{ - this->type(); -} - -// Determine the type. We have nothing to do here, but the 0 result -// needs to pass down to the caller. - -void -Call_result_expression::do_determine_type(const Type_context*) -{ - this->call_->determine_type_no_context(); -} - -// Return the tree. - -tree -Call_result_expression::do_get_tree(Translate_context* context) -{ - tree call_tree = this->call_->get_tree(context); - if (call_tree == error_mark_node) - return error_mark_node; - if (TREE_CODE(TREE_TYPE(call_tree)) != RECORD_TYPE) - { - go_assert(saw_errors()); - return error_mark_node; - } - tree field = TYPE_FIELDS(TREE_TYPE(call_tree)); - for (unsigned int i = 0; i < this->index_; ++i) - { - go_assert(field != NULL_TREE); - field = DECL_CHAIN(field); - } - go_assert(field != NULL_TREE); - return build3(COMPONENT_REF, TREE_TYPE(field), call_tree, field, NULL_TREE); -} - -// Make a reference to a single result of a call which returns -// multiple results. - -Expression* -Expression::make_call_result(Call_expression* call, unsigned int index) -{ - return new Call_result_expression(call, index); -} - -// Class Index_expression. - -// Traversal. - -int -Index_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT - || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT - || (this->end_ != NULL - && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Lower an index expression. This converts the generic index -// expression into an array index, a string index, or a map index. - -Expression* -Index_expression::do_lower(Gogo*, Named_object*, int) -{ - source_location location = this->location(); - Expression* left = this->left_; - Expression* start = this->start_; - Expression* end = this->end_; - - Type* type = left->type(); - if (type->is_error()) - return Expression::make_error(location); - else if (left->is_type_expression()) - { - error_at(location, "attempt to index type expression"); - return Expression::make_error(location); - } - else if (type->array_type() != NULL) - return Expression::make_array_index(left, start, end, location); - else if (type->points_to() != NULL - && type->points_to()->array_type() != NULL - && !type->points_to()->is_open_array_type()) - { - Expression* deref = Expression::make_unary(OPERATOR_MULT, left, - location); - return Expression::make_array_index(deref, start, end, location); - } - else if (type->is_string_type()) - return Expression::make_string_index(left, start, end, location); - else if (type->map_type() != NULL) - { - if (end != NULL) - { - error_at(location, "invalid slice of map"); - return Expression::make_error(location); - } - Map_index_expression* ret= Expression::make_map_index(left, start, - location); - if (this->is_lvalue_) - ret->set_is_lvalue(); - return ret; - } - else - { - error_at(location, - "attempt to index object which is not array, string, or map"); - return Expression::make_error(location); - } -} - -// Make an index expression. - -Expression* -Expression::make_index(Expression* left, Expression* start, Expression* end, - source_location location) -{ - return new Index_expression(left, start, end, location); -} - -// An array index. This is used for both indexing and slicing. - -class Array_index_expression : public Expression -{ - public: - Array_index_expression(Expression* array, Expression* start, - Expression* end, source_location location) - : Expression(EXPRESSION_ARRAY_INDEX, location), - array_(array), start_(start), end_(end), type_(NULL) - { } - - protected: - int - do_traverse(Traverse*); - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return Expression::make_array_index(this->array_->copy(), - this->start_->copy(), - (this->end_ == NULL - ? NULL - : this->end_->copy()), - this->location()); - } - - bool - do_is_addressable() const; - - void - do_address_taken(bool escapes) - { this->array_->address_taken(escapes); } - - tree - do_get_tree(Translate_context*); - - private: - // The array we are getting a value from. - Expression* array_; - // The start or only index. - Expression* start_; - // The end index of a slice. This may be NULL for a simple array - // index, or it may be a nil expression for the length of the array. - Expression* end_; - // The type of the expression. - Type* type_; -}; - -// Array index traversal. - -int -Array_index_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->end_ != NULL) - { - if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Return the type of an array index. - -Type* -Array_index_expression::do_type() -{ - if (this->type_ == NULL) - { - Array_type* type = this->array_->type()->array_type(); - if (type == NULL) - this->type_ = Type::make_error_type(); - else if (this->end_ == NULL) - this->type_ = type->element_type(); - else if (type->is_open_array_type()) - { - // A slice of a slice has the same type as the original - // slice. - this->type_ = this->array_->type()->deref(); - } - else - { - // A slice of an array is a slice. - this->type_ = Type::make_array_type(type->element_type(), NULL); - } - } - return this->type_; -} - -// Set the type of an array index. - -void -Array_index_expression::do_determine_type(const Type_context*) -{ - this->array_->determine_type_no_context(); - this->start_->determine_type_no_context(); - if (this->end_ != NULL) - this->end_->determine_type_no_context(); -} - -// Check types of an array index. - -void -Array_index_expression::do_check_types(Gogo*) -{ - if (this->start_->type()->integer_type() == NULL) - this->report_error(_("index must be integer")); - if (this->end_ != NULL - && this->end_->type()->integer_type() == NULL - && !this->end_->is_nil_expression()) - this->report_error(_("slice end must be integer")); - - Array_type* array_type = this->array_->type()->array_type(); - if (array_type == NULL) - { - go_assert(this->array_->type()->is_error()); - return; - } - - unsigned int int_bits = - Type::lookup_integer_type("int")->integer_type()->bits(); - - Type* dummy; - mpz_t lval; - mpz_init(lval); - bool lval_valid = (array_type->length() != NULL - && array_type->length()->integer_constant_value(true, - lval, - &dummy)); - mpz_t ival; - mpz_init(ival); - if (this->start_->integer_constant_value(true, ival, &dummy)) - { - if (mpz_sgn(ival) < 0 - || mpz_sizeinbase(ival, 2) >= int_bits - || (lval_valid - && (this->end_ == NULL - ? mpz_cmp(ival, lval) >= 0 - : mpz_cmp(ival, lval) > 0))) - { - error_at(this->start_->location(), "array index out of bounds"); - this->set_is_error(); - } - } - if (this->end_ != NULL && !this->end_->is_nil_expression()) - { - if (this->end_->integer_constant_value(true, ival, &dummy)) - { - if (mpz_sgn(ival) < 0 - || mpz_sizeinbase(ival, 2) >= int_bits - || (lval_valid && mpz_cmp(ival, lval) > 0)) - { - error_at(this->end_->location(), "array index out of bounds"); - this->set_is_error(); - } - } - } - mpz_clear(ival); - mpz_clear(lval); - - // A slice of an array requires an addressable array. A slice of a - // slice is always possible. - if (this->end_ != NULL && !array_type->is_open_array_type()) - { - if (!this->array_->is_addressable()) - this->report_error(_("array is not addressable")); - else - this->array_->address_taken(true); - } -} - -// Return whether this expression is addressable. - -bool -Array_index_expression::do_is_addressable() const -{ - // A slice expression is not addressable. - if (this->end_ != NULL) - return false; - - // An index into a slice is addressable. - if (this->array_->type()->is_open_array_type()) - return true; - - // An index into an array is addressable if the array is - // addressable. - return this->array_->is_addressable(); -} - -// Get a tree for an array index. - -tree -Array_index_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - source_location loc = this->location(); - - Array_type* array_type = this->array_->type()->array_type(); - if (array_type == NULL) - { - go_assert(this->array_->type()->is_error()); - return error_mark_node; - } - - tree type_tree = array_type->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - - tree array_tree = this->array_->get_tree(context); - if (array_tree == error_mark_node) - return error_mark_node; - - if (array_type->length() == NULL && !DECL_P(array_tree)) - array_tree = save_expr(array_tree); - tree length_tree = array_type->length_tree(gogo, array_tree); - if (length_tree == error_mark_node) - return error_mark_node; - length_tree = save_expr(length_tree); - tree length_type = TREE_TYPE(length_tree); - - tree bad_index = boolean_false_node; - - tree start_tree = this->start_->get_tree(context); - if (start_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(start_tree)) - start_tree = save_expr(start_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree))) - start_tree = convert_to_integer(length_type, start_tree); - - bad_index = Expression::check_bounds(start_tree, length_type, bad_index, - loc); - - start_tree = fold_convert_loc(loc, length_type, start_tree); - bad_index = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, bad_index, - fold_build2_loc(loc, - (this->end_ == NULL - ? GE_EXPR - : GT_EXPR), - boolean_type_node, start_tree, - length_tree)); - - int code = (array_type->length() != NULL - ? (this->end_ == NULL - ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS - : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS) - : (this->end_ == NULL - ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS - : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS)); - tree crash = Gogo::runtime_error(code, loc); - - if (this->end_ == NULL) - { - // Simple array indexing. This has to return an l-value, so - // wrap the index check into START_TREE. - start_tree = build2(COMPOUND_EXPR, TREE_TYPE(start_tree), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - start_tree); - start_tree = fold_convert_loc(loc, sizetype, start_tree); - - if (array_type->length() != NULL) - { - // Fixed array. - return build4(ARRAY_REF, TREE_TYPE(type_tree), array_tree, - start_tree, NULL_TREE, NULL_TREE); - } - else - { - // Open array. - tree values = array_type->value_pointer_tree(gogo, array_tree); - tree element_type_tree = array_type->element_type()->get_tree(gogo); - if (element_type_tree == error_mark_node) - return error_mark_node; - tree element_size = TYPE_SIZE_UNIT(element_type_tree); - tree offset = fold_build2_loc(loc, MULT_EXPR, sizetype, - start_tree, element_size); - tree ptr = fold_build2_loc(loc, POINTER_PLUS_EXPR, - TREE_TYPE(values), values, offset); - return build_fold_indirect_ref(ptr); - } - } - - // Array slice. - - tree capacity_tree = array_type->capacity_tree(gogo, array_tree); - if (capacity_tree == error_mark_node) - return error_mark_node; - capacity_tree = fold_convert_loc(loc, length_type, capacity_tree); - - tree end_tree; - if (this->end_->is_nil_expression()) - end_tree = length_tree; - else - { - end_tree = this->end_->get_tree(context); - if (end_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(end_tree)) - end_tree = save_expr(end_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree))) - end_tree = convert_to_integer(length_type, end_tree); - - bad_index = Expression::check_bounds(end_tree, length_type, bad_index, - loc); - - end_tree = fold_convert_loc(loc, length_type, end_tree); - - capacity_tree = save_expr(capacity_tree); - tree bad_end = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - fold_build2_loc(loc, LT_EXPR, - boolean_type_node, - end_tree, start_tree), - fold_build2_loc(loc, GT_EXPR, - boolean_type_node, - end_tree, capacity_tree)); - bad_index = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - bad_index, bad_end); - } - - tree element_type_tree = array_type->element_type()->get_tree(gogo); - if (element_type_tree == error_mark_node) - return error_mark_node; - tree element_size = TYPE_SIZE_UNIT(element_type_tree); - - tree offset = fold_build2_loc(loc, MULT_EXPR, sizetype, - fold_convert_loc(loc, sizetype, start_tree), - element_size); - - tree value_pointer = array_type->value_pointer_tree(gogo, array_tree); - if (value_pointer == error_mark_node) - return error_mark_node; - - value_pointer = fold_build2_loc(loc, POINTER_PLUS_EXPR, - TREE_TYPE(value_pointer), - value_pointer, offset); - - tree result_length_tree = fold_build2_loc(loc, MINUS_EXPR, length_type, - end_tree, start_tree); - - tree result_capacity_tree = fold_build2_loc(loc, MINUS_EXPR, length_type, - capacity_tree, start_tree); - - tree struct_tree = this->type()->get_tree(gogo); - go_assert(TREE_CODE(struct_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(struct_tree); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0); - elt->index = field; - elt->value = value_pointer; - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0); - elt->index = field; - elt->value = fold_convert_loc(loc, TREE_TYPE(field), result_length_tree); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0); - elt->index = field; - elt->value = fold_convert_loc(loc, TREE_TYPE(field), result_capacity_tree); - - tree constructor = build_constructor(struct_tree, init); - - if (TREE_CONSTANT(value_pointer) - && TREE_CONSTANT(result_length_tree) - && TREE_CONSTANT(result_capacity_tree)) - TREE_CONSTANT(constructor) = 1; - - return fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(constructor), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - constructor); -} - -// Make an array index expression. END may be NULL. - -Expression* -Expression::make_array_index(Expression* array, Expression* start, - Expression* end, source_location location) -{ - // Taking a slice of a composite literal requires moving the literal - // onto the heap. - if (end != NULL && array->is_composite_literal()) - { - array = Expression::make_heap_composite(array, location); - array = Expression::make_unary(OPERATOR_MULT, array, location); - } - return new Array_index_expression(array, start, end, location); -} - -// A string index. This is used for both indexing and slicing. - -class String_index_expression : public Expression -{ - public: - String_index_expression(Expression* string, Expression* start, - Expression* end, source_location location) - : Expression(EXPRESSION_STRING_INDEX, location), - string_(string), start_(start), end_(end) - { } - - protected: - int - do_traverse(Traverse*); - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return Expression::make_string_index(this->string_->copy(), - this->start_->copy(), - (this->end_ == NULL - ? NULL - : this->end_->copy()), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - private: - // The string we are getting a value from. - Expression* string_; - // The start or only index. - Expression* start_; - // The end index of a slice. This may be NULL for a single index, - // or it may be a nil expression for the length of the string. - Expression* end_; -}; - -// String index traversal. - -int -String_index_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->end_ != NULL) - { - if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Return the type of a string index. - -Type* -String_index_expression::do_type() -{ - if (this->end_ == NULL) - return Type::lookup_integer_type("uint8"); - else - return this->string_->type(); -} - -// Determine the type of a string index. - -void -String_index_expression::do_determine_type(const Type_context*) -{ - this->string_->determine_type_no_context(); - this->start_->determine_type_no_context(); - if (this->end_ != NULL) - this->end_->determine_type_no_context(); -} - -// Check types of a string index. - -void -String_index_expression::do_check_types(Gogo*) -{ - if (this->start_->type()->integer_type() == NULL) - this->report_error(_("index must be integer")); - if (this->end_ != NULL - && this->end_->type()->integer_type() == NULL - && !this->end_->is_nil_expression()) - this->report_error(_("slice end must be integer")); - - std::string sval; - bool sval_valid = this->string_->string_constant_value(&sval); - - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (this->start_->integer_constant_value(true, ival, &dummy)) - { - if (mpz_sgn(ival) < 0 - || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0)) - { - error_at(this->start_->location(), "string index out of bounds"); - this->set_is_error(); - } - } - if (this->end_ != NULL && !this->end_->is_nil_expression()) - { - if (this->end_->integer_constant_value(true, ival, &dummy)) - { - if (mpz_sgn(ival) < 0 - || (sval_valid && mpz_cmp_ui(ival, sval.length()) > 0)) - { - error_at(this->end_->location(), "string index out of bounds"); - this->set_is_error(); - } - } - } - mpz_clear(ival); -} - -// Get a tree for a string index. - -tree -String_index_expression::do_get_tree(Translate_context* context) -{ - source_location loc = this->location(); - - tree string_tree = this->string_->get_tree(context); - if (string_tree == error_mark_node) - return error_mark_node; - - if (this->string_->type()->points_to() != NULL) - string_tree = build_fold_indirect_ref(string_tree); - if (!DECL_P(string_tree)) - string_tree = save_expr(string_tree); - tree string_type = TREE_TYPE(string_tree); - - tree length_tree = String_type::length_tree(context->gogo(), string_tree); - length_tree = save_expr(length_tree); - tree length_type = TREE_TYPE(length_tree); - - tree bad_index = boolean_false_node; - - tree start_tree = this->start_->get_tree(context); - if (start_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(start_tree)) - start_tree = save_expr(start_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree))) - start_tree = convert_to_integer(length_type, start_tree); - - bad_index = Expression::check_bounds(start_tree, length_type, bad_index, - loc); - - start_tree = fold_convert_loc(loc, length_type, start_tree); - - int code = (this->end_ == NULL - ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS - : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS); - tree crash = Gogo::runtime_error(code, loc); - - if (this->end_ == NULL) - { - bad_index = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - bad_index, - fold_build2_loc(loc, GE_EXPR, - boolean_type_node, - start_tree, length_tree)); - - tree bytes_tree = String_type::bytes_tree(context->gogo(), string_tree); - tree ptr = fold_build2_loc(loc, POINTER_PLUS_EXPR, TREE_TYPE(bytes_tree), - bytes_tree, - fold_convert_loc(loc, sizetype, start_tree)); - tree index = build_fold_indirect_ref_loc(loc, ptr); - - return build2(COMPOUND_EXPR, TREE_TYPE(index), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - index); - } - else - { - tree end_tree; - if (this->end_->is_nil_expression()) - end_tree = build_int_cst(length_type, -1); - else - { - end_tree = this->end_->get_tree(context); - if (end_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(end_tree)) - end_tree = save_expr(end_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree))) - end_tree = convert_to_integer(length_type, end_tree); - - bad_index = Expression::check_bounds(end_tree, length_type, - bad_index, loc); - - end_tree = fold_convert_loc(loc, length_type, end_tree); - } - - static tree strslice_fndecl; - tree ret = Gogo::call_builtin(&strslice_fndecl, - loc, - "__go_string_slice", - 3, - string_type, - string_type, - string_tree, - length_type, - start_tree, - length_type, - end_tree); - if (ret == error_mark_node) - return error_mark_node; - // This will panic if the bounds are out of range for the - // string. - TREE_NOTHROW(strslice_fndecl) = 0; - - if (bad_index == boolean_false_node) - return ret; - else - return build2(COMPOUND_EXPR, TREE_TYPE(ret), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - ret); - } -} - -// Make a string index expression. END may be NULL. - -Expression* -Expression::make_string_index(Expression* string, Expression* start, - Expression* end, source_location location) -{ - return new String_index_expression(string, start, end, location); -} - -// Class Map_index. - -// Get the type of the map. - -Map_type* -Map_index_expression::get_map_type() const -{ - Map_type* mt = this->map_->type()->deref()->map_type(); - if (mt == NULL) - go_assert(saw_errors()); - return mt; -} - -// Map index traversal. - -int -Map_index_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return Expression::traverse(&this->index_, traverse); -} - -// Return the type of a map index. - -Type* -Map_index_expression::do_type() -{ - Map_type* mt = this->get_map_type(); - if (mt == NULL) - return Type::make_error_type(); - Type* type = mt->val_type(); - // If this map index is in a tuple assignment, we actually return a - // pointer to the value type. Tuple_map_assignment_statement is - // responsible for handling this correctly. We need to get the type - // right in case this gets assigned to a temporary variable. - if (this->is_in_tuple_assignment_) - type = Type::make_pointer_type(type); - return type; -} - -// Fix the type of a map index. - -void -Map_index_expression::do_determine_type(const Type_context*) -{ - this->map_->determine_type_no_context(); - Map_type* mt = this->get_map_type(); - Type* key_type = mt == NULL ? NULL : mt->key_type(); - Type_context subcontext(key_type, false); - this->index_->determine_type(&subcontext); -} - -// Check types of a map index. - -void -Map_index_expression::do_check_types(Gogo*) -{ - std::string reason; - Map_type* mt = this->get_map_type(); - if (mt == NULL) - return; - if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason)) - { - if (reason.empty()) - this->report_error(_("incompatible type for map index")); - else - { - error_at(this->location(), "incompatible type for map index (%s)", - reason.c_str()); - this->set_is_error(); - } - } -} - -// Get a tree for a map index. - -tree -Map_index_expression::do_get_tree(Translate_context* context) -{ - Map_type* type = this->get_map_type(); - if (type == NULL) - return error_mark_node; - - tree valptr = this->get_value_pointer(context, this->is_lvalue_); - if (valptr == error_mark_node) - return error_mark_node; - valptr = save_expr(valptr); - - tree val_type_tree = TREE_TYPE(TREE_TYPE(valptr)); - - if (this->is_lvalue_) - return build_fold_indirect_ref(valptr); - else if (this->is_in_tuple_assignment_) - { - // Tuple_map_assignment_statement is responsible for using this - // appropriately. - return valptr; - } - else - { - return fold_build3(COND_EXPR, val_type_tree, - fold_build2(EQ_EXPR, boolean_type_node, valptr, - fold_convert(TREE_TYPE(valptr), - null_pointer_node)), - type->val_type()->get_init_tree(context->gogo(), - false), - build_fold_indirect_ref(valptr)); - } -} - -// Get a tree for the map index. This returns a tree which evaluates -// to a pointer to a value. The pointer will be NULL if the key is -// not in the map. - -tree -Map_index_expression::get_value_pointer(Translate_context* context, - bool insert) -{ - Map_type* type = this->get_map_type(); - if (type == NULL) - return error_mark_node; - - tree map_tree = this->map_->get_tree(context); - tree index_tree = this->index_->get_tree(context); - index_tree = Expression::convert_for_assignment(context, type->key_type(), - this->index_->type(), - index_tree, - this->location()); - if (map_tree == error_mark_node || index_tree == error_mark_node) - return error_mark_node; - - if (this->map_->type()->points_to() != NULL) - map_tree = build_fold_indirect_ref(map_tree); - - // We need to pass in a pointer to the key, so stuff it into a - // variable. - tree tmp; - tree make_tmp; - if (current_function_decl != NULL) - { - tmp = create_tmp_var(TREE_TYPE(index_tree), get_name(index_tree)); - DECL_IGNORED_P(tmp) = 0; - DECL_INITIAL(tmp) = index_tree; - make_tmp = build1(DECL_EXPR, void_type_node, tmp); - TREE_ADDRESSABLE(tmp) = 1; - } - else - { - tmp = build_decl(this->location(), VAR_DECL, create_tmp_var_name("M"), - TREE_TYPE(index_tree)); - DECL_EXTERNAL(tmp) = 0; - TREE_PUBLIC(tmp) = 0; - TREE_STATIC(tmp) = 1; - DECL_ARTIFICIAL(tmp) = 1; - if (!TREE_CONSTANT(index_tree)) - make_tmp = fold_build2_loc(this->location(), INIT_EXPR, void_type_node, - tmp, index_tree); - else - { - TREE_READONLY(tmp) = 1; - TREE_CONSTANT(tmp) = 1; - DECL_INITIAL(tmp) = index_tree; - make_tmp = NULL_TREE; - } - rest_of_decl_compilation(tmp, 1, 0); - } - tree tmpref = fold_convert_loc(this->location(), const_ptr_type_node, - build_fold_addr_expr_loc(this->location(), - tmp)); - - static tree map_index_fndecl; - tree call = Gogo::call_builtin(&map_index_fndecl, - this->location(), - "__go_map_index", - 3, - const_ptr_type_node, - TREE_TYPE(map_tree), - map_tree, - const_ptr_type_node, - tmpref, - boolean_type_node, - (insert - ? boolean_true_node - : boolean_false_node)); - if (call == error_mark_node) - return error_mark_node; - // This can panic on a map of interface type if the interface holds - // an uncomparable or unhashable type. - TREE_NOTHROW(map_index_fndecl) = 0; - - tree val_type_tree = type->val_type()->get_tree(context->gogo()); - if (val_type_tree == error_mark_node) - return error_mark_node; - tree ptr_val_type_tree = build_pointer_type(val_type_tree); - - tree ret = fold_convert_loc(this->location(), ptr_val_type_tree, call); - if (make_tmp != NULL_TREE) - ret = build2(COMPOUND_EXPR, ptr_val_type_tree, make_tmp, ret); - return ret; -} - -// Make a map index expression. - -Map_index_expression* -Expression::make_map_index(Expression* map, Expression* index, - source_location location) -{ - return new Map_index_expression(map, index, location); -} - -// Class Field_reference_expression. - -// Return the type of a field reference. - -Type* -Field_reference_expression::do_type() -{ - Type* type = this->expr_->type(); - if (type->is_error()) - return type; - Struct_type* struct_type = type->struct_type(); - go_assert(struct_type != NULL); - return struct_type->field(this->field_index_)->type(); -} - -// Check the types for a field reference. - -void -Field_reference_expression::do_check_types(Gogo*) -{ - Type* type = this->expr_->type(); - if (type->is_error()) - return; - Struct_type* struct_type = type->struct_type(); - go_assert(struct_type != NULL); - go_assert(struct_type->field(this->field_index_) != NULL); -} - -// Get a tree for a field reference. - -tree -Field_reference_expression::do_get_tree(Translate_context* context) -{ - tree struct_tree = this->expr_->get_tree(context); - if (struct_tree == error_mark_node - || TREE_TYPE(struct_tree) == error_mark_node) - return error_mark_node; - go_assert(TREE_CODE(TREE_TYPE(struct_tree)) == RECORD_TYPE); - tree field = TYPE_FIELDS(TREE_TYPE(struct_tree)); - if (field == NULL_TREE) - { - // This can happen for a type which refers to itself indirectly - // and then turns out to be erroneous. - go_assert(saw_errors()); - return error_mark_node; - } - for (unsigned int i = this->field_index_; i > 0; --i) - { - field = DECL_CHAIN(field); - go_assert(field != NULL_TREE); - } - if (TREE_TYPE(field) == error_mark_node) - return error_mark_node; - return build3(COMPONENT_REF, TREE_TYPE(field), struct_tree, field, - NULL_TREE); -} - -// Make a reference to a qualified identifier in an expression. - -Field_reference_expression* -Expression::make_field_reference(Expression* expr, unsigned int field_index, - source_location location) -{ - return new Field_reference_expression(expr, field_index, location); -} - -// Class Interface_field_reference_expression. - -// Return a tree for the pointer to the function to call. - -tree -Interface_field_reference_expression::get_function_tree(Translate_context*, - tree expr) -{ - if (this->expr_->type()->points_to() != NULL) - expr = build_fold_indirect_ref(expr); - - tree expr_type = TREE_TYPE(expr); - go_assert(TREE_CODE(expr_type) == RECORD_TYPE); - - tree field = TYPE_FIELDS(expr_type); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0); - - tree table = build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE); - go_assert(POINTER_TYPE_P(TREE_TYPE(table))); - - table = build_fold_indirect_ref(table); - go_assert(TREE_CODE(TREE_TYPE(table)) == RECORD_TYPE); - - std::string name = Gogo::unpack_hidden_name(this->name_); - for (field = DECL_CHAIN(TYPE_FIELDS(TREE_TYPE(table))); - field != NULL_TREE; - field = DECL_CHAIN(field)) - { - if (name == IDENTIFIER_POINTER(DECL_NAME(field))) - break; - } - go_assert(field != NULL_TREE); - - return build3(COMPONENT_REF, TREE_TYPE(field), table, field, NULL_TREE); -} - -// Return a tree for the first argument to pass to the interface -// function. - -tree -Interface_field_reference_expression::get_underlying_object_tree( - Translate_context*, - tree expr) -{ - if (this->expr_->type()->points_to() != NULL) - expr = build_fold_indirect_ref(expr); - - tree expr_type = TREE_TYPE(expr); - go_assert(TREE_CODE(expr_type) == RECORD_TYPE); - - tree field = DECL_CHAIN(TYPE_FIELDS(expr_type)); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0); - - return build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE); -} - -// Traversal. - -int -Interface_field_reference_expression::do_traverse(Traverse* traverse) -{ - return Expression::traverse(&this->expr_, traverse); -} - -// Return the type of an interface field reference. - -Type* -Interface_field_reference_expression::do_type() -{ - Type* expr_type = this->expr_->type(); - - Type* points_to = expr_type->points_to(); - if (points_to != NULL) - expr_type = points_to; - - Interface_type* interface_type = expr_type->interface_type(); - if (interface_type == NULL) - return Type::make_error_type(); - - const Typed_identifier* method = interface_type->find_method(this->name_); - if (method == NULL) - return Type::make_error_type(); - - return method->type(); -} - -// Determine types. - -void -Interface_field_reference_expression::do_determine_type(const Type_context*) -{ - this->expr_->determine_type_no_context(); -} - -// Check the types for an interface field reference. - -void -Interface_field_reference_expression::do_check_types(Gogo*) -{ - Type* type = this->expr_->type(); - - Type* points_to = type->points_to(); - if (points_to != NULL) - type = points_to; - - Interface_type* interface_type = type->interface_type(); - if (interface_type == NULL) - { - if (!type->is_error_type()) - this->report_error(_("expected interface or pointer to interface")); - } - else - { - const Typed_identifier* method = - interface_type->find_method(this->name_); - if (method == NULL) - { - error_at(this->location(), "method %qs not in interface", - Gogo::message_name(this->name_).c_str()); - this->set_is_error(); - } - } -} - -// Get a tree for a reference to a field in an interface. There is no -// standard tree type representation for this: it's a function -// attached to its first argument, like a Bound_method_expression. -// The only places it may currently be used are in a Call_expression -// or a Go_statement, which will take it apart directly. So this has -// nothing to do at present. - -tree -Interface_field_reference_expression::do_get_tree(Translate_context*) -{ - go_unreachable(); -} - -// Make a reference to a field in an interface. - -Expression* -Expression::make_interface_field_reference(Expression* expr, - const std::string& field, - source_location location) -{ - return new Interface_field_reference_expression(expr, field, location); -} - -// A general selector. This is a Parser_expression for LEFT.NAME. It -// is lowered after we know the type of the left hand side. - -class Selector_expression : public Parser_expression -{ - public: - Selector_expression(Expression* left, const std::string& name, - source_location location) - : Parser_expression(EXPRESSION_SELECTOR, location), - left_(left), name_(name) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return Expression::traverse(&this->left_, traverse); } - - Expression* - do_lower(Gogo*, Named_object*, int); - - Expression* - do_copy() - { - return new Selector_expression(this->left_->copy(), this->name_, - this->location()); - } - - private: - Expression* - lower_method_expression(Gogo*); - - // The expression on the left hand side. - Expression* left_; - // The name on the right hand side. - std::string name_; -}; - -// Lower a selector expression once we know the real type of the left -// hand side. - -Expression* -Selector_expression::do_lower(Gogo* gogo, Named_object*, int) -{ - Expression* left = this->left_; - if (left->is_type_expression()) - return this->lower_method_expression(gogo); - return Type::bind_field_or_method(gogo, left->type(), left, this->name_, - this->location()); -} - -// Lower a method expression T.M or (*T).M. We turn this into a -// function literal. - -Expression* -Selector_expression::lower_method_expression(Gogo* gogo) -{ - source_location location = this->location(); - Type* type = this->left_->type(); - const std::string& name(this->name_); - - bool is_pointer; - if (type->points_to() == NULL) - is_pointer = false; - else - { - is_pointer = true; - type = type->points_to(); - } - Named_type* nt = type->named_type(); - if (nt == NULL) - { - error_at(location, - ("method expression requires named type or " - "pointer to named type")); - return Expression::make_error(location); - } - - bool is_ambiguous; - Method* method = nt->method_function(name, &is_ambiguous); - const Typed_identifier* imethod = NULL; - if (method == NULL && !is_pointer) - { - Interface_type* it = nt->interface_type(); - if (it != NULL) - imethod = it->find_method(name); - } - - if (method == NULL && imethod == NULL) - { - if (!is_ambiguous) - error_at(location, "type %<%s%s%> has no method %<%s%>", - is_pointer ? "*" : "", - nt->message_name().c_str(), - Gogo::message_name(name).c_str()); - else - error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>", - Gogo::message_name(name).c_str(), - is_pointer ? "*" : "", - nt->message_name().c_str()); - return Expression::make_error(location); - } - - if (method != NULL && !is_pointer && !method->is_value_method()) - { - error_at(location, "method requires pointer (use %<(*%s).%s)%>", - nt->message_name().c_str(), - Gogo::message_name(name).c_str()); - return Expression::make_error(location); - } - - // Build a new function type in which the receiver becomes the first - // argument. - Function_type* method_type; - if (method != NULL) - { - method_type = method->type(); - go_assert(method_type->is_method()); - } - else - { - method_type = imethod->type()->function_type(); - go_assert(method_type != NULL && !method_type->is_method()); - } - - const char* const receiver_name = "$this"; - Typed_identifier_list* parameters = new Typed_identifier_list(); - parameters->push_back(Typed_identifier(receiver_name, this->left_->type(), - location)); - - const Typed_identifier_list* method_parameters = method_type->parameters(); - if (method_parameters != NULL) - { - for (Typed_identifier_list::const_iterator p = method_parameters->begin(); - p != method_parameters->end(); - ++p) - parameters->push_back(*p); - } - - const Typed_identifier_list* method_results = method_type->results(); - Typed_identifier_list* results; - if (method_results == NULL) - results = NULL; - else - { - results = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator p = method_results->begin(); - p != method_results->end(); - ++p) - results->push_back(*p); - } - - Function_type* fntype = Type::make_function_type(NULL, parameters, results, - location); - if (method_type->is_varargs()) - fntype->set_is_varargs(); - - // We generate methods which always takes a pointer to the receiver - // as their first argument. If this is for a pointer type, we can - // simply reuse the existing function. We use an internal hack to - // get the right type. - - if (method != NULL && is_pointer) - { - Named_object* mno = (method->needs_stub_method() - ? method->stub_object() - : method->named_object()); - Expression* f = Expression::make_func_reference(mno, NULL, location); - f = Expression::make_cast(fntype, f, location); - Type_conversion_expression* tce = - static_cast(f); - tce->set_may_convert_function_types(); - return f; - } - - Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false, - location); - - Named_object* vno = gogo->lookup(receiver_name, NULL); - go_assert(vno != NULL); - Expression* ve = Expression::make_var_reference(vno, location); - Expression* bm; - if (method != NULL) - bm = Type::bind_field_or_method(gogo, nt, ve, name, location); - else - bm = Expression::make_interface_field_reference(ve, name, location); - - // Even though we found the method above, if it has an error type we - // may see an error here. - if (bm->is_error_expression()) - { - gogo->finish_function(location); - return bm; - } - - Expression_list* args; - if (method_parameters == NULL) - args = NULL; - else - { - args = new Expression_list(); - for (Typed_identifier_list::const_iterator p = method_parameters->begin(); - p != method_parameters->end(); - ++p) - { - vno = gogo->lookup(p->name(), NULL); - go_assert(vno != NULL); - args->push_back(Expression::make_var_reference(vno, location)); - } - } - - Call_expression* call = Expression::make_call(bm, args, - method_type->is_varargs(), - location); - - size_t count = call->result_count(); - Statement* s; - if (count == 0) - s = Statement::make_statement(call); - else - { - Expression_list* retvals = new Expression_list(); - if (count <= 1) - retvals->push_back(call); - else - { - for (size_t i = 0; i < count; ++i) - retvals->push_back(Expression::make_call_result(call, i)); - } - s = Statement::make_return_statement(retvals, location); - } - gogo->add_statement(s); - - gogo->finish_function(location); - - return Expression::make_func_reference(no, NULL, location); -} - -// Make a selector expression. - -Expression* -Expression::make_selector(Expression* left, const std::string& name, - source_location location) -{ - return new Selector_expression(left, name, location); -} - -// Implement the builtin function new. - -class Allocation_expression : public Expression -{ - public: - Allocation_expression(Type* type, source_location location) - : Expression(EXPRESSION_ALLOCATION, location), - type_(type) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return Type::traverse(this->type_, traverse); } - - Type* - do_type() - { return Type::make_pointer_type(this->type_); } - - void - do_determine_type(const Type_context*) - { } - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { return new Allocation_expression(this->type_, this->location()); } - - tree - do_get_tree(Translate_context*); - - private: - // The type we are allocating. - Type* type_; -}; - -// Check the type of an allocation expression. - -void -Allocation_expression::do_check_types(Gogo*) -{ - if (this->type_->function_type() != NULL) - this->report_error(_("invalid new of function type")); -} - -// Return a tree for an allocation expression. - -tree -Allocation_expression::do_get_tree(Translate_context* context) -{ - tree type_tree = this->type_->get_tree(context->gogo()); - if (type_tree == error_mark_node) - return error_mark_node; - tree size_tree = TYPE_SIZE_UNIT(type_tree); - tree space = context->gogo()->allocate_memory(this->type_, size_tree, - this->location()); - if (space == error_mark_node) - return error_mark_node; - return fold_convert(build_pointer_type(type_tree), space); -} - -// Make an allocation expression. - -Expression* -Expression::make_allocation(Type* type, source_location location) -{ - return new Allocation_expression(type, location); -} - -// Implement the builtin function make. - -class Make_expression : public Expression -{ - public: - Make_expression(Type* type, Expression_list* args, source_location location) - : Expression(EXPRESSION_MAKE, location), - type_(type), args_(args) - { } - - protected: - int - do_traverse(Traverse* traverse); - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Make_expression(this->type_, this->args_->copy(), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - private: - // The type we are making. - Type* type_; - // The arguments to pass to the make routine. - Expression_list* args_; -}; - -// Traversal. - -int -Make_expression::do_traverse(Traverse* traverse) -{ - if (this->args_ != NULL - && this->args_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Set types of arguments. - -void -Make_expression::do_determine_type(const Type_context*) -{ - if (this->args_ != NULL) - { - Type_context context(Type::lookup_integer_type("int"), false); - for (Expression_list::const_iterator pe = this->args_->begin(); - pe != this->args_->end(); - ++pe) - (*pe)->determine_type(&context); - } -} - -// Check types for a make expression. - -void -Make_expression::do_check_types(Gogo*) -{ - if (this->type_->channel_type() == NULL - && this->type_->map_type() == NULL - && (this->type_->array_type() == NULL - || this->type_->array_type()->length() != NULL)) - this->report_error(_("invalid type for make function")); - else if (!this->type_->check_make_expression(this->args_, this->location())) - this->set_is_error(); -} - -// Return a tree for a make expression. - -tree -Make_expression::do_get_tree(Translate_context* context) -{ - return this->type_->make_expression_tree(context, this->args_, - this->location()); -} - -// Make a make expression. - -Expression* -Expression::make_make(Type* type, Expression_list* args, - source_location location) -{ - return new Make_expression(type, args, location); -} - -// Construct a struct. - -class Struct_construction_expression : public Expression -{ - public: - Struct_construction_expression(Type* type, Expression_list* vals, - source_location location) - : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location), - type_(type), vals_(vals) - { } - - // Return whether this is a constant initializer. - bool - is_constant_struct() const; - - protected: - int - do_traverse(Traverse* traverse); - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Struct_construction_expression(this->type_, this->vals_->copy(), - this->location()); - } - - bool - do_is_addressable() const - { return true; } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The type of the struct to construct. - Type* type_; - // The list of values, in order of the fields in the struct. A NULL - // entry means that the field should be zero-initialized. - Expression_list* vals_; -}; - -// Traversal. - -int -Struct_construction_expression::do_traverse(Traverse* traverse) -{ - if (this->vals_ != NULL - && this->vals_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Return whether this is a constant initializer. - -bool -Struct_construction_expression::is_constant_struct() const -{ - if (this->vals_ == NULL) - return true; - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - if (*pv != NULL - && !(*pv)->is_constant() - && (!(*pv)->is_composite_literal() - || (*pv)->is_nonconstant_composite_literal())) - return false; - } - - const Struct_field_list* fields = this->type_->struct_type()->fields(); - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - // There are no constant constructors for interfaces. - if (pf->type()->interface_type() != NULL) - return false; - } - - return true; -} - -// Final type determination. - -void -Struct_construction_expression::do_determine_type(const Type_context*) -{ - if (this->vals_ == NULL) - return; - const Struct_field_list* fields = this->type_->struct_type()->fields(); - Expression_list::const_iterator pv = this->vals_->begin(); - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++pv) - { - if (pv == this->vals_->end()) - return; - if (*pv != NULL) - { - Type_context subcontext(pf->type(), false); - (*pv)->determine_type(&subcontext); - } - } - // Extra values are an error we will report elsewhere; we still want - // to determine the type to avoid knockon errors. - for (; pv != this->vals_->end(); ++pv) - (*pv)->determine_type_no_context(); -} - -// Check types. - -void -Struct_construction_expression::do_check_types(Gogo*) -{ - if (this->vals_ == NULL) - return; - - Struct_type* st = this->type_->struct_type(); - if (this->vals_->size() > st->field_count()) - { - this->report_error(_("too many expressions for struct")); - return; - } - - const Struct_field_list* fields = st->fields(); - Expression_list::const_iterator pv = this->vals_->begin(); - int i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++pv, ++i) - { - if (pv == this->vals_->end()) - { - this->report_error(_("too few expressions for struct")); - break; - } - - if (*pv == NULL) - continue; - - std::string reason; - if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason)) - { - if (reason.empty()) - error_at((*pv)->location(), - "incompatible type for field %d in struct construction", - i + 1); - else - error_at((*pv)->location(), - ("incompatible type for field %d in " - "struct construction (%s)"), - i + 1, reason.c_str()); - this->set_is_error(); - } - } - go_assert(pv == this->vals_->end()); -} - -// Return a tree for constructing a struct. - -tree -Struct_construction_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - - if (this->vals_ == NULL) - return this->type_->get_init_tree(gogo, false); - - tree type_tree = this->type_->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - go_assert(TREE_CODE(type_tree) == RECORD_TYPE); - - bool is_constant = true; - const Struct_field_list* fields = this->type_->struct_type()->fields(); - VEC(constructor_elt,gc)* elts = VEC_alloc(constructor_elt, gc, - fields->size()); - Struct_field_list::const_iterator pf = fields->begin(); - Expression_list::const_iterator pv = this->vals_->begin(); - for (tree field = TYPE_FIELDS(type_tree); - field != NULL_TREE; - field = DECL_CHAIN(field), ++pf) - { - go_assert(pf != fields->end()); - - tree val; - if (pv == this->vals_->end()) - val = pf->type()->get_init_tree(gogo, false); - else if (*pv == NULL) - { - val = pf->type()->get_init_tree(gogo, false); - ++pv; - } - else - { - val = Expression::convert_for_assignment(context, pf->type(), - (*pv)->type(), - (*pv)->get_tree(context), - this->location()); - ++pv; - } - - if (val == error_mark_node || TREE_TYPE(val) == error_mark_node) - return error_mark_node; - - constructor_elt* elt = VEC_quick_push(constructor_elt, elts, NULL); - elt->index = field; - elt->value = val; - if (!TREE_CONSTANT(val)) - is_constant = false; - } - go_assert(pf == fields->end()); - - tree ret = build_constructor(type_tree, elts); - if (is_constant) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Export a struct construction. - -void -Struct_construction_expression::do_export(Export* exp) const -{ - exp->write_c_string("convert("); - exp->write_type(this->type_); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - exp->write_c_string(", "); - if (*pv != NULL) - (*pv)->export_expression(exp); - } - exp->write_c_string(")"); -} - -// Make a struct composite literal. This used by the thunk code. - -Expression* -Expression::make_struct_composite_literal(Type* type, Expression_list* vals, - source_location location) -{ - go_assert(type->struct_type() != NULL); - return new Struct_construction_expression(type, vals, location); -} - -// Construct an array. This class is not used directly; instead we -// use the child classes, Fixed_array_construction_expression and -// Open_array_construction_expression. - -class Array_construction_expression : public Expression -{ - protected: - Array_construction_expression(Expression_classification classification, - Type* type, Expression_list* vals, - source_location location) - : Expression(classification, location), - type_(type), vals_(vals) - { } - - public: - // Return whether this is a constant initializer. - bool - is_constant_array() const; - - // Return the number of elements. - size_t - element_count() const - { return this->vals_ == NULL ? 0 : this->vals_->size(); } - -protected: - int - do_traverse(Traverse* traverse); - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - bool - do_is_addressable() const - { return true; } - - void - do_export(Export*) const; - - // The list of values. - Expression_list* - vals() - { return this->vals_; } - - // Get a constructor tree for the array values. - tree - get_constructor_tree(Translate_context* context, tree type_tree); - - private: - // The type of the array to construct. - Type* type_; - // The list of values. - Expression_list* vals_; -}; - -// Traversal. - -int -Array_construction_expression::do_traverse(Traverse* traverse) -{ - if (this->vals_ != NULL - && this->vals_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Return whether this is a constant initializer. - -bool -Array_construction_expression::is_constant_array() const -{ - if (this->vals_ == NULL) - return true; - - // There are no constant constructors for interfaces. - if (this->type_->array_type()->element_type()->interface_type() != NULL) - return false; - - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - if (*pv != NULL - && !(*pv)->is_constant() - && (!(*pv)->is_composite_literal() - || (*pv)->is_nonconstant_composite_literal())) - return false; - } - return true; -} - -// Final type determination. - -void -Array_construction_expression::do_determine_type(const Type_context*) -{ - if (this->vals_ == NULL) - return; - Type_context subcontext(this->type_->array_type()->element_type(), false); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - if (*pv != NULL) - (*pv)->determine_type(&subcontext); - } -} - -// Check types. - -void -Array_construction_expression::do_check_types(Gogo*) -{ - if (this->vals_ == NULL) - return; - - Array_type* at = this->type_->array_type(); - int i = 0; - Type* element_type = at->element_type(); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv, ++i) - { - if (*pv != NULL - && !Type::are_assignable(element_type, (*pv)->type(), NULL)) - { - error_at((*pv)->location(), - "incompatible type for element %d in composite literal", - i + 1); - this->set_is_error(); - } - } - - Expression* length = at->length(); - if (length != NULL) - { - mpz_t val; - mpz_init(val); - Type* type; - if (at->length()->integer_constant_value(true, val, &type)) - { - if (this->vals_->size() > mpz_get_ui(val)) - this->report_error(_("too many elements in composite literal")); - } - mpz_clear(val); - } -} - -// Get a constructor tree for the array values. - -tree -Array_construction_expression::get_constructor_tree(Translate_context* context, - tree type_tree) -{ - VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc, - (this->vals_ == NULL - ? 0 - : this->vals_->size())); - Type* element_type = this->type_->array_type()->element_type(); - bool is_constant = true; - if (this->vals_ != NULL) - { - size_t i = 0; - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv, ++i) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, values, NULL); - elt->index = size_int(i); - if (*pv == NULL) - elt->value = element_type->get_init_tree(context->gogo(), false); - else - { - tree value_tree = (*pv)->get_tree(context); - elt->value = Expression::convert_for_assignment(context, - element_type, - (*pv)->type(), - value_tree, - this->location()); - } - if (elt->value == error_mark_node) - return error_mark_node; - if (!TREE_CONSTANT(elt->value)) - is_constant = false; - } - } - - tree ret = build_constructor(type_tree, values); - if (is_constant) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Export an array construction. - -void -Array_construction_expression::do_export(Export* exp) const -{ - exp->write_c_string("convert("); - exp->write_type(this->type_); - if (this->vals_ != NULL) - { - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - exp->write_c_string(", "); - if (*pv != NULL) - (*pv)->export_expression(exp); - } - } - exp->write_c_string(")"); -} - -// Construct a fixed array. - -class Fixed_array_construction_expression : - public Array_construction_expression -{ - public: - Fixed_array_construction_expression(Type* type, Expression_list* vals, - source_location location) - : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION, - type, vals, location) - { - go_assert(type->array_type() != NULL - && type->array_type()->length() != NULL); - } - - protected: - Expression* - do_copy() - { - return new Fixed_array_construction_expression(this->type(), - (this->vals() == NULL - ? NULL - : this->vals()->copy()), - this->location()); - } - - tree - do_get_tree(Translate_context*); -}; - -// Return a tree for constructing a fixed array. - -tree -Fixed_array_construction_expression::do_get_tree(Translate_context* context) -{ - return this->get_constructor_tree(context, - this->type()->get_tree(context->gogo())); -} - -// Construct an open array. - -class Open_array_construction_expression : public Array_construction_expression -{ - public: - Open_array_construction_expression(Type* type, Expression_list* vals, - source_location location) - : Array_construction_expression(EXPRESSION_OPEN_ARRAY_CONSTRUCTION, - type, vals, location) - { - go_assert(type->array_type() != NULL - && type->array_type()->length() == NULL); - } - - protected: - // Note that taking the address of an open array literal is invalid. - - Expression* - do_copy() - { - return new Open_array_construction_expression(this->type(), - (this->vals() == NULL - ? NULL - : this->vals()->copy()), - this->location()); - } - - tree - do_get_tree(Translate_context*); -}; - -// Return a tree for constructing an open array. - -tree -Open_array_construction_expression::do_get_tree(Translate_context* context) -{ - Array_type* array_type = this->type()->array_type(); - if (array_type == NULL) - { - go_assert(this->type()->is_error()); - return error_mark_node; - } - - Type* element_type = array_type->element_type(); - tree element_type_tree = element_type->get_tree(context->gogo()); - if (element_type_tree == error_mark_node) - return error_mark_node; - - tree values; - tree length_tree; - if (this->vals() == NULL || this->vals()->empty()) - { - // We need to create a unique value. - tree max = size_int(0); - tree constructor_type = build_array_type(element_type_tree, - build_index_type(max)); - if (constructor_type == error_mark_node) - return error_mark_node; - VEC(constructor_elt,gc)* vec = VEC_alloc(constructor_elt, gc, 1); - constructor_elt* elt = VEC_quick_push(constructor_elt, vec, NULL); - elt->index = size_int(0); - elt->value = element_type->get_init_tree(context->gogo(), false); - values = build_constructor(constructor_type, vec); - if (TREE_CONSTANT(elt->value)) - TREE_CONSTANT(values) = 1; - length_tree = size_int(0); - } - else - { - tree max = size_int(this->vals()->size() - 1); - tree constructor_type = build_array_type(element_type_tree, - build_index_type(max)); - if (constructor_type == error_mark_node) - return error_mark_node; - values = this->get_constructor_tree(context, constructor_type); - length_tree = size_int(this->vals()->size()); - } - - if (values == error_mark_node) - return error_mark_node; - - bool is_constant_initializer = TREE_CONSTANT(values); - - // We have to copy the initial values into heap memory if we are in - // a function or if the values are not constants. We also have to - // copy them if they may contain pointers in a non-constant context, - // as otherwise the garbage collector won't see them. - bool copy_to_heap = (context->function() != NULL - || !is_constant_initializer - || (element_type->has_pointer() - && !context->is_const())); - - if (is_constant_initializer) - { - tree tmp = build_decl(this->location(), VAR_DECL, - create_tmp_var_name("C"), TREE_TYPE(values)); - DECL_EXTERNAL(tmp) = 0; - TREE_PUBLIC(tmp) = 0; - TREE_STATIC(tmp) = 1; - DECL_ARTIFICIAL(tmp) = 1; - if (copy_to_heap) - { - // If we are not copying the value to the heap, we will only - // initialize the value once, so we can use this directly - // rather than copying it. In that case we can't make it - // read-only, because the program is permitted to change it. - TREE_READONLY(tmp) = 1; - TREE_CONSTANT(tmp) = 1; - } - DECL_INITIAL(tmp) = values; - rest_of_decl_compilation(tmp, 1, 0); - values = tmp; - } - - tree space; - tree set; - if (!copy_to_heap) - { - // the initializer will only run once. - space = build_fold_addr_expr(values); - set = NULL_TREE; - } - else - { - tree memsize = TYPE_SIZE_UNIT(TREE_TYPE(values)); - space = context->gogo()->allocate_memory(element_type, memsize, - this->location()); - space = save_expr(space); - - tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space); - tree ref = build_fold_indirect_ref_loc(this->location(), s); - TREE_THIS_NOTRAP(ref) = 1; - set = build2(MODIFY_EXPR, void_type_node, ref, values); - } - - // Build a constructor for the open array. - - tree type_tree = this->type()->get_tree(context->gogo()); - if (type_tree == error_mark_node) - return error_mark_node; - go_assert(TREE_CODE(type_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(type_tree); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), space); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), length_tree); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), length_tree); - - tree constructor = build_constructor(type_tree, init); - if (constructor == error_mark_node) - return error_mark_node; - if (!copy_to_heap) - TREE_CONSTANT(constructor) = 1; - - if (set == NULL_TREE) - return constructor; - else - return build2(COMPOUND_EXPR, type_tree, set, constructor); -} - -// Make a slice composite literal. This is used by the type -// descriptor code. - -Expression* -Expression::make_slice_composite_literal(Type* type, Expression_list* vals, - source_location location) -{ - go_assert(type->is_open_array_type()); - return new Open_array_construction_expression(type, vals, location); -} - -// Construct a map. - -class Map_construction_expression : public Expression -{ - public: - Map_construction_expression(Type* type, Expression_list* vals, - source_location location) - : Expression(EXPRESSION_MAP_CONSTRUCTION, location), - type_(type), vals_(vals) - { go_assert(vals == NULL || vals->size() % 2 == 0); } - - protected: - int - do_traverse(Traverse* traverse); - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Map_construction_expression(this->type_, this->vals_->copy(), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The type of the map to construct. - Type* type_; - // The list of values. - Expression_list* vals_; -}; - -// Traversal. - -int -Map_construction_expression::do_traverse(Traverse* traverse) -{ - if (this->vals_ != NULL - && this->vals_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Final type determination. - -void -Map_construction_expression::do_determine_type(const Type_context*) -{ - if (this->vals_ == NULL) - return; - - Map_type* mt = this->type_->map_type(); - Type_context key_context(mt->key_type(), false); - Type_context val_context(mt->val_type(), false); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - (*pv)->determine_type(&key_context); - ++pv; - (*pv)->determine_type(&val_context); - } -} - -// Check types. - -void -Map_construction_expression::do_check_types(Gogo*) -{ - if (this->vals_ == NULL) - return; - - Map_type* mt = this->type_->map_type(); - int i = 0; - Type* key_type = mt->key_type(); - Type* val_type = mt->val_type(); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv, ++i) - { - if (!Type::are_assignable(key_type, (*pv)->type(), NULL)) - { - error_at((*pv)->location(), - "incompatible type for element %d key in map construction", - i + 1); - this->set_is_error(); - } - ++pv; - if (!Type::are_assignable(val_type, (*pv)->type(), NULL)) - { - error_at((*pv)->location(), - ("incompatible type for element %d value " - "in map construction"), - i + 1); - this->set_is_error(); - } - } -} - -// Return a tree for constructing a map. - -tree -Map_construction_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - source_location loc = this->location(); - - Map_type* mt = this->type_->map_type(); - - // Build a struct to hold the key and value. - tree struct_type = make_node(RECORD_TYPE); - - Type* key_type = mt->key_type(); - tree id = get_identifier("__key"); - tree key_type_tree = key_type->get_tree(gogo); - if (key_type_tree == error_mark_node) - return error_mark_node; - tree key_field = build_decl(loc, FIELD_DECL, id, key_type_tree); - DECL_CONTEXT(key_field) = struct_type; - TYPE_FIELDS(struct_type) = key_field; - - Type* val_type = mt->val_type(); - id = get_identifier("__val"); - tree val_type_tree = val_type->get_tree(gogo); - if (val_type_tree == error_mark_node) - return error_mark_node; - tree val_field = build_decl(loc, FIELD_DECL, id, val_type_tree); - DECL_CONTEXT(val_field) = struct_type; - DECL_CHAIN(key_field) = val_field; - - layout_type(struct_type); - - bool is_constant = true; - size_t i = 0; - tree valaddr; - tree make_tmp; - - if (this->vals_ == NULL || this->vals_->empty()) - { - valaddr = null_pointer_node; - make_tmp = NULL_TREE; - } - else - { - VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc, - this->vals_->size() / 2); - - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv, ++i) - { - bool one_is_constant = true; - - VEC(constructor_elt,gc)* one = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, one, NULL); - elt->index = key_field; - tree val_tree = (*pv)->get_tree(context); - elt->value = Expression::convert_for_assignment(context, key_type, - (*pv)->type(), - val_tree, loc); - if (elt->value == error_mark_node) - return error_mark_node; - if (!TREE_CONSTANT(elt->value)) - one_is_constant = false; - - ++pv; - - elt = VEC_quick_push(constructor_elt, one, NULL); - elt->index = val_field; - val_tree = (*pv)->get_tree(context); - elt->value = Expression::convert_for_assignment(context, val_type, - (*pv)->type(), - val_tree, loc); - if (elt->value == error_mark_node) - return error_mark_node; - if (!TREE_CONSTANT(elt->value)) - one_is_constant = false; - - elt = VEC_quick_push(constructor_elt, values, NULL); - elt->index = size_int(i); - elt->value = build_constructor(struct_type, one); - if (one_is_constant) - TREE_CONSTANT(elt->value) = 1; - else - is_constant = false; - } - - tree index_type = build_index_type(size_int(i - 1)); - tree array_type = build_array_type(struct_type, index_type); - tree init = build_constructor(array_type, values); - if (is_constant) - TREE_CONSTANT(init) = 1; - tree tmp; - if (current_function_decl != NULL) - { - tmp = create_tmp_var(array_type, get_name(array_type)); - DECL_INITIAL(tmp) = init; - make_tmp = fold_build1_loc(loc, DECL_EXPR, void_type_node, tmp); - TREE_ADDRESSABLE(tmp) = 1; - } - else - { - tmp = build_decl(loc, VAR_DECL, create_tmp_var_name("M"), array_type); - DECL_EXTERNAL(tmp) = 0; - TREE_PUBLIC(tmp) = 0; - TREE_STATIC(tmp) = 1; - DECL_ARTIFICIAL(tmp) = 1; - if (!TREE_CONSTANT(init)) - make_tmp = fold_build2_loc(loc, INIT_EXPR, void_type_node, tmp, - init); - else - { - TREE_READONLY(tmp) = 1; - TREE_CONSTANT(tmp) = 1; - DECL_INITIAL(tmp) = init; - make_tmp = NULL_TREE; - } - rest_of_decl_compilation(tmp, 1, 0); - } - - valaddr = build_fold_addr_expr(tmp); - } - - tree descriptor = gogo->map_descriptor(mt); - - tree type_tree = this->type_->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - - static tree construct_map_fndecl; - tree call = Gogo::call_builtin(&construct_map_fndecl, - loc, - "__go_construct_map", - 6, - type_tree, - TREE_TYPE(descriptor), - descriptor, - sizetype, - size_int(i), - sizetype, - TYPE_SIZE_UNIT(struct_type), - sizetype, - byte_position(val_field), - sizetype, - TYPE_SIZE_UNIT(TREE_TYPE(val_field)), - const_ptr_type_node, - fold_convert(const_ptr_type_node, valaddr)); - if (call == error_mark_node) - return error_mark_node; - - tree ret; - if (make_tmp == NULL) - ret = call; - else - ret = fold_build2_loc(loc, COMPOUND_EXPR, type_tree, make_tmp, call); - return ret; -} - -// Export an array construction. - -void -Map_construction_expression::do_export(Export* exp) const -{ - exp->write_c_string("convert("); - exp->write_type(this->type_); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - exp->write_c_string(", "); - (*pv)->export_expression(exp); - } - exp->write_c_string(")"); -} - -// A general composite literal. This is lowered to a type specific -// version. - -class Composite_literal_expression : public Parser_expression -{ - public: - Composite_literal_expression(Type* type, int depth, bool has_keys, - Expression_list* vals, source_location location) - : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location), - type_(type), depth_(depth), vals_(vals), has_keys_(has_keys) - { } - - protected: - int - do_traverse(Traverse* traverse); - - Expression* - do_lower(Gogo*, Named_object*, int); - - Expression* - do_copy() - { - return new Composite_literal_expression(this->type_, this->depth_, - this->has_keys_, - (this->vals_ == NULL - ? NULL - : this->vals_->copy()), - this->location()); - } - - private: - Expression* - lower_struct(Gogo*, Type*); - - Expression* - lower_array(Type*); - - Expression* - make_array(Type*, Expression_list*); - - Expression* - lower_map(Gogo*, Named_object*, Type*); - - // The type of the composite literal. - Type* type_; - // The depth within a list of composite literals within a composite - // literal, when the type is omitted. - int depth_; - // The values to put in the composite literal. - Expression_list* vals_; - // If this is true, then VALS_ is a list of pairs: a key and a - // value. In an array initializer, a missing key will be NULL. - bool has_keys_; -}; - -// Traversal. - -int -Composite_literal_expression::do_traverse(Traverse* traverse) -{ - if (this->vals_ != NULL - && this->vals_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return Type::traverse(this->type_, traverse); -} - -// Lower a generic composite literal into a specific version based on -// the type. - -Expression* -Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function, int) -{ - Type* type = this->type_; - - for (int depth = this->depth_; depth > 0; --depth) - { - if (type->array_type() != NULL) - type = type->array_type()->element_type(); - else if (type->map_type() != NULL) - type = type->map_type()->val_type(); - else - { - if (!type->is_error()) - error_at(this->location(), - ("may only omit types within composite literals " - "of slice, array, or map type")); - return Expression::make_error(this->location()); - } - } - - if (type->is_error()) - return Expression::make_error(this->location()); - else if (type->struct_type() != NULL) - return this->lower_struct(gogo, type); - else if (type->array_type() != NULL) - return this->lower_array(type); - else if (type->map_type() != NULL) - return this->lower_map(gogo, function, type); - else - { - error_at(this->location(), - ("expected struct, slice, array, or map type " - "for composite literal")); - return Expression::make_error(this->location()); - } -} - -// Lower a struct composite literal. - -Expression* -Composite_literal_expression::lower_struct(Gogo* gogo, Type* type) -{ - source_location location = this->location(); - Struct_type* st = type->struct_type(); - if (this->vals_ == NULL || !this->has_keys_) - return new Struct_construction_expression(type, this->vals_, location); - - size_t field_count = st->field_count(); - std::vector vals(field_count); - Expression_list::const_iterator p = this->vals_->begin(); - while (p != this->vals_->end()) - { - Expression* name_expr = *p; - - ++p; - go_assert(p != this->vals_->end()); - Expression* val = *p; - - ++p; - - if (name_expr == NULL) - { - error_at(val->location(), "mixture of field and value initializers"); - return Expression::make_error(location); - } - - bool bad_key = false; - std::string name; - const Named_object* no = NULL; - switch (name_expr->classification()) - { - case EXPRESSION_UNKNOWN_REFERENCE: - name = name_expr->unknown_expression()->name(); - break; - - case EXPRESSION_CONST_REFERENCE: - no = static_cast(name_expr)->named_object(); - break; - - case EXPRESSION_TYPE: - { - Type* t = name_expr->type(); - Named_type* nt = t->named_type(); - if (nt == NULL) - bad_key = true; - else - no = nt->named_object(); - } - break; - - case EXPRESSION_VAR_REFERENCE: - no = name_expr->var_expression()->named_object(); - break; - - case EXPRESSION_FUNC_REFERENCE: - no = name_expr->func_expression()->named_object(); - break; - - case EXPRESSION_UNARY: - // If there is a local variable around with the same name as - // the field, and this occurs in the closure, then the - // parser may turn the field reference into an indirection - // through the closure. FIXME: This is a mess. - { - bad_key = true; - Unary_expression* ue = static_cast(name_expr); - if (ue->op() == OPERATOR_MULT) - { - Field_reference_expression* fre = - ue->operand()->field_reference_expression(); - if (fre != NULL) - { - Struct_type* st = - fre->expr()->type()->deref()->struct_type(); - if (st != NULL) - { - const Struct_field* sf = st->field(fre->field_index()); - name = sf->field_name(); - char buf[20]; - snprintf(buf, sizeof buf, "%u", fre->field_index()); - size_t buflen = strlen(buf); - if (name.compare(name.length() - buflen, buflen, buf) - == 0) - { - name = name.substr(0, name.length() - buflen); - bad_key = false; - } - } - } - } - } - break; - - default: - bad_key = true; - break; - } - if (bad_key) - { - error_at(name_expr->location(), "expected struct field name"); - return Expression::make_error(location); - } - - if (no != NULL) - { - name = no->name(); - - // A predefined name won't be packed. If it starts with a - // lower case letter we need to check for that case, because - // the field name will be packed. - if (!Gogo::is_hidden_name(name) - && name[0] >= 'a' - && name[0] <= 'z') - { - Named_object* gno = gogo->lookup_global(name.c_str()); - if (gno == no) - name = gogo->pack_hidden_name(name, false); - } - } - - unsigned int index; - const Struct_field* sf = st->find_local_field(name, &index); - if (sf == NULL) - { - error_at(name_expr->location(), "unknown field %qs in %qs", - Gogo::message_name(name).c_str(), - (type->named_type() != NULL - ? type->named_type()->message_name().c_str() - : "unnamed struct")); - return Expression::make_error(location); - } - if (vals[index] != NULL) - { - error_at(name_expr->location(), - "duplicate value for field %qs in %qs", - Gogo::message_name(name).c_str(), - (type->named_type() != NULL - ? type->named_type()->message_name().c_str() - : "unnamed struct")); - return Expression::make_error(location); - } - - vals[index] = val; - } - - Expression_list* list = new Expression_list; - list->reserve(field_count); - for (size_t i = 0; i < field_count; ++i) - list->push_back(vals[i]); - - return new Struct_construction_expression(type, list, location); -} - -// Lower an array composite literal. - -Expression* -Composite_literal_expression::lower_array(Type* type) -{ - source_location location = this->location(); - if (this->vals_ == NULL || !this->has_keys_) - return this->make_array(type, this->vals_); - - std::vector vals; - vals.reserve(this->vals_->size()); - unsigned long index = 0; - Expression_list::const_iterator p = this->vals_->begin(); - while (p != this->vals_->end()) - { - Expression* index_expr = *p; - - ++p; - go_assert(p != this->vals_->end()); - Expression* val = *p; - - ++p; - - if (index_expr != NULL) - { - mpz_t ival; - mpz_init(ival); - - Type* dummy; - if (!index_expr->integer_constant_value(true, ival, &dummy)) - { - mpz_clear(ival); - error_at(index_expr->location(), - "index expression is not integer constant"); - return Expression::make_error(location); - } - - if (mpz_sgn(ival) < 0) - { - mpz_clear(ival); - error_at(index_expr->location(), "index expression is negative"); - return Expression::make_error(location); - } - - index = mpz_get_ui(ival); - if (mpz_cmp_ui(ival, index) != 0) - { - mpz_clear(ival); - error_at(index_expr->location(), "index value overflow"); - return Expression::make_error(location); - } - - Named_type* ntype = Type::lookup_integer_type("int"); - Integer_type* inttype = ntype->integer_type(); - mpz_t max; - mpz_init_set_ui(max, 1); - mpz_mul_2exp(max, max, inttype->bits() - 1); - bool ok = mpz_cmp(ival, max) < 0; - mpz_clear(max); - if (!ok) - { - mpz_clear(ival); - error_at(index_expr->location(), "index value overflow"); - return Expression::make_error(location); - } - - mpz_clear(ival); - - // FIXME: Our representation isn't very good; this avoids - // thrashing. - if (index > 0x1000000) - { - error_at(index_expr->location(), "index too large for compiler"); - return Expression::make_error(location); - } - } - - if (index == vals.size()) - vals.push_back(val); - else - { - if (index > vals.size()) - { - vals.reserve(index + 32); - vals.resize(index + 1, static_cast(NULL)); - } - if (vals[index] != NULL) - { - error_at((index_expr != NULL - ? index_expr->location() - : val->location()), - "duplicate value for index %lu", - index); - return Expression::make_error(location); - } - vals[index] = val; - } - - ++index; - } - - size_t size = vals.size(); - Expression_list* list = new Expression_list; - list->reserve(size); - for (size_t i = 0; i < size; ++i) - list->push_back(vals[i]); - - return this->make_array(type, list); -} - -// Actually build the array composite literal. This handles -// [...]{...}. - -Expression* -Composite_literal_expression::make_array(Type* type, Expression_list* vals) -{ - source_location location = this->location(); - Array_type* at = type->array_type(); - if (at->length() != NULL && at->length()->is_nil_expression()) - { - size_t size = vals == NULL ? 0 : vals->size(); - mpz_t vlen; - mpz_init_set_ui(vlen, size); - Expression* elen = Expression::make_integer(&vlen, NULL, location); - mpz_clear(vlen); - at = Type::make_array_type(at->element_type(), elen); - type = at; - } - if (at->length() != NULL) - return new Fixed_array_construction_expression(type, vals, location); - else - return new Open_array_construction_expression(type, vals, location); -} - -// Lower a map composite literal. - -Expression* -Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function, - Type* type) -{ - source_location location = this->location(); - if (this->vals_ != NULL) - { - if (!this->has_keys_) - { - error_at(location, "map composite literal must have keys"); - return Expression::make_error(location); - } - - for (Expression_list::iterator p = this->vals_->begin(); - p != this->vals_->end(); - p += 2) - { - if (*p == NULL) - { - ++p; - error_at((*p)->location(), - "map composite literal must have keys for every value"); - return Expression::make_error(location); - } - // Make sure we have lowered the key; it may not have been - // lowered in order to handle keys for struct composite - // literals. Lower it now to get the right error message. - if ((*p)->unknown_expression() != NULL) - { - (*p)->unknown_expression()->clear_is_composite_literal_key(); - gogo->lower_expression(function, &*p); - go_assert((*p)->is_error_expression()); - return Expression::make_error(location); - } - } - } - - return new Map_construction_expression(type, this->vals_, location); -} - -// Make a composite literal expression. - -Expression* -Expression::make_composite_literal(Type* type, int depth, bool has_keys, - Expression_list* vals, - source_location location) -{ - return new Composite_literal_expression(type, depth, has_keys, vals, - location); -} - -// Return whether this expression is a composite literal. - -bool -Expression::is_composite_literal() const -{ - switch (this->classification_) - { - case EXPRESSION_COMPOSITE_LITERAL: - case EXPRESSION_STRUCT_CONSTRUCTION: - case EXPRESSION_FIXED_ARRAY_CONSTRUCTION: - case EXPRESSION_OPEN_ARRAY_CONSTRUCTION: - case EXPRESSION_MAP_CONSTRUCTION: - return true; - default: - return false; - } -} - -// Return whether this expression is a composite literal which is not -// constant. - -bool -Expression::is_nonconstant_composite_literal() const -{ - switch (this->classification_) - { - case EXPRESSION_STRUCT_CONSTRUCTION: - { - const Struct_construction_expression *psce = - static_cast(this); - return !psce->is_constant_struct(); - } - case EXPRESSION_FIXED_ARRAY_CONSTRUCTION: - { - const Fixed_array_construction_expression *pace = - static_cast(this); - return !pace->is_constant_array(); - } - case EXPRESSION_OPEN_ARRAY_CONSTRUCTION: - { - const Open_array_construction_expression *pace = - static_cast(this); - return !pace->is_constant_array(); - } - case EXPRESSION_MAP_CONSTRUCTION: - return true; - default: - return false; - } -} - -// Return true if this is a reference to a local variable. - -bool -Expression::is_local_variable() const -{ - const Var_expression* ve = this->var_expression(); - if (ve == NULL) - return false; - const Named_object* no = ve->named_object(); - return (no->is_result_variable() - || (no->is_variable() && !no->var_value()->is_global())); -} - -// Class Type_guard_expression. - -// Traversal. - -int -Type_guard_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT - || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Check types of a type guard expression. The expression must have -// an interface type, but the actual type conversion is checked at run -// time. - -void -Type_guard_expression::do_check_types(Gogo*) -{ - // 6g permits using a type guard with unsafe.pointer; we are - // compatible. - Type* expr_type = this->expr_->type(); - if (expr_type->is_unsafe_pointer_type()) - { - if (this->type_->points_to() == NULL - && (this->type_->integer_type() == NULL - || (this->type_->forwarded() - != Type::lookup_integer_type("uintptr")))) - this->report_error(_("invalid unsafe.Pointer conversion")); - } - else if (this->type_->is_unsafe_pointer_type()) - { - if (expr_type->points_to() == NULL - && (expr_type->integer_type() == NULL - || (expr_type->forwarded() - != Type::lookup_integer_type("uintptr")))) - this->report_error(_("invalid unsafe.Pointer conversion")); - } - else if (expr_type->interface_type() == NULL) - { - if (!expr_type->is_error() && !this->type_->is_error()) - this->report_error(_("type assertion only valid for interface types")); - this->set_is_error(); - } - else if (this->type_->interface_type() == NULL) - { - std::string reason; - if (!expr_type->interface_type()->implements_interface(this->type_, - &reason)) - { - if (!this->type_->is_error()) - { - if (reason.empty()) - this->report_error(_("impossible type assertion: " - "type does not implement interface")); - else - error_at(this->location(), - ("impossible type assertion: " - "type does not implement interface (%s)"), - reason.c_str()); - } - this->set_is_error(); - } - } -} - -// Return a tree for a type guard expression. - -tree -Type_guard_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree expr_tree = this->expr_->get_tree(context); - if (expr_tree == error_mark_node) - return error_mark_node; - Type* expr_type = this->expr_->type(); - if ((this->type_->is_unsafe_pointer_type() - && (expr_type->points_to() != NULL - || expr_type->integer_type() != NULL)) - || (expr_type->is_unsafe_pointer_type() - && this->type_->points_to() != NULL)) - return convert_to_pointer(this->type_->get_tree(gogo), expr_tree); - else if (expr_type->is_unsafe_pointer_type() - && this->type_->integer_type() != NULL) - return convert_to_integer(this->type_->get_tree(gogo), expr_tree); - else if (this->type_->interface_type() != NULL) - return Expression::convert_interface_to_interface(context, this->type_, - this->expr_->type(), - expr_tree, true, - this->location()); - else - return Expression::convert_for_assignment(context, this->type_, - this->expr_->type(), expr_tree, - this->location()); -} - -// Make a type guard expression. - -Expression* -Expression::make_type_guard(Expression* expr, Type* type, - source_location location) -{ - return new Type_guard_expression(expr, type, location); -} - -// Class Heap_composite_expression. - -// When you take the address of a composite literal, it is allocated -// on the heap. This class implements that. - -class Heap_composite_expression : public Expression -{ - public: - Heap_composite_expression(Expression* expr, source_location location) - : Expression(EXPRESSION_HEAP_COMPOSITE, location), - expr_(expr) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return Expression::traverse(&this->expr_, traverse); } - - Type* - do_type() - { return Type::make_pointer_type(this->expr_->type()); } - - void - do_determine_type(const Type_context*) - { this->expr_->determine_type_no_context(); } - - Expression* - do_copy() - { - return Expression::make_heap_composite(this->expr_->copy(), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - // We only export global objects, and the parser does not generate - // this in global scope. - void - do_export(Export*) const - { go_unreachable(); } - - private: - // The composite literal which is being put on the heap. - Expression* expr_; -}; - -// Return a tree which allocates a composite literal on the heap. - -tree -Heap_composite_expression::do_get_tree(Translate_context* context) -{ - tree expr_tree = this->expr_->get_tree(context); - if (expr_tree == error_mark_node) - return error_mark_node; - tree expr_size = TYPE_SIZE_UNIT(TREE_TYPE(expr_tree)); - go_assert(TREE_CODE(expr_size) == INTEGER_CST); - tree space = context->gogo()->allocate_memory(this->expr_->type(), - expr_size, this->location()); - space = fold_convert(build_pointer_type(TREE_TYPE(expr_tree)), space); - space = save_expr(space); - tree ref = build_fold_indirect_ref_loc(this->location(), space); - TREE_THIS_NOTRAP(ref) = 1; - tree ret = build2(COMPOUND_EXPR, TREE_TYPE(space), - build2(MODIFY_EXPR, void_type_node, ref, expr_tree), - space); - SET_EXPR_LOCATION(ret, this->location()); - return ret; -} - -// Allocate a composite literal on the heap. - -Expression* -Expression::make_heap_composite(Expression* expr, source_location location) -{ - return new Heap_composite_expression(expr, location); -} - -// Class Receive_expression. - -// Return the type of a receive expression. - -Type* -Receive_expression::do_type() -{ - Channel_type* channel_type = this->channel_->type()->channel_type(); - if (channel_type == NULL) - return Type::make_error_type(); - return channel_type->element_type(); -} - -// Check types for a receive expression. - -void -Receive_expression::do_check_types(Gogo*) -{ - Type* type = this->channel_->type(); - if (type->is_error()) - { - this->set_is_error(); - return; - } - if (type->channel_type() == NULL) - { - this->report_error(_("expected channel")); - return; - } - if (!type->channel_type()->may_receive()) - { - this->report_error(_("invalid receive on send-only channel")); - return; - } -} - -// Get a tree for a receive expression. - -tree -Receive_expression::do_get_tree(Translate_context* context) -{ - Channel_type* channel_type = this->channel_->type()->channel_type(); - if (channel_type == NULL) - { - go_assert(this->channel_->type()->is_error()); - return error_mark_node; - } - Type* element_type = channel_type->element_type(); - tree element_type_tree = element_type->get_tree(context->gogo()); - - tree channel = this->channel_->get_tree(context); - if (element_type_tree == error_mark_node || channel == error_mark_node) - return error_mark_node; - - return Gogo::receive_from_channel(element_type_tree, channel, - this->for_select_, this->location()); -} - -// Make a receive expression. - -Receive_expression* -Expression::make_receive(Expression* channel, source_location location) -{ - return new Receive_expression(channel, location); -} - -// An expression which evaluates to a pointer to the type descriptor -// of a type. - -class Type_descriptor_expression : public Expression -{ - public: - Type_descriptor_expression(Type* type, source_location location) - : Expression(EXPRESSION_TYPE_DESCRIPTOR, location), - type_(type) - { } - - protected: - Type* - do_type() - { return Type::make_type_descriptor_ptr_type(); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context* context) - { return this->type_->type_descriptor_pointer(context->gogo()); } - - private: - // The type for which this is the descriptor. - Type* type_; -}; - -// Make a type descriptor expression. - -Expression* -Expression::make_type_descriptor(Type* type, source_location location) -{ - return new Type_descriptor_expression(type, location); -} - -// An expression which evaluates to some characteristic of a type. -// This is only used to initialize fields of a type descriptor. Using -// a new expression class is slightly inefficient but gives us a good -// separation between the frontend and the middle-end with regard to -// how types are laid out. - -class Type_info_expression : public Expression -{ - public: - Type_info_expression(Type* type, Type_info type_info) - : Expression(EXPRESSION_TYPE_INFO, BUILTINS_LOCATION), - type_(type), type_info_(type_info) - { } - - protected: - Type* - do_type(); - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context* context); - - private: - // The type for which we are getting information. - Type* type_; - // What information we want. - Type_info type_info_; -}; - -// The type is chosen to match what the type descriptor struct -// expects. - -Type* -Type_info_expression::do_type() -{ - switch (this->type_info_) - { - case TYPE_INFO_SIZE: - return Type::lookup_integer_type("uintptr"); - case TYPE_INFO_ALIGNMENT: - case TYPE_INFO_FIELD_ALIGNMENT: - return Type::lookup_integer_type("uint8"); - default: - go_unreachable(); - } -} - -// Return type information in GENERIC. - -tree -Type_info_expression::do_get_tree(Translate_context* context) -{ - tree type_tree = this->type_->get_tree(context->gogo()); - if (type_tree == error_mark_node) - return error_mark_node; - - tree val_type_tree = this->type()->get_tree(context->gogo()); - go_assert(val_type_tree != error_mark_node); - - if (this->type_info_ == TYPE_INFO_SIZE) - return fold_convert_loc(BUILTINS_LOCATION, val_type_tree, - TYPE_SIZE_UNIT(type_tree)); - else - { - unsigned int val; - if (this->type_info_ == TYPE_INFO_ALIGNMENT) - val = go_type_alignment(type_tree); - else - val = go_field_alignment(type_tree); - return build_int_cstu(val_type_tree, val); - } -} - -// Make a type info expression. - -Expression* -Expression::make_type_info(Type* type, Type_info type_info) -{ - return new Type_info_expression(type, type_info); -} - -// An expression which evaluates to the offset of a field within a -// struct. This, like Type_info_expression, q.v., is only used to -// initialize fields of a type descriptor. - -class Struct_field_offset_expression : public Expression -{ - public: - Struct_field_offset_expression(Struct_type* type, const Struct_field* field) - : Expression(EXPRESSION_STRUCT_FIELD_OFFSET, BUILTINS_LOCATION), - type_(type), field_(field) - { } - - protected: - Type* - do_type() - { return Type::lookup_integer_type("uintptr"); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context* context); - - private: - // The type of the struct. - Struct_type* type_; - // The field. - const Struct_field* field_; -}; - -// Return a struct field offset in GENERIC. - -tree -Struct_field_offset_expression::do_get_tree(Translate_context* context) -{ - tree type_tree = this->type_->get_tree(context->gogo()); - if (type_tree == error_mark_node) - return error_mark_node; - - tree val_type_tree = this->type()->get_tree(context->gogo()); - go_assert(val_type_tree != error_mark_node); - - const Struct_field_list* fields = this->type_->fields(); - tree struct_field_tree = TYPE_FIELDS(type_tree); - Struct_field_list::const_iterator p; - for (p = fields->begin(); - p != fields->end(); - ++p, struct_field_tree = DECL_CHAIN(struct_field_tree)) - { - go_assert(struct_field_tree != NULL_TREE); - if (&*p == this->field_) - break; - } - go_assert(&*p == this->field_); - - return fold_convert_loc(BUILTINS_LOCATION, val_type_tree, - byte_position(struct_field_tree)); -} - -// Make an expression for a struct field offset. - -Expression* -Expression::make_struct_field_offset(Struct_type* type, - const Struct_field* field) -{ - return new Struct_field_offset_expression(type, field); -} - -// An expression which evaluates to the address of an unnamed label. - -class Label_addr_expression : public Expression -{ - public: - Label_addr_expression(Label* label, source_location location) - : Expression(EXPRESSION_LABEL_ADDR, location), - label_(label) - { } - - protected: - Type* - do_type() - { return Type::make_pointer_type(Type::make_void_type()); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return new Label_addr_expression(this->label_, this->location()); } - - tree - do_get_tree(Translate_context* context) - { - return expr_to_tree(this->label_->get_addr(context, this->location())); - } - - private: - // The label whose address we are taking. - Label* label_; -}; - -// Make an expression for the address of an unnamed label. - -Expression* -Expression::make_label_addr(Label* label, source_location location) -{ - return new Label_addr_expression(label, location); -} - -// Import an expression. This comes at the end in order to see the -// various class definitions. - -Expression* -Expression::import_expression(Import* imp) -{ - int c = imp->peek_char(); - if (imp->match_c_string("- ") - || imp->match_c_string("! ") - || imp->match_c_string("^ ")) - return Unary_expression::do_import(imp); - else if (c == '(') - return Binary_expression::do_import(imp); - else if (imp->match_c_string("true") - || imp->match_c_string("false")) - return Boolean_expression::do_import(imp); - else if (c == '"') - return String_expression::do_import(imp); - else if (c == '-' || (c >= '0' && c <= '9')) - { - // This handles integers, floats and complex constants. - return Integer_expression::do_import(imp); - } - else if (imp->match_c_string("nil")) - return Nil_expression::do_import(imp); - else if (imp->match_c_string("convert")) - return Type_conversion_expression::do_import(imp); - else - { - error_at(imp->location(), "import error: expected expression"); - return Expression::make_error(imp->location()); - } -} - -// Class Expression_list. - -// Traverse the list. - -int -Expression_list::traverse(Traverse* traverse) -{ - for (Expression_list::iterator p = this->begin(); - p != this->end(); - ++p) - { - if (*p != NULL) - { - if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - return TRAVERSE_CONTINUE; -} - -// Copy the list. - -Expression_list* -Expression_list::copy() -{ - Expression_list* ret = new Expression_list(); - for (Expression_list::iterator p = this->begin(); - p != this->end(); - ++p) - { - if (*p == NULL) - ret->push_back(NULL); - else - ret->push_back((*p)->copy()); - } - return ret; -} - -// Return whether an expression list has an error expression. - -bool -Expression_list::contains_error() const -{ - for (Expression_list::const_iterator p = this->begin(); - p != this->end(); - ++p) - if (*p != NULL && (*p)->is_error_expression()) - return true; - return false; -} diff --git a/gcc/go/gofrontend/expressions.cc.working b/gcc/go/gofrontend/expressions.cc.working deleted file mode 100644 index 861d5c0ca99..00000000000 --- a/gcc/go/gofrontend/expressions.cc.working +++ /dev/null @@ -1,12663 +0,0 @@ -// expressions.cc -- Go frontend expression handling. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include - -#ifndef ENABLE_BUILD_WITH_CXX -extern "C" -{ -#endif - -#include "toplev.h" -#include "intl.h" -#include "tree.h" -#include "gimple.h" -#include "tree-iterator.h" -#include "convert.h" -#include "real.h" -#include "realmpfr.h" - -#ifndef ENABLE_BUILD_WITH_CXX -} -#endif - -#include "go-c.h" -#include "gogo.h" -#include "types.h" -#include "export.h" -#include "import.h" -#include "statements.h" -#include "lex.h" -#include "expressions.h" - -// Class Expression. - -Expression::Expression(Expression_classification classification, - source_location location) - : classification_(classification), location_(location) -{ -} - -Expression::~Expression() -{ -} - -// If this expression has a constant integer value, return it. - -bool -Expression::integer_constant_value(bool iota_is_constant, mpz_t val, - Type** ptype) const -{ - *ptype = NULL; - return this->do_integer_constant_value(iota_is_constant, val, ptype); -} - -// If this expression has a constant floating point value, return it. - -bool -Expression::float_constant_value(mpfr_t val, Type** ptype) const -{ - *ptype = NULL; - if (this->do_float_constant_value(val, ptype)) - return true; - mpz_t ival; - mpz_init(ival); - Type* t; - bool ret; - if (!this->do_integer_constant_value(false, ival, &t)) - ret = false; - else - { - mpfr_set_z(val, ival, GMP_RNDN); - ret = true; - } - mpz_clear(ival); - return ret; -} - -// If this expression has a constant complex value, return it. - -bool -Expression::complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - *ptype = NULL; - if (this->do_complex_constant_value(real, imag, ptype)) - return true; - Type *t; - if (this->float_constant_value(real, &t)) - { - mpfr_set_ui(imag, 0, GMP_RNDN); - return true; - } - return false; -} - -// Traverse the expressions. - -int -Expression::traverse(Expression** pexpr, Traverse* traverse) -{ - Expression* expr = *pexpr; - if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0) - { - int t = traverse->expression(pexpr); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - return TRAVERSE_CONTINUE; - } - return expr->do_traverse(traverse); -} - -// Traverse subexpressions of this expression. - -int -Expression::traverse_subexpressions(Traverse* traverse) -{ - return this->do_traverse(traverse); -} - -// Default implementation for do_traverse for child classes. - -int -Expression::do_traverse(Traverse*) -{ - return TRAVERSE_CONTINUE; -} - -// This virtual function is called by the parser if the value of this -// expression is being discarded. By default, we warn. Expressions -// with side effects override. - -void -Expression::do_discarding_value() -{ - this->warn_about_unused_value(); -} - -// This virtual function is called to export expressions. This will -// only be used by expressions which may be constant. - -void -Expression::do_export(Export*) const -{ - gcc_unreachable(); -} - -// Warn that the value of the expression is not used. - -void -Expression::warn_about_unused_value() -{ - warning_at(this->location(), OPT_Wunused_value, "value computed is not used"); -} - -// Note that this expression is an error. This is called by children -// when they discover an error. - -void -Expression::set_is_error() -{ - this->classification_ = EXPRESSION_ERROR; -} - -// For children to call to report an error conveniently. - -void -Expression::report_error(const char* msg) -{ - error_at(this->location_, "%s", msg); - this->set_is_error(); -} - -// Set types of variables and constants. This is implemented by the -// child class. - -void -Expression::determine_type(const Type_context* context) -{ - this->do_determine_type(context); -} - -// Set types when there is no context. - -void -Expression::determine_type_no_context() -{ - Type_context context; - this->do_determine_type(&context); -} - -// Return a tree handling any conversions which must be done during -// assignment. - -tree -Expression::convert_for_assignment(Translate_context* context, Type* lhs_type, - Type* rhs_type, tree rhs_tree, - source_location location) -{ - if (lhs_type == rhs_type) - return rhs_tree; - - if (lhs_type->is_error_type() || rhs_type->is_error_type()) - return error_mark_node; - - if (lhs_type->is_undefined() || rhs_type->is_undefined()) - { - // Make sure we report the error. - lhs_type->base(); - rhs_type->base(); - return error_mark_node; - } - - if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node) - return error_mark_node; - - Gogo* gogo = context->gogo(); - - tree lhs_type_tree = lhs_type->get_tree(gogo); - if (lhs_type_tree == error_mark_node) - return error_mark_node; - - if (lhs_type->interface_type() != NULL) - { - if (rhs_type->interface_type() == NULL) - return Expression::convert_type_to_interface(context, lhs_type, - rhs_type, rhs_tree, - location); - else - return Expression::convert_interface_to_interface(context, lhs_type, - rhs_type, rhs_tree, - false, location); - } - else if (rhs_type->interface_type() != NULL) - return Expression::convert_interface_to_type(context, lhs_type, rhs_type, - rhs_tree, location); - else if (lhs_type->is_open_array_type() - && rhs_type->is_nil_type()) - { - // Assigning nil to an open array. - gcc_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(lhs_type_tree); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__values") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), null_pointer_node); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__count") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), integer_zero_node); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__capacity") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), integer_zero_node); - - tree val = build_constructor(lhs_type_tree, init); - TREE_CONSTANT(val) = 1; - - return val; - } - else if (rhs_type->is_nil_type()) - { - // The left hand side should be a pointer type at the tree - // level. - gcc_assert(POINTER_TYPE_P(lhs_type_tree)); - return fold_convert(lhs_type_tree, null_pointer_node); - } - else if (lhs_type_tree == TREE_TYPE(rhs_tree)) - { - // No conversion is needed. - return rhs_tree; - } - else if (POINTER_TYPE_P(lhs_type_tree) - || INTEGRAL_TYPE_P(lhs_type_tree) - || SCALAR_FLOAT_TYPE_P(lhs_type_tree) - || COMPLEX_FLOAT_TYPE_P(lhs_type_tree)) - return fold_convert_loc(location, lhs_type_tree, rhs_tree); - else if (TREE_CODE(lhs_type_tree) == RECORD_TYPE - && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE) - { - // This conversion must be permitted by Go, or we wouldn't have - // gotten here. - gcc_assert(int_size_in_bytes(lhs_type_tree) - == int_size_in_bytes(TREE_TYPE(rhs_tree))); - return fold_build1_loc(location, VIEW_CONVERT_EXPR, lhs_type_tree, - rhs_tree); - } - else - { - gcc_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree))); - return rhs_tree; - } -} - -// Return a tree for a conversion from a non-interface type to an -// interface type. - -tree -Expression::convert_type_to_interface(Translate_context* context, - Type* lhs_type, Type* rhs_type, - tree rhs_tree, source_location location) -{ - Gogo* gogo = context->gogo(); - Interface_type* lhs_interface_type = lhs_type->interface_type(); - bool lhs_is_empty = lhs_interface_type->is_empty(); - - // Since RHS_TYPE is a static type, we can create the interface - // method table at compile time. - - // When setting an interface to nil, we just set both fields to - // NULL. - if (rhs_type->is_nil_type()) - return lhs_type->get_init_tree(gogo, false); - - // This should have been checked already. - gcc_assert(lhs_interface_type->implements_interface(rhs_type, NULL)); - - tree lhs_type_tree = lhs_type->get_tree(gogo); - if (lhs_type_tree == error_mark_node) - return error_mark_node; - - // An interface is a tuple. If LHS_TYPE is an empty interface type, - // then the first field is the type descriptor for RHS_TYPE. - // Otherwise it is the interface method table for RHS_TYPE. - tree first_field_value; - if (lhs_is_empty) - first_field_value = rhs_type->type_descriptor_pointer(gogo); - else - { - // Build the interface method table for this interface and this - // object type: a list of function pointers for each interface - // method. - Named_type* rhs_named_type = rhs_type->named_type(); - bool is_pointer = false; - if (rhs_named_type == NULL) - { - rhs_named_type = rhs_type->deref()->named_type(); - is_pointer = true; - } - tree method_table; - if (rhs_named_type == NULL) - method_table = null_pointer_node; - else - method_table = - rhs_named_type->interface_method_table(gogo, lhs_interface_type, - is_pointer); - first_field_value = fold_convert_loc(location, const_ptr_type_node, - method_table); - } - if (first_field_value == error_mark_node) - return error_mark_node; - - // Start building a constructor for the value we will return. - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(lhs_type_tree); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0); - elt->index = field; - elt->value = fold_convert_loc(location, TREE_TYPE(field), first_field_value); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0); - elt->index = field; - - if (rhs_type->points_to() != NULL) - { - // We are assigning a pointer to the interface; the interface - // holds the pointer itself. - elt->value = rhs_tree; - return build_constructor(lhs_type_tree, init); - } - - // We are assigning a non-pointer value to the interface; the - // interface gets a copy of the value in the heap. - - tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree)); - - tree space = gogo->allocate_memory(rhs_type, object_size, location); - space = fold_convert_loc(location, build_pointer_type(TREE_TYPE(rhs_tree)), - space); - space = save_expr(space); - - tree ref = build_fold_indirect_ref_loc(location, space); - TREE_THIS_NOTRAP(ref) = 1; - tree set = fold_build2_loc(location, MODIFY_EXPR, void_type_node, - ref, rhs_tree); - - elt->value = fold_convert_loc(location, TREE_TYPE(field), space); - - return build2(COMPOUND_EXPR, lhs_type_tree, set, - build_constructor(lhs_type_tree, init)); -} - -// Return a tree for the type descriptor of RHS_TREE, which has -// interface type RHS_TYPE. If RHS_TREE is nil the result will be -// NULL. - -tree -Expression::get_interface_type_descriptor(Translate_context*, - Type* rhs_type, tree rhs_tree, - source_location location) -{ - tree rhs_type_tree = TREE_TYPE(rhs_tree); - gcc_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE); - tree rhs_field = TYPE_FIELDS(rhs_type_tree); - tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field, - NULL_TREE); - if (rhs_type->interface_type()->is_empty()) - { - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), - "__type_descriptor") == 0); - return v; - } - - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods") - == 0); - gcc_assert(POINTER_TYPE_P(TREE_TYPE(v))); - v = save_expr(v); - tree v1 = build_fold_indirect_ref_loc(location, v); - gcc_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE); - tree f = TYPE_FIELDS(TREE_TYPE(v1)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor") - == 0); - v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE); - - tree eq = fold_build2_loc(location, EQ_EXPR, boolean_type_node, v, - fold_convert_loc(location, TREE_TYPE(v), - null_pointer_node)); - tree n = fold_convert_loc(location, TREE_TYPE(v1), null_pointer_node); - return fold_build3_loc(location, COND_EXPR, TREE_TYPE(v1), - eq, n, v1); -} - -// Return a tree for the conversion of an interface type to an -// interface type. - -tree -Expression::convert_interface_to_interface(Translate_context* context, - Type *lhs_type, Type *rhs_type, - tree rhs_tree, bool for_type_guard, - source_location location) -{ - Gogo* gogo = context->gogo(); - Interface_type* lhs_interface_type = lhs_type->interface_type(); - bool lhs_is_empty = lhs_interface_type->is_empty(); - - tree lhs_type_tree = lhs_type->get_tree(gogo); - if (lhs_type_tree == error_mark_node) - return error_mark_node; - - // In the general case this requires runtime examination of the type - // method table to match it up with the interface methods. - - // FIXME: If all of the methods in the right hand side interface - // also appear in the left hand side interface, then we don't need - // to do a runtime check, although we still need to build a new - // method table. - - // Get the type descriptor for the right hand side. This will be - // NULL for a nil interface. - - if (!DECL_P(rhs_tree)) - rhs_tree = save_expr(rhs_tree); - - tree rhs_type_descriptor = - Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree, - location); - - // The result is going to be a two element constructor. - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(lhs_type_tree); - elt->index = field; - - if (for_type_guard) - { - // A type assertion fails when converting a nil interface. - tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo); - static tree assert_interface_decl; - tree call = Gogo::call_builtin(&assert_interface_decl, - location, - "__go_assert_interface", - 2, - ptr_type_node, - TREE_TYPE(lhs_type_descriptor), - lhs_type_descriptor, - TREE_TYPE(rhs_type_descriptor), - rhs_type_descriptor); - if (call == error_mark_node) - return error_mark_node; - // This will panic if the interface conversion fails. - TREE_NOTHROW(assert_interface_decl) = 0; - elt->value = fold_convert_loc(location, TREE_TYPE(field), call); - } - else if (lhs_is_empty) - { - // A convertion to an empty interface always succeeds, and the - // first field is just the type descriptor of the object. - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__type_descriptor") == 0); - gcc_assert(TREE_TYPE(field) == TREE_TYPE(rhs_type_descriptor)); - elt->value = rhs_type_descriptor; - } - else - { - // A conversion to a non-empty interface may fail, but unlike a - // type assertion converting nil will always succeed. - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") - == 0); - tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo); - static tree convert_interface_decl; - tree call = Gogo::call_builtin(&convert_interface_decl, - location, - "__go_convert_interface", - 2, - ptr_type_node, - TREE_TYPE(lhs_type_descriptor), - lhs_type_descriptor, - TREE_TYPE(rhs_type_descriptor), - rhs_type_descriptor); - if (call == error_mark_node) - return error_mark_node; - // This will panic if the interface conversion fails. - TREE_NOTHROW(convert_interface_decl) = 0; - elt->value = fold_convert_loc(location, TREE_TYPE(field), call); - } - - // The second field is simply the object pointer. - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0); - elt->index = field; - - tree rhs_type_tree = TREE_TYPE(rhs_tree); - gcc_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE); - tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0); - elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field, - NULL_TREE); - - return build_constructor(lhs_type_tree, init); -} - -// Return a tree for the conversion of an interface type to a -// non-interface type. - -tree -Expression::convert_interface_to_type(Translate_context* context, - Type *lhs_type, Type* rhs_type, - tree rhs_tree, source_location location) -{ - Gogo* gogo = context->gogo(); - tree rhs_type_tree = TREE_TYPE(rhs_tree); - - tree lhs_type_tree = lhs_type->get_tree(gogo); - if (lhs_type_tree == error_mark_node) - return error_mark_node; - - // Call a function to check that the type is valid. The function - // will panic with an appropriate runtime type error if the type is - // not valid. - - tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo); - - if (!DECL_P(rhs_tree)) - rhs_tree = save_expr(rhs_tree); - - tree rhs_type_descriptor = - Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree, - location); - - tree rhs_inter_descriptor = rhs_type->type_descriptor_pointer(gogo); - - static tree check_interface_type_decl; - tree call = Gogo::call_builtin(&check_interface_type_decl, - location, - "__go_check_interface_type", - 3, - void_type_node, - TREE_TYPE(lhs_type_descriptor), - lhs_type_descriptor, - TREE_TYPE(rhs_type_descriptor), - rhs_type_descriptor, - TREE_TYPE(rhs_inter_descriptor), - rhs_inter_descriptor); - if (call == error_mark_node) - return error_mark_node; - // This call will panic if the conversion is invalid. - TREE_NOTHROW(check_interface_type_decl) = 0; - - // If the call succeeds, pull out the value. - gcc_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE); - tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0); - tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field, - NULL_TREE); - - // If the value is a pointer, then it is the value we want. - // Otherwise it points to the value. - if (lhs_type->points_to() == NULL) - { - val = fold_convert_loc(location, build_pointer_type(lhs_type_tree), val); - val = build_fold_indirect_ref_loc(location, val); - } - - return build2(COMPOUND_EXPR, lhs_type_tree, call, - fold_convert_loc(location, lhs_type_tree, val)); -} - -// Convert an expression to a tree. This is implemented by the child -// class. Not that it is not in general safe to call this multiple -// times for a single expression, but that we don't catch such errors. - -tree -Expression::get_tree(Translate_context* context) -{ - // The child may have marked this expression as having an error. - if (this->classification_ == EXPRESSION_ERROR) - return error_mark_node; - - return this->do_get_tree(context); -} - -// Return a tree for VAL in TYPE. - -tree -Expression::integer_constant_tree(mpz_t val, tree type) -{ - if (type == error_mark_node) - return error_mark_node; - else if (TREE_CODE(type) == INTEGER_TYPE) - return double_int_to_tree(type, - mpz_get_double_int(type, val, true)); - else if (TREE_CODE(type) == REAL_TYPE) - { - mpfr_t fval; - mpfr_init_set_z(fval, val, GMP_RNDN); - tree ret = Expression::float_constant_tree(fval, type); - mpfr_clear(fval); - return ret; - } - else if (TREE_CODE(type) == COMPLEX_TYPE) - { - mpfr_t fval; - mpfr_init_set_z(fval, val, GMP_RNDN); - tree real = Expression::float_constant_tree(fval, TREE_TYPE(type)); - mpfr_clear(fval); - tree imag = build_real_from_int_cst(TREE_TYPE(type), - integer_zero_node); - return build_complex(type, real, imag); - } - else - gcc_unreachable(); -} - -// Return a tree for VAL in TYPE. - -tree -Expression::float_constant_tree(mpfr_t val, tree type) -{ - if (type == error_mark_node) - return error_mark_node; - else if (TREE_CODE(type) == INTEGER_TYPE) - { - mpz_t ival; - mpz_init(ival); - mpfr_get_z(ival, val, GMP_RNDN); - tree ret = Expression::integer_constant_tree(ival, type); - mpz_clear(ival); - return ret; - } - else if (TREE_CODE(type) == REAL_TYPE) - { - REAL_VALUE_TYPE r1; - real_from_mpfr(&r1, val, type, GMP_RNDN); - REAL_VALUE_TYPE r2; - real_convert(&r2, TYPE_MODE(type), &r1); - return build_real(type, r2); - } - else if (TREE_CODE(type) == COMPLEX_TYPE) - { - REAL_VALUE_TYPE r1; - real_from_mpfr(&r1, val, TREE_TYPE(type), GMP_RNDN); - REAL_VALUE_TYPE r2; - real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1); - tree imag = build_real_from_int_cst(TREE_TYPE(type), - integer_zero_node); - return build_complex(type, build_real(TREE_TYPE(type), r2), imag); - } - else - gcc_unreachable(); -} - -// Return a tree for REAL/IMAG in TYPE. - -tree -Expression::complex_constant_tree(mpfr_t real, mpfr_t imag, tree type) -{ - if (type == error_mark_node) - return error_mark_node; - else if (TREE_CODE(type) == INTEGER_TYPE || TREE_CODE(type) == REAL_TYPE) - return Expression::float_constant_tree(real, type); - else if (TREE_CODE(type) == COMPLEX_TYPE) - { - REAL_VALUE_TYPE r1; - real_from_mpfr(&r1, real, TREE_TYPE(type), GMP_RNDN); - REAL_VALUE_TYPE r2; - real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1); - - REAL_VALUE_TYPE r3; - real_from_mpfr(&r3, imag, TREE_TYPE(type), GMP_RNDN); - REAL_VALUE_TYPE r4; - real_convert(&r4, TYPE_MODE(TREE_TYPE(type)), &r3); - - return build_complex(type, build_real(TREE_TYPE(type), r2), - build_real(TREE_TYPE(type), r4)); - } - else - gcc_unreachable(); -} - -// Return a tree which evaluates to true if VAL, of arbitrary integer -// type, is negative or is more than the maximum value of BOUND_TYPE. -// If SOFAR is not NULL, it is or'red into the result. The return -// value may be NULL if SOFAR is NULL. - -tree -Expression::check_bounds(tree val, tree bound_type, tree sofar, - source_location loc) -{ - tree val_type = TREE_TYPE(val); - tree ret = NULL_TREE; - - if (!TYPE_UNSIGNED(val_type)) - { - ret = fold_build2_loc(loc, LT_EXPR, boolean_type_node, val, - build_int_cst(val_type, 0)); - if (ret == boolean_false_node) - ret = NULL_TREE; - } - - if ((TYPE_UNSIGNED(val_type) && !TYPE_UNSIGNED(bound_type)) - || TYPE_SIZE(val_type) > TYPE_SIZE(bound_type)) - { - tree max = TYPE_MAX_VALUE(bound_type); - tree big = fold_build2_loc(loc, GT_EXPR, boolean_type_node, val, - fold_convert_loc(loc, val_type, max)); - if (big == boolean_false_node) - ; - else if (ret == NULL_TREE) - ret = big; - else - ret = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - ret, big); - } - - if (ret == NULL_TREE) - return sofar; - else if (sofar == NULL_TREE) - return ret; - else - return fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - sofar, ret); -} - -// Error expressions. This are used to avoid cascading errors. - -class Error_expression : public Expression -{ - public: - Error_expression(source_location location) - : Expression(EXPRESSION_ERROR, location) - { } - - protected: - bool - do_is_constant() const - { return true; } - - bool - do_integer_constant_value(bool, mpz_t val, Type**) const - { - mpz_set_ui(val, 0); - return true; - } - - bool - do_float_constant_value(mpfr_t val, Type**) const - { - mpfr_set_ui(val, 0, GMP_RNDN); - return true; - } - - bool - do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const - { - mpfr_set_ui(real, 0, GMP_RNDN); - mpfr_set_ui(imag, 0, GMP_RNDN); - return true; - } - - void - do_discarding_value() - { } - - Type* - do_type() - { return Type::make_error_type(); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - bool - do_is_addressable() const - { return true; } - - tree - do_get_tree(Translate_context*) - { return error_mark_node; } -}; - -Expression* -Expression::make_error(source_location location) -{ - return new Error_expression(location); -} - -// An expression which is really a type. This is used during parsing. -// It is an error if these survive after lowering. - -class -Type_expression : public Expression -{ - public: - Type_expression(Type* type, source_location location) - : Expression(EXPRESSION_TYPE, location), - type_(type) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return Type::traverse(this->type_, traverse); } - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*) - { } - - void - do_check_types(Gogo*) - { this->report_error(_("invalid use of type")); } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // The type which we are representing as an expression. - Type* type_; -}; - -Expression* -Expression::make_type(Type* type, source_location location) -{ - return new Type_expression(type, location); -} - -// Class Parser_expression. - -Type* -Parser_expression::do_type() -{ - // We should never really ask for the type of a Parser_expression. - // However, it can happen, at least when we have an invalid const - // whose initializer refers to the const itself. In that case we - // may ask for the type when lowering the const itself. - gcc_assert(saw_errors()); - return Type::make_error_type(); -} - -// Class Var_expression. - -// Lower a variable expression. Here we just make sure that the -// initialization expression of the variable has been lowered. This -// ensures that we will be able to determine the type of the variable -// if necessary. - -Expression* -Var_expression::do_lower(Gogo* gogo, Named_object* function, int) -{ - if (this->variable_->is_variable()) - { - Variable* var = this->variable_->var_value(); - // This is either a local variable or a global variable. A - // reference to a variable which is local to an enclosing - // function will be a reference to a field in a closure. - if (var->is_global()) - function = NULL; - var->lower_init_expression(gogo, function); - } - return this; -} - -// Return the type of a reference to a variable. - -Type* -Var_expression::do_type() -{ - if (this->variable_->is_variable()) - return this->variable_->var_value()->type(); - else if (this->variable_->is_result_variable()) - return this->variable_->result_var_value()->type(); - else - gcc_unreachable(); -} - -// Determine the type of a reference to a variable. - -void -Var_expression::do_determine_type(const Type_context*) -{ - if (this->variable_->is_variable()) - this->variable_->var_value()->determine_type(); -} - -// Something takes the address of this variable. This means that we -// may want to move the variable onto the heap. - -void -Var_expression::do_address_taken(bool escapes) -{ - if (!escapes) - ; - else if (this->variable_->is_variable()) - this->variable_->var_value()->set_address_taken(); - else if (this->variable_->is_result_variable()) - this->variable_->result_var_value()->set_address_taken(); - else - gcc_unreachable(); -} - -// Get the tree for a reference to a variable. - -tree -Var_expression::do_get_tree(Translate_context* context) -{ - return this->variable_->get_tree(context->gogo(), context->function()); -} - -// Make a reference to a variable in an expression. - -Expression* -Expression::make_var_reference(Named_object* var, source_location location) -{ - if (var->is_sink()) - return Expression::make_sink(location); - - // FIXME: Creating a new object for each reference to a variable is - // wasteful. - return new Var_expression(var, location); -} - -// Class Temporary_reference_expression. - -// The type. - -Type* -Temporary_reference_expression::do_type() -{ - return this->statement_->type(); -} - -// Called if something takes the address of this temporary variable. -// We never have to move temporary variables to the heap, but we do -// need to know that they must live in the stack rather than in a -// register. - -void -Temporary_reference_expression::do_address_taken(bool) -{ - this->statement_->set_is_address_taken(); -} - -// Get a tree referring to the variable. - -tree -Temporary_reference_expression::do_get_tree(Translate_context*) -{ - return this->statement_->get_decl(); -} - -// Make a reference to a temporary variable. - -Expression* -Expression::make_temporary_reference(Temporary_statement* statement, - source_location location) -{ - return new Temporary_reference_expression(statement, location); -} - -// A sink expression--a use of the blank identifier _. - -class Sink_expression : public Expression -{ - public: - Sink_expression(source_location location) - : Expression(EXPRESSION_SINK, location), - type_(NULL), var_(NULL_TREE) - { } - - protected: - void - do_discarding_value() - { } - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - Expression* - do_copy() - { return new Sink_expression(this->location()); } - - tree - do_get_tree(Translate_context*); - - private: - // The type of this sink variable. - Type* type_; - // The temporary variable we generate. - tree var_; -}; - -// Return the type of a sink expression. - -Type* -Sink_expression::do_type() -{ - if (this->type_ == NULL) - return Type::make_sink_type(); - return this->type_; -} - -// Determine the type of a sink expression. - -void -Sink_expression::do_determine_type(const Type_context* context) -{ - if (context->type != NULL) - this->type_ = context->type; -} - -// Return a temporary variable for a sink expression. This will -// presumably be a write-only variable which the middle-end will drop. - -tree -Sink_expression::do_get_tree(Translate_context* context) -{ - if (this->var_ == NULL_TREE) - { - gcc_assert(this->type_ != NULL && !this->type_->is_sink_type()); - this->var_ = create_tmp_var(this->type_->get_tree(context->gogo()), - "blank"); - } - return this->var_; -} - -// Make a sink expression. - -Expression* -Expression::make_sink(source_location location) -{ - return new Sink_expression(location); -} - -// Class Func_expression. - -// FIXME: Can a function expression appear in a constant expression? -// The value is unchanging. Initializing a constant to the address of -// a function seems like it could work, though there might be little -// point to it. - -// Traversal. - -int -Func_expression::do_traverse(Traverse* traverse) -{ - return (this->closure_ == NULL - ? TRAVERSE_CONTINUE - : Expression::traverse(&this->closure_, traverse)); -} - -// Return the type of a function expression. - -Type* -Func_expression::do_type() -{ - if (this->function_->is_function()) - return this->function_->func_value()->type(); - else if (this->function_->is_function_declaration()) - return this->function_->func_declaration_value()->type(); - else - gcc_unreachable(); -} - -// Get the tree for a function expression without evaluating the -// closure. - -tree -Func_expression::get_tree_without_closure(Gogo* gogo) -{ - Function_type* fntype; - if (this->function_->is_function()) - fntype = this->function_->func_value()->type(); - else if (this->function_->is_function_declaration()) - fntype = this->function_->func_declaration_value()->type(); - else - gcc_unreachable(); - - // Builtin functions are handled specially by Call_expression. We - // can't take their address. - if (fntype->is_builtin()) - { - error_at(this->location(), "invalid use of special builtin function %qs", - this->function_->name().c_str()); - return error_mark_node; - } - - Named_object* no = this->function_; - - tree id = no->get_id(gogo); - if (id == error_mark_node) - return error_mark_node; - - tree fndecl; - if (no->is_function()) - fndecl = no->func_value()->get_or_make_decl(gogo, no, id); - else if (no->is_function_declaration()) - fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no, id); - else - gcc_unreachable(); - - if (fndecl == error_mark_node) - return error_mark_node; - - return build_fold_addr_expr_loc(this->location(), fndecl); -} - -// Get the tree for a function expression. This is used when we take -// the address of a function rather than simply calling it. If the -// function has a closure, we must use a trampoline. - -tree -Func_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - - tree fnaddr = this->get_tree_without_closure(gogo); - if (fnaddr == error_mark_node) - return error_mark_node; - - gcc_assert(TREE_CODE(fnaddr) == ADDR_EXPR - && TREE_CODE(TREE_OPERAND(fnaddr, 0)) == FUNCTION_DECL); - TREE_ADDRESSABLE(TREE_OPERAND(fnaddr, 0)) = 1; - - // For a normal non-nested function call, that is all we have to do. - if (!this->function_->is_function() - || this->function_->func_value()->enclosing() == NULL) - { - gcc_assert(this->closure_ == NULL); - return fnaddr; - } - - // For a nested function call, we have to always allocate a - // trampoline. If we don't always allocate, then closures will not - // be reliably distinct. - Expression* closure = this->closure_; - tree closure_tree; - if (closure == NULL) - closure_tree = null_pointer_node; - else - { - // Get the value of the closure. This will be a pointer to - // space allocated on the heap. - closure_tree = closure->get_tree(context); - if (closure_tree == error_mark_node) - return error_mark_node; - gcc_assert(POINTER_TYPE_P(TREE_TYPE(closure_tree))); - } - - // Now we need to build some code on the heap. This code will load - // the static chain pointer with the closure and then jump to the - // body of the function. The normal gcc approach is to build the - // code on the stack. Unfortunately we can not do that, as Go - // permits us to return the function pointer. - - return gogo->make_trampoline(fnaddr, closure_tree, this->location()); -} - -// Make a reference to a function in an expression. - -Expression* -Expression::make_func_reference(Named_object* function, Expression* closure, - source_location location) -{ - return new Func_expression(function, closure, location); -} - -// Class Unknown_expression. - -// Return the name of an unknown expression. - -const std::string& -Unknown_expression::name() const -{ - return this->named_object_->name(); -} - -// Lower a reference to an unknown name. - -Expression* -Unknown_expression::do_lower(Gogo*, Named_object*, int) -{ - source_location location = this->location(); - Named_object* no = this->named_object_; - Named_object* real; - if (!no->is_unknown()) - real = no; - else - { - real = no->unknown_value()->real_named_object(); - if (real == NULL) - { - if (this->is_composite_literal_key_) - return this; - error_at(location, "reference to undefined name %qs", - this->named_object_->message_name().c_str()); - return Expression::make_error(location); - } - } - switch (real->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - return Expression::make_const_reference(real, location); - case Named_object::NAMED_OBJECT_TYPE: - return Expression::make_type(real->type_value(), location); - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - if (this->is_composite_literal_key_) - return this; - error_at(location, "reference to undefined type %qs", - real->message_name().c_str()); - return Expression::make_error(location); - case Named_object::NAMED_OBJECT_VAR: - return Expression::make_var_reference(real, location); - case Named_object::NAMED_OBJECT_FUNC: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - return Expression::make_func_reference(real, NULL, location); - case Named_object::NAMED_OBJECT_PACKAGE: - if (this->is_composite_literal_key_) - return this; - error_at(location, "unexpected reference to package"); - return Expression::make_error(location); - default: - gcc_unreachable(); - } -} - -// Make a reference to an unknown name. - -Expression* -Expression::make_unknown_reference(Named_object* no, source_location location) -{ - gcc_assert(no->resolve()->is_unknown()); - return new Unknown_expression(no, location); -} - -// A boolean expression. - -class Boolean_expression : public Expression -{ - public: - Boolean_expression(bool val, source_location location) - : Expression(EXPRESSION_BOOLEAN, location), - val_(val), type_(NULL) - { } - - static Expression* - do_import(Import*); - - protected: - bool - do_is_constant() const - { return true; } - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context*) - { return this->val_ ? boolean_true_node : boolean_false_node; } - - void - do_export(Export* exp) const - { exp->write_c_string(this->val_ ? "true" : "false"); } - - private: - // The constant. - bool val_; - // The type as determined by context. - Type* type_; -}; - -// Get the type. - -Type* -Boolean_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_boolean_type(); - return this->type_; -} - -// Set the type from the context. - -void -Boolean_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL && context->type->is_boolean_type()) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_bool_type(); -} - -// Import a boolean constant. - -Expression* -Boolean_expression::do_import(Import* imp) -{ - if (imp->peek_char() == 't') - { - imp->require_c_string("true"); - return Expression::make_boolean(true, imp->location()); - } - else - { - imp->require_c_string("false"); - return Expression::make_boolean(false, imp->location()); - } -} - -// Make a boolean expression. - -Expression* -Expression::make_boolean(bool val, source_location location) -{ - return new Boolean_expression(val, location); -} - -// Class String_expression. - -// Get the type. - -Type* -String_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_string_type(); - return this->type_; -} - -// Set the type from the context. - -void -String_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL && context->type->is_string_type()) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_string_type(); -} - -// Build a string constant. - -tree -String_expression::do_get_tree(Translate_context* context) -{ - return context->gogo()->go_string_constant_tree(this->val_); -} - -// Export a string expression. - -void -String_expression::do_export(Export* exp) const -{ - std::string s; - s.reserve(this->val_.length() * 4 + 2); - s += '"'; - for (std::string::const_iterator p = this->val_.begin(); - p != this->val_.end(); - ++p) - { - if (*p == '\\' || *p == '"') - { - s += '\\'; - s += *p; - } - else if (*p >= 0x20 && *p < 0x7f) - s += *p; - else if (*p == '\n') - s += "\\n"; - else if (*p == '\t') - s += "\\t"; - else - { - s += "\\x"; - unsigned char c = *p; - unsigned int dig = c >> 4; - s += dig < 10 ? '0' + dig : 'A' + dig - 10; - dig = c & 0xf; - s += dig < 10 ? '0' + dig : 'A' + dig - 10; - } - } - s += '"'; - exp->write_string(s); -} - -// Import a string expression. - -Expression* -String_expression::do_import(Import* imp) -{ - imp->require_c_string("\""); - std::string val; - while (true) - { - int c = imp->get_char(); - if (c == '"' || c == -1) - break; - if (c != '\\') - val += static_cast(c); - else - { - c = imp->get_char(); - if (c == '\\' || c == '"') - val += static_cast(c); - else if (c == 'n') - val += '\n'; - else if (c == 't') - val += '\t'; - else if (c == 'x') - { - c = imp->get_char(); - unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10; - c = imp->get_char(); - unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10; - char v = (vh << 4) | vl; - val += v; - } - else - { - error_at(imp->location(), "bad string constant"); - return Expression::make_error(imp->location()); - } - } - } - return Expression::make_string(val, imp->location()); -} - -// Make a string expression. - -Expression* -Expression::make_string(const std::string& val, source_location location) -{ - return new String_expression(val, location); -} - -// Make an integer expression. - -class Integer_expression : public Expression -{ - public: - Integer_expression(const mpz_t* val, Type* type, source_location location) - : Expression(EXPRESSION_INTEGER, location), - type_(type) - { mpz_init_set(this->val_, *val); } - - static Expression* - do_import(Import*); - - // Return whether VAL fits in the type. - static bool - check_constant(mpz_t val, Type*, source_location); - - // Write VAL to export data. - static void - export_integer(Export* exp, const mpz_t val); - - protected: - bool - do_is_constant() const - { return true; } - - bool - do_integer_constant_value(bool, mpz_t val, Type** ptype) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context* context); - - void - do_check_types(Gogo*); - - tree - do_get_tree(Translate_context*); - - Expression* - do_copy() - { return Expression::make_integer(&this->val_, this->type_, - this->location()); } - - void - do_export(Export*) const; - - private: - // The integer value. - mpz_t val_; - // The type so far. - Type* type_; -}; - -// Return an integer constant value. - -bool -Integer_expression::do_integer_constant_value(bool, mpz_t val, - Type** ptype) const -{ - if (this->type_ != NULL) - *ptype = this->type_; - mpz_set(val, this->val_); - return true; -} - -// Return the current type. If we haven't set the type yet, we return -// an abstract integer type. - -Type* -Integer_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_abstract_integer_type(); - return this->type_; -} - -// Set the type of the integer value. Here we may switch from an -// abstract type to a real type. - -void -Integer_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL - && (context->type->integer_type() != NULL - || context->type->float_type() != NULL - || context->type->complex_type() != NULL)) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_integer_type("int"); -} - -// Return true if the integer VAL fits in the range of the type TYPE. -// Otherwise give an error and return false. TYPE may be NULL. - -bool -Integer_expression::check_constant(mpz_t val, Type* type, - source_location location) -{ - if (type == NULL) - return true; - Integer_type* itype = type->integer_type(); - if (itype == NULL || itype->is_abstract()) - return true; - - int bits = mpz_sizeinbase(val, 2); - - if (itype->is_unsigned()) - { - // For an unsigned type we can only accept a nonnegative number, - // and we must be able to represent at least BITS. - if (mpz_sgn(val) >= 0 - && bits <= itype->bits()) - return true; - } - else - { - // For a signed type we need an extra bit to indicate the sign. - // We have to handle the most negative integer specially. - if (bits + 1 <= itype->bits() - || (bits <= itype->bits() - && mpz_sgn(val) < 0 - && (mpz_scan1(val, 0) - == static_cast(itype->bits() - 1)) - && mpz_scan0(val, itype->bits()) == ULONG_MAX)) - return true; - } - - error_at(location, "integer constant overflow"); - return false; -} - -// Check the type of an integer constant. - -void -Integer_expression::do_check_types(Gogo*) -{ - if (this->type_ == NULL) - return; - if (!Integer_expression::check_constant(this->val_, this->type_, - this->location())) - this->set_is_error(); -} - -// Get a tree for an integer constant. - -tree -Integer_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type; - if (this->type_ != NULL && !this->type_->is_abstract()) - type = this->type_->get_tree(gogo); - else if (this->type_ != NULL && this->type_->float_type() != NULL) - { - // We are converting to an abstract floating point type. - type = Type::lookup_float_type("float64")->get_tree(gogo); - } - else if (this->type_ != NULL && this->type_->complex_type() != NULL) - { - // We are converting to an abstract complex type. - type = Type::lookup_complex_type("complex128")->get_tree(gogo); - } - else - { - // If we still have an abstract type here, then this is being - // used in a constant expression which didn't get reduced for - // some reason. Use a type which will fit the value. We use <, - // not <=, because we need an extra bit for the sign bit. - int bits = mpz_sizeinbase(this->val_, 2); - if (bits < INT_TYPE_SIZE) - type = Type::lookup_integer_type("int")->get_tree(gogo); - else if (bits < 64) - type = Type::lookup_integer_type("int64")->get_tree(gogo); - else - type = long_long_integer_type_node; - } - return Expression::integer_constant_tree(this->val_, type); -} - -// Write VAL to export data. - -void -Integer_expression::export_integer(Export* exp, const mpz_t val) -{ - char* s = mpz_get_str(NULL, 10, val); - exp->write_c_string(s); - free(s); -} - -// Export an integer in a constant expression. - -void -Integer_expression::do_export(Export* exp) const -{ - Integer_expression::export_integer(exp, this->val_); - // A trailing space lets us reliably identify the end of the number. - exp->write_c_string(" "); -} - -// Import an integer, floating point, or complex value. This handles -// all these types because they all start with digits. - -Expression* -Integer_expression::do_import(Import* imp) -{ - std::string num = imp->read_identifier(); - imp->require_c_string(" "); - if (!num.empty() && num[num.length() - 1] == 'i') - { - mpfr_t real; - size_t plus_pos = num.find('+', 1); - size_t minus_pos = num.find('-', 1); - size_t pos; - if (plus_pos == std::string::npos) - pos = minus_pos; - else if (minus_pos == std::string::npos) - pos = plus_pos; - else - { - error_at(imp->location(), "bad number in import data: %qs", - num.c_str()); - return Expression::make_error(imp->location()); - } - if (pos == std::string::npos) - mpfr_set_ui(real, 0, GMP_RNDN); - else - { - std::string real_str = num.substr(0, pos); - if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0) - { - error_at(imp->location(), "bad number in import data: %qs", - real_str.c_str()); - return Expression::make_error(imp->location()); - } - } - - std::string imag_str; - if (pos == std::string::npos) - imag_str = num; - else - imag_str = num.substr(pos); - imag_str = imag_str.substr(0, imag_str.size() - 1); - mpfr_t imag; - if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0) - { - error_at(imp->location(), "bad number in import data: %qs", - imag_str.c_str()); - return Expression::make_error(imp->location()); - } - Expression* ret = Expression::make_complex(&real, &imag, NULL, - imp->location()); - mpfr_clear(real); - mpfr_clear(imag); - return ret; - } - else if (num.find('.') == std::string::npos - && num.find('E') == std::string::npos) - { - mpz_t val; - if (mpz_init_set_str(val, num.c_str(), 10) != 0) - { - error_at(imp->location(), "bad number in import data: %qs", - num.c_str()); - return Expression::make_error(imp->location()); - } - Expression* ret = Expression::make_integer(&val, NULL, imp->location()); - mpz_clear(val); - return ret; - } - else - { - mpfr_t val; - if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0) - { - error_at(imp->location(), "bad number in import data: %qs", - num.c_str()); - return Expression::make_error(imp->location()); - } - Expression* ret = Expression::make_float(&val, NULL, imp->location()); - mpfr_clear(val); - return ret; - } -} - -// Build a new integer value. - -Expression* -Expression::make_integer(const mpz_t* val, Type* type, - source_location location) -{ - return new Integer_expression(val, type, location); -} - -// Floats. - -class Float_expression : public Expression -{ - public: - Float_expression(const mpfr_t* val, Type* type, source_location location) - : Expression(EXPRESSION_FLOAT, location), - type_(type) - { - mpfr_init_set(this->val_, *val, GMP_RNDN); - } - - // Constrain VAL to fit into TYPE. - static void - constrain_float(mpfr_t val, Type* type); - - // Return whether VAL fits in the type. - static bool - check_constant(mpfr_t val, Type*, source_location); - - // Write VAL to export data. - static void - export_float(Export* exp, const mpfr_t val); - - protected: - bool - do_is_constant() const - { return true; } - - bool - do_float_constant_value(mpfr_t val, Type**) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { return Expression::make_float(&this->val_, this->type_, - this->location()); } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The floating point value. - mpfr_t val_; - // The type so far. - Type* type_; -}; - -// Constrain VAL to fit into TYPE. - -void -Float_expression::constrain_float(mpfr_t val, Type* type) -{ - Float_type* ftype = type->float_type(); - if (ftype != NULL && !ftype->is_abstract()) - { - tree type_tree = ftype->type_tree(); - REAL_VALUE_TYPE rvt; - real_from_mpfr(&rvt, val, type_tree, GMP_RNDN); - real_convert(&rvt, TYPE_MODE(type_tree), &rvt); - mpfr_from_real(val, &rvt, GMP_RNDN); - } -} - -// Return a floating point constant value. - -bool -Float_expression::do_float_constant_value(mpfr_t val, Type** ptype) const -{ - if (this->type_ != NULL) - *ptype = this->type_; - mpfr_set(val, this->val_, GMP_RNDN); - return true; -} - -// Return the current type. If we haven't set the type yet, we return -// an abstract float type. - -Type* -Float_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_abstract_float_type(); - return this->type_; -} - -// Set the type of the float value. Here we may switch from an -// abstract type to a real type. - -void -Float_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL - && (context->type->integer_type() != NULL - || context->type->float_type() != NULL - || context->type->complex_type() != NULL)) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_float_type("float64"); -} - -// Return true if the floating point value VAL fits in the range of -// the type TYPE. Otherwise give an error and return false. TYPE may -// be NULL. - -bool -Float_expression::check_constant(mpfr_t val, Type* type, - source_location location) -{ - if (type == NULL) - return true; - Float_type* ftype = type->float_type(); - if (ftype == NULL || ftype->is_abstract()) - return true; - - // A NaN or Infinity always fits in the range of the type. - if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val)) - return true; - - mp_exp_t exp = mpfr_get_exp(val); - mp_exp_t max_exp; - switch (ftype->bits()) - { - case 32: - max_exp = 128; - break; - case 64: - max_exp = 1024; - break; - default: - gcc_unreachable(); - } - if (exp > max_exp) - { - error_at(location, "floating point constant overflow"); - return false; - } - return true; -} - -// Check the type of a float value. - -void -Float_expression::do_check_types(Gogo*) -{ - if (this->type_ == NULL) - return; - - if (!Float_expression::check_constant(this->val_, this->type_, - this->location())) - this->set_is_error(); - - Integer_type* integer_type = this->type_->integer_type(); - if (integer_type != NULL) - { - if (!mpfr_integer_p(this->val_)) - this->report_error(_("floating point constant truncated to integer")); - else - { - gcc_assert(!integer_type->is_abstract()); - mpz_t ival; - mpz_init(ival); - mpfr_get_z(ival, this->val_, GMP_RNDN); - Integer_expression::check_constant(ival, integer_type, - this->location()); - mpz_clear(ival); - } - } -} - -// Get a tree for a float constant. - -tree -Float_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type; - if (this->type_ != NULL && !this->type_->is_abstract()) - type = this->type_->get_tree(gogo); - else if (this->type_ != NULL && this->type_->integer_type() != NULL) - { - // We have an abstract integer type. We just hope for the best. - type = Type::lookup_integer_type("int")->get_tree(gogo); - } - else - { - // If we still have an abstract type here, then this is being - // used in a constant expression which didn't get reduced. We - // just use float64 and hope for the best. - type = Type::lookup_float_type("float64")->get_tree(gogo); - } - return Expression::float_constant_tree(this->val_, type); -} - -// Write a floating point number to export data. - -void -Float_expression::export_float(Export *exp, const mpfr_t val) -{ - mp_exp_t exponent; - char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN); - if (*s == '-') - exp->write_c_string("-"); - exp->write_c_string("0."); - exp->write_c_string(*s == '-' ? s + 1 : s); - mpfr_free_str(s); - char buf[30]; - snprintf(buf, sizeof buf, "E%ld", exponent); - exp->write_c_string(buf); -} - -// Export a floating point number in a constant expression. - -void -Float_expression::do_export(Export* exp) const -{ - Float_expression::export_float(exp, this->val_); - // A trailing space lets us reliably identify the end of the number. - exp->write_c_string(" "); -} - -// Make a float expression. - -Expression* -Expression::make_float(const mpfr_t* val, Type* type, source_location location) -{ - return new Float_expression(val, type, location); -} - -// Complex numbers. - -class Complex_expression : public Expression -{ - public: - Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type, - source_location location) - : Expression(EXPRESSION_COMPLEX, location), - type_(type) - { - mpfr_init_set(this->real_, *real, GMP_RNDN); - mpfr_init_set(this->imag_, *imag, GMP_RNDN); - } - - // Constrain REAL/IMAG to fit into TYPE. - static void - constrain_complex(mpfr_t real, mpfr_t imag, Type* type); - - // Return whether REAL/IMAG fits in the type. - static bool - check_constant(mpfr_t real, mpfr_t imag, Type*, source_location); - - // Write REAL/IMAG to export data. - static void - export_complex(Export* exp, const mpfr_t real, const mpfr_t val); - - protected: - bool - do_is_constant() const - { return true; } - - bool - do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return Expression::make_complex(&this->real_, &this->imag_, this->type_, - this->location()); - } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The real part. - mpfr_t real_; - // The imaginary part; - mpfr_t imag_; - // The type if known. - Type* type_; -}; - -// Constrain REAL/IMAG to fit into TYPE. - -void -Complex_expression::constrain_complex(mpfr_t real, mpfr_t imag, Type* type) -{ - Complex_type* ctype = type->complex_type(); - if (ctype != NULL && !ctype->is_abstract()) - { - tree type_tree = ctype->type_tree(); - - REAL_VALUE_TYPE rvt; - real_from_mpfr(&rvt, real, TREE_TYPE(type_tree), GMP_RNDN); - real_convert(&rvt, TYPE_MODE(TREE_TYPE(type_tree)), &rvt); - mpfr_from_real(real, &rvt, GMP_RNDN); - - real_from_mpfr(&rvt, imag, TREE_TYPE(type_tree), GMP_RNDN); - real_convert(&rvt, TYPE_MODE(TREE_TYPE(type_tree)), &rvt); - mpfr_from_real(imag, &rvt, GMP_RNDN); - } -} - -// Return a complex constant value. - -bool -Complex_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - if (this->type_ != NULL) - *ptype = this->type_; - mpfr_set(real, this->real_, GMP_RNDN); - mpfr_set(imag, this->imag_, GMP_RNDN); - return true; -} - -// Return the current type. If we haven't set the type yet, we return -// an abstract complex type. - -Type* -Complex_expression::do_type() -{ - if (this->type_ == NULL) - this->type_ = Type::make_abstract_complex_type(); - return this->type_; -} - -// Set the type of the complex value. Here we may switch from an -// abstract type to a real type. - -void -Complex_expression::do_determine_type(const Type_context* context) -{ - if (this->type_ != NULL && !this->type_->is_abstract()) - ; - else if (context->type != NULL - && context->type->complex_type() != NULL) - this->type_ = context->type; - else if (!context->may_be_abstract) - this->type_ = Type::lookup_complex_type("complex128"); -} - -// Return true if the complex value REAL/IMAG fits in the range of the -// type TYPE. Otherwise give an error and return false. TYPE may be -// NULL. - -bool -Complex_expression::check_constant(mpfr_t real, mpfr_t imag, Type* type, - source_location location) -{ - if (type == NULL) - return true; - Complex_type* ctype = type->complex_type(); - if (ctype == NULL || ctype->is_abstract()) - return true; - - mp_exp_t max_exp; - switch (ctype->bits()) - { - case 64: - max_exp = 128; - break; - case 128: - max_exp = 1024; - break; - default: - gcc_unreachable(); - } - - // A NaN or Infinity always fits in the range of the type. - if (!mpfr_nan_p(real) && !mpfr_inf_p(real) && !mpfr_zero_p(real)) - { - if (mpfr_get_exp(real) > max_exp) - { - error_at(location, "complex real part constant overflow"); - return false; - } - } - - if (!mpfr_nan_p(imag) && !mpfr_inf_p(imag) && !mpfr_zero_p(imag)) - { - if (mpfr_get_exp(imag) > max_exp) - { - error_at(location, "complex imaginary part constant overflow"); - return false; - } - } - - return true; -} - -// Check the type of a complex value. - -void -Complex_expression::do_check_types(Gogo*) -{ - if (this->type_ == NULL) - return; - - if (!Complex_expression::check_constant(this->real_, this->imag_, - this->type_, this->location())) - this->set_is_error(); -} - -// Get a tree for a complex constant. - -tree -Complex_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type; - if (this->type_ != NULL && !this->type_->is_abstract()) - type = this->type_->get_tree(gogo); - else - { - // If we still have an abstract type here, this this is being - // used in a constant expression which didn't get reduced. We - // just use complex128 and hope for the best. - type = Type::lookup_complex_type("complex128")->get_tree(gogo); - } - return Expression::complex_constant_tree(this->real_, this->imag_, type); -} - -// Write REAL/IMAG to export data. - -void -Complex_expression::export_complex(Export* exp, const mpfr_t real, - const mpfr_t imag) -{ - if (!mpfr_zero_p(real)) - { - Float_expression::export_float(exp, real); - if (mpfr_sgn(imag) > 0) - exp->write_c_string("+"); - } - Float_expression::export_float(exp, imag); - exp->write_c_string("i"); -} - -// Export a complex number in a constant expression. - -void -Complex_expression::do_export(Export* exp) const -{ - Complex_expression::export_complex(exp, this->real_, this->imag_); - // A trailing space lets us reliably identify the end of the number. - exp->write_c_string(" "); -} - -// Make a complex expression. - -Expression* -Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type, - source_location location) -{ - return new Complex_expression(real, imag, type, location); -} - -// Find a named object in an expression. - -class Find_named_object : public Traverse -{ - public: - Find_named_object(Named_object* no) - : Traverse(traverse_expressions), - no_(no), found_(false) - { } - - // Whether we found the object. - bool - found() const - { return this->found_; } - - protected: - int - expression(Expression**); - - private: - // The object we are looking for. - Named_object* no_; - // Whether we found it. - bool found_; -}; - -// A reference to a const in an expression. - -class Const_expression : public Expression -{ - public: - Const_expression(Named_object* constant, source_location location) - : Expression(EXPRESSION_CONST_REFERENCE, location), - constant_(constant), type_(NULL), seen_(false) - { } - - Named_object* - named_object() - { return this->constant_; } - - // Check that the initializer does not refer to the constant itself. - void - check_for_init_loop(); - - protected: - int - do_traverse(Traverse*); - - Expression* - do_lower(Gogo*, Named_object*, int); - - bool - do_is_constant() const - { return true; } - - bool - do_integer_constant_value(bool, mpz_t val, Type**) const; - - bool - do_float_constant_value(mpfr_t val, Type**) const; - - bool - do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const; - - bool - do_string_constant_value(std::string* val) const - { return this->constant_->const_value()->expr()->string_constant_value(val); } - - Type* - do_type(); - - // The type of a const is set by the declaration, not the use. - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context* context); - - // When exporting a reference to a const as part of a const - // expression, we export the value. We ignore the fact that it has - // a name. - void - do_export(Export* exp) const - { this->constant_->const_value()->expr()->export_expression(exp); } - - private: - // The constant. - Named_object* constant_; - // The type of this reference. This is used if the constant has an - // abstract type. - Type* type_; - // Used to prevent infinite recursion when a constant incorrectly - // refers to itself. - mutable bool seen_; -}; - -// Traversal. - -int -Const_expression::do_traverse(Traverse* traverse) -{ - if (this->type_ != NULL) - return Type::traverse(this->type_, traverse); - return TRAVERSE_CONTINUE; -} - -// Lower a constant expression. This is where we convert the -// predeclared constant iota into an integer value. - -Expression* -Const_expression::do_lower(Gogo* gogo, Named_object*, int iota_value) -{ - if (this->constant_->const_value()->expr()->classification() - == EXPRESSION_IOTA) - { - if (iota_value == -1) - { - error_at(this->location(), - "iota is only defined in const declarations"); - iota_value = 0; - } - mpz_t val; - mpz_init_set_ui(val, static_cast(iota_value)); - Expression* ret = Expression::make_integer(&val, NULL, - this->location()); - mpz_clear(val); - return ret; - } - - // Make sure that the constant itself has been lowered. - gogo->lower_constant(this->constant_); - - return this; -} - -// Return an integer constant value. - -bool -Const_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val, - Type** ptype) const -{ - if (this->seen_) - return false; - - Type* ctype; - if (this->type_ != NULL) - ctype = this->type_; - else - ctype = this->constant_->const_value()->type(); - if (ctype != NULL && ctype->integer_type() == NULL) - return false; - - Expression* e = this->constant_->const_value()->expr(); - - this->seen_ = true; - - Type* t; - bool r = e->integer_constant_value(iota_is_constant, val, &t); - - this->seen_ = false; - - if (r - && ctype != NULL - && !Integer_expression::check_constant(val, ctype, this->location())) - return false; - - *ptype = ctype != NULL ? ctype : t; - return r; -} - -// Return a floating point constant value. - -bool -Const_expression::do_float_constant_value(mpfr_t val, Type** ptype) const -{ - if (this->seen_) - return false; - - Type* ctype; - if (this->type_ != NULL) - ctype = this->type_; - else - ctype = this->constant_->const_value()->type(); - if (ctype != NULL && ctype->float_type() == NULL) - return false; - - this->seen_ = true; - - Type* t; - bool r = this->constant_->const_value()->expr()->float_constant_value(val, - &t); - - this->seen_ = false; - - if (r && ctype != NULL) - { - if (!Float_expression::check_constant(val, ctype, this->location())) - return false; - Float_expression::constrain_float(val, ctype); - } - *ptype = ctype != NULL ? ctype : t; - return r; -} - -// Return a complex constant value. - -bool -Const_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type **ptype) const -{ - if (this->seen_) - return false; - - Type* ctype; - if (this->type_ != NULL) - ctype = this->type_; - else - ctype = this->constant_->const_value()->type(); - if (ctype != NULL && ctype->complex_type() == NULL) - return false; - - this->seen_ = true; - - Type *t; - bool r = this->constant_->const_value()->expr()->complex_constant_value(real, - imag, - &t); - - this->seen_ = false; - - if (r && ctype != NULL) - { - if (!Complex_expression::check_constant(real, imag, ctype, - this->location())) - return false; - Complex_expression::constrain_complex(real, imag, ctype); - } - *ptype = ctype != NULL ? ctype : t; - return r; -} - -// Return the type of the const reference. - -Type* -Const_expression::do_type() -{ - if (this->type_ != NULL) - return this->type_; - - Named_constant* nc = this->constant_->const_value(); - - if (this->seen_ || nc->lowering()) - { - this->report_error(_("constant refers to itself")); - this->type_ = Type::make_error_type(); - return this->type_; - } - - this->seen_ = true; - - Type* ret = nc->type(); - - if (ret != NULL) - { - this->seen_ = false; - return ret; - } - - // During parsing, a named constant may have a NULL type, but we - // must not return a NULL type here. - ret = nc->expr()->type(); - - this->seen_ = false; - - return ret; -} - -// Set the type of the const reference. - -void -Const_expression::do_determine_type(const Type_context* context) -{ - Type* ctype = this->constant_->const_value()->type(); - Type* cetype = (ctype != NULL - ? ctype - : this->constant_->const_value()->expr()->type()); - if (ctype != NULL && !ctype->is_abstract()) - ; - else if (context->type != NULL - && (context->type->integer_type() != NULL - || context->type->float_type() != NULL - || context->type->complex_type() != NULL) - && (cetype->integer_type() != NULL - || cetype->float_type() != NULL - || cetype->complex_type() != NULL)) - this->type_ = context->type; - else if (context->type != NULL - && context->type->is_string_type() - && cetype->is_string_type()) - this->type_ = context->type; - else if (context->type != NULL - && context->type->is_boolean_type() - && cetype->is_boolean_type()) - this->type_ = context->type; - else if (!context->may_be_abstract) - { - if (cetype->is_abstract()) - cetype = cetype->make_non_abstract_type(); - this->type_ = cetype; - } -} - -// Check for a loop in which the initializer of a constant refers to -// the constant itself. - -void -Const_expression::check_for_init_loop() -{ - if (this->type_ != NULL && this->type_->is_error_type()) - return; - - if (this->seen_) - { - this->report_error(_("constant refers to itself")); - this->type_ = Type::make_error_type(); - return; - } - - Expression* init = this->constant_->const_value()->expr(); - Find_named_object find_named_object(this->constant_); - - this->seen_ = true; - Expression::traverse(&init, &find_named_object); - this->seen_ = false; - - if (find_named_object.found()) - { - if (this->type_ == NULL || !this->type_->is_error_type()) - { - this->report_error(_("constant refers to itself")); - this->type_ = Type::make_error_type(); - } - return; - } -} - -// Check types of a const reference. - -void -Const_expression::do_check_types(Gogo*) -{ - if (this->type_ != NULL && this->type_->is_error_type()) - return; - - this->check_for_init_loop(); - - if (this->type_ == NULL || this->type_->is_abstract()) - return; - - // Check for integer overflow. - if (this->type_->integer_type() != NULL) - { - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (!this->integer_constant_value(true, ival, &dummy)) - { - mpfr_t fval; - mpfr_init(fval); - Expression* cexpr = this->constant_->const_value()->expr(); - if (cexpr->float_constant_value(fval, &dummy)) - { - if (!mpfr_integer_p(fval)) - this->report_error(_("floating point constant " - "truncated to integer")); - else - { - mpfr_get_z(ival, fval, GMP_RNDN); - Integer_expression::check_constant(ival, this->type_, - this->location()); - } - } - mpfr_clear(fval); - } - mpz_clear(ival); - } -} - -// Return a tree for the const reference. - -tree -Const_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type_tree; - if (this->type_ == NULL) - type_tree = NULL_TREE; - else - { - type_tree = this->type_->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - } - - // If the type has been set for this expression, but the underlying - // object is an abstract int or float, we try to get the abstract - // value. Otherwise we may lose something in the conversion. - if (this->type_ != NULL - && (this->constant_->const_value()->type() == NULL - || this->constant_->const_value()->type()->is_abstract())) - { - Expression* expr = this->constant_->const_value()->expr(); - mpz_t ival; - mpz_init(ival); - Type* t; - if (expr->integer_constant_value(true, ival, &t)) - { - tree ret = Expression::integer_constant_tree(ival, type_tree); - mpz_clear(ival); - return ret; - } - mpz_clear(ival); - - mpfr_t fval; - mpfr_init(fval); - if (expr->float_constant_value(fval, &t)) - { - tree ret = Expression::float_constant_tree(fval, type_tree); - mpfr_clear(fval); - return ret; - } - - mpfr_t imag; - mpfr_init(imag); - if (expr->complex_constant_value(fval, imag, &t)) - { - tree ret = Expression::complex_constant_tree(fval, imag, type_tree); - mpfr_clear(fval); - mpfr_clear(imag); - return ret; - } - mpfr_clear(imag); - mpfr_clear(fval); - } - - tree const_tree = this->constant_->get_tree(gogo, context->function()); - if (this->type_ == NULL - || const_tree == error_mark_node - || TREE_TYPE(const_tree) == error_mark_node) - return const_tree; - - tree ret; - if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree))) - ret = fold_convert(type_tree, const_tree); - else if (TREE_CODE(type_tree) == INTEGER_TYPE) - ret = fold(convert_to_integer(type_tree, const_tree)); - else if (TREE_CODE(type_tree) == REAL_TYPE) - ret = fold(convert_to_real(type_tree, const_tree)); - else if (TREE_CODE(type_tree) == COMPLEX_TYPE) - ret = fold(convert_to_complex(type_tree, const_tree)); - else - gcc_unreachable(); - return ret; -} - -// Make a reference to a constant in an expression. - -Expression* -Expression::make_const_reference(Named_object* constant, - source_location location) -{ - return new Const_expression(constant, location); -} - -// Find a named object in an expression. - -int -Find_named_object::expression(Expression** pexpr) -{ - switch ((*pexpr)->classification()) - { - case Expression::EXPRESSION_CONST_REFERENCE: - { - Const_expression* ce = static_cast(*pexpr); - if (ce->named_object() == this->no_) - break; - - // We need to check a constant initializer explicitly, as - // loops here will not be caught by the loop checking for - // variable initializers. - ce->check_for_init_loop(); - - return TRAVERSE_CONTINUE; - } - - case Expression::EXPRESSION_VAR_REFERENCE: - if ((*pexpr)->var_expression()->named_object() == this->no_) - break; - return TRAVERSE_CONTINUE; - case Expression::EXPRESSION_FUNC_REFERENCE: - if ((*pexpr)->func_expression()->named_object() == this->no_) - break; - return TRAVERSE_CONTINUE; - default: - return TRAVERSE_CONTINUE; - } - this->found_ = true; - return TRAVERSE_EXIT; -} - -// The nil value. - -class Nil_expression : public Expression -{ - public: - Nil_expression(source_location location) - : Expression(EXPRESSION_NIL, location) - { } - - static Expression* - do_import(Import*); - - protected: - bool - do_is_constant() const - { return true; } - - Type* - do_type() - { return Type::make_nil_type(); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context*) - { return null_pointer_node; } - - void - do_export(Export* exp) const - { exp->write_c_string("nil"); } -}; - -// Import a nil expression. - -Expression* -Nil_expression::do_import(Import* imp) -{ - imp->require_c_string("nil"); - return Expression::make_nil(imp->location()); -} - -// Make a nil expression. - -Expression* -Expression::make_nil(source_location location) -{ - return new Nil_expression(location); -} - -// The value of the predeclared constant iota. This is little more -// than a marker. This will be lowered to an integer in -// Const_expression::do_lower, which is where we know the value that -// it should have. - -class Iota_expression : public Parser_expression -{ - public: - Iota_expression(source_location location) - : Parser_expression(EXPRESSION_IOTA, location) - { } - - protected: - Expression* - do_lower(Gogo*, Named_object*, int) - { gcc_unreachable(); } - - // There should only ever be one of these. - Expression* - do_copy() - { gcc_unreachable(); } -}; - -// Make an iota expression. This is only called for one case: the -// value of the predeclared constant iota. - -Expression* -Expression::make_iota() -{ - static Iota_expression iota_expression(UNKNOWN_LOCATION); - return &iota_expression; -} - -// A type conversion expression. - -class Type_conversion_expression : public Expression -{ - public: - Type_conversion_expression(Type* type, Expression* expr, - source_location location) - : Expression(EXPRESSION_CONVERSION, location), - type_(type), expr_(expr), may_convert_function_types_(false) - { } - - // Return the type to which we are converting. - Type* - type() const - { return this->type_; } - - // Return the expression which we are converting. - Expression* - expr() const - { return this->expr_; } - - // Permit converting from one function type to another. This is - // used internally for method expressions. - void - set_may_convert_function_types() - { - this->may_convert_function_types_ = true; - } - - // Import a type conversion expression. - static Expression* - do_import(Import*); - - protected: - int - do_traverse(Traverse* traverse); - - Expression* - do_lower(Gogo*, Named_object*, int); - - bool - do_is_constant() const - { return this->expr_->is_constant(); } - - bool - do_integer_constant_value(bool, mpz_t, Type**) const; - - bool - do_float_constant_value(mpfr_t, Type**) const; - - bool - do_complex_constant_value(mpfr_t, mpfr_t, Type**) const; - - bool - do_string_constant_value(std::string*) const; - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*) - { - Type_context subcontext(this->type_, false); - this->expr_->determine_type(&subcontext); - } - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Type_conversion_expression(this->type_, this->expr_->copy(), - this->location()); - } - - tree - do_get_tree(Translate_context* context); - - void - do_export(Export*) const; - - private: - // The type to convert to. - Type* type_; - // The expression to convert. - Expression* expr_; - // True if this is permitted to convert function types. This is - // used internally for method expressions. - bool may_convert_function_types_; -}; - -// Traversal. - -int -Type_conversion_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT - || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Convert to a constant at lowering time. - -Expression* -Type_conversion_expression::do_lower(Gogo*, Named_object*, int) -{ - Type* type = this->type_; - Expression* val = this->expr_; - source_location location = this->location(); - - if (type->integer_type() != NULL) - { - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (val->integer_constant_value(false, ival, &dummy)) - { - if (!Integer_expression::check_constant(ival, type, location)) - mpz_set_ui(ival, 0); - Expression* ret = Expression::make_integer(&ival, type, location); - mpz_clear(ival); - return ret; - } - - mpfr_t fval; - mpfr_init(fval); - if (val->float_constant_value(fval, &dummy)) - { - if (!mpfr_integer_p(fval)) - { - error_at(location, - "floating point constant truncated to integer"); - return Expression::make_error(location); - } - mpfr_get_z(ival, fval, GMP_RNDN); - if (!Integer_expression::check_constant(ival, type, location)) - mpz_set_ui(ival, 0); - Expression* ret = Expression::make_integer(&ival, type, location); - mpfr_clear(fval); - mpz_clear(ival); - return ret; - } - mpfr_clear(fval); - mpz_clear(ival); - } - - if (type->float_type() != NULL) - { - mpfr_t fval; - mpfr_init(fval); - Type* dummy; - if (val->float_constant_value(fval, &dummy)) - { - if (!Float_expression::check_constant(fval, type, location)) - mpfr_set_ui(fval, 0, GMP_RNDN); - Float_expression::constrain_float(fval, type); - Expression *ret = Expression::make_float(&fval, type, location); - mpfr_clear(fval); - return ret; - } - mpfr_clear(fval); - } - - if (type->complex_type() != NULL) - { - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - Type* dummy; - if (val->complex_constant_value(real, imag, &dummy)) - { - if (!Complex_expression::check_constant(real, imag, type, location)) - { - mpfr_set_ui(real, 0, GMP_RNDN); - mpfr_set_ui(imag, 0, GMP_RNDN); - } - Complex_expression::constrain_complex(real, imag, type); - Expression* ret = Expression::make_complex(&real, &imag, type, - location); - mpfr_clear(real); - mpfr_clear(imag); - return ret; - } - mpfr_clear(real); - mpfr_clear(imag); - } - - if (type->is_open_array_type() && type->named_type() == NULL) - { - Type* element_type = type->array_type()->element_type()->forwarded(); - bool is_byte = element_type == Type::lookup_integer_type("uint8"); - bool is_int = element_type == Type::lookup_integer_type("int"); - if (is_byte || is_int) - { - std::string s; - if (val->string_constant_value(&s)) - { - Expression_list* vals = new Expression_list(); - if (is_byte) - { - for (std::string::const_iterator p = s.begin(); - p != s.end(); - p++) - { - mpz_t val; - mpz_init_set_ui(val, static_cast(*p)); - Expression* v = Expression::make_integer(&val, - element_type, - location); - vals->push_back(v); - mpz_clear(val); - } - } - else - { - const char *p = s.data(); - const char *pend = s.data() + s.length(); - while (p < pend) - { - unsigned int c; - int adv = Lex::fetch_char(p, &c); - if (adv == 0) - { - warning_at(this->location(), 0, - "invalid UTF-8 encoding"); - adv = 1; - } - p += adv; - mpz_t val; - mpz_init_set_ui(val, c); - Expression* v = Expression::make_integer(&val, - element_type, - location); - vals->push_back(v); - mpz_clear(val); - } - } - - return Expression::make_slice_composite_literal(type, vals, - location); - } - } - } - - return this; -} - -// Return the constant integer value if there is one. - -bool -Type_conversion_expression::do_integer_constant_value(bool iota_is_constant, - mpz_t val, - Type** ptype) const -{ - if (this->type_->integer_type() == NULL) - return false; - - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (this->expr_->integer_constant_value(iota_is_constant, ival, &dummy)) - { - if (!Integer_expression::check_constant(ival, this->type_, - this->location())) - { - mpz_clear(ival); - return false; - } - mpz_set(val, ival); - mpz_clear(ival); - *ptype = this->type_; - return true; - } - mpz_clear(ival); - - mpfr_t fval; - mpfr_init(fval); - if (this->expr_->float_constant_value(fval, &dummy)) - { - mpfr_get_z(val, fval, GMP_RNDN); - mpfr_clear(fval); - if (!Integer_expression::check_constant(val, this->type_, - this->location())) - return false; - *ptype = this->type_; - return true; - } - mpfr_clear(fval); - - return false; -} - -// Return the constant floating point value if there is one. - -bool -Type_conversion_expression::do_float_constant_value(mpfr_t val, - Type** ptype) const -{ - if (this->type_->float_type() == NULL) - return false; - - mpfr_t fval; - mpfr_init(fval); - Type* dummy; - if (this->expr_->float_constant_value(fval, &dummy)) - { - if (!Float_expression::check_constant(fval, this->type_, - this->location())) - { - mpfr_clear(fval); - return false; - } - mpfr_set(val, fval, GMP_RNDN); - mpfr_clear(fval); - Float_expression::constrain_float(val, this->type_); - *ptype = this->type_; - return true; - } - mpfr_clear(fval); - - return false; -} - -// Return the constant complex value if there is one. - -bool -Type_conversion_expression::do_complex_constant_value(mpfr_t real, - mpfr_t imag, - Type **ptype) const -{ - if (this->type_->complex_type() == NULL) - return false; - - mpfr_t rval; - mpfr_t ival; - mpfr_init(rval); - mpfr_init(ival); - Type* dummy; - if (this->expr_->complex_constant_value(rval, ival, &dummy)) - { - if (!Complex_expression::check_constant(rval, ival, this->type_, - this->location())) - { - mpfr_clear(rval); - mpfr_clear(ival); - return false; - } - mpfr_set(real, rval, GMP_RNDN); - mpfr_set(imag, ival, GMP_RNDN); - mpfr_clear(rval); - mpfr_clear(ival); - Complex_expression::constrain_complex(real, imag, this->type_); - *ptype = this->type_; - return true; - } - mpfr_clear(rval); - mpfr_clear(ival); - - return false; -} - -// Return the constant string value if there is one. - -bool -Type_conversion_expression::do_string_constant_value(std::string* val) const -{ - if (this->type_->is_string_type() - && this->expr_->type()->integer_type() != NULL) - { - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (this->expr_->integer_constant_value(false, ival, &dummy)) - { - unsigned long ulval = mpz_get_ui(ival); - if (mpz_cmp_ui(ival, ulval) == 0) - { - Lex::append_char(ulval, true, val, this->location()); - mpz_clear(ival); - return true; - } - } - mpz_clear(ival); - } - - // FIXME: Could handle conversion from const []int here. - - return false; -} - -// Check that types are convertible. - -void -Type_conversion_expression::do_check_types(Gogo*) -{ - Type* type = this->type_; - Type* expr_type = this->expr_->type(); - std::string reason; - - if (type->is_error_type() - || type->is_undefined() - || expr_type->is_error_type() - || expr_type->is_undefined()) - { - // Make sure we emit an error for an undefined type. - type->base(); - expr_type->base(); - this->set_is_error(); - return; - } - - if (this->may_convert_function_types_ - && type->function_type() != NULL - && expr_type->function_type() != NULL) - return; - - if (Type::are_convertible(type, expr_type, &reason)) - return; - - error_at(this->location(), "%s", reason.c_str()); - this->set_is_error(); -} - -// Get a tree for a type conversion. - -tree -Type_conversion_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree type_tree = this->type_->get_tree(gogo); - tree expr_tree = this->expr_->get_tree(context); - - if (type_tree == error_mark_node - || expr_tree == error_mark_node - || TREE_TYPE(expr_tree) == error_mark_node) - return error_mark_node; - - if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree))) - return fold_convert(type_tree, expr_tree); - - Type* type = this->type_; - Type* expr_type = this->expr_->type(); - tree ret; - if (type->interface_type() != NULL || expr_type->interface_type() != NULL) - ret = Expression::convert_for_assignment(context, type, expr_type, - expr_tree, this->location()); - else if (type->integer_type() != NULL) - { - if (expr_type->integer_type() != NULL - || expr_type->float_type() != NULL - || expr_type->is_unsafe_pointer_type()) - ret = fold(convert_to_integer(type_tree, expr_tree)); - else - gcc_unreachable(); - } - else if (type->float_type() != NULL) - { - if (expr_type->integer_type() != NULL - || expr_type->float_type() != NULL) - ret = fold(convert_to_real(type_tree, expr_tree)); - else - gcc_unreachable(); - } - else if (type->complex_type() != NULL) - { - if (expr_type->complex_type() != NULL) - ret = fold(convert_to_complex(type_tree, expr_tree)); - else - gcc_unreachable(); - } - else if (type->is_string_type() - && expr_type->integer_type() != NULL) - { - expr_tree = fold_convert(integer_type_node, expr_tree); - if (host_integerp(expr_tree, 0)) - { - HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0); - std::string s; - Lex::append_char(intval, true, &s, this->location()); - Expression* se = Expression::make_string(s, this->location()); - return se->get_tree(context); - } - - static tree int_to_string_fndecl; - ret = Gogo::call_builtin(&int_to_string_fndecl, - this->location(), - "__go_int_to_string", - 1, - type_tree, - integer_type_node, - fold_convert(integer_type_node, expr_tree)); - } - else if (type->is_string_type() - && (expr_type->array_type() != NULL - || (expr_type->points_to() != NULL - && expr_type->points_to()->array_type() != NULL))) - { - Type* t = expr_type; - if (t->points_to() != NULL) - { - t = t->points_to(); - expr_tree = build_fold_indirect_ref(expr_tree); - } - if (!DECL_P(expr_tree)) - expr_tree = save_expr(expr_tree); - Array_type* a = t->array_type(); - Type* e = a->element_type()->forwarded(); - gcc_assert(e->integer_type() != NULL); - tree valptr = fold_convert(const_ptr_type_node, - a->value_pointer_tree(gogo, expr_tree)); - tree len = a->length_tree(gogo, expr_tree); - len = fold_convert_loc(this->location(), size_type_node, len); - if (e->integer_type()->is_unsigned() - && e->integer_type()->bits() == 8) - { - static tree byte_array_to_string_fndecl; - ret = Gogo::call_builtin(&byte_array_to_string_fndecl, - this->location(), - "__go_byte_array_to_string", - 2, - type_tree, - const_ptr_type_node, - valptr, - size_type_node, - len); - } - else - { - gcc_assert(e == Type::lookup_integer_type("int")); - static tree int_array_to_string_fndecl; - ret = Gogo::call_builtin(&int_array_to_string_fndecl, - this->location(), - "__go_int_array_to_string", - 2, - type_tree, - const_ptr_type_node, - valptr, - size_type_node, - len); - } - } - else if (type->is_open_array_type() && expr_type->is_string_type()) - { - Type* e = type->array_type()->element_type()->forwarded(); - gcc_assert(e->integer_type() != NULL); - if (e->integer_type()->is_unsigned() - && e->integer_type()->bits() == 8) - { - static tree string_to_byte_array_fndecl; - ret = Gogo::call_builtin(&string_to_byte_array_fndecl, - this->location(), - "__go_string_to_byte_array", - 1, - type_tree, - TREE_TYPE(expr_tree), - expr_tree); - } - else - { - gcc_assert(e == Type::lookup_integer_type("int")); - static tree string_to_int_array_fndecl; - ret = Gogo::call_builtin(&string_to_int_array_fndecl, - this->location(), - "__go_string_to_int_array", - 1, - type_tree, - TREE_TYPE(expr_tree), - expr_tree); - } - } - else if ((type->is_unsafe_pointer_type() - && expr_type->points_to() != NULL) - || (expr_type->is_unsafe_pointer_type() - && type->points_to() != NULL)) - ret = fold_convert(type_tree, expr_tree); - else if (type->is_unsafe_pointer_type() - && expr_type->integer_type() != NULL) - ret = convert_to_pointer(type_tree, expr_tree); - else if (this->may_convert_function_types_ - && type->function_type() != NULL - && expr_type->function_type() != NULL) - ret = fold_convert_loc(this->location(), type_tree, expr_tree); - else - ret = Expression::convert_for_assignment(context, type, expr_type, - expr_tree, this->location()); - - return ret; -} - -// Output a type conversion in a constant expression. - -void -Type_conversion_expression::do_export(Export* exp) const -{ - exp->write_c_string("convert("); - exp->write_type(this->type_); - exp->write_c_string(", "); - this->expr_->export_expression(exp); - exp->write_c_string(")"); -} - -// Import a type conversion or a struct construction. - -Expression* -Type_conversion_expression::do_import(Import* imp) -{ - imp->require_c_string("convert("); - Type* type = imp->read_type(); - imp->require_c_string(", "); - Expression* val = Expression::import_expression(imp); - imp->require_c_string(")"); - return Expression::make_cast(type, val, imp->location()); -} - -// Make a type cast expression. - -Expression* -Expression::make_cast(Type* type, Expression* val, source_location location) -{ - if (type->is_error_type() || val->is_error_expression()) - return Expression::make_error(location); - return new Type_conversion_expression(type, val, location); -} - -// Unary expressions. - -class Unary_expression : public Expression -{ - public: - Unary_expression(Operator op, Expression* expr, source_location location) - : Expression(EXPRESSION_UNARY, location), - op_(op), escapes_(true), expr_(expr) - { } - - // Return the operator. - Operator - op() const - { return this->op_; } - - // Return the operand. - Expression* - operand() const - { return this->expr_; } - - // Record that an address expression does not escape. - void - set_does_not_escape() - { - gcc_assert(this->op_ == OPERATOR_AND); - this->escapes_ = false; - } - - // Apply unary opcode OP to UVAL, setting VAL. Return true if this - // could be done, false if not. - static bool - eval_integer(Operator op, Type* utype, mpz_t uval, mpz_t val, - source_location); - - // Apply unary opcode OP to UVAL, setting VAL. Return true if this - // could be done, false if not. - static bool - eval_float(Operator op, mpfr_t uval, mpfr_t val); - - // Apply unary opcode OP to UREAL/UIMAG, setting REAL/IMAG. Return - // true if this could be done, false if not. - static bool - eval_complex(Operator op, mpfr_t ureal, mpfr_t uimag, mpfr_t real, - mpfr_t imag); - - static Expression* - do_import(Import*); - - protected: - int - do_traverse(Traverse* traverse) - { return Expression::traverse(&this->expr_, traverse); } - - Expression* - do_lower(Gogo*, Named_object*, int); - - bool - do_is_constant() const; - - bool - do_integer_constant_value(bool, mpz_t, Type**) const; - - bool - do_float_constant_value(mpfr_t, Type**) const; - - bool - do_complex_constant_value(mpfr_t, mpfr_t, Type**) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return Expression::make_unary(this->op_, this->expr_->copy(), - this->location()); - } - - bool - do_is_addressable() const - { return this->op_ == OPERATOR_MULT; } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The unary operator to apply. - Operator op_; - // Normally true. False if this is an address expression which does - // not escape the current function. - bool escapes_; - // The operand. - Expression* expr_; -}; - -// If we are taking the address of a composite literal, and the -// contents are not constant, then we want to make a heap composite -// instead. - -Expression* -Unary_expression::do_lower(Gogo*, Named_object*, int) -{ - source_location loc = this->location(); - Operator op = this->op_; - Expression* expr = this->expr_; - - if (op == OPERATOR_MULT && expr->is_type_expression()) - return Expression::make_type(Type::make_pointer_type(expr->type()), loc); - - // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require - // moving x to the heap. FIXME: Is it worth doing a real escape - // analysis here? This case is found in math/unsafe.go and is - // therefore worth special casing. - if (op == OPERATOR_MULT) - { - Expression* e = expr; - while (e->classification() == EXPRESSION_CONVERSION) - { - Type_conversion_expression* te - = static_cast(e); - e = te->expr(); - } - - if (e->classification() == EXPRESSION_UNARY) - { - Unary_expression* ue = static_cast(e); - if (ue->op_ == OPERATOR_AND) - { - if (e == expr) - { - // *&x == x. - return ue->expr_; - } - ue->set_does_not_escape(); - } - } - } - - if (op == OPERATOR_PLUS || op == OPERATOR_MINUS - || op == OPERATOR_NOT || op == OPERATOR_XOR) - { - Expression* ret = NULL; - - mpz_t eval; - mpz_init(eval); - Type* etype; - if (expr->integer_constant_value(false, eval, &etype)) - { - mpz_t val; - mpz_init(val); - if (Unary_expression::eval_integer(op, etype, eval, val, loc)) - ret = Expression::make_integer(&val, etype, loc); - mpz_clear(val); - } - mpz_clear(eval); - if (ret != NULL) - return ret; - - if (op == OPERATOR_PLUS || op == OPERATOR_MINUS) - { - mpfr_t fval; - mpfr_init(fval); - Type* ftype; - if (expr->float_constant_value(fval, &ftype)) - { - mpfr_t val; - mpfr_init(val); - if (Unary_expression::eval_float(op, fval, val)) - ret = Expression::make_float(&val, ftype, loc); - mpfr_clear(val); - } - if (ret != NULL) - { - mpfr_clear(fval); - return ret; - } - - mpfr_t ival; - mpfr_init(ival); - if (expr->complex_constant_value(fval, ival, &ftype)) - { - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - if (Unary_expression::eval_complex(op, fval, ival, real, imag)) - ret = Expression::make_complex(&real, &imag, ftype, loc); - mpfr_clear(real); - mpfr_clear(imag); - } - mpfr_clear(ival); - mpfr_clear(fval); - if (ret != NULL) - return ret; - } - } - - return this; -} - -// Return whether a unary expression is a constant. - -bool -Unary_expression::do_is_constant() const -{ - if (this->op_ == OPERATOR_MULT) - { - // Indirecting through a pointer is only constant if the object - // to which the expression points is constant, but we currently - // have no way to determine that. - return false; - } - else if (this->op_ == OPERATOR_AND) - { - // Taking the address of a variable is constant if it is a - // global variable, not constant otherwise. In other cases - // taking the address is probably not a constant. - Var_expression* ve = this->expr_->var_expression(); - if (ve != NULL) - { - Named_object* no = ve->named_object(); - return no->is_variable() && no->var_value()->is_global(); - } - return false; - } - else - return this->expr_->is_constant(); -} - -// Apply unary opcode OP to UVAL, setting VAL. UTYPE is the type of -// UVAL, if known; it may be NULL. Return true if this could be done, -// false if not. - -bool -Unary_expression::eval_integer(Operator op, Type* utype, mpz_t uval, mpz_t val, - source_location location) -{ - switch (op) - { - case OPERATOR_PLUS: - mpz_set(val, uval); - return true; - case OPERATOR_MINUS: - mpz_neg(val, uval); - return Integer_expression::check_constant(val, utype, location); - case OPERATOR_NOT: - mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0); - return true; - case OPERATOR_XOR: - if (utype == NULL - || utype->integer_type() == NULL - || utype->integer_type()->is_abstract()) - mpz_com(val, uval); - else - { - // The number of HOST_WIDE_INTs that it takes to represent - // UVAL. - size_t count = ((mpz_sizeinbase(uval, 2) - + HOST_BITS_PER_WIDE_INT - - 1) - / HOST_BITS_PER_WIDE_INT); - - unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count]; - memset(phwi, 0, count * sizeof(HOST_WIDE_INT)); - - size_t ecount; - mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval); - gcc_assert(ecount <= count); - - // Trim down to the number of words required by the type. - size_t obits = utype->integer_type()->bits(); - if (!utype->integer_type()->is_unsigned()) - ++obits; - size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1) - / HOST_BITS_PER_WIDE_INT); - gcc_assert(ocount <= ocount); - - for (size_t i = 0; i < ocount; ++i) - phwi[i] = ~phwi[i]; - - size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits; - if (clearbits != 0) - phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1) - >> clearbits); - - mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi); - - delete[] phwi; - } - return Integer_expression::check_constant(val, utype, location); - case OPERATOR_AND: - case OPERATOR_MULT: - return false; - default: - gcc_unreachable(); - } -} - -// Apply unary opcode OP to UVAL, setting VAL. Return true if this -// could be done, false if not. - -bool -Unary_expression::eval_float(Operator op, mpfr_t uval, mpfr_t val) -{ - switch (op) - { - case OPERATOR_PLUS: - mpfr_set(val, uval, GMP_RNDN); - return true; - case OPERATOR_MINUS: - mpfr_neg(val, uval, GMP_RNDN); - return true; - case OPERATOR_NOT: - case OPERATOR_XOR: - case OPERATOR_AND: - case OPERATOR_MULT: - return false; - default: - gcc_unreachable(); - } -} - -// Apply unary opcode OP to RVAL/IVAL, setting REAL/IMAG. Return true -// if this could be done, false if not. - -bool -Unary_expression::eval_complex(Operator op, mpfr_t rval, mpfr_t ival, - mpfr_t real, mpfr_t imag) -{ - switch (op) - { - case OPERATOR_PLUS: - mpfr_set(real, rval, GMP_RNDN); - mpfr_set(imag, ival, GMP_RNDN); - return true; - case OPERATOR_MINUS: - mpfr_neg(real, rval, GMP_RNDN); - mpfr_neg(imag, ival, GMP_RNDN); - return true; - case OPERATOR_NOT: - case OPERATOR_XOR: - case OPERATOR_AND: - case OPERATOR_MULT: - return false; - default: - gcc_unreachable(); - } -} - -// Return the integral constant value of a unary expression, if it has one. - -bool -Unary_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val, - Type** ptype) const -{ - mpz_t uval; - mpz_init(uval); - bool ret; - if (!this->expr_->integer_constant_value(iota_is_constant, uval, ptype)) - ret = false; - else - ret = Unary_expression::eval_integer(this->op_, *ptype, uval, val, - this->location()); - mpz_clear(uval); - return ret; -} - -// Return the floating point constant value of a unary expression, if -// it has one. - -bool -Unary_expression::do_float_constant_value(mpfr_t val, Type** ptype) const -{ - mpfr_t uval; - mpfr_init(uval); - bool ret; - if (!this->expr_->float_constant_value(uval, ptype)) - ret = false; - else - ret = Unary_expression::eval_float(this->op_, uval, val); - mpfr_clear(uval); - return ret; -} - -// Return the complex constant value of a unary expression, if it has -// one. - -bool -Unary_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - mpfr_t rval; - mpfr_t ival; - mpfr_init(rval); - mpfr_init(ival); - bool ret; - if (!this->expr_->complex_constant_value(rval, ival, ptype)) - ret = false; - else - ret = Unary_expression::eval_complex(this->op_, rval, ival, real, imag); - mpfr_clear(rval); - mpfr_clear(ival); - return ret; -} - -// Return the type of a unary expression. - -Type* -Unary_expression::do_type() -{ - switch (this->op_) - { - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_NOT: - case OPERATOR_XOR: - return this->expr_->type(); - - case OPERATOR_AND: - return Type::make_pointer_type(this->expr_->type()); - - case OPERATOR_MULT: - { - Type* subtype = this->expr_->type(); - Type* points_to = subtype->points_to(); - if (points_to == NULL) - return Type::make_error_type(); - return points_to; - } - - default: - gcc_unreachable(); - } -} - -// Determine abstract types for a unary expression. - -void -Unary_expression::do_determine_type(const Type_context* context) -{ - switch (this->op_) - { - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_NOT: - case OPERATOR_XOR: - this->expr_->determine_type(context); - break; - - case OPERATOR_AND: - // Taking the address of something. - { - Type* subtype = (context->type == NULL - ? NULL - : context->type->points_to()); - Type_context subcontext(subtype, false); - this->expr_->determine_type(&subcontext); - } - break; - - case OPERATOR_MULT: - // Indirecting through a pointer. - { - Type* subtype = (context->type == NULL - ? NULL - : Type::make_pointer_type(context->type)); - Type_context subcontext(subtype, false); - this->expr_->determine_type(&subcontext); - } - break; - - default: - gcc_unreachable(); - } -} - -// Check types for a unary expression. - -void -Unary_expression::do_check_types(Gogo*) -{ - Type* type = this->expr_->type(); - if (type->is_error_type()) - { - this->set_is_error(); - return; - } - - switch (this->op_) - { - case OPERATOR_PLUS: - case OPERATOR_MINUS: - if (type->integer_type() == NULL - && type->float_type() == NULL - && type->complex_type() == NULL) - this->report_error(_("expected numeric type")); - break; - - case OPERATOR_NOT: - case OPERATOR_XOR: - if (type->integer_type() == NULL - && !type->is_boolean_type()) - this->report_error(_("expected integer or boolean type")); - break; - - case OPERATOR_AND: - if (!this->expr_->is_addressable()) - this->report_error(_("invalid operand for unary %<&%>")); - else - this->expr_->address_taken(this->escapes_); - break; - - case OPERATOR_MULT: - // Indirecting through a pointer. - if (type->points_to() == NULL) - this->report_error(_("expected pointer")); - break; - - default: - gcc_unreachable(); - } -} - -// Get a tree for a unary expression. - -tree -Unary_expression::do_get_tree(Translate_context* context) -{ - tree expr = this->expr_->get_tree(context); - if (expr == error_mark_node) - return error_mark_node; - - source_location loc = this->location(); - switch (this->op_) - { - case OPERATOR_PLUS: - return expr; - - case OPERATOR_MINUS: - { - tree type = TREE_TYPE(expr); - tree compute_type = excess_precision_type(type); - if (compute_type != NULL_TREE) - expr = ::convert(compute_type, expr); - tree ret = fold_build1_loc(loc, NEGATE_EXPR, - (compute_type != NULL_TREE - ? compute_type - : type), - expr); - if (compute_type != NULL_TREE) - ret = ::convert(type, ret); - return ret; - } - - case OPERATOR_NOT: - if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE) - return fold_build1_loc(loc, TRUTH_NOT_EXPR, TREE_TYPE(expr), expr); - else - return fold_build2_loc(loc, NE_EXPR, boolean_type_node, expr, - build_int_cst(TREE_TYPE(expr), 0)); - - case OPERATOR_XOR: - return fold_build1_loc(loc, BIT_NOT_EXPR, TREE_TYPE(expr), expr); - - case OPERATOR_AND: - // We should not see a non-constant constructor here; cases - // where we would see one should have been moved onto the heap - // at parse time. Taking the address of a nonconstant - // constructor will not do what the programmer expects. - gcc_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr)); - gcc_assert(TREE_CODE(expr) != ADDR_EXPR); - - // Build a decl for a constant constructor. - if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr)) - { - tree decl = build_decl(this->location(), VAR_DECL, - create_tmp_var_name("C"), TREE_TYPE(expr)); - DECL_EXTERNAL(decl) = 0; - TREE_PUBLIC(decl) = 0; - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - TREE_STATIC(decl) = 1; - TREE_ADDRESSABLE(decl) = 1; - DECL_ARTIFICIAL(decl) = 1; - DECL_INITIAL(decl) = expr; - rest_of_decl_compilation(decl, 1, 0); - expr = decl; - } - - return build_fold_addr_expr_loc(loc, expr); - - case OPERATOR_MULT: - { - gcc_assert(POINTER_TYPE_P(TREE_TYPE(expr))); - - // If we are dereferencing the pointer to a large struct, we - // need to check for nil. We don't bother to check for small - // structs because we expect the system to crash on a nil - // pointer dereference. - HOST_WIDE_INT s = int_size_in_bytes(TREE_TYPE(TREE_TYPE(expr))); - if (s == -1 || s >= 4096) - { - if (!DECL_P(expr)) - expr = save_expr(expr); - tree compare = fold_build2_loc(loc, EQ_EXPR, boolean_type_node, - expr, - fold_convert(TREE_TYPE(expr), - null_pointer_node)); - tree crash = Gogo::runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, - loc); - expr = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(expr), - build3(COND_EXPR, void_type_node, - compare, crash, NULL_TREE), - expr); - } - - // If the type of EXPR is a recursive pointer type, then we - // need to insert a cast before indirecting. - if (TREE_TYPE(TREE_TYPE(expr)) == ptr_type_node) - { - Type* pt = this->expr_->type()->points_to(); - tree ind = pt->get_tree(context->gogo()); - expr = fold_convert_loc(loc, build_pointer_type(ind), expr); - } - - return build_fold_indirect_ref_loc(loc, expr); - } - - default: - gcc_unreachable(); - } -} - -// Export a unary expression. - -void -Unary_expression::do_export(Export* exp) const -{ - switch (this->op_) - { - case OPERATOR_PLUS: - exp->write_c_string("+ "); - break; - case OPERATOR_MINUS: - exp->write_c_string("- "); - break; - case OPERATOR_NOT: - exp->write_c_string("! "); - break; - case OPERATOR_XOR: - exp->write_c_string("^ "); - break; - case OPERATOR_AND: - case OPERATOR_MULT: - default: - gcc_unreachable(); - } - this->expr_->export_expression(exp); -} - -// Import a unary expression. - -Expression* -Unary_expression::do_import(Import* imp) -{ - Operator op; - switch (imp->get_char()) - { - case '+': - op = OPERATOR_PLUS; - break; - case '-': - op = OPERATOR_MINUS; - break; - case '!': - op = OPERATOR_NOT; - break; - case '^': - op = OPERATOR_XOR; - break; - default: - gcc_unreachable(); - } - imp->require_c_string(" "); - Expression* expr = Expression::import_expression(imp); - return Expression::make_unary(op, expr, imp->location()); -} - -// Make a unary expression. - -Expression* -Expression::make_unary(Operator op, Expression* expr, source_location location) -{ - return new Unary_expression(op, expr, location); -} - -// If this is an indirection through a pointer, return the expression -// being pointed through. Otherwise return this. - -Expression* -Expression::deref() -{ - if (this->classification_ == EXPRESSION_UNARY) - { - Unary_expression* ue = static_cast(this); - if (ue->op() == OPERATOR_MULT) - return ue->operand(); - } - return this; -} - -// Class Binary_expression. - -// Traversal. - -int -Binary_expression::do_traverse(Traverse* traverse) -{ - int t = Expression::traverse(&this->left_, traverse); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return Expression::traverse(&this->right_, traverse); -} - -// Compare integer constants according to OP. - -bool -Binary_expression::compare_integer(Operator op, mpz_t left_val, - mpz_t right_val) -{ - int i = mpz_cmp(left_val, right_val); - switch (op) - { - case OPERATOR_EQEQ: - return i == 0; - case OPERATOR_NOTEQ: - return i != 0; - case OPERATOR_LT: - return i < 0; - case OPERATOR_LE: - return i <= 0; - case OPERATOR_GT: - return i > 0; - case OPERATOR_GE: - return i >= 0; - default: - gcc_unreachable(); - } -} - -// Compare floating point constants according to OP. - -bool -Binary_expression::compare_float(Operator op, Type* type, mpfr_t left_val, - mpfr_t right_val) -{ - int i; - if (type == NULL) - i = mpfr_cmp(left_val, right_val); - else - { - mpfr_t lv; - mpfr_init_set(lv, left_val, GMP_RNDN); - mpfr_t rv; - mpfr_init_set(rv, right_val, GMP_RNDN); - Float_expression::constrain_float(lv, type); - Float_expression::constrain_float(rv, type); - i = mpfr_cmp(lv, rv); - mpfr_clear(lv); - mpfr_clear(rv); - } - switch (op) - { - case OPERATOR_EQEQ: - return i == 0; - case OPERATOR_NOTEQ: - return i != 0; - case OPERATOR_LT: - return i < 0; - case OPERATOR_LE: - return i <= 0; - case OPERATOR_GT: - return i > 0; - case OPERATOR_GE: - return i >= 0; - default: - gcc_unreachable(); - } -} - -// Compare complex constants according to OP. Complex numbers may -// only be compared for equality. - -bool -Binary_expression::compare_complex(Operator op, Type* type, - mpfr_t left_real, mpfr_t left_imag, - mpfr_t right_real, mpfr_t right_imag) -{ - bool is_equal; - if (type == NULL) - is_equal = (mpfr_cmp(left_real, right_real) == 0 - && mpfr_cmp(left_imag, right_imag) == 0); - else - { - mpfr_t lr; - mpfr_t li; - mpfr_init_set(lr, left_real, GMP_RNDN); - mpfr_init_set(li, left_imag, GMP_RNDN); - mpfr_t rr; - mpfr_t ri; - mpfr_init_set(rr, right_real, GMP_RNDN); - mpfr_init_set(ri, right_imag, GMP_RNDN); - Complex_expression::constrain_complex(lr, li, type); - Complex_expression::constrain_complex(rr, ri, type); - is_equal = mpfr_cmp(lr, rr) == 0 && mpfr_cmp(li, ri) == 0; - mpfr_clear(lr); - mpfr_clear(li); - mpfr_clear(rr); - mpfr_clear(ri); - } - switch (op) - { - case OPERATOR_EQEQ: - return is_equal; - case OPERATOR_NOTEQ: - return !is_equal; - default: - gcc_unreachable(); - } -} - -// Apply binary opcode OP to LEFT_VAL and RIGHT_VAL, setting VAL. -// LEFT_TYPE is the type of LEFT_VAL, RIGHT_TYPE is the type of -// RIGHT_VAL; LEFT_TYPE and/or RIGHT_TYPE may be NULL. Return true if -// this could be done, false if not. - -bool -Binary_expression::eval_integer(Operator op, Type* left_type, mpz_t left_val, - Type* right_type, mpz_t right_val, - source_location location, mpz_t val) -{ - bool is_shift_op = false; - switch (op) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - // These return boolean values. We should probably handle them - // anyhow in case a type conversion is used on the result. - return false; - case OPERATOR_PLUS: - mpz_add(val, left_val, right_val); - break; - case OPERATOR_MINUS: - mpz_sub(val, left_val, right_val); - break; - case OPERATOR_OR: - mpz_ior(val, left_val, right_val); - break; - case OPERATOR_XOR: - mpz_xor(val, left_val, right_val); - break; - case OPERATOR_MULT: - mpz_mul(val, left_val, right_val); - break; - case OPERATOR_DIV: - if (mpz_sgn(right_val) != 0) - mpz_tdiv_q(val, left_val, right_val); - else - { - error_at(location, "division by zero"); - mpz_set_ui(val, 0); - return true; - } - break; - case OPERATOR_MOD: - if (mpz_sgn(right_val) != 0) - mpz_tdiv_r(val, left_val, right_val); - else - { - error_at(location, "division by zero"); - mpz_set_ui(val, 0); - return true; - } - break; - case OPERATOR_LSHIFT: - { - unsigned long shift = mpz_get_ui(right_val); - if (mpz_cmp_ui(right_val, shift) != 0 || shift > 0x100000) - { - error_at(location, "shift count overflow"); - mpz_set_ui(val, 0); - return true; - } - mpz_mul_2exp(val, left_val, shift); - is_shift_op = true; - break; - } - break; - case OPERATOR_RSHIFT: - { - unsigned long shift = mpz_get_ui(right_val); - if (mpz_cmp_ui(right_val, shift) != 0) - { - error_at(location, "shift count overflow"); - mpz_set_ui(val, 0); - return true; - } - if (mpz_cmp_ui(left_val, 0) >= 0) - mpz_tdiv_q_2exp(val, left_val, shift); - else - mpz_fdiv_q_2exp(val, left_val, shift); - is_shift_op = true; - break; - } - break; - case OPERATOR_AND: - mpz_and(val, left_val, right_val); - break; - case OPERATOR_BITCLEAR: - { - mpz_t tval; - mpz_init(tval); - mpz_com(tval, right_val); - mpz_and(val, left_val, tval); - mpz_clear(tval); - } - break; - default: - gcc_unreachable(); - } - - Type* type = left_type; - if (!is_shift_op) - { - if (type == NULL) - type = right_type; - else if (type != right_type && right_type != NULL) - { - if (type->is_abstract()) - type = right_type; - else if (!right_type->is_abstract()) - { - // This look like a type error which should be diagnosed - // elsewhere. Don't do anything here, to avoid an - // unhelpful chain of error messages. - return true; - } - } - } - - if (type != NULL && !type->is_abstract()) - { - // We have to check the operands too, as we have implicitly - // coerced them to TYPE. - if ((type != left_type - && !Integer_expression::check_constant(left_val, type, location)) - || (!is_shift_op - && type != right_type - && !Integer_expression::check_constant(right_val, type, - location)) - || !Integer_expression::check_constant(val, type, location)) - mpz_set_ui(val, 0); - } - - return true; -} - -// Apply binary opcode OP to LEFT_VAL and RIGHT_VAL, setting VAL. -// Return true if this could be done, false if not. - -bool -Binary_expression::eval_float(Operator op, Type* left_type, mpfr_t left_val, - Type* right_type, mpfr_t right_val, - mpfr_t val, source_location location) -{ - switch (op) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - // These return boolean values. We should probably handle them - // anyhow in case a type conversion is used on the result. - return false; - case OPERATOR_PLUS: - mpfr_add(val, left_val, right_val, GMP_RNDN); - break; - case OPERATOR_MINUS: - mpfr_sub(val, left_val, right_val, GMP_RNDN); - break; - case OPERATOR_OR: - case OPERATOR_XOR: - case OPERATOR_AND: - case OPERATOR_BITCLEAR: - return false; - case OPERATOR_MULT: - mpfr_mul(val, left_val, right_val, GMP_RNDN); - break; - case OPERATOR_DIV: - if (mpfr_zero_p(right_val)) - error_at(location, "division by zero"); - mpfr_div(val, left_val, right_val, GMP_RNDN); - break; - case OPERATOR_MOD: - return false; - case OPERATOR_LSHIFT: - case OPERATOR_RSHIFT: - return false; - default: - gcc_unreachable(); - } - - Type* type = left_type; - if (type == NULL) - type = right_type; - else if (type != right_type && right_type != NULL) - { - if (type->is_abstract()) - type = right_type; - else if (!right_type->is_abstract()) - { - // This looks like a type error which should be diagnosed - // elsewhere. Don't do anything here, to avoid an unhelpful - // chain of error messages. - return true; - } - } - - if (type != NULL && !type->is_abstract()) - { - if ((type != left_type - && !Float_expression::check_constant(left_val, type, location)) - || (type != right_type - && !Float_expression::check_constant(right_val, type, - location)) - || !Float_expression::check_constant(val, type, location)) - mpfr_set_ui(val, 0, GMP_RNDN); - } - - return true; -} - -// Apply binary opcode OP to LEFT_REAL/LEFT_IMAG and -// RIGHT_REAL/RIGHT_IMAG, setting REAL/IMAG. Return true if this -// could be done, false if not. - -bool -Binary_expression::eval_complex(Operator op, Type* left_type, - mpfr_t left_real, mpfr_t left_imag, - Type *right_type, - mpfr_t right_real, mpfr_t right_imag, - mpfr_t real, mpfr_t imag, - source_location location) -{ - switch (op) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - // These return boolean values and must be handled differently. - return false; - case OPERATOR_PLUS: - mpfr_add(real, left_real, right_real, GMP_RNDN); - mpfr_add(imag, left_imag, right_imag, GMP_RNDN); - break; - case OPERATOR_MINUS: - mpfr_sub(real, left_real, right_real, GMP_RNDN); - mpfr_sub(imag, left_imag, right_imag, GMP_RNDN); - break; - case OPERATOR_OR: - case OPERATOR_XOR: - case OPERATOR_AND: - case OPERATOR_BITCLEAR: - return false; - case OPERATOR_MULT: - { - // You might think that multiplying two complex numbers would - // be simple, and you would be right, until you start to think - // about getting the right answer for infinity. If one - // operand here is infinity and the other is anything other - // than zero or NaN, then we are going to wind up subtracting - // two infinity values. That will give us a NaN, but the - // correct answer is infinity. - - mpfr_t lrrr; - mpfr_init(lrrr); - mpfr_mul(lrrr, left_real, right_real, GMP_RNDN); - - mpfr_t lrri; - mpfr_init(lrri); - mpfr_mul(lrri, left_real, right_imag, GMP_RNDN); - - mpfr_t lirr; - mpfr_init(lirr); - mpfr_mul(lirr, left_imag, right_real, GMP_RNDN); - - mpfr_t liri; - mpfr_init(liri); - mpfr_mul(liri, left_imag, right_imag, GMP_RNDN); - - mpfr_sub(real, lrrr, liri, GMP_RNDN); - mpfr_add(imag, lrri, lirr, GMP_RNDN); - - // If we get NaN on both sides, check whether it should really - // be infinity. The rule is that if either side of the - // complex number is infinity, then the whole value is - // infinity, even if the other side is NaN. So the only case - // we have to fix is the one in which both sides are NaN. - if (mpfr_nan_p(real) && mpfr_nan_p(imag) - && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag)) - && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag))) - { - bool is_infinity = false; - - mpfr_t lr; - mpfr_t li; - mpfr_init_set(lr, left_real, GMP_RNDN); - mpfr_init_set(li, left_imag, GMP_RNDN); - - mpfr_t rr; - mpfr_t ri; - mpfr_init_set(rr, right_real, GMP_RNDN); - mpfr_init_set(ri, right_imag, GMP_RNDN); - - // If the left side is infinity, then the result is - // infinity. - if (mpfr_inf_p(lr) || mpfr_inf_p(li)) - { - mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN); - mpfr_copysign(lr, lr, left_real, GMP_RNDN); - mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN); - mpfr_copysign(li, li, left_imag, GMP_RNDN); - if (mpfr_nan_p(rr)) - { - mpfr_set_ui(rr, 0, GMP_RNDN); - mpfr_copysign(rr, rr, right_real, GMP_RNDN); - } - if (mpfr_nan_p(ri)) - { - mpfr_set_ui(ri, 0, GMP_RNDN); - mpfr_copysign(ri, ri, right_imag, GMP_RNDN); - } - is_infinity = true; - } - - // If the right side is infinity, then the result is - // infinity. - if (mpfr_inf_p(rr) || mpfr_inf_p(ri)) - { - mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN); - mpfr_copysign(rr, rr, right_real, GMP_RNDN); - mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN); - mpfr_copysign(ri, ri, right_imag, GMP_RNDN); - if (mpfr_nan_p(lr)) - { - mpfr_set_ui(lr, 0, GMP_RNDN); - mpfr_copysign(lr, lr, left_real, GMP_RNDN); - } - if (mpfr_nan_p(li)) - { - mpfr_set_ui(li, 0, GMP_RNDN); - mpfr_copysign(li, li, left_imag, GMP_RNDN); - } - is_infinity = true; - } - - // If we got an overflow in the intermediate computations, - // then the result is infinity. - if (!is_infinity - && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri) - || mpfr_inf_p(lirr) || mpfr_inf_p(liri))) - { - if (mpfr_nan_p(lr)) - { - mpfr_set_ui(lr, 0, GMP_RNDN); - mpfr_copysign(lr, lr, left_real, GMP_RNDN); - } - if (mpfr_nan_p(li)) - { - mpfr_set_ui(li, 0, GMP_RNDN); - mpfr_copysign(li, li, left_imag, GMP_RNDN); - } - if (mpfr_nan_p(rr)) - { - mpfr_set_ui(rr, 0, GMP_RNDN); - mpfr_copysign(rr, rr, right_real, GMP_RNDN); - } - if (mpfr_nan_p(ri)) - { - mpfr_set_ui(ri, 0, GMP_RNDN); - mpfr_copysign(ri, ri, right_imag, GMP_RNDN); - } - is_infinity = true; - } - - if (is_infinity) - { - mpfr_mul(lrrr, lr, rr, GMP_RNDN); - mpfr_mul(lrri, lr, ri, GMP_RNDN); - mpfr_mul(lirr, li, rr, GMP_RNDN); - mpfr_mul(liri, li, ri, GMP_RNDN); - mpfr_sub(real, lrrr, liri, GMP_RNDN); - mpfr_add(imag, lrri, lirr, GMP_RNDN); - mpfr_set_inf(real, mpfr_sgn(real)); - mpfr_set_inf(imag, mpfr_sgn(imag)); - } - - mpfr_clear(lr); - mpfr_clear(li); - mpfr_clear(rr); - mpfr_clear(ri); - } - - mpfr_clear(lrrr); - mpfr_clear(lrri); - mpfr_clear(lirr); - mpfr_clear(liri); - } - break; - case OPERATOR_DIV: - { - // For complex division we want to avoid having an - // intermediate overflow turn the whole result in a NaN. We - // scale the values to try to avoid this. - - if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag)) - error_at(location, "division by zero"); - - mpfr_t rra; - mpfr_t ria; - mpfr_init(rra); - mpfr_init(ria); - mpfr_abs(rra, right_real, GMP_RNDN); - mpfr_abs(ria, right_imag, GMP_RNDN); - mpfr_t t; - mpfr_init(t); - mpfr_max(t, rra, ria, GMP_RNDN); - - mpfr_t rr; - mpfr_t ri; - mpfr_init_set(rr, right_real, GMP_RNDN); - mpfr_init_set(ri, right_imag, GMP_RNDN); - long ilogbw = 0; - if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t)) - { - ilogbw = mpfr_get_exp(t); - mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN); - mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN); - } - - mpfr_t denom; - mpfr_init(denom); - mpfr_mul(denom, rr, rr, GMP_RNDN); - mpfr_mul(t, ri, ri, GMP_RNDN); - mpfr_add(denom, denom, t, GMP_RNDN); - - mpfr_mul(real, left_real, rr, GMP_RNDN); - mpfr_mul(t, left_imag, ri, GMP_RNDN); - mpfr_add(real, real, t, GMP_RNDN); - mpfr_div(real, real, denom, GMP_RNDN); - mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN); - - mpfr_mul(imag, left_imag, rr, GMP_RNDN); - mpfr_mul(t, left_real, ri, GMP_RNDN); - mpfr_sub(imag, imag, t, GMP_RNDN); - mpfr_div(imag, imag, denom, GMP_RNDN); - mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN); - - // If we wind up with NaN on both sides, check whether we - // should really have infinity. The rule is that if either - // side of the complex number is infinity, then the whole - // value is infinity, even if the other side is NaN. So the - // only case we have to fix is the one in which both sides are - // NaN. - if (mpfr_nan_p(real) && mpfr_nan_p(imag) - && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag)) - && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag))) - { - if (mpfr_zero_p(denom)) - { - mpfr_set_inf(real, mpfr_sgn(rr)); - mpfr_mul(real, real, left_real, GMP_RNDN); - mpfr_set_inf(imag, mpfr_sgn(rr)); - mpfr_mul(imag, imag, left_imag, GMP_RNDN); - } - else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag)) - && mpfr_number_p(rr) && mpfr_number_p(ri)) - { - mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN); - mpfr_copysign(t, t, left_real, GMP_RNDN); - - mpfr_t t2; - mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN); - mpfr_copysign(t2, t2, left_imag, GMP_RNDN); - - mpfr_t t3; - mpfr_init(t3); - mpfr_mul(t3, t, rr, GMP_RNDN); - - mpfr_t t4; - mpfr_init(t4); - mpfr_mul(t4, t2, ri, GMP_RNDN); - - mpfr_add(t3, t3, t4, GMP_RNDN); - mpfr_set_inf(real, mpfr_sgn(t3)); - - mpfr_mul(t3, t2, rr, GMP_RNDN); - mpfr_mul(t4, t, ri, GMP_RNDN); - mpfr_sub(t3, t3, t4, GMP_RNDN); - mpfr_set_inf(imag, mpfr_sgn(t3)); - - mpfr_clear(t2); - mpfr_clear(t3); - mpfr_clear(t4); - } - else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag)) - && mpfr_number_p(left_real) && mpfr_number_p(left_imag)) - { - mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN); - mpfr_copysign(t, t, rr, GMP_RNDN); - - mpfr_t t2; - mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN); - mpfr_copysign(t2, t2, ri, GMP_RNDN); - - mpfr_t t3; - mpfr_init(t3); - mpfr_mul(t3, left_real, t, GMP_RNDN); - - mpfr_t t4; - mpfr_init(t4); - mpfr_mul(t4, left_imag, t2, GMP_RNDN); - - mpfr_add(t3, t3, t4, GMP_RNDN); - mpfr_set_ui(real, 0, GMP_RNDN); - mpfr_mul(real, real, t3, GMP_RNDN); - - mpfr_mul(t3, left_imag, t, GMP_RNDN); - mpfr_mul(t4, left_real, t2, GMP_RNDN); - mpfr_sub(t3, t3, t4, GMP_RNDN); - mpfr_set_ui(imag, 0, GMP_RNDN); - mpfr_mul(imag, imag, t3, GMP_RNDN); - - mpfr_clear(t2); - mpfr_clear(t3); - mpfr_clear(t4); - } - } - - mpfr_clear(denom); - mpfr_clear(rr); - mpfr_clear(ri); - mpfr_clear(t); - mpfr_clear(rra); - mpfr_clear(ria); - } - break; - case OPERATOR_MOD: - return false; - case OPERATOR_LSHIFT: - case OPERATOR_RSHIFT: - return false; - default: - gcc_unreachable(); - } - - Type* type = left_type; - if (type == NULL) - type = right_type; - else if (type != right_type && right_type != NULL) - { - if (type->is_abstract()) - type = right_type; - else if (!right_type->is_abstract()) - { - // This looks like a type error which should be diagnosed - // elsewhere. Don't do anything here, to avoid an unhelpful - // chain of error messages. - return true; - } - } - - if (type != NULL && !type->is_abstract()) - { - if ((type != left_type - && !Complex_expression::check_constant(left_real, left_imag, - type, location)) - || (type != right_type - && !Complex_expression::check_constant(right_real, right_imag, - type, location)) - || !Complex_expression::check_constant(real, imag, type, - location)) - { - mpfr_set_ui(real, 0, GMP_RNDN); - mpfr_set_ui(imag, 0, GMP_RNDN); - } - } - - return true; -} - -// Lower a binary expression. We have to evaluate constant -// expressions now, in order to implement Go's unlimited precision -// constants. - -Expression* -Binary_expression::do_lower(Gogo*, Named_object*, int) -{ - source_location location = this->location(); - Operator op = this->op_; - Expression* left = this->left_; - Expression* right = this->right_; - - const bool is_comparison = (op == OPERATOR_EQEQ - || op == OPERATOR_NOTEQ - || op == OPERATOR_LT - || op == OPERATOR_LE - || op == OPERATOR_GT - || op == OPERATOR_GE); - - // Integer constant expressions. - { - mpz_t left_val; - mpz_init(left_val); - Type* left_type; - mpz_t right_val; - mpz_init(right_val); - Type* right_type; - if (left->integer_constant_value(false, left_val, &left_type) - && right->integer_constant_value(false, right_val, &right_type)) - { - Expression* ret = NULL; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base() - && op != OPERATOR_LSHIFT - && op != OPERATOR_RSHIFT) - { - // May be a type error--let it be diagnosed later. - } - else if (is_comparison) - { - bool b = Binary_expression::compare_integer(op, left_val, - right_val); - ret = Expression::make_cast(Type::lookup_bool_type(), - Expression::make_boolean(b, location), - location); - } - else - { - mpz_t val; - mpz_init(val); - - if (Binary_expression::eval_integer(op, left_type, left_val, - right_type, right_val, - location, val)) - { - gcc_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND); - Type* type; - if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT) - type = left_type; - else if (left_type == NULL) - type = right_type; - else if (right_type == NULL) - type = left_type; - else if (!left_type->is_abstract() - && left_type->named_type() != NULL) - type = left_type; - else if (!right_type->is_abstract() - && right_type->named_type() != NULL) - type = right_type; - else if (!left_type->is_abstract()) - type = left_type; - else if (!right_type->is_abstract()) - type = right_type; - else if (left_type->float_type() != NULL) - type = left_type; - else if (right_type->float_type() != NULL) - type = right_type; - else if (left_type->complex_type() != NULL) - type = left_type; - else if (right_type->complex_type() != NULL) - type = right_type; - else - type = left_type; - ret = Expression::make_integer(&val, type, location); - } - - mpz_clear(val); - } - - if (ret != NULL) - { - mpz_clear(right_val); - mpz_clear(left_val); - return ret; - } - } - mpz_clear(right_val); - mpz_clear(left_val); - } - - // Floating point constant expressions. - { - mpfr_t left_val; - mpfr_init(left_val); - Type* left_type; - mpfr_t right_val; - mpfr_init(right_val); - Type* right_type; - if (left->float_constant_value(left_val, &left_type) - && right->float_constant_value(right_val, &right_type)) - { - Expression* ret = NULL; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base() - && op != OPERATOR_LSHIFT - && op != OPERATOR_RSHIFT) - { - // May be a type error--let it be diagnosed later. - } - else if (is_comparison) - { - bool b = Binary_expression::compare_float(op, - (left_type != NULL - ? left_type - : right_type), - left_val, right_val); - ret = Expression::make_boolean(b, location); - } - else - { - mpfr_t val; - mpfr_init(val); - - if (Binary_expression::eval_float(op, left_type, left_val, - right_type, right_val, val, - location)) - { - gcc_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND - && op != OPERATOR_LSHIFT && op != OPERATOR_RSHIFT); - Type* type; - if (left_type == NULL) - type = right_type; - else if (right_type == NULL) - type = left_type; - else if (!left_type->is_abstract() - && left_type->named_type() != NULL) - type = left_type; - else if (!right_type->is_abstract() - && right_type->named_type() != NULL) - type = right_type; - else if (!left_type->is_abstract()) - type = left_type; - else if (!right_type->is_abstract()) - type = right_type; - else if (left_type->float_type() != NULL) - type = left_type; - else if (right_type->float_type() != NULL) - type = right_type; - else - type = left_type; - ret = Expression::make_float(&val, type, location); - } - - mpfr_clear(val); - } - - if (ret != NULL) - { - mpfr_clear(right_val); - mpfr_clear(left_val); - return ret; - } - } - mpfr_clear(right_val); - mpfr_clear(left_val); - } - - // Complex constant expressions. - { - mpfr_t left_real; - mpfr_t left_imag; - mpfr_init(left_real); - mpfr_init(left_imag); - Type* left_type; - - mpfr_t right_real; - mpfr_t right_imag; - mpfr_init(right_real); - mpfr_init(right_imag); - Type* right_type; - - if (left->complex_constant_value(left_real, left_imag, &left_type) - && right->complex_constant_value(right_real, right_imag, &right_type)) - { - Expression* ret = NULL; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base()) - { - // May be a type error--let it be diagnosed later. - } - else if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ) - { - bool b = Binary_expression::compare_complex(op, - (left_type != NULL - ? left_type - : right_type), - left_real, - left_imag, - right_real, - right_imag); - ret = Expression::make_boolean(b, location); - } - else - { - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - - if (Binary_expression::eval_complex(op, left_type, - left_real, left_imag, - right_type, - right_real, right_imag, - real, imag, - location)) - { - gcc_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND - && op != OPERATOR_LSHIFT && op != OPERATOR_RSHIFT); - Type* type; - if (left_type == NULL) - type = right_type; - else if (right_type == NULL) - type = left_type; - else if (!left_type->is_abstract() - && left_type->named_type() != NULL) - type = left_type; - else if (!right_type->is_abstract() - && right_type->named_type() != NULL) - type = right_type; - else if (!left_type->is_abstract()) - type = left_type; - else if (!right_type->is_abstract()) - type = right_type; - else if (left_type->complex_type() != NULL) - type = left_type; - else if (right_type->complex_type() != NULL) - type = right_type; - else - type = left_type; - ret = Expression::make_complex(&real, &imag, type, - location); - } - mpfr_clear(real); - mpfr_clear(imag); - } - - if (ret != NULL) - { - mpfr_clear(left_real); - mpfr_clear(left_imag); - mpfr_clear(right_real); - mpfr_clear(right_imag); - return ret; - } - } - - mpfr_clear(left_real); - mpfr_clear(left_imag); - mpfr_clear(right_real); - mpfr_clear(right_imag); - } - - // String constant expressions. - if (op == OPERATOR_PLUS - && left->type()->is_string_type() - && right->type()->is_string_type()) - { - std::string left_string; - std::string right_string; - if (left->string_constant_value(&left_string) - && right->string_constant_value(&right_string)) - return Expression::make_string(left_string + right_string, location); - } - - return this; -} - -// Return the integer constant value, if it has one. - -bool -Binary_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val, - Type** ptype) const -{ - mpz_t left_val; - mpz_init(left_val); - Type* left_type; - if (!this->left_->integer_constant_value(iota_is_constant, left_val, - &left_type)) - { - mpz_clear(left_val); - return false; - } - - mpz_t right_val; - mpz_init(right_val); - Type* right_type; - if (!this->right_->integer_constant_value(iota_is_constant, right_val, - &right_type)) - { - mpz_clear(right_val); - mpz_clear(left_val); - return false; - } - - bool ret; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base() - && this->op_ != OPERATOR_RSHIFT - && this->op_ != OPERATOR_LSHIFT) - ret = false; - else - ret = Binary_expression::eval_integer(this->op_, left_type, left_val, - right_type, right_val, - this->location(), val); - - mpz_clear(right_val); - mpz_clear(left_val); - - if (ret) - *ptype = left_type; - - return ret; -} - -// Return the floating point constant value, if it has one. - -bool -Binary_expression::do_float_constant_value(mpfr_t val, Type** ptype) const -{ - mpfr_t left_val; - mpfr_init(left_val); - Type* left_type; - if (!this->left_->float_constant_value(left_val, &left_type)) - { - mpfr_clear(left_val); - return false; - } - - mpfr_t right_val; - mpfr_init(right_val); - Type* right_type; - if (!this->right_->float_constant_value(right_val, &right_type)) - { - mpfr_clear(right_val); - mpfr_clear(left_val); - return false; - } - - bool ret; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base()) - ret = false; - else - ret = Binary_expression::eval_float(this->op_, left_type, left_val, - right_type, right_val, - val, this->location()); - - mpfr_clear(left_val); - mpfr_clear(right_val); - - if (ret) - *ptype = left_type; - - return ret; -} - -// Return the complex constant value, if it has one. - -bool -Binary_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - mpfr_t left_real; - mpfr_t left_imag; - mpfr_init(left_real); - mpfr_init(left_imag); - Type* left_type; - if (!this->left_->complex_constant_value(left_real, left_imag, &left_type)) - { - mpfr_clear(left_real); - mpfr_clear(left_imag); - return false; - } - - mpfr_t right_real; - mpfr_t right_imag; - mpfr_init(right_real); - mpfr_init(right_imag); - Type* right_type; - if (!this->right_->complex_constant_value(right_real, right_imag, - &right_type)) - { - mpfr_clear(left_real); - mpfr_clear(left_imag); - mpfr_clear(right_real); - mpfr_clear(right_imag); - return false; - } - - bool ret; - if (left_type != right_type - && left_type != NULL - && right_type != NULL - && left_type->base() != right_type->base()) - ret = false; - else - ret = Binary_expression::eval_complex(this->op_, left_type, - left_real, left_imag, - right_type, - right_real, right_imag, - real, imag, - this->location()); - mpfr_clear(left_real); - mpfr_clear(left_imag); - mpfr_clear(right_real); - mpfr_clear(right_imag); - - if (ret) - *ptype = left_type; - - return ret; -} - -// Note that the value is being discarded. - -void -Binary_expression::do_discarding_value() -{ - if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND) - this->right_->discarding_value(); - else - this->warn_about_unused_value(); -} - -// Get type. - -Type* -Binary_expression::do_type() -{ - if (this->classification() == EXPRESSION_ERROR) - return Type::make_error_type(); - - switch (this->op_) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - return Type::lookup_bool_type(); - - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_OR: - case OPERATOR_XOR: - case OPERATOR_MULT: - case OPERATOR_DIV: - case OPERATOR_MOD: - case OPERATOR_AND: - case OPERATOR_BITCLEAR: - { - Type* left_type = this->left_->type(); - Type* right_type = this->right_->type(); - if (left_type->is_error_type()) - return left_type; - else if (right_type->is_error_type()) - return right_type; - else if (!Type::are_compatible_for_binop(left_type, right_type)) - { - this->report_error(_("incompatible types in binary expression")); - return Type::make_error_type(); - } - else if (!left_type->is_abstract() && left_type->named_type() != NULL) - return left_type; - else if (!right_type->is_abstract() && right_type->named_type() != NULL) - return right_type; - else if (!left_type->is_abstract()) - return left_type; - else if (!right_type->is_abstract()) - return right_type; - else if (left_type->complex_type() != NULL) - return left_type; - else if (right_type->complex_type() != NULL) - return right_type; - else if (left_type->float_type() != NULL) - return left_type; - else if (right_type->float_type() != NULL) - return right_type; - else - return left_type; - } - - case OPERATOR_LSHIFT: - case OPERATOR_RSHIFT: - return this->left_->type(); - - default: - gcc_unreachable(); - } -} - -// Set type for a binary expression. - -void -Binary_expression::do_determine_type(const Type_context* context) -{ - Type* tleft = this->left_->type(); - Type* tright = this->right_->type(); - - // Both sides should have the same type, except for the shift - // operations. For a comparison, we should ignore the incoming - // type. - - bool is_shift_op = (this->op_ == OPERATOR_LSHIFT - || this->op_ == OPERATOR_RSHIFT); - - bool is_comparison = (this->op_ == OPERATOR_EQEQ - || this->op_ == OPERATOR_NOTEQ - || this->op_ == OPERATOR_LT - || this->op_ == OPERATOR_LE - || this->op_ == OPERATOR_GT - || this->op_ == OPERATOR_GE); - - Type_context subcontext(*context); - - if (is_comparison) - { - // In a comparison, the context does not determine the types of - // the operands. - subcontext.type = NULL; - } - - // Set the context for the left hand operand. - if (is_shift_op) - { - // The right hand operand plays no role in determining the type - // of the left hand operand. A shift of an abstract integer in - // a string context gets special treatment, which may be a - // language bug. - if (subcontext.type != NULL - && subcontext.type->is_string_type() - && tleft->is_abstract()) - error_at(this->location(), "shift of non-integer operand"); - } - else if (!tleft->is_abstract()) - subcontext.type = tleft; - else if (!tright->is_abstract()) - subcontext.type = tright; - else if (subcontext.type == NULL) - { - if ((tleft->integer_type() != NULL && tright->integer_type() != NULL) - || (tleft->float_type() != NULL && tright->float_type() != NULL) - || (tleft->complex_type() != NULL && tright->complex_type() != NULL)) - { - // Both sides have an abstract integer, abstract float, or - // abstract complex type. Just let CONTEXT determine - // whether they may remain abstract or not. - } - else if (tleft->complex_type() != NULL) - subcontext.type = tleft; - else if (tright->complex_type() != NULL) - subcontext.type = tright; - else if (tleft->float_type() != NULL) - subcontext.type = tleft; - else if (tright->float_type() != NULL) - subcontext.type = tright; - else - subcontext.type = tleft; - - if (subcontext.type != NULL && !context->may_be_abstract) - subcontext.type = subcontext.type->make_non_abstract_type(); - } - - this->left_->determine_type(&subcontext); - - // The context for the right hand operand is the same as for the - // left hand operand, except for a shift operator. - if (is_shift_op) - { - subcontext.type = Type::lookup_integer_type("uint"); - subcontext.may_be_abstract = false; - } - - this->right_->determine_type(&subcontext); -} - -// Report an error if the binary operator OP does not support TYPE. -// Return whether the operation is OK. This should not be used for -// shift. - -bool -Binary_expression::check_operator_type(Operator op, Type* type, - source_location location) -{ - switch (op) - { - case OPERATOR_OROR: - case OPERATOR_ANDAND: - if (!type->is_boolean_type()) - { - error_at(location, "expected boolean type"); - return false; - } - break; - - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - if (type->integer_type() == NULL - && type->float_type() == NULL - && type->complex_type() == NULL - && !type->is_string_type() - && type->points_to() == NULL - && !type->is_nil_type() - && !type->is_boolean_type() - && type->interface_type() == NULL - && (type->array_type() == NULL - || type->array_type()->length() != NULL) - && type->map_type() == NULL - && type->channel_type() == NULL - && type->function_type() == NULL) - { - error_at(location, - ("expected integer, floating, complex, string, pointer, " - "boolean, interface, slice, map, channel, " - "or function type")); - return false; - } - break; - - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - if (type->integer_type() == NULL - && type->float_type() == NULL - && !type->is_string_type()) - { - error_at(location, "expected integer, floating, or string type"); - return false; - } - break; - - case OPERATOR_PLUS: - case OPERATOR_PLUSEQ: - if (type->integer_type() == NULL - && type->float_type() == NULL - && type->complex_type() == NULL - && !type->is_string_type()) - { - error_at(location, - "expected integer, floating, complex, or string type"); - return false; - } - break; - - case OPERATOR_MINUS: - case OPERATOR_MINUSEQ: - case OPERATOR_MULT: - case OPERATOR_MULTEQ: - case OPERATOR_DIV: - case OPERATOR_DIVEQ: - if (type->integer_type() == NULL - && type->float_type() == NULL - && type->complex_type() == NULL) - { - error_at(location, "expected integer, floating, or complex type"); - return false; - } - break; - - case OPERATOR_MOD: - case OPERATOR_MODEQ: - case OPERATOR_OR: - case OPERATOR_OREQ: - case OPERATOR_AND: - case OPERATOR_ANDEQ: - case OPERATOR_XOR: - case OPERATOR_XOREQ: - case OPERATOR_BITCLEAR: - case OPERATOR_BITCLEAREQ: - if (type->integer_type() == NULL) - { - error_at(location, "expected integer type"); - return false; - } - break; - - default: - gcc_unreachable(); - } - - return true; -} - -// Check types. - -void -Binary_expression::do_check_types(Gogo*) -{ - if (this->classification() == EXPRESSION_ERROR) - return; - - Type* left_type = this->left_->type(); - Type* right_type = this->right_->type(); - if (left_type->is_error_type() || right_type->is_error_type()) - { - this->set_is_error(); - return; - } - - if (this->op_ == OPERATOR_EQEQ - || this->op_ == OPERATOR_NOTEQ - || this->op_ == OPERATOR_LT - || this->op_ == OPERATOR_LE - || this->op_ == OPERATOR_GT - || this->op_ == OPERATOR_GE) - { - if (!Type::are_assignable(left_type, right_type, NULL) - && !Type::are_assignable(right_type, left_type, NULL)) - { - this->report_error(_("incompatible types in binary expression")); - return; - } - if (!Binary_expression::check_operator_type(this->op_, left_type, - this->location()) - || !Binary_expression::check_operator_type(this->op_, right_type, - this->location())) - { - this->set_is_error(); - return; - } - } - else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT) - { - if (!Type::are_compatible_for_binop(left_type, right_type)) - { - this->report_error(_("incompatible types in binary expression")); - return; - } - if (!Binary_expression::check_operator_type(this->op_, left_type, - this->location())) - { - this->set_is_error(); - return; - } - } - else - { - if (left_type->integer_type() == NULL) - this->report_error(_("shift of non-integer operand")); - - if (!right_type->is_abstract() - && (right_type->integer_type() == NULL - || !right_type->integer_type()->is_unsigned())) - this->report_error(_("shift count not unsigned integer")); - else - { - mpz_t val; - mpz_init(val); - Type* type; - if (this->right_->integer_constant_value(true, val, &type)) - { - if (mpz_sgn(val) < 0) - this->report_error(_("negative shift count")); - } - mpz_clear(val); - } - } -} - -// Get a tree for a binary expression. - -tree -Binary_expression::do_get_tree(Translate_context* context) -{ - tree left = this->left_->get_tree(context); - tree right = this->right_->get_tree(context); - - if (left == error_mark_node || right == error_mark_node) - return error_mark_node; - - enum tree_code code; - bool use_left_type = true; - bool is_shift_op = false; - switch (this->op_) - { - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - return Expression::comparison_tree(context, this->op_, - this->left_->type(), left, - this->right_->type(), right, - this->location()); - - case OPERATOR_OROR: - code = TRUTH_ORIF_EXPR; - use_left_type = false; - break; - case OPERATOR_ANDAND: - code = TRUTH_ANDIF_EXPR; - use_left_type = false; - break; - case OPERATOR_PLUS: - code = PLUS_EXPR; - break; - case OPERATOR_MINUS: - code = MINUS_EXPR; - break; - case OPERATOR_OR: - code = BIT_IOR_EXPR; - break; - case OPERATOR_XOR: - code = BIT_XOR_EXPR; - break; - case OPERATOR_MULT: - code = MULT_EXPR; - break; - case OPERATOR_DIV: - { - Type *t = this->left_->type(); - if (t->float_type() != NULL || t->complex_type() != NULL) - code = RDIV_EXPR; - else - code = TRUNC_DIV_EXPR; - } - break; - case OPERATOR_MOD: - code = TRUNC_MOD_EXPR; - break; - case OPERATOR_LSHIFT: - code = LSHIFT_EXPR; - is_shift_op = true; - break; - case OPERATOR_RSHIFT: - code = RSHIFT_EXPR; - is_shift_op = true; - break; - case OPERATOR_AND: - code = BIT_AND_EXPR; - break; - case OPERATOR_BITCLEAR: - right = fold_build1(BIT_NOT_EXPR, TREE_TYPE(right), right); - code = BIT_AND_EXPR; - break; - default: - gcc_unreachable(); - } - - tree type = use_left_type ? TREE_TYPE(left) : TREE_TYPE(right); - - if (this->left_->type()->is_string_type()) - { - gcc_assert(this->op_ == OPERATOR_PLUS); - tree string_type = Type::make_string_type()->get_tree(context->gogo()); - static tree string_plus_decl; - return Gogo::call_builtin(&string_plus_decl, - this->location(), - "__go_string_plus", - 2, - string_type, - string_type, - left, - string_type, - right); - } - - tree compute_type = excess_precision_type(type); - if (compute_type != NULL_TREE) - { - left = ::convert(compute_type, left); - right = ::convert(compute_type, right); - } - - tree eval_saved = NULL_TREE; - if (is_shift_op) - { - // Make sure the values are evaluated. - if (!DECL_P(left) && TREE_SIDE_EFFECTS(left)) - { - left = save_expr(left); - eval_saved = left; - } - if (!DECL_P(right) && TREE_SIDE_EFFECTS(right)) - { - right = save_expr(right); - if (eval_saved == NULL_TREE) - eval_saved = right; - else - eval_saved = fold_build2_loc(this->location(), COMPOUND_EXPR, - void_type_node, eval_saved, right); - } - } - - tree ret = fold_build2_loc(this->location(), - code, - compute_type != NULL_TREE ? compute_type : type, - left, right); - - if (compute_type != NULL_TREE) - ret = ::convert(type, ret); - - // In Go, a shift larger than the size of the type is well-defined. - // This is not true in GENERIC, so we need to insert a conditional. - if (is_shift_op) - { - gcc_assert(INTEGRAL_TYPE_P(TREE_TYPE(left))); - gcc_assert(this->left_->type()->integer_type() != NULL); - int bits = TYPE_PRECISION(TREE_TYPE(left)); - - tree compare = fold_build2(LT_EXPR, boolean_type_node, right, - build_int_cst_type(TREE_TYPE(right), bits)); - - tree overflow_result = fold_convert_loc(this->location(), - TREE_TYPE(left), - integer_zero_node); - if (this->op_ == OPERATOR_RSHIFT - && !this->left_->type()->integer_type()->is_unsigned()) - { - tree neg = fold_build2_loc(this->location(), LT_EXPR, - boolean_type_node, left, - fold_convert_loc(this->location(), - TREE_TYPE(left), - integer_zero_node)); - tree neg_one = fold_build2_loc(this->location(), - MINUS_EXPR, TREE_TYPE(left), - fold_convert_loc(this->location(), - TREE_TYPE(left), - integer_zero_node), - fold_convert_loc(this->location(), - TREE_TYPE(left), - integer_one_node)); - overflow_result = fold_build3_loc(this->location(), COND_EXPR, - TREE_TYPE(left), neg, neg_one, - overflow_result); - } - - ret = fold_build3_loc(this->location(), COND_EXPR, TREE_TYPE(left), - compare, ret, overflow_result); - - if (eval_saved != NULL_TREE) - ret = fold_build2_loc(this->location(), COMPOUND_EXPR, - TREE_TYPE(ret), eval_saved, ret); - } - - return ret; -} - -// Export a binary expression. - -void -Binary_expression::do_export(Export* exp) const -{ - exp->write_c_string("("); - this->left_->export_expression(exp); - switch (this->op_) - { - case OPERATOR_OROR: - exp->write_c_string(" || "); - break; - case OPERATOR_ANDAND: - exp->write_c_string(" && "); - break; - case OPERATOR_EQEQ: - exp->write_c_string(" == "); - break; - case OPERATOR_NOTEQ: - exp->write_c_string(" != "); - break; - case OPERATOR_LT: - exp->write_c_string(" < "); - break; - case OPERATOR_LE: - exp->write_c_string(" <= "); - break; - case OPERATOR_GT: - exp->write_c_string(" > "); - break; - case OPERATOR_GE: - exp->write_c_string(" >= "); - break; - case OPERATOR_PLUS: - exp->write_c_string(" + "); - break; - case OPERATOR_MINUS: - exp->write_c_string(" - "); - break; - case OPERATOR_OR: - exp->write_c_string(" | "); - break; - case OPERATOR_XOR: - exp->write_c_string(" ^ "); - break; - case OPERATOR_MULT: - exp->write_c_string(" * "); - break; - case OPERATOR_DIV: - exp->write_c_string(" / "); - break; - case OPERATOR_MOD: - exp->write_c_string(" % "); - break; - case OPERATOR_LSHIFT: - exp->write_c_string(" << "); - break; - case OPERATOR_RSHIFT: - exp->write_c_string(" >> "); - break; - case OPERATOR_AND: - exp->write_c_string(" & "); - break; - case OPERATOR_BITCLEAR: - exp->write_c_string(" &^ "); - break; - default: - gcc_unreachable(); - } - this->right_->export_expression(exp); - exp->write_c_string(")"); -} - -// Import a binary expression. - -Expression* -Binary_expression::do_import(Import* imp) -{ - imp->require_c_string("("); - - Expression* left = Expression::import_expression(imp); - - Operator op; - if (imp->match_c_string(" || ")) - { - op = OPERATOR_OROR; - imp->advance(4); - } - else if (imp->match_c_string(" && ")) - { - op = OPERATOR_ANDAND; - imp->advance(4); - } - else if (imp->match_c_string(" == ")) - { - op = OPERATOR_EQEQ; - imp->advance(4); - } - else if (imp->match_c_string(" != ")) - { - op = OPERATOR_NOTEQ; - imp->advance(4); - } - else if (imp->match_c_string(" < ")) - { - op = OPERATOR_LT; - imp->advance(3); - } - else if (imp->match_c_string(" <= ")) - { - op = OPERATOR_LE; - imp->advance(4); - } - else if (imp->match_c_string(" > ")) - { - op = OPERATOR_GT; - imp->advance(3); - } - else if (imp->match_c_string(" >= ")) - { - op = OPERATOR_GE; - imp->advance(4); - } - else if (imp->match_c_string(" + ")) - { - op = OPERATOR_PLUS; - imp->advance(3); - } - else if (imp->match_c_string(" - ")) - { - op = OPERATOR_MINUS; - imp->advance(3); - } - else if (imp->match_c_string(" | ")) - { - op = OPERATOR_OR; - imp->advance(3); - } - else if (imp->match_c_string(" ^ ")) - { - op = OPERATOR_XOR; - imp->advance(3); - } - else if (imp->match_c_string(" * ")) - { - op = OPERATOR_MULT; - imp->advance(3); - } - else if (imp->match_c_string(" / ")) - { - op = OPERATOR_DIV; - imp->advance(3); - } - else if (imp->match_c_string(" % ")) - { - op = OPERATOR_MOD; - imp->advance(3); - } - else if (imp->match_c_string(" << ")) - { - op = OPERATOR_LSHIFT; - imp->advance(4); - } - else if (imp->match_c_string(" >> ")) - { - op = OPERATOR_RSHIFT; - imp->advance(4); - } - else if (imp->match_c_string(" & ")) - { - op = OPERATOR_AND; - imp->advance(3); - } - else if (imp->match_c_string(" &^ ")) - { - op = OPERATOR_BITCLEAR; - imp->advance(4); - } - else - { - error_at(imp->location(), "unrecognized binary operator"); - return Expression::make_error(imp->location()); - } - - Expression* right = Expression::import_expression(imp); - - imp->require_c_string(")"); - - return Expression::make_binary(op, left, right, imp->location()); -} - -// Make a binary expression. - -Expression* -Expression::make_binary(Operator op, Expression* left, Expression* right, - source_location location) -{ - return new Binary_expression(op, left, right, location); -} - -// Implement a comparison. - -tree -Expression::comparison_tree(Translate_context* context, Operator op, - Type* left_type, tree left_tree, - Type* right_type, tree right_tree, - source_location location) -{ - enum tree_code code; - switch (op) - { - case OPERATOR_EQEQ: - code = EQ_EXPR; - break; - case OPERATOR_NOTEQ: - code = NE_EXPR; - break; - case OPERATOR_LT: - code = LT_EXPR; - break; - case OPERATOR_LE: - code = LE_EXPR; - break; - case OPERATOR_GT: - code = GT_EXPR; - break; - case OPERATOR_GE: - code = GE_EXPR; - break; - default: - gcc_unreachable(); - } - - if (left_type->is_string_type() && right_type->is_string_type()) - { - tree string_type = Type::make_string_type()->get_tree(context->gogo()); - static tree string_compare_decl; - left_tree = Gogo::call_builtin(&string_compare_decl, - location, - "__go_strcmp", - 2, - integer_type_node, - string_type, - left_tree, - string_type, - right_tree); - right_tree = build_int_cst_type(integer_type_node, 0); - } - else if ((left_type->interface_type() != NULL - && right_type->interface_type() == NULL - && !right_type->is_nil_type()) - || (left_type->interface_type() == NULL - && !left_type->is_nil_type() - && right_type->interface_type() != NULL)) - { - // Comparing an interface value to a non-interface value. - if (left_type->interface_type() == NULL) - { - std::swap(left_type, right_type); - std::swap(left_tree, right_tree); - } - - // The right operand is not an interface. We need to take its - // address if it is not a pointer. - tree make_tmp; - tree arg; - if (right_type->points_to() != NULL) - { - make_tmp = NULL_TREE; - arg = right_tree; - } - else if (TREE_ADDRESSABLE(TREE_TYPE(right_tree)) || DECL_P(right_tree)) - { - make_tmp = NULL_TREE; - arg = build_fold_addr_expr_loc(location, right_tree); - if (DECL_P(right_tree)) - TREE_ADDRESSABLE(right_tree) = 1; - } - else - { - tree tmp = create_tmp_var(TREE_TYPE(right_tree), - get_name(right_tree)); - DECL_IGNORED_P(tmp) = 0; - DECL_INITIAL(tmp) = right_tree; - TREE_ADDRESSABLE(tmp) = 1; - make_tmp = build1(DECL_EXPR, void_type_node, tmp); - SET_EXPR_LOCATION(make_tmp, location); - arg = build_fold_addr_expr_loc(location, tmp); - } - arg = fold_convert_loc(location, ptr_type_node, arg); - - tree descriptor = right_type->type_descriptor_pointer(context->gogo()); - - if (left_type->interface_type()->is_empty()) - { - static tree empty_interface_value_compare_decl; - left_tree = Gogo::call_builtin(&empty_interface_value_compare_decl, - location, - "__go_empty_interface_value_compare", - 3, - integer_type_node, - TREE_TYPE(left_tree), - left_tree, - TREE_TYPE(descriptor), - descriptor, - ptr_type_node, - arg); - if (left_tree == error_mark_node) - return error_mark_node; - // This can panic if the type is not comparable. - TREE_NOTHROW(empty_interface_value_compare_decl) = 0; - } - else - { - static tree interface_value_compare_decl; - left_tree = Gogo::call_builtin(&interface_value_compare_decl, - location, - "__go_interface_value_compare", - 3, - integer_type_node, - TREE_TYPE(left_tree), - left_tree, - TREE_TYPE(descriptor), - descriptor, - ptr_type_node, - arg); - if (left_tree == error_mark_node) - return error_mark_node; - // This can panic if the type is not comparable. - TREE_NOTHROW(interface_value_compare_decl) = 0; - } - right_tree = build_int_cst_type(integer_type_node, 0); - - if (make_tmp != NULL_TREE) - left_tree = build2(COMPOUND_EXPR, TREE_TYPE(left_tree), make_tmp, - left_tree); - } - else if (left_type->interface_type() != NULL - && right_type->interface_type() != NULL) - { - if (left_type->interface_type()->is_empty() - && right_type->interface_type()->is_empty()) - { - static tree empty_interface_compare_decl; - left_tree = Gogo::call_builtin(&empty_interface_compare_decl, - location, - "__go_empty_interface_compare", - 2, - integer_type_node, - TREE_TYPE(left_tree), - left_tree, - TREE_TYPE(right_tree), - right_tree); - if (left_tree == error_mark_node) - return error_mark_node; - // This can panic if the type is uncomparable. - TREE_NOTHROW(empty_interface_compare_decl) = 0; - } - else if (!left_type->interface_type()->is_empty() - && !right_type->interface_type()->is_empty()) - { - static tree interface_compare_decl; - left_tree = Gogo::call_builtin(&interface_compare_decl, - location, - "__go_interface_compare", - 2, - integer_type_node, - TREE_TYPE(left_tree), - left_tree, - TREE_TYPE(right_tree), - right_tree); - if (left_tree == error_mark_node) - return error_mark_node; - // This can panic if the type is uncomparable. - TREE_NOTHROW(interface_compare_decl) = 0; - } - else - { - if (left_type->interface_type()->is_empty()) - { - gcc_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ); - std::swap(left_type, right_type); - std::swap(left_tree, right_tree); - } - gcc_assert(!left_type->interface_type()->is_empty()); - gcc_assert(right_type->interface_type()->is_empty()); - static tree interface_empty_compare_decl; - left_tree = Gogo::call_builtin(&interface_empty_compare_decl, - location, - "__go_interface_empty_compare", - 2, - integer_type_node, - TREE_TYPE(left_tree), - left_tree, - TREE_TYPE(right_tree), - right_tree); - if (left_tree == error_mark_node) - return error_mark_node; - // This can panic if the type is uncomparable. - TREE_NOTHROW(interface_empty_compare_decl) = 0; - } - - right_tree = build_int_cst_type(integer_type_node, 0); - } - - if (left_type->is_nil_type() - && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)) - { - std::swap(left_type, right_type); - std::swap(left_tree, right_tree); - } - - if (right_type->is_nil_type()) - { - if (left_type->array_type() != NULL - && left_type->array_type()->length() == NULL) - { - Array_type* at = left_type->array_type(); - left_tree = at->value_pointer_tree(context->gogo(), left_tree); - right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node); - } - else if (left_type->interface_type() != NULL) - { - // An interface is nil if the first field is nil. - tree left_type_tree = TREE_TYPE(left_tree); - gcc_assert(TREE_CODE(left_type_tree) == RECORD_TYPE); - tree field = TYPE_FIELDS(left_type_tree); - left_tree = build3(COMPONENT_REF, TREE_TYPE(field), left_tree, - field, NULL_TREE); - right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node); - } - else - { - gcc_assert(POINTER_TYPE_P(TREE_TYPE(left_tree))); - right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node); - } - } - - if (left_tree == error_mark_node || right_tree == error_mark_node) - return error_mark_node; - - tree ret = fold_build2(code, boolean_type_node, left_tree, right_tree); - if (CAN_HAVE_LOCATION_P(ret)) - SET_EXPR_LOCATION(ret, location); - return ret; -} - -// Class Bound_method_expression. - -// Traversal. - -int -Bound_method_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return Expression::traverse(&this->method_, traverse); -} - -// Return the type of a bound method expression. The type of this -// object is really the type of the method with no receiver. We -// should be able to get away with just returning the type of the -// method. - -Type* -Bound_method_expression::do_type() -{ - return this->method_->type(); -} - -// Determine the types of a method expression. - -void -Bound_method_expression::do_determine_type(const Type_context*) -{ - this->method_->determine_type_no_context(); - Type* mtype = this->method_->type(); - Function_type* fntype = mtype == NULL ? NULL : mtype->function_type(); - if (fntype == NULL || !fntype->is_method()) - this->expr_->determine_type_no_context(); - else - { - Type_context subcontext(fntype->receiver()->type(), false); - this->expr_->determine_type(&subcontext); - } -} - -// Check the types of a method expression. - -void -Bound_method_expression::do_check_types(Gogo*) -{ - Type* type = this->method_->type()->deref(); - if (type == NULL - || type->function_type() == NULL - || !type->function_type()->is_method()) - this->report_error(_("object is not a method")); - else - { - Type* rtype = type->function_type()->receiver()->type()->deref(); - Type* etype = (this->expr_type_ != NULL - ? this->expr_type_ - : this->expr_->type()); - etype = etype->deref(); - if (!Type::are_identical(rtype, etype, true, NULL)) - this->report_error(_("method type does not match object type")); - } -} - -// Get the tree for a method expression. There is no standard tree -// representation for this. The only places it may currently be used -// are in a Call_expression or a Go_statement, which will take it -// apart directly. So this has nothing to do at present. - -tree -Bound_method_expression::do_get_tree(Translate_context*) -{ - error_at(this->location(), "reference to method other than calling it"); - return error_mark_node; -} - -// Make a method expression. - -Bound_method_expression* -Expression::make_bound_method(Expression* expr, Expression* method, - source_location location) -{ - return new Bound_method_expression(expr, method, location); -} - -// Class Builtin_call_expression. This is used for a call to a -// builtin function. - -class Builtin_call_expression : public Call_expression -{ - public: - Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args, - bool is_varargs, source_location location); - - protected: - // This overrides Call_expression::do_lower. - Expression* - do_lower(Gogo*, Named_object*, int); - - bool - do_is_constant() const; - - bool - do_integer_constant_value(bool, mpz_t, Type**) const; - - bool - do_float_constant_value(mpfr_t, Type**) const; - - bool - do_complex_constant_value(mpfr_t, mpfr_t, Type**) const; - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Builtin_call_expression(this->gogo_, this->fn()->copy(), - this->args()->copy(), - this->is_varargs(), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - virtual bool - do_is_recover_call() const; - - virtual void - do_set_recover_arg(Expression*); - - private: - // The builtin functions. - enum Builtin_function_code - { - BUILTIN_INVALID, - - // Predeclared builtin functions. - BUILTIN_APPEND, - BUILTIN_CAP, - BUILTIN_CLOSE, - BUILTIN_COMPLEX, - BUILTIN_COPY, - BUILTIN_IMAG, - BUILTIN_LEN, - BUILTIN_MAKE, - BUILTIN_NEW, - BUILTIN_PANIC, - BUILTIN_PRINT, - BUILTIN_PRINTLN, - BUILTIN_REAL, - BUILTIN_RECOVER, - - // Builtin functions from the unsafe package. - BUILTIN_ALIGNOF, - BUILTIN_OFFSETOF, - BUILTIN_SIZEOF - }; - - Expression* - one_arg() const; - - bool - check_one_arg(); - - static Type* - real_imag_type(Type*); - - static Type* - complex_type(Type*); - - // A pointer back to the general IR structure. This avoids a global - // variable, or passing it around everywhere. - Gogo* gogo_; - // The builtin function being called. - Builtin_function_code code_; - // Used to stop endless loops when the length of an array uses len - // or cap of the array itself. - mutable bool seen_; -}; - -Builtin_call_expression::Builtin_call_expression(Gogo* gogo, - Expression* fn, - Expression_list* args, - bool is_varargs, - source_location location) - : Call_expression(fn, args, is_varargs, location), - gogo_(gogo), code_(BUILTIN_INVALID), seen_(false) -{ - Func_expression* fnexp = this->fn()->func_expression(); - gcc_assert(fnexp != NULL); - const std::string& name(fnexp->named_object()->name()); - if (name == "append") - this->code_ = BUILTIN_APPEND; - else if (name == "cap") - this->code_ = BUILTIN_CAP; - else if (name == "close") - this->code_ = BUILTIN_CLOSE; - else if (name == "complex") - this->code_ = BUILTIN_COMPLEX; - else if (name == "copy") - this->code_ = BUILTIN_COPY; - else if (name == "imag") - this->code_ = BUILTIN_IMAG; - else if (name == "len") - this->code_ = BUILTIN_LEN; - else if (name == "make") - this->code_ = BUILTIN_MAKE; - else if (name == "new") - this->code_ = BUILTIN_NEW; - else if (name == "panic") - this->code_ = BUILTIN_PANIC; - else if (name == "print") - this->code_ = BUILTIN_PRINT; - else if (name == "println") - this->code_ = BUILTIN_PRINTLN; - else if (name == "real") - this->code_ = BUILTIN_REAL; - else if (name == "recover") - this->code_ = BUILTIN_RECOVER; - else if (name == "Alignof") - this->code_ = BUILTIN_ALIGNOF; - else if (name == "Offsetof") - this->code_ = BUILTIN_OFFSETOF; - else if (name == "Sizeof") - this->code_ = BUILTIN_SIZEOF; - else - gcc_unreachable(); -} - -// Return whether this is a call to recover. This is a virtual -// function called from the parent class. - -bool -Builtin_call_expression::do_is_recover_call() const -{ - if (this->classification() == EXPRESSION_ERROR) - return false; - return this->code_ == BUILTIN_RECOVER; -} - -// Set the argument for a call to recover. - -void -Builtin_call_expression::do_set_recover_arg(Expression* arg) -{ - const Expression_list* args = this->args(); - gcc_assert(args == NULL || args->empty()); - Expression_list* new_args = new Expression_list(); - new_args->push_back(arg); - this->set_args(new_args); -} - -// A traversal class which looks for a call expression. - -class Find_call_expression : public Traverse -{ - public: - Find_call_expression() - : Traverse(traverse_expressions), - found_(false) - { } - - int - expression(Expression**); - - bool - found() - { return this->found_; } - - private: - bool found_; -}; - -int -Find_call_expression::expression(Expression** pexpr) -{ - if ((*pexpr)->call_expression() != NULL) - { - this->found_ = true; - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lower a builtin call expression. This turns new and make into -// specific expressions. We also convert to a constant if we can. - -Expression* -Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function, int) -{ - if (this->code_ == BUILTIN_NEW) - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 1) - this->report_error(_("not enough arguments")); - else if (args->size() > 1) - this->report_error(_("too many arguments")); - else - { - Expression* arg = args->front(); - if (!arg->is_type_expression()) - { - error_at(arg->location(), "expected type"); - this->set_is_error(); - } - else - return Expression::make_allocation(arg->type(), this->location()); - } - } - else if (this->code_ == BUILTIN_MAKE) - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 1) - this->report_error(_("not enough arguments")); - else - { - Expression* arg = args->front(); - if (!arg->is_type_expression()) - { - error_at(arg->location(), "expected type"); - this->set_is_error(); - } - else - { - Expression_list* newargs; - if (args->size() == 1) - newargs = NULL; - else - { - newargs = new Expression_list(); - Expression_list::const_iterator p = args->begin(); - ++p; - for (; p != args->end(); ++p) - newargs->push_back(*p); - } - return Expression::make_make(arg->type(), newargs, - this->location()); - } - } - } - else if (this->is_constant()) - { - // We can only lower len and cap if there are no function calls - // in the arguments. Otherwise we have to make the call. - if (this->code_ == BUILTIN_LEN || this->code_ == BUILTIN_CAP) - { - Expression* arg = this->one_arg(); - if (!arg->is_constant()) - { - Find_call_expression find_call; - Expression::traverse(&arg, &find_call); - if (find_call.found()) - return this; - } - } - - mpz_t ival; - mpz_init(ival); - Type* type; - if (this->integer_constant_value(true, ival, &type)) - { - Expression* ret = Expression::make_integer(&ival, type, - this->location()); - mpz_clear(ival); - return ret; - } - mpz_clear(ival); - - mpfr_t rval; - mpfr_init(rval); - if (this->float_constant_value(rval, &type)) - { - Expression* ret = Expression::make_float(&rval, type, - this->location()); - mpfr_clear(rval); - return ret; - } - - mpfr_t imag; - mpfr_init(imag); - if (this->complex_constant_value(rval, imag, &type)) - { - Expression* ret = Expression::make_complex(&rval, &imag, type, - this->location()); - mpfr_clear(rval); - mpfr_clear(imag); - return ret; - } - mpfr_clear(rval); - mpfr_clear(imag); - } - else if (this->code_ == BUILTIN_RECOVER) - { - if (function != NULL) - function->func_value()->set_calls_recover(); - else - { - // Calling recover outside of a function always returns the - // nil empty interface. - Type* eface = Type::make_interface_type(NULL, this->location()); - return Expression::make_cast(eface, - Expression::make_nil(this->location()), - this->location()); - } - } - else if (this->code_ == BUILTIN_APPEND) - { - // Lower the varargs. - const Expression_list* args = this->args(); - if (args == NULL || args->empty()) - return this; - Type* slice_type = args->front()->type(); - if (!slice_type->is_open_array_type()) - { - error_at(args->front()->location(), "argument 1 must be a slice"); - this->set_is_error(); - return this; - } - return this->lower_varargs(gogo, function, slice_type, 2); - } - - return this; -} - -// Return the type of the real or imag functions, given the type of -// the argument. We need to map complex to float, complex64 to -// float32, and complex128 to float64, so it has to be done by name. -// This returns NULL if it can't figure out the type. - -Type* -Builtin_call_expression::real_imag_type(Type* arg_type) -{ - if (arg_type == NULL || arg_type->is_abstract()) - return NULL; - Named_type* nt = arg_type->named_type(); - if (nt == NULL) - return NULL; - while (nt->real_type()->named_type() != NULL) - nt = nt->real_type()->named_type(); - if (nt->name() == "complex64") - return Type::lookup_float_type("float32"); - else if (nt->name() == "complex128") - return Type::lookup_float_type("float64"); - else - return NULL; -} - -// Return the type of the complex function, given the type of one of the -// argments. Like real_imag_type, we have to map by name. - -Type* -Builtin_call_expression::complex_type(Type* arg_type) -{ - if (arg_type == NULL || arg_type->is_abstract()) - return NULL; - Named_type* nt = arg_type->named_type(); - if (nt == NULL) - return NULL; - while (nt->real_type()->named_type() != NULL) - nt = nt->real_type()->named_type(); - if (nt->name() == "float32") - return Type::lookup_complex_type("complex64"); - else if (nt->name() == "float64") - return Type::lookup_complex_type("complex128"); - else - return NULL; -} - -// Return a single argument, or NULL if there isn't one. - -Expression* -Builtin_call_expression::one_arg() const -{ - const Expression_list* args = this->args(); - if (args->size() != 1) - return NULL; - return args->front(); -} - -// Return whether this is constant: len of a string, or len or cap of -// a fixed array, or unsafe.Sizeof, unsafe.Offsetof, unsafe.Alignof. - -bool -Builtin_call_expression::do_is_constant() const -{ - switch (this->code_) - { - case BUILTIN_LEN: - case BUILTIN_CAP: - { - if (this->seen_) - return false; - - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - Type* arg_type = arg->type(); - - if (arg_type->points_to() != NULL - && arg_type->points_to()->array_type() != NULL - && !arg_type->points_to()->is_open_array_type()) - arg_type = arg_type->points_to(); - - if (arg_type->array_type() != NULL - && arg_type->array_type()->length() != NULL) - return true; - - if (this->code_ == BUILTIN_LEN && arg_type->is_string_type()) - { - this->seen_ = true; - bool ret = arg->is_constant(); - this->seen_ = false; - return ret; - } - } - break; - - case BUILTIN_SIZEOF: - case BUILTIN_ALIGNOF: - return this->one_arg() != NULL; - - case BUILTIN_OFFSETOF: - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - return arg->field_reference_expression() != NULL; - } - - case BUILTIN_COMPLEX: - { - const Expression_list* args = this->args(); - if (args != NULL && args->size() == 2) - return args->front()->is_constant() && args->back()->is_constant(); - } - break; - - case BUILTIN_REAL: - case BUILTIN_IMAG: - { - Expression* arg = this->one_arg(); - return arg != NULL && arg->is_constant(); - } - - default: - break; - } - - return false; -} - -// Return an integer constant value if possible. - -bool -Builtin_call_expression::do_integer_constant_value(bool iota_is_constant, - mpz_t val, - Type** ptype) const -{ - if (this->code_ == BUILTIN_LEN - || this->code_ == BUILTIN_CAP) - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - Type* arg_type = arg->type(); - - if (this->code_ == BUILTIN_LEN && arg_type->is_string_type()) - { - std::string sval; - if (arg->string_constant_value(&sval)) - { - mpz_set_ui(val, sval.length()); - *ptype = Type::lookup_integer_type("int"); - return true; - } - } - - if (arg_type->points_to() != NULL - && arg_type->points_to()->array_type() != NULL - && !arg_type->points_to()->is_open_array_type()) - arg_type = arg_type->points_to(); - - if (arg_type->array_type() != NULL - && arg_type->array_type()->length() != NULL) - { - if (this->seen_) - return false; - Expression* e = arg_type->array_type()->length(); - this->seen_ = true; - bool r = e->integer_constant_value(iota_is_constant, val, ptype); - this->seen_ = false; - if (r) - { - *ptype = Type::lookup_integer_type("int"); - return true; - } - } - } - else if (this->code_ == BUILTIN_SIZEOF - || this->code_ == BUILTIN_ALIGNOF) - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - Type* arg_type = arg->type(); - if (arg_type->is_error_type() || arg_type->is_undefined()) - return false; - if (arg_type->is_abstract()) - return false; - if (arg_type->named_type() != NULL) - arg_type->named_type()->convert(this->gogo_); - tree arg_type_tree = arg_type->get_tree(this->gogo_); - if (arg_type_tree == error_mark_node) - return false; - unsigned long val_long; - if (this->code_ == BUILTIN_SIZEOF) - { - tree type_size = TYPE_SIZE_UNIT(arg_type_tree); - gcc_assert(TREE_CODE(type_size) == INTEGER_CST); - if (TREE_INT_CST_HIGH(type_size) != 0) - return false; - unsigned HOST_WIDE_INT val_wide = TREE_INT_CST_LOW(type_size); - val_long = static_cast(val_wide); - if (val_long != val_wide) - return false; - } - else if (this->code_ == BUILTIN_ALIGNOF) - { - if (arg->field_reference_expression() == NULL) - val_long = go_type_alignment(arg_type_tree); - else - { - // Calling unsafe.Alignof(s.f) returns the alignment of - // the type of f when it is used as a field in a struct. - val_long = go_field_alignment(arg_type_tree); - } - } - else - gcc_unreachable(); - mpz_set_ui(val, val_long); - *ptype = NULL; - return true; - } - else if (this->code_ == BUILTIN_OFFSETOF) - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - Field_reference_expression* farg = arg->field_reference_expression(); - if (farg == NULL) - return false; - Expression* struct_expr = farg->expr(); - Type* st = struct_expr->type(); - if (st->struct_type() == NULL) - return false; - if (st->named_type() != NULL) - st->named_type()->convert(this->gogo_); - tree struct_tree = st->get_tree(this->gogo_); - gcc_assert(TREE_CODE(struct_tree) == RECORD_TYPE); - tree field = TYPE_FIELDS(struct_tree); - for (unsigned int index = farg->field_index(); index > 0; --index) - { - field = DECL_CHAIN(field); - gcc_assert(field != NULL_TREE); - } - HOST_WIDE_INT offset_wide = int_byte_position (field); - if (offset_wide < 0) - return false; - unsigned long offset_long = static_cast(offset_wide); - if (offset_long != static_cast(offset_wide)) - return false; - mpz_set_ui(val, offset_long); - return true; - } - return false; -} - -// Return a floating point constant value if possible. - -bool -Builtin_call_expression::do_float_constant_value(mpfr_t val, - Type** ptype) const -{ - if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG) - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return false; - - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - - bool ret = false; - Type* type; - if (arg->complex_constant_value(real, imag, &type)) - { - if (this->code_ == BUILTIN_REAL) - mpfr_set(val, real, GMP_RNDN); - else - mpfr_set(val, imag, GMP_RNDN); - *ptype = Builtin_call_expression::real_imag_type(type); - ret = true; - } - - mpfr_clear(real); - mpfr_clear(imag); - return ret; - } - - return false; -} - -// Return a complex constant value if possible. - -bool -Builtin_call_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag, - Type** ptype) const -{ - if (this->code_ == BUILTIN_COMPLEX) - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() != 2) - return false; - - mpfr_t r; - mpfr_init(r); - Type* rtype; - if (!args->front()->float_constant_value(r, &rtype)) - { - mpfr_clear(r); - return false; - } - - mpfr_t i; - mpfr_init(i); - - bool ret = false; - Type* itype; - if (args->back()->float_constant_value(i, &itype) - && Type::are_identical(rtype, itype, false, NULL)) - { - mpfr_set(real, r, GMP_RNDN); - mpfr_set(imag, i, GMP_RNDN); - *ptype = Builtin_call_expression::complex_type(rtype); - ret = true; - } - - mpfr_clear(r); - mpfr_clear(i); - - return ret; - } - - return false; -} - -// Return the type. - -Type* -Builtin_call_expression::do_type() -{ - switch (this->code_) - { - case BUILTIN_INVALID: - default: - gcc_unreachable(); - - case BUILTIN_NEW: - case BUILTIN_MAKE: - { - const Expression_list* args = this->args(); - if (args == NULL || args->empty()) - return Type::make_error_type(); - return Type::make_pointer_type(args->front()->type()); - } - - case BUILTIN_CAP: - case BUILTIN_COPY: - case BUILTIN_LEN: - case BUILTIN_ALIGNOF: - case BUILTIN_OFFSETOF: - case BUILTIN_SIZEOF: - return Type::lookup_integer_type("int"); - - case BUILTIN_CLOSE: - case BUILTIN_PANIC: - case BUILTIN_PRINT: - case BUILTIN_PRINTLN: - return Type::make_void_type(); - - case BUILTIN_RECOVER: - return Type::make_interface_type(NULL, BUILTINS_LOCATION); - - case BUILTIN_APPEND: - { - const Expression_list* args = this->args(); - if (args == NULL || args->empty()) - return Type::make_error_type(); - return args->front()->type(); - } - - case BUILTIN_REAL: - case BUILTIN_IMAG: - { - Expression* arg = this->one_arg(); - if (arg == NULL) - return Type::make_error_type(); - Type* t = arg->type(); - if (t->is_abstract()) - t = t->make_non_abstract_type(); - t = Builtin_call_expression::real_imag_type(t); - if (t == NULL) - t = Type::make_error_type(); - return t; - } - - case BUILTIN_COMPLEX: - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() != 2) - return Type::make_error_type(); - Type* t = args->front()->type(); - if (t->is_abstract()) - { - t = args->back()->type(); - if (t->is_abstract()) - t = t->make_non_abstract_type(); - } - t = Builtin_call_expression::complex_type(t); - if (t == NULL) - t = Type::make_error_type(); - return t; - } - } -} - -// Determine the type. - -void -Builtin_call_expression::do_determine_type(const Type_context* context) -{ - if (!this->determining_types()) - return; - - this->fn()->determine_type_no_context(); - - const Expression_list* args = this->args(); - - bool is_print; - Type* arg_type = NULL; - switch (this->code_) - { - case BUILTIN_PRINT: - case BUILTIN_PRINTLN: - // Do not force a large integer constant to "int". - is_print = true; - break; - - case BUILTIN_REAL: - case BUILTIN_IMAG: - arg_type = Builtin_call_expression::complex_type(context->type); - is_print = false; - break; - - case BUILTIN_COMPLEX: - { - // For the complex function the type of one operand can - // determine the type of the other, as in a binary expression. - arg_type = Builtin_call_expression::real_imag_type(context->type); - if (args != NULL && args->size() == 2) - { - Type* t1 = args->front()->type(); - Type* t2 = args->front()->type(); - if (!t1->is_abstract()) - arg_type = t1; - else if (!t2->is_abstract()) - arg_type = t2; - } - is_print = false; - } - break; - - default: - is_print = false; - break; - } - - if (args != NULL) - { - for (Expression_list::const_iterator pa = args->begin(); - pa != args->end(); - ++pa) - { - Type_context subcontext; - subcontext.type = arg_type; - - if (is_print) - { - // We want to print large constants, we so can't just - // use the appropriate nonabstract type. Use uint64 for - // an integer if we know it is nonnegative, otherwise - // use int64 for a integer, otherwise use float64 for a - // float or complex128 for a complex. - Type* want_type = NULL; - Type* atype = (*pa)->type(); - if (atype->is_abstract()) - { - if (atype->integer_type() != NULL) - { - mpz_t val; - mpz_init(val); - Type* dummy; - if (this->integer_constant_value(true, val, &dummy) - && mpz_sgn(val) >= 0) - want_type = Type::lookup_integer_type("uint64"); - else - want_type = Type::lookup_integer_type("int64"); - mpz_clear(val); - } - else if (atype->float_type() != NULL) - want_type = Type::lookup_float_type("float64"); - else if (atype->complex_type() != NULL) - want_type = Type::lookup_complex_type("complex128"); - else if (atype->is_abstract_string_type()) - want_type = Type::lookup_string_type(); - else if (atype->is_abstract_boolean_type()) - want_type = Type::lookup_bool_type(); - else - gcc_unreachable(); - subcontext.type = want_type; - } - } - - (*pa)->determine_type(&subcontext); - } - } -} - -// If there is exactly one argument, return true. Otherwise give an -// error message and return false. - -bool -Builtin_call_expression::check_one_arg() -{ - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 1) - { - this->report_error(_("not enough arguments")); - return false; - } - else if (args->size() > 1) - { - this->report_error(_("too many arguments")); - return false; - } - if (args->front()->is_error_expression() - || args->front()->type()->is_error_type() - || args->front()->type()->is_undefined()) - { - this->set_is_error(); - return false; - } - return true; -} - -// Check argument types for a builtin function. - -void -Builtin_call_expression::do_check_types(Gogo*) -{ - switch (this->code_) - { - case BUILTIN_INVALID: - case BUILTIN_NEW: - case BUILTIN_MAKE: - return; - - case BUILTIN_LEN: - case BUILTIN_CAP: - { - // The single argument may be either a string or an array or a - // map or a channel, or a pointer to a closed array. - if (this->check_one_arg()) - { - Type* arg_type = this->one_arg()->type(); - if (arg_type->points_to() != NULL - && arg_type->points_to()->array_type() != NULL - && !arg_type->points_to()->is_open_array_type()) - arg_type = arg_type->points_to(); - if (this->code_ == BUILTIN_CAP) - { - if (!arg_type->is_error_type() - && arg_type->array_type() == NULL - && arg_type->channel_type() == NULL) - this->report_error(_("argument must be array or slice " - "or channel")); - } - else - { - if (!arg_type->is_error_type() - && !arg_type->is_string_type() - && arg_type->array_type() == NULL - && arg_type->map_type() == NULL - && arg_type->channel_type() == NULL) - this->report_error(_("argument must be string or " - "array or slice or map or channel")); - } - } - } - break; - - case BUILTIN_PRINT: - case BUILTIN_PRINTLN: - { - const Expression_list* args = this->args(); - if (args == NULL) - { - if (this->code_ == BUILTIN_PRINT) - warning_at(this->location(), 0, - "no arguments for builtin function %<%s%>", - (this->code_ == BUILTIN_PRINT - ? "print" - : "println")); - } - else - { - for (Expression_list::const_iterator p = args->begin(); - p != args->end(); - ++p) - { - Type* type = (*p)->type(); - if (type->is_error_type() - || type->is_string_type() - || type->integer_type() != NULL - || type->float_type() != NULL - || type->complex_type() != NULL - || type->is_boolean_type() - || type->points_to() != NULL - || type->interface_type() != NULL - || type->channel_type() != NULL - || type->map_type() != NULL - || type->function_type() != NULL - || type->is_open_array_type()) - ; - else - this->report_error(_("unsupported argument type to " - "builtin function")); - } - } - } - break; - - case BUILTIN_CLOSE: - if (this->check_one_arg()) - { - if (this->one_arg()->type()->channel_type() == NULL) - this->report_error(_("argument must be channel")); - } - break; - - case BUILTIN_PANIC: - case BUILTIN_SIZEOF: - case BUILTIN_ALIGNOF: - this->check_one_arg(); - break; - - case BUILTIN_RECOVER: - if (this->args() != NULL && !this->args()->empty()) - this->report_error(_("too many arguments")); - break; - - case BUILTIN_OFFSETOF: - if (this->check_one_arg()) - { - Expression* arg = this->one_arg(); - if (arg->field_reference_expression() == NULL) - this->report_error(_("argument must be a field reference")); - } - break; - - case BUILTIN_COPY: - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 2) - { - this->report_error(_("not enough arguments")); - break; - } - else if (args->size() > 2) - { - this->report_error(_("too many arguments")); - break; - } - Type* arg1_type = args->front()->type(); - Type* arg2_type = args->back()->type(); - if (arg1_type->is_error_type() || arg2_type->is_error_type()) - break; - - Type* e1; - if (arg1_type->is_open_array_type()) - e1 = arg1_type->array_type()->element_type(); - else - { - this->report_error(_("left argument must be a slice")); - break; - } - - Type* e2; - if (arg2_type->is_open_array_type()) - e2 = arg2_type->array_type()->element_type(); - else if (arg2_type->is_string_type()) - e2 = Type::lookup_integer_type("uint8"); - else - { - this->report_error(_("right argument must be a slice or a string")); - break; - } - - if (!Type::are_identical(e1, e2, true, NULL)) - this->report_error(_("element types must be the same")); - } - break; - - case BUILTIN_APPEND: - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 2) - { - this->report_error(_("not enough arguments")); - break; - } - if (args->size() > 2) - { - this->report_error(_("too many arguments")); - break; - } - std::string reason; - if (!Type::are_assignable(args->front()->type(), args->back()->type(), - &reason)) - { - if (reason.empty()) - this->report_error(_("arguments 1 and 2 have different types")); - else - { - error_at(this->location(), - "arguments 1 and 2 have different types (%s)", - reason.c_str()); - this->set_is_error(); - } - } - break; - } - - case BUILTIN_REAL: - case BUILTIN_IMAG: - if (this->check_one_arg()) - { - if (this->one_arg()->type()->complex_type() == NULL) - this->report_error(_("argument must have complex type")); - } - break; - - case BUILTIN_COMPLEX: - { - const Expression_list* args = this->args(); - if (args == NULL || args->size() < 2) - this->report_error(_("not enough arguments")); - else if (args->size() > 2) - this->report_error(_("too many arguments")); - else if (args->front()->is_error_expression() - || args->front()->type()->is_error_type() - || args->back()->is_error_expression() - || args->back()->type()->is_error_type()) - this->set_is_error(); - else if (!Type::are_identical(args->front()->type(), - args->back()->type(), true, NULL)) - this->report_error(_("complex arguments must have identical types")); - else if (args->front()->type()->float_type() == NULL) - this->report_error(_("complex arguments must have " - "floating-point type")); - } - break; - - default: - gcc_unreachable(); - } -} - -// Return the tree for a builtin function. - -tree -Builtin_call_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - source_location location = this->location(); - switch (this->code_) - { - case BUILTIN_INVALID: - case BUILTIN_NEW: - case BUILTIN_MAKE: - gcc_unreachable(); - - case BUILTIN_LEN: - case BUILTIN_CAP: - { - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 1); - Expression* arg = *args->begin(); - Type* arg_type = arg->type(); - - if (this->seen_) - { - gcc_assert(saw_errors()); - return error_mark_node; - } - this->seen_ = true; - - tree arg_tree = arg->get_tree(context); - - this->seen_ = false; - - if (arg_tree == error_mark_node) - return error_mark_node; - - if (arg_type->points_to() != NULL) - { - arg_type = arg_type->points_to(); - gcc_assert(arg_type->array_type() != NULL - && !arg_type->is_open_array_type()); - gcc_assert(POINTER_TYPE_P(TREE_TYPE(arg_tree))); - arg_tree = build_fold_indirect_ref(arg_tree); - } - - tree val_tree; - if (this->code_ == BUILTIN_LEN) - { - if (arg_type->is_string_type()) - val_tree = String_type::length_tree(gogo, arg_tree); - else if (arg_type->array_type() != NULL) - { - if (this->seen_) - { - gcc_assert(saw_errors()); - return error_mark_node; - } - this->seen_ = true; - val_tree = arg_type->array_type()->length_tree(gogo, arg_tree); - this->seen_ = false; - } - else if (arg_type->map_type() != NULL) - { - static tree map_len_fndecl; - val_tree = Gogo::call_builtin(&map_len_fndecl, - location, - "__go_map_len", - 1, - sizetype, - arg_type->get_tree(gogo), - arg_tree); - } - else if (arg_type->channel_type() != NULL) - { - static tree chan_len_fndecl; - val_tree = Gogo::call_builtin(&chan_len_fndecl, - location, - "__go_chan_len", - 1, - sizetype, - arg_type->get_tree(gogo), - arg_tree); - } - else - gcc_unreachable(); - } - else - { - if (arg_type->array_type() != NULL) - { - if (this->seen_) - { - gcc_assert(saw_errors()); - return error_mark_node; - } - this->seen_ = true; - val_tree = arg_type->array_type()->capacity_tree(gogo, - arg_tree); - this->seen_ = false; - } - else if (arg_type->channel_type() != NULL) - { - static tree chan_cap_fndecl; - val_tree = Gogo::call_builtin(&chan_cap_fndecl, - location, - "__go_chan_cap", - 1, - sizetype, - arg_type->get_tree(gogo), - arg_tree); - } - else - gcc_unreachable(); - } - - if (val_tree == error_mark_node) - return error_mark_node; - - tree type_tree = Type::lookup_integer_type("int")->get_tree(gogo); - if (type_tree == TREE_TYPE(val_tree)) - return val_tree; - else - return fold(convert_to_integer(type_tree, val_tree)); - } - - case BUILTIN_PRINT: - case BUILTIN_PRINTLN: - { - const bool is_ln = this->code_ == BUILTIN_PRINTLN; - tree stmt_list = NULL_TREE; - - const Expression_list* call_args = this->args(); - if (call_args != NULL) - { - for (Expression_list::const_iterator p = call_args->begin(); - p != call_args->end(); - ++p) - { - if (is_ln && p != call_args->begin()) - { - static tree print_space_fndecl; - tree call = Gogo::call_builtin(&print_space_fndecl, - location, - "__go_print_space", - 0, - void_type_node); - if (call == error_mark_node) - return error_mark_node; - append_to_statement_list(call, &stmt_list); - } - - Type* type = (*p)->type(); - - tree arg = (*p)->get_tree(context); - if (arg == error_mark_node) - return error_mark_node; - - tree* pfndecl; - const char* fnname; - if (type->is_string_type()) - { - static tree print_string_fndecl; - pfndecl = &print_string_fndecl; - fnname = "__go_print_string"; - } - else if (type->integer_type() != NULL - && type->integer_type()->is_unsigned()) - { - static tree print_uint64_fndecl; - pfndecl = &print_uint64_fndecl; - fnname = "__go_print_uint64"; - Type* itype = Type::lookup_integer_type("uint64"); - arg = fold_convert_loc(location, itype->get_tree(gogo), - arg); - } - else if (type->integer_type() != NULL) - { - static tree print_int64_fndecl; - pfndecl = &print_int64_fndecl; - fnname = "__go_print_int64"; - Type* itype = Type::lookup_integer_type("int64"); - arg = fold_convert_loc(location, itype->get_tree(gogo), - arg); - } - else if (type->float_type() != NULL) - { - static tree print_double_fndecl; - pfndecl = &print_double_fndecl; - fnname = "__go_print_double"; - arg = fold_convert_loc(location, double_type_node, arg); - } - else if (type->complex_type() != NULL) - { - static tree print_complex_fndecl; - pfndecl = &print_complex_fndecl; - fnname = "__go_print_complex"; - arg = fold_convert_loc(location, complex_double_type_node, - arg); - } - else if (type->is_boolean_type()) - { - static tree print_bool_fndecl; - pfndecl = &print_bool_fndecl; - fnname = "__go_print_bool"; - } - else if (type->points_to() != NULL - || type->channel_type() != NULL - || type->map_type() != NULL - || type->function_type() != NULL) - { - static tree print_pointer_fndecl; - pfndecl = &print_pointer_fndecl; - fnname = "__go_print_pointer"; - arg = fold_convert_loc(location, ptr_type_node, arg); - } - else if (type->interface_type() != NULL) - { - if (type->interface_type()->is_empty()) - { - static tree print_empty_interface_fndecl; - pfndecl = &print_empty_interface_fndecl; - fnname = "__go_print_empty_interface"; - } - else - { - static tree print_interface_fndecl; - pfndecl = &print_interface_fndecl; - fnname = "__go_print_interface"; - } - } - else if (type->is_open_array_type()) - { - static tree print_slice_fndecl; - pfndecl = &print_slice_fndecl; - fnname = "__go_print_slice"; - } - else - gcc_unreachable(); - - tree call = Gogo::call_builtin(pfndecl, - location, - fnname, - 1, - void_type_node, - TREE_TYPE(arg), - arg); - if (call == error_mark_node) - return error_mark_node; - append_to_statement_list(call, &stmt_list); - } - } - - if (is_ln) - { - static tree print_nl_fndecl; - tree call = Gogo::call_builtin(&print_nl_fndecl, - location, - "__go_print_nl", - 0, - void_type_node); - if (call == error_mark_node) - return error_mark_node; - append_to_statement_list(call, &stmt_list); - } - - return stmt_list; - } - - case BUILTIN_PANIC: - { - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 1); - Expression* arg = args->front(); - tree arg_tree = arg->get_tree(context); - if (arg_tree == error_mark_node) - return error_mark_node; - Type *empty = Type::make_interface_type(NULL, BUILTINS_LOCATION); - arg_tree = Expression::convert_for_assignment(context, empty, - arg->type(), - arg_tree, location); - static tree panic_fndecl; - tree call = Gogo::call_builtin(&panic_fndecl, - location, - "__go_panic", - 1, - void_type_node, - TREE_TYPE(arg_tree), - arg_tree); - if (call == error_mark_node) - return error_mark_node; - // This function will throw an exception. - TREE_NOTHROW(panic_fndecl) = 0; - // This function will not return. - TREE_THIS_VOLATILE(panic_fndecl) = 1; - return call; - } - - case BUILTIN_RECOVER: - { - // The argument is set when building recover thunks. It's a - // boolean value which is true if we can recover a value now. - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 1); - Expression* arg = args->front(); - tree arg_tree = arg->get_tree(context); - if (arg_tree == error_mark_node) - return error_mark_node; - - Type *empty = Type::make_interface_type(NULL, BUILTINS_LOCATION); - tree empty_tree = empty->get_tree(context->gogo()); - - Type* nil_type = Type::make_nil_type(); - Expression* nil = Expression::make_nil(location); - tree nil_tree = nil->get_tree(context); - tree empty_nil_tree = Expression::convert_for_assignment(context, - empty, - nil_type, - nil_tree, - location); - - // We need to handle a deferred call to recover specially, - // because it changes whether it can recover a panic or not. - // See test7 in test/recover1.go. - tree call; - if (this->is_deferred()) - { - static tree deferred_recover_fndecl; - call = Gogo::call_builtin(&deferred_recover_fndecl, - location, - "__go_deferred_recover", - 0, - empty_tree); - } - else - { - static tree recover_fndecl; - call = Gogo::call_builtin(&recover_fndecl, - location, - "__go_recover", - 0, - empty_tree); - } - if (call == error_mark_node) - return error_mark_node; - return fold_build3_loc(location, COND_EXPR, empty_tree, arg_tree, - call, empty_nil_tree); - } - - case BUILTIN_CLOSE: - { - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 1); - Expression* arg = args->front(); - tree arg_tree = arg->get_tree(context); - if (arg_tree == error_mark_node) - return error_mark_node; - static tree close_fndecl; - return Gogo::call_builtin(&close_fndecl, - location, - "__go_builtin_close", - 1, - void_type_node, - TREE_TYPE(arg_tree), - arg_tree); - } - - case BUILTIN_SIZEOF: - case BUILTIN_OFFSETOF: - case BUILTIN_ALIGNOF: - { - mpz_t val; - mpz_init(val); - Type* dummy; - bool b = this->integer_constant_value(true, val, &dummy); - if (!b) - { - gcc_assert(saw_errors()); - return error_mark_node; - } - tree type = Type::lookup_integer_type("int")->get_tree(gogo); - tree ret = Expression::integer_constant_tree(val, type); - mpz_clear(val); - return ret; - } - - case BUILTIN_COPY: - { - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 2); - Expression* arg1 = args->front(); - Expression* arg2 = args->back(); - - tree arg1_tree = arg1->get_tree(context); - tree arg2_tree = arg2->get_tree(context); - if (arg1_tree == error_mark_node || arg2_tree == error_mark_node) - return error_mark_node; - - Type* arg1_type = arg1->type(); - Array_type* at = arg1_type->array_type(); - arg1_tree = save_expr(arg1_tree); - tree arg1_val = at->value_pointer_tree(gogo, arg1_tree); - tree arg1_len = at->length_tree(gogo, arg1_tree); - if (arg1_val == error_mark_node || arg1_len == error_mark_node) - return error_mark_node; - - Type* arg2_type = arg2->type(); - tree arg2_val; - tree arg2_len; - if (arg2_type->is_open_array_type()) - { - at = arg2_type->array_type(); - arg2_tree = save_expr(arg2_tree); - arg2_val = at->value_pointer_tree(gogo, arg2_tree); - arg2_len = at->length_tree(gogo, arg2_tree); - } - else - { - arg2_tree = save_expr(arg2_tree); - arg2_val = String_type::bytes_tree(gogo, arg2_tree); - arg2_len = String_type::length_tree(gogo, arg2_tree); - } - if (arg2_val == error_mark_node || arg2_len == error_mark_node) - return error_mark_node; - - arg1_len = save_expr(arg1_len); - arg2_len = save_expr(arg2_len); - tree len = fold_build3_loc(location, COND_EXPR, TREE_TYPE(arg1_len), - fold_build2_loc(location, LT_EXPR, - boolean_type_node, - arg1_len, arg2_len), - arg1_len, arg2_len); - len = save_expr(len); - - Type* element_type = at->element_type(); - tree element_type_tree = element_type->get_tree(gogo); - if (element_type_tree == error_mark_node) - return error_mark_node; - tree element_size = TYPE_SIZE_UNIT(element_type_tree); - tree bytecount = fold_convert_loc(location, TREE_TYPE(element_size), - len); - bytecount = fold_build2_loc(location, MULT_EXPR, - TREE_TYPE(element_size), - bytecount, element_size); - bytecount = fold_convert_loc(location, size_type_node, bytecount); - - arg1_val = fold_convert_loc(location, ptr_type_node, arg1_val); - arg2_val = fold_convert_loc(location, ptr_type_node, arg2_val); - - static tree copy_fndecl; - tree call = Gogo::call_builtin(©_fndecl, - location, - "__go_copy", - 3, - void_type_node, - ptr_type_node, - arg1_val, - ptr_type_node, - arg2_val, - size_type_node, - bytecount); - if (call == error_mark_node) - return error_mark_node; - - return fold_build2_loc(location, COMPOUND_EXPR, TREE_TYPE(len), - call, len); - } - - case BUILTIN_APPEND: - { - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 2); - Expression* arg1 = args->front(); - Expression* arg2 = args->back(); - - tree arg1_tree = arg1->get_tree(context); - tree arg2_tree = arg2->get_tree(context); - if (arg1_tree == error_mark_node || arg2_tree == error_mark_node) - return error_mark_node; - - Array_type* at = arg1->type()->array_type(); - Type* element_type = at->element_type(); - - arg2_tree = Expression::convert_for_assignment(context, at, - arg2->type(), - arg2_tree, - location); - if (arg2_tree == error_mark_node) - return error_mark_node; - - arg2_tree = save_expr(arg2_tree); - tree arg2_val = at->value_pointer_tree(gogo, arg2_tree); - tree arg2_len = at->length_tree(gogo, arg2_tree); - if (arg2_val == error_mark_node || arg2_len == error_mark_node) - return error_mark_node; - arg2_val = fold_convert_loc(location, ptr_type_node, arg2_val); - arg2_len = fold_convert_loc(location, size_type_node, arg2_len); - - tree element_type_tree = element_type->get_tree(gogo); - if (element_type_tree == error_mark_node) - return error_mark_node; - tree element_size = TYPE_SIZE_UNIT(element_type_tree); - element_size = fold_convert_loc(location, size_type_node, - element_size); - - // We rebuild the decl each time since the slice types may - // change. - tree append_fndecl = NULL_TREE; - return Gogo::call_builtin(&append_fndecl, - location, - "__go_append", - 4, - TREE_TYPE(arg1_tree), - TREE_TYPE(arg1_tree), - arg1_tree, - ptr_type_node, - arg2_val, - size_type_node, - arg2_len, - size_type_node, - element_size); - } - - case BUILTIN_REAL: - case BUILTIN_IMAG: - { - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 1); - Expression* arg = args->front(); - tree arg_tree = arg->get_tree(context); - if (arg_tree == error_mark_node) - return error_mark_node; - gcc_assert(COMPLEX_FLOAT_TYPE_P(TREE_TYPE(arg_tree))); - if (this->code_ == BUILTIN_REAL) - return fold_build1_loc(location, REALPART_EXPR, - TREE_TYPE(TREE_TYPE(arg_tree)), - arg_tree); - else - return fold_build1_loc(location, IMAGPART_EXPR, - TREE_TYPE(TREE_TYPE(arg_tree)), - arg_tree); - } - - case BUILTIN_COMPLEX: - { - const Expression_list* args = this->args(); - gcc_assert(args != NULL && args->size() == 2); - tree r = args->front()->get_tree(context); - tree i = args->back()->get_tree(context); - if (r == error_mark_node || i == error_mark_node) - return error_mark_node; - gcc_assert(TYPE_MAIN_VARIANT(TREE_TYPE(r)) - == TYPE_MAIN_VARIANT(TREE_TYPE(i))); - gcc_assert(SCALAR_FLOAT_TYPE_P(TREE_TYPE(r))); - return fold_build2_loc(location, COMPLEX_EXPR, - build_complex_type(TREE_TYPE(r)), - r, i); - } - - default: - gcc_unreachable(); - } -} - -// We have to support exporting a builtin call expression, because -// code can set a constant to the result of a builtin expression. - -void -Builtin_call_expression::do_export(Export* exp) const -{ - bool ok = false; - - mpz_t val; - mpz_init(val); - Type* dummy; - if (this->integer_constant_value(true, val, &dummy)) - { - Integer_expression::export_integer(exp, val); - ok = true; - } - mpz_clear(val); - - if (!ok) - { - mpfr_t fval; - mpfr_init(fval); - if (this->float_constant_value(fval, &dummy)) - { - Float_expression::export_float(exp, fval); - ok = true; - } - mpfr_clear(fval); - } - - if (!ok) - { - mpfr_t real; - mpfr_t imag; - mpfr_init(real); - mpfr_init(imag); - if (this->complex_constant_value(real, imag, &dummy)) - { - Complex_expression::export_complex(exp, real, imag); - ok = true; - } - mpfr_clear(real); - mpfr_clear(imag); - } - - if (!ok) - { - error_at(this->location(), "value is not constant"); - return; - } - - // A trailing space lets us reliably identify the end of the number. - exp->write_c_string(" "); -} - -// Class Call_expression. - -// Traversal. - -int -Call_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->args_ != NULL) - { - if (this->args_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lower a call statement. - -Expression* -Call_expression::do_lower(Gogo* gogo, Named_object* function, int) -{ - // A type case can look like a function call. - if (this->fn_->is_type_expression() - && this->args_ != NULL - && this->args_->size() == 1) - return Expression::make_cast(this->fn_->type(), this->args_->front(), - this->location()); - - // Recognize a call to a builtin function. - Func_expression* fne = this->fn_->func_expression(); - if (fne != NULL - && fne->named_object()->is_function_declaration() - && fne->named_object()->func_declaration_value()->type()->is_builtin()) - return new Builtin_call_expression(gogo, this->fn_, this->args_, - this->is_varargs_, this->location()); - - // Handle an argument which is a call to a function which returns - // multiple results. - if (this->args_ != NULL - && this->args_->size() == 1 - && this->args_->front()->call_expression() != NULL - && this->fn_->type()->function_type() != NULL) - { - Function_type* fntype = this->fn_->type()->function_type(); - size_t rc = this->args_->front()->call_expression()->result_count(); - if (rc > 1 - && fntype->parameters() != NULL - && (fntype->parameters()->size() == rc - || (fntype->is_varargs() - && fntype->parameters()->size() - 1 <= rc))) - { - Call_expression* call = this->args_->front()->call_expression(); - Expression_list* args = new Expression_list; - for (size_t i = 0; i < rc; ++i) - args->push_back(Expression::make_call_result(call, i)); - // We can't return a new call expression here, because this - // one may be referenced by Call_result expressions. We - // also can't delete the old arguments, because we may still - // traverse them somewhere up the call stack. FIXME. - this->args_ = args; - } - } - - // Handle a call to a varargs function by packaging up the extra - // parameters. - if (this->fn_->type()->function_type() != NULL - && this->fn_->type()->function_type()->is_varargs()) - { - Function_type* fntype = this->fn_->type()->function_type(); - const Typed_identifier_list* parameters = fntype->parameters(); - gcc_assert(parameters != NULL && !parameters->empty()); - Type* varargs_type = parameters->back().type(); - return this->lower_varargs(gogo, function, varargs_type, - parameters->size()); - } - - return this; -} - -// Lower a call to a varargs function. FUNCTION is the function in -// which the call occurs--it's not the function we are calling. -// VARARGS_TYPE is the type of the varargs parameter, a slice type. -// PARAM_COUNT is the number of parameters of the function we are -// calling; the last of these parameters will be the varargs -// parameter. - -Expression* -Call_expression::lower_varargs(Gogo* gogo, Named_object* function, - Type* varargs_type, size_t param_count) -{ - if (this->varargs_are_lowered_) - return this; - - source_location loc = this->location(); - - gcc_assert(param_count > 0); - gcc_assert(varargs_type->is_open_array_type()); - - size_t arg_count = this->args_ == NULL ? 0 : this->args_->size(); - if (arg_count < param_count - 1) - { - // Not enough arguments; will be caught in check_types. - return this; - } - - Expression_list* old_args = this->args_; - Expression_list* new_args = new Expression_list(); - bool push_empty_arg = false; - if (old_args == NULL || old_args->empty()) - { - gcc_assert(param_count == 1); - push_empty_arg = true; - } - else - { - Expression_list::const_iterator pa; - int i = 1; - for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i) - { - if (static_cast(i) == param_count) - break; - new_args->push_back(*pa); - } - - // We have reached the varargs parameter. - - bool issued_error = false; - if (pa == old_args->end()) - push_empty_arg = true; - else if (pa + 1 == old_args->end() && this->is_varargs_) - new_args->push_back(*pa); - else if (this->is_varargs_) - { - this->report_error(_("too many arguments")); - return this; - } - else - { - Type* element_type = varargs_type->array_type()->element_type(); - Expression_list* vals = new Expression_list; - for (; pa != old_args->end(); ++pa, ++i) - { - // Check types here so that we get a better message. - Type* patype = (*pa)->type(); - source_location paloc = (*pa)->location(); - if (!this->check_argument_type(i, element_type, patype, - paloc, issued_error)) - continue; - vals->push_back(*pa); - } - Expression* val = - Expression::make_slice_composite_literal(varargs_type, vals, loc); - new_args->push_back(val); - } - } - - if (push_empty_arg) - new_args->push_back(Expression::make_nil(loc)); - - // We can't return a new call expression here, because this one may - // be referenced by Call_result expressions. FIXME. - if (old_args != NULL) - delete old_args; - this->args_ = new_args; - this->varargs_are_lowered_ = true; - - // Lower all the new subexpressions. - Expression* ret = this; - gogo->lower_expression(function, &ret); - gcc_assert(ret == this); - return ret; -} - -// Get the function type. Returns NULL if we don't know the type. If -// this returns NULL, and if_ERROR is true, issues an error. - -Function_type* -Call_expression::get_function_type() const -{ - return this->fn_->type()->function_type(); -} - -// Return the number of values which this call will return. - -size_t -Call_expression::result_count() const -{ - const Function_type* fntype = this->get_function_type(); - if (fntype == NULL) - return 0; - if (fntype->results() == NULL) - return 0; - return fntype->results()->size(); -} - -// Return whether this is a call to the predeclared function recover. - -bool -Call_expression::is_recover_call() const -{ - return this->do_is_recover_call(); -} - -// Set the argument to the recover function. - -void -Call_expression::set_recover_arg(Expression* arg) -{ - this->do_set_recover_arg(arg); -} - -// Virtual functions also implemented by Builtin_call_expression. - -bool -Call_expression::do_is_recover_call() const -{ - return false; -} - -void -Call_expression::do_set_recover_arg(Expression*) -{ - gcc_unreachable(); -} - -// Get the type. - -Type* -Call_expression::do_type() -{ - if (this->type_ != NULL) - return this->type_; - - Type* ret; - Function_type* fntype = this->get_function_type(); - if (fntype == NULL) - return Type::make_error_type(); - - const Typed_identifier_list* results = fntype->results(); - if (results == NULL) - ret = Type::make_void_type(); - else if (results->size() == 1) - ret = results->begin()->type(); - else - ret = Type::make_call_multiple_result_type(this); - - this->type_ = ret; - - return this->type_; -} - -// Determine types for a call expression. We can use the function -// parameter types to set the types of the arguments. - -void -Call_expression::do_determine_type(const Type_context*) -{ - if (!this->determining_types()) - return; - - this->fn_->determine_type_no_context(); - Function_type* fntype = this->get_function_type(); - const Typed_identifier_list* parameters = NULL; - if (fntype != NULL) - parameters = fntype->parameters(); - if (this->args_ != NULL) - { - Typed_identifier_list::const_iterator pt; - if (parameters != NULL) - pt = parameters->begin(); - for (Expression_list::const_iterator pa = this->args_->begin(); - pa != this->args_->end(); - ++pa) - { - if (parameters != NULL && pt != parameters->end()) - { - Type_context subcontext(pt->type(), false); - (*pa)->determine_type(&subcontext); - ++pt; - } - else - (*pa)->determine_type_no_context(); - } - } -} - -// Called when determining types for a Call_expression. Return true -// if we should go ahead, false if they have already been determined. - -bool -Call_expression::determining_types() -{ - if (this->types_are_determined_) - return false; - else - { - this->types_are_determined_ = true; - return true; - } -} - -// Check types for parameter I. - -bool -Call_expression::check_argument_type(int i, const Type* parameter_type, - const Type* argument_type, - source_location argument_location, - bool issued_error) -{ - std::string reason; - if (!Type::are_assignable(parameter_type, argument_type, &reason)) - { - if (!issued_error) - { - if (reason.empty()) - error_at(argument_location, "argument %d has incompatible type", i); - else - error_at(argument_location, - "argument %d has incompatible type (%s)", - i, reason.c_str()); - } - this->set_is_error(); - return false; - } - return true; -} - -// Check types. - -void -Call_expression::do_check_types(Gogo*) -{ - Function_type* fntype = this->get_function_type(); - if (fntype == NULL) - { - if (!this->fn_->type()->is_error_type()) - this->report_error(_("expected function")); - return; - } - - if (fntype->is_method()) - { - // We don't support pointers to methods, so the function has to - // be a bound method expression. - Bound_method_expression* bme = this->fn_->bound_method_expression(); - if (bme == NULL) - { - this->report_error(_("method call without object")); - return; - } - Type* first_arg_type = bme->first_argument()->type(); - if (first_arg_type->points_to() == NULL) - { - // When passing a value, we need to check that we are - // permitted to copy it. - std::string reason; - if (!Type::are_assignable(fntype->receiver()->type(), - first_arg_type, &reason)) - { - if (reason.empty()) - this->report_error(_("incompatible type for receiver")); - else - { - error_at(this->location(), - "incompatible type for receiver (%s)", - reason.c_str()); - this->set_is_error(); - } - } - } - } - - // Note that varargs was handled by the lower_varargs() method, so - // we don't have to worry about it here. - - const Typed_identifier_list* parameters = fntype->parameters(); - if (this->args_ == NULL) - { - if (parameters != NULL && !parameters->empty()) - this->report_error(_("not enough arguments")); - } - else if (parameters == NULL) - this->report_error(_("too many arguments")); - else - { - int i = 0; - Typed_identifier_list::const_iterator pt = parameters->begin(); - for (Expression_list::const_iterator pa = this->args_->begin(); - pa != this->args_->end(); - ++pa, ++pt, ++i) - { - if (pt == parameters->end()) - { - this->report_error(_("too many arguments")); - return; - } - this->check_argument_type(i + 1, pt->type(), (*pa)->type(), - (*pa)->location(), false); - } - if (pt != parameters->end()) - this->report_error(_("not enough arguments")); - } -} - -// Return whether we have to use a temporary variable to ensure that -// we evaluate this call expression in order. If the call returns no -// results then it will inevitably be executed last. If the call -// returns more than one result then it will be used with Call_result -// expressions. So we only have to use a temporary variable if the -// call returns exactly one result. - -bool -Call_expression::do_must_eval_in_order() const -{ - return this->result_count() == 1; -} - -// Get the function and the first argument to use when calling a bound -// method. - -tree -Call_expression::bound_method_function(Translate_context* context, - Bound_method_expression* bound_method, - tree* first_arg_ptr) -{ - Expression* first_argument = bound_method->first_argument(); - tree first_arg = first_argument->get_tree(context); - if (first_arg == error_mark_node) - return error_mark_node; - - // We always pass a pointer to the first argument when calling a - // method. - if (first_argument->type()->points_to() == NULL) - { - tree pointer_to_arg_type = build_pointer_type(TREE_TYPE(first_arg)); - if (TREE_ADDRESSABLE(TREE_TYPE(first_arg)) - || DECL_P(first_arg) - || TREE_CODE(first_arg) == INDIRECT_REF - || TREE_CODE(first_arg) == COMPONENT_REF) - { - first_arg = build_fold_addr_expr(first_arg); - if (DECL_P(first_arg)) - TREE_ADDRESSABLE(first_arg) = 1; - } - else - { - tree tmp = create_tmp_var(TREE_TYPE(first_arg), - get_name(first_arg)); - DECL_IGNORED_P(tmp) = 0; - DECL_INITIAL(tmp) = first_arg; - first_arg = build2(COMPOUND_EXPR, pointer_to_arg_type, - build1(DECL_EXPR, void_type_node, tmp), - build_fold_addr_expr(tmp)); - TREE_ADDRESSABLE(tmp) = 1; - } - if (first_arg == error_mark_node) - return error_mark_node; - } - - Type* fatype = bound_method->first_argument_type(); - if (fatype != NULL) - { - if (fatype->points_to() == NULL) - fatype = Type::make_pointer_type(fatype); - first_arg = fold_convert(fatype->get_tree(context->gogo()), first_arg); - if (first_arg == error_mark_node - || TREE_TYPE(first_arg) == error_mark_node) - return error_mark_node; - } - - *first_arg_ptr = first_arg; - - return bound_method->method()->get_tree(context); -} - -// Get the function and the first argument to use when calling an -// interface method. - -tree -Call_expression::interface_method_function( - Translate_context* context, - Interface_field_reference_expression* interface_method, - tree* first_arg_ptr) -{ - tree expr = interface_method->expr()->get_tree(context); - if (expr == error_mark_node) - return error_mark_node; - expr = save_expr(expr); - tree first_arg = interface_method->get_underlying_object_tree(context, expr); - if (first_arg == error_mark_node) - return error_mark_node; - *first_arg_ptr = first_arg; - return interface_method->get_function_tree(context, expr); -} - -// Build the call expression. - -tree -Call_expression::do_get_tree(Translate_context* context) -{ - if (this->tree_ != NULL_TREE) - return this->tree_; - - Function_type* fntype = this->get_function_type(); - if (fntype == NULL) - return error_mark_node; - - if (this->fn_->is_error_expression()) - return error_mark_node; - - Gogo* gogo = context->gogo(); - source_location location = this->location(); - - Func_expression* func = this->fn_->func_expression(); - Bound_method_expression* bound_method = this->fn_->bound_method_expression(); - Interface_field_reference_expression* interface_method = - this->fn_->interface_field_reference_expression(); - const bool has_closure = func != NULL && func->closure() != NULL; - const bool is_method = bound_method != NULL || interface_method != NULL; - gcc_assert(!fntype->is_method() || is_method); - - int nargs; - tree* args; - if (this->args_ == NULL || this->args_->empty()) - { - nargs = is_method ? 1 : 0; - args = nargs == 0 ? NULL : new tree[nargs]; - } - else - { - const Typed_identifier_list* params = fntype->parameters(); - gcc_assert(params != NULL); - - nargs = this->args_->size(); - int i = is_method ? 1 : 0; - nargs += i; - args = new tree[nargs]; - - Typed_identifier_list::const_iterator pp = params->begin(); - Expression_list::const_iterator pe; - for (pe = this->args_->begin(); - pe != this->args_->end(); - ++pe, ++pp, ++i) - { - gcc_assert(pp != params->end()); - tree arg_val = (*pe)->get_tree(context); - args[i] = Expression::convert_for_assignment(context, - pp->type(), - (*pe)->type(), - arg_val, - location); - if (args[i] == error_mark_node) - { - delete[] args; - return error_mark_node; - } - } - gcc_assert(pp == params->end()); - gcc_assert(i == nargs); - } - - tree rettype = TREE_TYPE(TREE_TYPE(fntype->get_tree(gogo))); - if (rettype == error_mark_node) - { - delete[] args; - return error_mark_node; - } - - tree fn; - if (has_closure) - fn = func->get_tree_without_closure(gogo); - else if (!is_method) - fn = this->fn_->get_tree(context); - else if (bound_method != NULL) - fn = this->bound_method_function(context, bound_method, &args[0]); - else if (interface_method != NULL) - fn = this->interface_method_function(context, interface_method, &args[0]); - else - gcc_unreachable(); - - if (fn == error_mark_node || TREE_TYPE(fn) == error_mark_node) - { - delete[] args; - return error_mark_node; - } - - tree fndecl = fn; - if (TREE_CODE(fndecl) == ADDR_EXPR) - fndecl = TREE_OPERAND(fndecl, 0); - - // Add a type cast in case the type of the function is a recursive - // type which refers to itself. - if (!DECL_P(fndecl) || !DECL_IS_BUILTIN(fndecl)) - { - tree fnt = fntype->get_tree(gogo); - if (fnt == error_mark_node) - return error_mark_node; - fn = fold_convert_loc(location, fnt, fn); - } - - // This is to support builtin math functions when using 80387 math. - tree excess_type = NULL_TREE; - if (DECL_P(fndecl) - && DECL_IS_BUILTIN(fndecl) - && DECL_BUILT_IN_CLASS(fndecl) == BUILT_IN_NORMAL - && nargs > 0 - && ((SCALAR_FLOAT_TYPE_P(rettype) - && SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[0]))) - || (COMPLEX_FLOAT_TYPE_P(rettype) - && COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[0]))))) - { - excess_type = excess_precision_type(TREE_TYPE(args[0])); - if (excess_type != NULL_TREE) - { - tree excess_fndecl = mathfn_built_in(excess_type, - DECL_FUNCTION_CODE(fndecl)); - if (excess_fndecl == NULL_TREE) - excess_type = NULL_TREE; - else - { - fn = build_fold_addr_expr_loc(location, excess_fndecl); - for (int i = 0; i < nargs; ++i) - args[i] = ::convert(excess_type, args[i]); - } - } - } - - tree ret = build_call_array(excess_type != NULL_TREE ? excess_type : rettype, - fn, nargs, args); - delete[] args; - - SET_EXPR_LOCATION(ret, location); - - if (has_closure) - { - tree closure_tree = func->closure()->get_tree(context); - if (closure_tree != error_mark_node) - CALL_EXPR_STATIC_CHAIN(ret) = closure_tree; - } - - // If this is a recursive function type which returns itself, as in - // type F func() F - // we have used ptr_type_node for the return type. Add a cast here - // to the correct type. - if (TREE_TYPE(ret) == ptr_type_node) - { - tree t = this->type()->base()->get_tree(gogo); - ret = fold_convert_loc(location, t, ret); - } - - if (excess_type != NULL_TREE) - { - // Calling convert here can undo our excess precision change. - // That may or may not be a bug in convert_to_real. - ret = build1(NOP_EXPR, rettype, ret); - } - - // If there is more than one result, we will refer to the call - // multiple times. - if (fntype->results() != NULL && fntype->results()->size() > 1) - ret = save_expr(ret); - - this->tree_ = ret; - - return ret; -} - -// Make a call expression. - -Call_expression* -Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs, - source_location location) -{ - return new Call_expression(fn, args, is_varargs, location); -} - -// A single result from a call which returns multiple results. - -class Call_result_expression : public Expression -{ - public: - Call_result_expression(Call_expression* call, unsigned int index) - : Expression(EXPRESSION_CALL_RESULT, call->location()), - call_(call), index_(index) - { } - - protected: - int - do_traverse(Traverse*); - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Call_result_expression(this->call_->call_expression(), - this->index_); - } - - bool - do_must_eval_in_order() const - { return true; } - - tree - do_get_tree(Translate_context*); - - private: - // The underlying call expression. - Expression* call_; - // Which result we want. - unsigned int index_; -}; - -// Traverse a call result. - -int -Call_result_expression::do_traverse(Traverse* traverse) -{ - if (traverse->remember_expression(this->call_)) - { - // We have already traversed the call expression. - return TRAVERSE_CONTINUE; - } - return Expression::traverse(&this->call_, traverse); -} - -// Get the type. - -Type* -Call_result_expression::do_type() -{ - if (this->classification() == EXPRESSION_ERROR) - return Type::make_error_type(); - - // THIS->CALL_ can be replaced with a temporary reference due to - // Call_expression::do_must_eval_in_order when there is an error. - Call_expression* ce = this->call_->call_expression(); - if (ce == NULL) - { - this->set_is_error(); - return Type::make_error_type(); - } - Function_type* fntype = ce->get_function_type(); - if (fntype == NULL) - { - this->set_is_error(); - return Type::make_error_type(); - } - const Typed_identifier_list* results = fntype->results(); - if (results == NULL) - { - this->report_error(_("number of results does not match " - "number of values")); - return Type::make_error_type(); - } - Typed_identifier_list::const_iterator pr = results->begin(); - for (unsigned int i = 0; i < this->index_; ++i) - { - if (pr == results->end()) - break; - ++pr; - } - if (pr == results->end()) - { - this->report_error(_("number of results does not match " - "number of values")); - return Type::make_error_type(); - } - return pr->type(); -} - -// Check the type. Just make sure that we trigger the warning in -// do_type. - -void -Call_result_expression::do_check_types(Gogo*) -{ - this->type(); -} - -// Determine the type. We have nothing to do here, but the 0 result -// needs to pass down to the caller. - -void -Call_result_expression::do_determine_type(const Type_context*) -{ - this->call_->determine_type_no_context(); -} - -// Return the tree. - -tree -Call_result_expression::do_get_tree(Translate_context* context) -{ - tree call_tree = this->call_->get_tree(context); - if (call_tree == error_mark_node) - return error_mark_node; - if (TREE_CODE(TREE_TYPE(call_tree)) != RECORD_TYPE) - { - gcc_assert(saw_errors()); - return error_mark_node; - } - tree field = TYPE_FIELDS(TREE_TYPE(call_tree)); - for (unsigned int i = 0; i < this->index_; ++i) - { - gcc_assert(field != NULL_TREE); - field = DECL_CHAIN(field); - } - gcc_assert(field != NULL_TREE); - return build3(COMPONENT_REF, TREE_TYPE(field), call_tree, field, NULL_TREE); -} - -// Make a reference to a single result of a call which returns -// multiple results. - -Expression* -Expression::make_call_result(Call_expression* call, unsigned int index) -{ - return new Call_result_expression(call, index); -} - -// Class Index_expression. - -// Traversal. - -int -Index_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT - || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT - || (this->end_ != NULL - && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Lower an index expression. This converts the generic index -// expression into an array index, a string index, or a map index. - -Expression* -Index_expression::do_lower(Gogo*, Named_object*, int) -{ - source_location location = this->location(); - Expression* left = this->left_; - Expression* start = this->start_; - Expression* end = this->end_; - - Type* type = left->type(); - if (type->is_error_type()) - return Expression::make_error(location); - else if (left->is_type_expression()) - { - error_at(location, "attempt to index type expression"); - return Expression::make_error(location); - } - else if (type->array_type() != NULL) - return Expression::make_array_index(left, start, end, location); - else if (type->points_to() != NULL - && type->points_to()->array_type() != NULL - && !type->points_to()->is_open_array_type()) - { - Expression* deref = Expression::make_unary(OPERATOR_MULT, left, - location); - return Expression::make_array_index(deref, start, end, location); - } - else if (type->is_string_type()) - return Expression::make_string_index(left, start, end, location); - else if (type->map_type() != NULL) - { - if (end != NULL) - { - error_at(location, "invalid slice of map"); - return Expression::make_error(location); - } - Map_index_expression* ret= Expression::make_map_index(left, start, - location); - if (this->is_lvalue_) - ret->set_is_lvalue(); - return ret; - } - else - { - error_at(location, - "attempt to index object which is not array, string, or map"); - return Expression::make_error(location); - } -} - -// Make an index expression. - -Expression* -Expression::make_index(Expression* left, Expression* start, Expression* end, - source_location location) -{ - return new Index_expression(left, start, end, location); -} - -// An array index. This is used for both indexing and slicing. - -class Array_index_expression : public Expression -{ - public: - Array_index_expression(Expression* array, Expression* start, - Expression* end, source_location location) - : Expression(EXPRESSION_ARRAY_INDEX, location), - array_(array), start_(start), end_(end), type_(NULL) - { } - - protected: - int - do_traverse(Traverse*); - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return Expression::make_array_index(this->array_->copy(), - this->start_->copy(), - (this->end_ == NULL - ? NULL - : this->end_->copy()), - this->location()); - } - - bool - do_is_addressable() const; - - void - do_address_taken(bool escapes) - { this->array_->address_taken(escapes); } - - tree - do_get_tree(Translate_context*); - - private: - // The array we are getting a value from. - Expression* array_; - // The start or only index. - Expression* start_; - // The end index of a slice. This may be NULL for a simple array - // index, or it may be a nil expression for the length of the array. - Expression* end_; - // The type of the expression. - Type* type_; -}; - -// Array index traversal. - -int -Array_index_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->end_ != NULL) - { - if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Return the type of an array index. - -Type* -Array_index_expression::do_type() -{ - if (this->type_ == NULL) - { - Array_type* type = this->array_->type()->array_type(); - if (type == NULL) - this->type_ = Type::make_error_type(); - else if (this->end_ == NULL) - this->type_ = type->element_type(); - else if (type->is_open_array_type()) - { - // A slice of a slice has the same type as the original - // slice. - this->type_ = this->array_->type()->deref(); - } - else - { - // A slice of an array is a slice. - this->type_ = Type::make_array_type(type->element_type(), NULL); - } - } - return this->type_; -} - -// Set the type of an array index. - -void -Array_index_expression::do_determine_type(const Type_context*) -{ - this->array_->determine_type_no_context(); - this->start_->determine_type_no_context(); - if (this->end_ != NULL) - this->end_->determine_type_no_context(); -} - -// Check types of an array index. - -void -Array_index_expression::do_check_types(Gogo*) -{ - if (this->start_->type()->integer_type() == NULL) - this->report_error(_("index must be integer")); - if (this->end_ != NULL - && this->end_->type()->integer_type() == NULL - && !this->end_->is_nil_expression()) - this->report_error(_("slice end must be integer")); - - Array_type* array_type = this->array_->type()->array_type(); - if (array_type == NULL) - { - gcc_assert(this->array_->type()->is_error_type()); - return; - } - - unsigned int int_bits = - Type::lookup_integer_type("int")->integer_type()->bits(); - - Type* dummy; - mpz_t lval; - mpz_init(lval); - bool lval_valid = (array_type->length() != NULL - && array_type->length()->integer_constant_value(true, - lval, - &dummy)); - mpz_t ival; - mpz_init(ival); - if (this->start_->integer_constant_value(true, ival, &dummy)) - { - if (mpz_sgn(ival) < 0 - || mpz_sizeinbase(ival, 2) >= int_bits - || (lval_valid - && (this->end_ == NULL - ? mpz_cmp(ival, lval) >= 0 - : mpz_cmp(ival, lval) > 0))) - { - error_at(this->start_->location(), "array index out of bounds"); - this->set_is_error(); - } - } - if (this->end_ != NULL && !this->end_->is_nil_expression()) - { - if (this->end_->integer_constant_value(true, ival, &dummy)) - { - if (mpz_sgn(ival) < 0 - || mpz_sizeinbase(ival, 2) >= int_bits - || (lval_valid && mpz_cmp(ival, lval) > 0)) - { - error_at(this->end_->location(), "array index out of bounds"); - this->set_is_error(); - } - } - } - mpz_clear(ival); - mpz_clear(lval); - - // A slice of an array requires an addressable array. A slice of a - // slice is always possible. - if (this->end_ != NULL - && !array_type->is_open_array_type() - && !this->array_->is_addressable()) - this->report_error(_("array is not addressable")); -} - -// Return whether this expression is addressable. - -bool -Array_index_expression::do_is_addressable() const -{ - // A slice expression is not addressable. - if (this->end_ != NULL) - return false; - - // An index into a slice is addressable. - if (this->array_->type()->is_open_array_type()) - return true; - - // An index into an array is addressable if the array is - // addressable. - return this->array_->is_addressable(); -} - -// Get a tree for an array index. - -tree -Array_index_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - source_location loc = this->location(); - - Array_type* array_type = this->array_->type()->array_type(); - if (array_type == NULL) - { - gcc_assert(this->array_->type()->is_error_type()); - return error_mark_node; - } - - tree type_tree = array_type->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - - tree array_tree = this->array_->get_tree(context); - if (array_tree == error_mark_node) - return error_mark_node; - - if (array_type->length() == NULL && !DECL_P(array_tree)) - array_tree = save_expr(array_tree); - tree length_tree = array_type->length_tree(gogo, array_tree); - if (length_tree == error_mark_node) - return error_mark_node; - length_tree = save_expr(length_tree); - tree length_type = TREE_TYPE(length_tree); - - tree bad_index = boolean_false_node; - - tree start_tree = this->start_->get_tree(context); - if (start_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(start_tree)) - start_tree = save_expr(start_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree))) - start_tree = convert_to_integer(length_type, start_tree); - - bad_index = Expression::check_bounds(start_tree, length_type, bad_index, - loc); - - start_tree = fold_convert_loc(loc, length_type, start_tree); - bad_index = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, bad_index, - fold_build2_loc(loc, - (this->end_ == NULL - ? GE_EXPR - : GT_EXPR), - boolean_type_node, start_tree, - length_tree)); - - int code = (array_type->length() != NULL - ? (this->end_ == NULL - ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS - : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS) - : (this->end_ == NULL - ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS - : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS)); - tree crash = Gogo::runtime_error(code, loc); - - if (this->end_ == NULL) - { - // Simple array indexing. This has to return an l-value, so - // wrap the index check into START_TREE. - start_tree = build2(COMPOUND_EXPR, TREE_TYPE(start_tree), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - start_tree); - start_tree = fold_convert_loc(loc, sizetype, start_tree); - - if (array_type->length() != NULL) - { - // Fixed array. - return build4(ARRAY_REF, TREE_TYPE(type_tree), array_tree, - start_tree, NULL_TREE, NULL_TREE); - } - else - { - // Open array. - tree values = array_type->value_pointer_tree(gogo, array_tree); - tree element_type_tree = array_type->element_type()->get_tree(gogo); - if (element_type_tree == error_mark_node) - return error_mark_node; - tree element_size = TYPE_SIZE_UNIT(element_type_tree); - tree offset = fold_build2_loc(loc, MULT_EXPR, sizetype, - start_tree, element_size); - tree ptr = fold_build2_loc(loc, POINTER_PLUS_EXPR, - TREE_TYPE(values), values, offset); - return build_fold_indirect_ref(ptr); - } - } - - // Array slice. - - tree capacity_tree = array_type->capacity_tree(gogo, array_tree); - if (capacity_tree == error_mark_node) - return error_mark_node; - capacity_tree = fold_convert_loc(loc, length_type, capacity_tree); - - tree end_tree; - if (this->end_->is_nil_expression()) - end_tree = length_tree; - else - { - end_tree = this->end_->get_tree(context); - if (end_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(end_tree)) - end_tree = save_expr(end_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree))) - end_tree = convert_to_integer(length_type, end_tree); - - bad_index = Expression::check_bounds(end_tree, length_type, bad_index, - loc); - - end_tree = fold_convert_loc(loc, length_type, end_tree); - - capacity_tree = save_expr(capacity_tree); - tree bad_end = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - fold_build2_loc(loc, LT_EXPR, - boolean_type_node, - end_tree, start_tree), - fold_build2_loc(loc, GT_EXPR, - boolean_type_node, - end_tree, capacity_tree)); - bad_index = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - bad_index, bad_end); - } - - tree element_type_tree = array_type->element_type()->get_tree(gogo); - if (element_type_tree == error_mark_node) - return error_mark_node; - tree element_size = TYPE_SIZE_UNIT(element_type_tree); - - tree offset = fold_build2_loc(loc, MULT_EXPR, sizetype, - fold_convert_loc(loc, sizetype, start_tree), - element_size); - - tree value_pointer = array_type->value_pointer_tree(gogo, array_tree); - if (value_pointer == error_mark_node) - return error_mark_node; - - value_pointer = fold_build2_loc(loc, POINTER_PLUS_EXPR, - TREE_TYPE(value_pointer), - value_pointer, offset); - - tree result_length_tree = fold_build2_loc(loc, MINUS_EXPR, length_type, - end_tree, start_tree); - - tree result_capacity_tree = fold_build2_loc(loc, MINUS_EXPR, length_type, - capacity_tree, start_tree); - - tree struct_tree = this->type()->get_tree(gogo); - gcc_assert(TREE_CODE(struct_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(struct_tree); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0); - elt->index = field; - elt->value = value_pointer; - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0); - elt->index = field; - elt->value = fold_convert_loc(loc, TREE_TYPE(field), result_length_tree); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0); - elt->index = field; - elt->value = fold_convert_loc(loc, TREE_TYPE(field), result_capacity_tree); - - tree constructor = build_constructor(struct_tree, init); - - if (TREE_CONSTANT(value_pointer) - && TREE_CONSTANT(result_length_tree) - && TREE_CONSTANT(result_capacity_tree)) - TREE_CONSTANT(constructor) = 1; - - return fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(constructor), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - constructor); -} - -// Make an array index expression. END may be NULL. - -Expression* -Expression::make_array_index(Expression* array, Expression* start, - Expression* end, source_location location) -{ - // Taking a slice of a composite literal requires moving the literal - // onto the heap. - if (end != NULL && array->is_composite_literal()) - { - array = Expression::make_heap_composite(array, location); - array = Expression::make_unary(OPERATOR_MULT, array, location); - } - return new Array_index_expression(array, start, end, location); -} - -// A string index. This is used for both indexing and slicing. - -class String_index_expression : public Expression -{ - public: - String_index_expression(Expression* string, Expression* start, - Expression* end, source_location location) - : Expression(EXPRESSION_STRING_INDEX, location), - string_(string), start_(start), end_(end) - { } - - protected: - int - do_traverse(Traverse*); - - Type* - do_type(); - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return Expression::make_string_index(this->string_->copy(), - this->start_->copy(), - (this->end_ == NULL - ? NULL - : this->end_->copy()), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - private: - // The string we are getting a value from. - Expression* string_; - // The start or only index. - Expression* start_; - // The end index of a slice. This may be NULL for a single index, - // or it may be a nil expression for the length of the string. - Expression* end_; -}; - -// String index traversal. - -int -String_index_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->end_ != NULL) - { - if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Return the type of a string index. - -Type* -String_index_expression::do_type() -{ - if (this->end_ == NULL) - return Type::lookup_integer_type("uint8"); - else - return this->string_->type(); -} - -// Determine the type of a string index. - -void -String_index_expression::do_determine_type(const Type_context*) -{ - this->string_->determine_type_no_context(); - this->start_->determine_type_no_context(); - if (this->end_ != NULL) - this->end_->determine_type_no_context(); -} - -// Check types of a string index. - -void -String_index_expression::do_check_types(Gogo*) -{ - if (this->start_->type()->integer_type() == NULL) - this->report_error(_("index must be integer")); - if (this->end_ != NULL - && this->end_->type()->integer_type() == NULL - && !this->end_->is_nil_expression()) - this->report_error(_("slice end must be integer")); - - std::string sval; - bool sval_valid = this->string_->string_constant_value(&sval); - - mpz_t ival; - mpz_init(ival); - Type* dummy; - if (this->start_->integer_constant_value(true, ival, &dummy)) - { - if (mpz_sgn(ival) < 0 - || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0)) - { - error_at(this->start_->location(), "string index out of bounds"); - this->set_is_error(); - } - } - if (this->end_ != NULL && !this->end_->is_nil_expression()) - { - if (this->end_->integer_constant_value(true, ival, &dummy)) - { - if (mpz_sgn(ival) < 0 - || (sval_valid && mpz_cmp_ui(ival, sval.length()) > 0)) - { - error_at(this->end_->location(), "string index out of bounds"); - this->set_is_error(); - } - } - } - mpz_clear(ival); -} - -// Get a tree for a string index. - -tree -String_index_expression::do_get_tree(Translate_context* context) -{ - source_location loc = this->location(); - - tree string_tree = this->string_->get_tree(context); - if (string_tree == error_mark_node) - return error_mark_node; - - if (this->string_->type()->points_to() != NULL) - string_tree = build_fold_indirect_ref(string_tree); - if (!DECL_P(string_tree)) - string_tree = save_expr(string_tree); - tree string_type = TREE_TYPE(string_tree); - - tree length_tree = String_type::length_tree(context->gogo(), string_tree); - length_tree = save_expr(length_tree); - tree length_type = TREE_TYPE(length_tree); - - tree bad_index = boolean_false_node; - - tree start_tree = this->start_->get_tree(context); - if (start_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(start_tree)) - start_tree = save_expr(start_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree))) - start_tree = convert_to_integer(length_type, start_tree); - - bad_index = Expression::check_bounds(start_tree, length_type, bad_index, - loc); - - start_tree = fold_convert_loc(loc, length_type, start_tree); - - int code = (this->end_ == NULL - ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS - : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS); - tree crash = Gogo::runtime_error(code, loc); - - if (this->end_ == NULL) - { - bad_index = fold_build2_loc(loc, TRUTH_OR_EXPR, boolean_type_node, - bad_index, - fold_build2_loc(loc, GE_EXPR, - boolean_type_node, - start_tree, length_tree)); - - tree bytes_tree = String_type::bytes_tree(context->gogo(), string_tree); - tree ptr = fold_build2_loc(loc, POINTER_PLUS_EXPR, TREE_TYPE(bytes_tree), - bytes_tree, - fold_convert_loc(loc, sizetype, start_tree)); - tree index = build_fold_indirect_ref_loc(loc, ptr); - - return build2(COMPOUND_EXPR, TREE_TYPE(index), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - index); - } - else - { - tree end_tree; - if (this->end_->is_nil_expression()) - end_tree = build_int_cst(length_type, -1); - else - { - end_tree = this->end_->get_tree(context); - if (end_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(end_tree)) - end_tree = save_expr(end_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree))) - end_tree = convert_to_integer(length_type, end_tree); - - bad_index = Expression::check_bounds(end_tree, length_type, - bad_index, loc); - - end_tree = fold_convert_loc(loc, length_type, end_tree); - } - - static tree strslice_fndecl; - tree ret = Gogo::call_builtin(&strslice_fndecl, - loc, - "__go_string_slice", - 3, - string_type, - string_type, - string_tree, - length_type, - start_tree, - length_type, - end_tree); - if (ret == error_mark_node) - return error_mark_node; - // This will panic if the bounds are out of range for the - // string. - TREE_NOTHROW(strslice_fndecl) = 0; - - if (bad_index == boolean_false_node) - return ret; - else - return build2(COMPOUND_EXPR, TREE_TYPE(ret), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - ret); - } -} - -// Make a string index expression. END may be NULL. - -Expression* -Expression::make_string_index(Expression* string, Expression* start, - Expression* end, source_location location) -{ - return new String_index_expression(string, start, end, location); -} - -// Class Map_index. - -// Get the type of the map. - -Map_type* -Map_index_expression::get_map_type() const -{ - Map_type* mt = this->map_->type()->deref()->map_type(); - if (mt == NULL) - gcc_assert(saw_errors()); - return mt; -} - -// Map index traversal. - -int -Map_index_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return Expression::traverse(&this->index_, traverse); -} - -// Return the type of a map index. - -Type* -Map_index_expression::do_type() -{ - Map_type* mt = this->get_map_type(); - if (mt == NULL) - return Type::make_error_type(); - Type* type = mt->val_type(); - // If this map index is in a tuple assignment, we actually return a - // pointer to the value type. Tuple_map_assignment_statement is - // responsible for handling this correctly. We need to get the type - // right in case this gets assigned to a temporary variable. - if (this->is_in_tuple_assignment_) - type = Type::make_pointer_type(type); - return type; -} - -// Fix the type of a map index. - -void -Map_index_expression::do_determine_type(const Type_context*) -{ - this->map_->determine_type_no_context(); - Map_type* mt = this->get_map_type(); - Type* key_type = mt == NULL ? NULL : mt->key_type(); - Type_context subcontext(key_type, false); - this->index_->determine_type(&subcontext); -} - -// Check types of a map index. - -void -Map_index_expression::do_check_types(Gogo*) -{ - std::string reason; - Map_type* mt = this->get_map_type(); - if (mt == NULL) - return; - if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason)) - { - if (reason.empty()) - this->report_error(_("incompatible type for map index")); - else - { - error_at(this->location(), "incompatible type for map index (%s)", - reason.c_str()); - this->set_is_error(); - } - } -} - -// Get a tree for a map index. - -tree -Map_index_expression::do_get_tree(Translate_context* context) -{ - Map_type* type = this->get_map_type(); - if (type == NULL) - return error_mark_node; - - tree valptr = this->get_value_pointer(context, this->is_lvalue_); - if (valptr == error_mark_node) - return error_mark_node; - valptr = save_expr(valptr); - - tree val_type_tree = TREE_TYPE(TREE_TYPE(valptr)); - - if (this->is_lvalue_) - return build_fold_indirect_ref(valptr); - else if (this->is_in_tuple_assignment_) - { - // Tuple_map_assignment_statement is responsible for using this - // appropriately. - return valptr; - } - else - { - return fold_build3(COND_EXPR, val_type_tree, - fold_build2(EQ_EXPR, boolean_type_node, valptr, - fold_convert(TREE_TYPE(valptr), - null_pointer_node)), - type->val_type()->get_init_tree(context->gogo(), - false), - build_fold_indirect_ref(valptr)); - } -} - -// Get a tree for the map index. This returns a tree which evaluates -// to a pointer to a value. The pointer will be NULL if the key is -// not in the map. - -tree -Map_index_expression::get_value_pointer(Translate_context* context, - bool insert) -{ - Map_type* type = this->get_map_type(); - if (type == NULL) - return error_mark_node; - - tree map_tree = this->map_->get_tree(context); - tree index_tree = this->index_->get_tree(context); - index_tree = Expression::convert_for_assignment(context, type->key_type(), - this->index_->type(), - index_tree, - this->location()); - if (map_tree == error_mark_node || index_tree == error_mark_node) - return error_mark_node; - - if (this->map_->type()->points_to() != NULL) - map_tree = build_fold_indirect_ref(map_tree); - - // We need to pass in a pointer to the key, so stuff it into a - // variable. - tree tmp; - tree make_tmp; - if (current_function_decl != NULL) - { - tmp = create_tmp_var(TREE_TYPE(index_tree), get_name(index_tree)); - DECL_IGNORED_P(tmp) = 0; - DECL_INITIAL(tmp) = index_tree; - make_tmp = build1(DECL_EXPR, void_type_node, tmp); - TREE_ADDRESSABLE(tmp) = 1; - } - else - { - tmp = build_decl(this->location(), VAR_DECL, create_tmp_var_name("M"), - TREE_TYPE(index_tree)); - DECL_EXTERNAL(tmp) = 0; - TREE_PUBLIC(tmp) = 0; - TREE_STATIC(tmp) = 1; - DECL_ARTIFICIAL(tmp) = 1; - if (!TREE_CONSTANT(index_tree)) - make_tmp = fold_build2_loc(this->location(), INIT_EXPR, void_type_node, - tmp, index_tree); - else - { - TREE_READONLY(tmp) = 1; - TREE_CONSTANT(tmp) = 1; - DECL_INITIAL(tmp) = index_tree; - make_tmp = NULL_TREE; - } - rest_of_decl_compilation(tmp, 1, 0); - } - tree tmpref = fold_convert_loc(this->location(), const_ptr_type_node, - build_fold_addr_expr_loc(this->location(), - tmp)); - - static tree map_index_fndecl; - tree call = Gogo::call_builtin(&map_index_fndecl, - this->location(), - "__go_map_index", - 3, - const_ptr_type_node, - TREE_TYPE(map_tree), - map_tree, - const_ptr_type_node, - tmpref, - boolean_type_node, - (insert - ? boolean_true_node - : boolean_false_node)); - if (call == error_mark_node) - return error_mark_node; - // This can panic on a map of interface type if the interface holds - // an uncomparable or unhashable type. - TREE_NOTHROW(map_index_fndecl) = 0; - - tree val_type_tree = type->val_type()->get_tree(context->gogo()); - if (val_type_tree == error_mark_node) - return error_mark_node; - tree ptr_val_type_tree = build_pointer_type(val_type_tree); - - tree ret = fold_convert_loc(this->location(), ptr_val_type_tree, call); - if (make_tmp != NULL_TREE) - ret = build2(COMPOUND_EXPR, ptr_val_type_tree, make_tmp, ret); - return ret; -} - -// Make a map index expression. - -Map_index_expression* -Expression::make_map_index(Expression* map, Expression* index, - source_location location) -{ - return new Map_index_expression(map, index, location); -} - -// Class Field_reference_expression. - -// Return the type of a field reference. - -Type* -Field_reference_expression::do_type() -{ - Type* type = this->expr_->type(); - if (type->is_error_type()) - return type; - Struct_type* struct_type = type->struct_type(); - gcc_assert(struct_type != NULL); - return struct_type->field(this->field_index_)->type(); -} - -// Check the types for a field reference. - -void -Field_reference_expression::do_check_types(Gogo*) -{ - Type* type = this->expr_->type(); - if (type->is_error_type()) - return; - Struct_type* struct_type = type->struct_type(); - gcc_assert(struct_type != NULL); - gcc_assert(struct_type->field(this->field_index_) != NULL); -} - -// Get a tree for a field reference. - -tree -Field_reference_expression::do_get_tree(Translate_context* context) -{ - tree struct_tree = this->expr_->get_tree(context); - if (struct_tree == error_mark_node - || TREE_TYPE(struct_tree) == error_mark_node) - return error_mark_node; - gcc_assert(TREE_CODE(TREE_TYPE(struct_tree)) == RECORD_TYPE); - tree field = TYPE_FIELDS(TREE_TYPE(struct_tree)); - if (field == NULL_TREE) - { - // This can happen for a type which refers to itself indirectly - // and then turns out to be erroneous. - gcc_assert(saw_errors()); - return error_mark_node; - } - for (unsigned int i = this->field_index_; i > 0; --i) - { - field = DECL_CHAIN(field); - gcc_assert(field != NULL_TREE); - } - if (TREE_TYPE(field) == error_mark_node) - return error_mark_node; - return build3(COMPONENT_REF, TREE_TYPE(field), struct_tree, field, - NULL_TREE); -} - -// Make a reference to a qualified identifier in an expression. - -Field_reference_expression* -Expression::make_field_reference(Expression* expr, unsigned int field_index, - source_location location) -{ - return new Field_reference_expression(expr, field_index, location); -} - -// Class Interface_field_reference_expression. - -// Return a tree for the pointer to the function to call. - -tree -Interface_field_reference_expression::get_function_tree(Translate_context*, - tree expr) -{ - if (this->expr_->type()->points_to() != NULL) - expr = build_fold_indirect_ref(expr); - - tree expr_type = TREE_TYPE(expr); - gcc_assert(TREE_CODE(expr_type) == RECORD_TYPE); - - tree field = TYPE_FIELDS(expr_type); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0); - - tree table = build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE); - gcc_assert(POINTER_TYPE_P(TREE_TYPE(table))); - - table = build_fold_indirect_ref(table); - gcc_assert(TREE_CODE(TREE_TYPE(table)) == RECORD_TYPE); - - std::string name = Gogo::unpack_hidden_name(this->name_); - for (field = DECL_CHAIN(TYPE_FIELDS(TREE_TYPE(table))); - field != NULL_TREE; - field = DECL_CHAIN(field)) - { - if (name == IDENTIFIER_POINTER(DECL_NAME(field))) - break; - } - gcc_assert(field != NULL_TREE); - - return build3(COMPONENT_REF, TREE_TYPE(field), table, field, NULL_TREE); -} - -// Return a tree for the first argument to pass to the interface -// function. - -tree -Interface_field_reference_expression::get_underlying_object_tree( - Translate_context*, - tree expr) -{ - if (this->expr_->type()->points_to() != NULL) - expr = build_fold_indirect_ref(expr); - - tree expr_type = TREE_TYPE(expr); - gcc_assert(TREE_CODE(expr_type) == RECORD_TYPE); - - tree field = DECL_CHAIN(TYPE_FIELDS(expr_type)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0); - - return build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE); -} - -// Traversal. - -int -Interface_field_reference_expression::do_traverse(Traverse* traverse) -{ - return Expression::traverse(&this->expr_, traverse); -} - -// Return the type of an interface field reference. - -Type* -Interface_field_reference_expression::do_type() -{ - Type* expr_type = this->expr_->type(); - - Type* points_to = expr_type->points_to(); - if (points_to != NULL) - expr_type = points_to; - - Interface_type* interface_type = expr_type->interface_type(); - if (interface_type == NULL) - return Type::make_error_type(); - - const Typed_identifier* method = interface_type->find_method(this->name_); - if (method == NULL) - return Type::make_error_type(); - - return method->type(); -} - -// Determine types. - -void -Interface_field_reference_expression::do_determine_type(const Type_context*) -{ - this->expr_->determine_type_no_context(); -} - -// Check the types for an interface field reference. - -void -Interface_field_reference_expression::do_check_types(Gogo*) -{ - Type* type = this->expr_->type(); - - Type* points_to = type->points_to(); - if (points_to != NULL) - type = points_to; - - Interface_type* interface_type = type->interface_type(); - if (interface_type == NULL) - this->report_error(_("expected interface or pointer to interface")); - else - { - const Typed_identifier* method = - interface_type->find_method(this->name_); - if (method == NULL) - { - error_at(this->location(), "method %qs not in interface", - Gogo::message_name(this->name_).c_str()); - this->set_is_error(); - } - } -} - -// Get a tree for a reference to a field in an interface. There is no -// standard tree type representation for this: it's a function -// attached to its first argument, like a Bound_method_expression. -// The only places it may currently be used are in a Call_expression -// or a Go_statement, which will take it apart directly. So this has -// nothing to do at present. - -tree -Interface_field_reference_expression::do_get_tree(Translate_context*) -{ - gcc_unreachable(); -} - -// Make a reference to a field in an interface. - -Expression* -Expression::make_interface_field_reference(Expression* expr, - const std::string& field, - source_location location) -{ - return new Interface_field_reference_expression(expr, field, location); -} - -// A general selector. This is a Parser_expression for LEFT.NAME. It -// is lowered after we know the type of the left hand side. - -class Selector_expression : public Parser_expression -{ - public: - Selector_expression(Expression* left, const std::string& name, - source_location location) - : Parser_expression(EXPRESSION_SELECTOR, location), - left_(left), name_(name) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return Expression::traverse(&this->left_, traverse); } - - Expression* - do_lower(Gogo*, Named_object*, int); - - Expression* - do_copy() - { - return new Selector_expression(this->left_->copy(), this->name_, - this->location()); - } - - private: - Expression* - lower_method_expression(Gogo*); - - // The expression on the left hand side. - Expression* left_; - // The name on the right hand side. - std::string name_; -}; - -// Lower a selector expression once we know the real type of the left -// hand side. - -Expression* -Selector_expression::do_lower(Gogo* gogo, Named_object*, int) -{ - Expression* left = this->left_; - if (left->is_type_expression()) - return this->lower_method_expression(gogo); - return Type::bind_field_or_method(gogo, left->type(), left, this->name_, - this->location()); -} - -// Lower a method expression T.M or (*T).M. We turn this into a -// function literal. - -Expression* -Selector_expression::lower_method_expression(Gogo* gogo) -{ - source_location location = this->location(); - Type* type = this->left_->type(); - const std::string& name(this->name_); - - bool is_pointer; - if (type->points_to() == NULL) - is_pointer = false; - else - { - is_pointer = true; - type = type->points_to(); - } - Named_type* nt = type->named_type(); - if (nt == NULL) - { - error_at(location, - ("method expression requires named type or " - "pointer to named type")); - return Expression::make_error(location); - } - - bool is_ambiguous; - Method* method = nt->method_function(name, &is_ambiguous); - if (method == NULL) - { - if (!is_ambiguous) - error_at(location, "type %<%s%> has no method %<%s%>", - nt->message_name().c_str(), - Gogo::message_name(name).c_str()); - else - error_at(location, "method %<%s%> is ambiguous in type %<%s%>", - Gogo::message_name(name).c_str(), - nt->message_name().c_str()); - return Expression::make_error(location); - } - - if (!is_pointer && !method->is_value_method()) - { - error_at(location, "method requires pointer (use %<(*%s).%s)%>", - nt->message_name().c_str(), - Gogo::message_name(name).c_str()); - return Expression::make_error(location); - } - - // Build a new function type in which the receiver becomes the first - // argument. - Function_type* method_type = method->type(); - gcc_assert(method_type->is_method()); - - const char* const receiver_name = "$this"; - Typed_identifier_list* parameters = new Typed_identifier_list(); - parameters->push_back(Typed_identifier(receiver_name, this->left_->type(), - location)); - - const Typed_identifier_list* method_parameters = method_type->parameters(); - if (method_parameters != NULL) - { - for (Typed_identifier_list::const_iterator p = method_parameters->begin(); - p != method_parameters->end(); - ++p) - parameters->push_back(*p); - } - - const Typed_identifier_list* method_results = method_type->results(); - Typed_identifier_list* results; - if (method_results == NULL) - results = NULL; - else - { - results = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator p = method_results->begin(); - p != method_results->end(); - ++p) - results->push_back(*p); - } - - Function_type* fntype = Type::make_function_type(NULL, parameters, results, - location); - if (method_type->is_varargs()) - fntype->set_is_varargs(); - - // We generate methods which always takes a pointer to the receiver - // as their first argument. If this is for a pointer type, we can - // simply reuse the existing function. We use an internal hack to - // get the right type. - - if (is_pointer) - { - Named_object* mno = (method->needs_stub_method() - ? method->stub_object() - : method->named_object()); - Expression* f = Expression::make_func_reference(mno, NULL, location); - f = Expression::make_cast(fntype, f, location); - Type_conversion_expression* tce = - static_cast(f); - tce->set_may_convert_function_types(); - return f; - } - - Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false, - location); - - Named_object* vno = gogo->lookup(receiver_name, NULL); - gcc_assert(vno != NULL); - Expression* ve = Expression::make_var_reference(vno, location); - Expression* bm = Type::bind_field_or_method(gogo, nt, ve, name, location); - - // Even though we found the method above, if it has an error type we - // may see an error here. - if (bm->is_error_expression()) - { - gogo->finish_function(location); - return bm; - } - - Expression_list* args; - if (method_parameters == NULL) - args = NULL; - else - { - args = new Expression_list(); - for (Typed_identifier_list::const_iterator p = method_parameters->begin(); - p != method_parameters->end(); - ++p) - { - vno = gogo->lookup(p->name(), NULL); - gcc_assert(vno != NULL); - args->push_back(Expression::make_var_reference(vno, location)); - } - } - - Call_expression* call = Expression::make_call(bm, args, - method_type->is_varargs(), - location); - - size_t count = call->result_count(); - Statement* s; - if (count == 0) - s = Statement::make_statement(call); - else - { - Expression_list* retvals = new Expression_list(); - if (count <= 1) - retvals->push_back(call); - else - { - for (size_t i = 0; i < count; ++i) - retvals->push_back(Expression::make_call_result(call, i)); - } - s = Statement::make_return_statement(no->func_value()->type()->results(), - retvals, location); - } - gogo->add_statement(s); - - gogo->finish_function(location); - - return Expression::make_func_reference(no, NULL, location); -} - -// Make a selector expression. - -Expression* -Expression::make_selector(Expression* left, const std::string& name, - source_location location) -{ - return new Selector_expression(left, name, location); -} - -// Implement the builtin function new. - -class Allocation_expression : public Expression -{ - public: - Allocation_expression(Type* type, source_location location) - : Expression(EXPRESSION_ALLOCATION, location), - type_(type) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return Type::traverse(this->type_, traverse); } - - Type* - do_type() - { return Type::make_pointer_type(this->type_); } - - void - do_determine_type(const Type_context*) - { } - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { return new Allocation_expression(this->type_, this->location()); } - - tree - do_get_tree(Translate_context*); - - private: - // The type we are allocating. - Type* type_; -}; - -// Check the type of an allocation expression. - -void -Allocation_expression::do_check_types(Gogo*) -{ - if (this->type_->function_type() != NULL) - this->report_error(_("invalid new of function type")); -} - -// Return a tree for an allocation expression. - -tree -Allocation_expression::do_get_tree(Translate_context* context) -{ - tree type_tree = this->type_->get_tree(context->gogo()); - if (type_tree == error_mark_node) - return error_mark_node; - tree size_tree = TYPE_SIZE_UNIT(type_tree); - tree space = context->gogo()->allocate_memory(this->type_, size_tree, - this->location()); - if (space == error_mark_node) - return error_mark_node; - return fold_convert(build_pointer_type(type_tree), space); -} - -// Make an allocation expression. - -Expression* -Expression::make_allocation(Type* type, source_location location) -{ - return new Allocation_expression(type, location); -} - -// Implement the builtin function make. - -class Make_expression : public Expression -{ - public: - Make_expression(Type* type, Expression_list* args, source_location location) - : Expression(EXPRESSION_MAKE, location), - type_(type), args_(args) - { } - - protected: - int - do_traverse(Traverse* traverse); - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Make_expression(this->type_, this->args_->copy(), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - private: - // The type we are making. - Type* type_; - // The arguments to pass to the make routine. - Expression_list* args_; -}; - -// Traversal. - -int -Make_expression::do_traverse(Traverse* traverse) -{ - if (this->args_ != NULL - && this->args_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Set types of arguments. - -void -Make_expression::do_determine_type(const Type_context*) -{ - if (this->args_ != NULL) - { - Type_context context(Type::lookup_integer_type("int"), false); - for (Expression_list::const_iterator pe = this->args_->begin(); - pe != this->args_->end(); - ++pe) - (*pe)->determine_type(&context); - } -} - -// Check types for a make expression. - -void -Make_expression::do_check_types(Gogo*) -{ - if (this->type_->channel_type() == NULL - && this->type_->map_type() == NULL - && (this->type_->array_type() == NULL - || this->type_->array_type()->length() != NULL)) - this->report_error(_("invalid type for make function")); - else if (!this->type_->check_make_expression(this->args_, this->location())) - this->set_is_error(); -} - -// Return a tree for a make expression. - -tree -Make_expression::do_get_tree(Translate_context* context) -{ - return this->type_->make_expression_tree(context, this->args_, - this->location()); -} - -// Make a make expression. - -Expression* -Expression::make_make(Type* type, Expression_list* args, - source_location location) -{ - return new Make_expression(type, args, location); -} - -// Construct a struct. - -class Struct_construction_expression : public Expression -{ - public: - Struct_construction_expression(Type* type, Expression_list* vals, - source_location location) - : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location), - type_(type), vals_(vals) - { } - - // Return whether this is a constant initializer. - bool - is_constant_struct() const; - - protected: - int - do_traverse(Traverse* traverse); - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Struct_construction_expression(this->type_, this->vals_->copy(), - this->location()); - } - - bool - do_is_addressable() const - { return true; } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The type of the struct to construct. - Type* type_; - // The list of values, in order of the fields in the struct. A NULL - // entry means that the field should be zero-initialized. - Expression_list* vals_; -}; - -// Traversal. - -int -Struct_construction_expression::do_traverse(Traverse* traverse) -{ - if (this->vals_ != NULL - && this->vals_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Return whether this is a constant initializer. - -bool -Struct_construction_expression::is_constant_struct() const -{ - if (this->vals_ == NULL) - return true; - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - if (*pv != NULL - && !(*pv)->is_constant() - && (!(*pv)->is_composite_literal() - || (*pv)->is_nonconstant_composite_literal())) - return false; - } - - const Struct_field_list* fields = this->type_->struct_type()->fields(); - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - // There are no constant constructors for interfaces. - if (pf->type()->interface_type() != NULL) - return false; - } - - return true; -} - -// Final type determination. - -void -Struct_construction_expression::do_determine_type(const Type_context*) -{ - if (this->vals_ == NULL) - return; - const Struct_field_list* fields = this->type_->struct_type()->fields(); - Expression_list::const_iterator pv = this->vals_->begin(); - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++pv) - { - if (pv == this->vals_->end()) - return; - if (*pv != NULL) - { - Type_context subcontext(pf->type(), false); - (*pv)->determine_type(&subcontext); - } - } - // Extra values are an error we will report elsewhere; we still want - // to determine the type to avoid knockon errors. - for (; pv != this->vals_->end(); ++pv) - (*pv)->determine_type_no_context(); -} - -// Check types. - -void -Struct_construction_expression::do_check_types(Gogo*) -{ - if (this->vals_ == NULL) - return; - - Struct_type* st = this->type_->struct_type(); - if (this->vals_->size() > st->field_count()) - { - this->report_error(_("too many expressions for struct")); - return; - } - - const Struct_field_list* fields = st->fields(); - Expression_list::const_iterator pv = this->vals_->begin(); - int i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++pv, ++i) - { - if (pv == this->vals_->end()) - { - this->report_error(_("too few expressions for struct")); - break; - } - - if (*pv == NULL) - continue; - - std::string reason; - if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason)) - { - if (reason.empty()) - error_at((*pv)->location(), - "incompatible type for field %d in struct construction", - i + 1); - else - error_at((*pv)->location(), - ("incompatible type for field %d in " - "struct construction (%s)"), - i + 1, reason.c_str()); - this->set_is_error(); - } - } - gcc_assert(pv == this->vals_->end()); -} - -// Return a tree for constructing a struct. - -tree -Struct_construction_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - - if (this->vals_ == NULL) - return this->type_->get_init_tree(gogo, false); - - tree type_tree = this->type_->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - gcc_assert(TREE_CODE(type_tree) == RECORD_TYPE); - - bool is_constant = true; - const Struct_field_list* fields = this->type_->struct_type()->fields(); - VEC(constructor_elt,gc)* elts = VEC_alloc(constructor_elt, gc, - fields->size()); - Struct_field_list::const_iterator pf = fields->begin(); - Expression_list::const_iterator pv = this->vals_->begin(); - for (tree field = TYPE_FIELDS(type_tree); - field != NULL_TREE; - field = DECL_CHAIN(field), ++pf) - { - gcc_assert(pf != fields->end()); - - tree val; - if (pv == this->vals_->end()) - val = pf->type()->get_init_tree(gogo, false); - else if (*pv == NULL) - { - val = pf->type()->get_init_tree(gogo, false); - ++pv; - } - else - { - val = Expression::convert_for_assignment(context, pf->type(), - (*pv)->type(), - (*pv)->get_tree(context), - this->location()); - ++pv; - } - - if (val == error_mark_node || TREE_TYPE(val) == error_mark_node) - return error_mark_node; - - constructor_elt* elt = VEC_quick_push(constructor_elt, elts, NULL); - elt->index = field; - elt->value = val; - if (!TREE_CONSTANT(val)) - is_constant = false; - } - gcc_assert(pf == fields->end()); - - tree ret = build_constructor(type_tree, elts); - if (is_constant) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Export a struct construction. - -void -Struct_construction_expression::do_export(Export* exp) const -{ - exp->write_c_string("convert("); - exp->write_type(this->type_); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - exp->write_c_string(", "); - if (*pv != NULL) - (*pv)->export_expression(exp); - } - exp->write_c_string(")"); -} - -// Make a struct composite literal. This used by the thunk code. - -Expression* -Expression::make_struct_composite_literal(Type* type, Expression_list* vals, - source_location location) -{ - gcc_assert(type->struct_type() != NULL); - return new Struct_construction_expression(type, vals, location); -} - -// Construct an array. This class is not used directly; instead we -// use the child classes, Fixed_array_construction_expression and -// Open_array_construction_expression. - -class Array_construction_expression : public Expression -{ - protected: - Array_construction_expression(Expression_classification classification, - Type* type, Expression_list* vals, - source_location location) - : Expression(classification, location), - type_(type), vals_(vals) - { } - - public: - // Return whether this is a constant initializer. - bool - is_constant_array() const; - - // Return the number of elements. - size_t - element_count() const - { return this->vals_ == NULL ? 0 : this->vals_->size(); } - -protected: - int - do_traverse(Traverse* traverse); - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - bool - do_is_addressable() const - { return true; } - - void - do_export(Export*) const; - - // The list of values. - Expression_list* - vals() - { return this->vals_; } - - // Get a constructor tree for the array values. - tree - get_constructor_tree(Translate_context* context, tree type_tree); - - private: - // The type of the array to construct. - Type* type_; - // The list of values. - Expression_list* vals_; -}; - -// Traversal. - -int -Array_construction_expression::do_traverse(Traverse* traverse) -{ - if (this->vals_ != NULL - && this->vals_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Return whether this is a constant initializer. - -bool -Array_construction_expression::is_constant_array() const -{ - if (this->vals_ == NULL) - return true; - - // There are no constant constructors for interfaces. - if (this->type_->array_type()->element_type()->interface_type() != NULL) - return false; - - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - if (*pv != NULL - && !(*pv)->is_constant() - && (!(*pv)->is_composite_literal() - || (*pv)->is_nonconstant_composite_literal())) - return false; - } - return true; -} - -// Final type determination. - -void -Array_construction_expression::do_determine_type(const Type_context*) -{ - if (this->vals_ == NULL) - return; - Type_context subcontext(this->type_->array_type()->element_type(), false); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - if (*pv != NULL) - (*pv)->determine_type(&subcontext); - } -} - -// Check types. - -void -Array_construction_expression::do_check_types(Gogo*) -{ - if (this->vals_ == NULL) - return; - - Array_type* at = this->type_->array_type(); - int i = 0; - Type* element_type = at->element_type(); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv, ++i) - { - if (*pv != NULL - && !Type::are_assignable(element_type, (*pv)->type(), NULL)) - { - error_at((*pv)->location(), - "incompatible type for element %d in composite literal", - i + 1); - this->set_is_error(); - } - } - - Expression* length = at->length(); - if (length != NULL) - { - mpz_t val; - mpz_init(val); - Type* type; - if (at->length()->integer_constant_value(true, val, &type)) - { - if (this->vals_->size() > mpz_get_ui(val)) - this->report_error(_("too many elements in composite literal")); - } - mpz_clear(val); - } -} - -// Get a constructor tree for the array values. - -tree -Array_construction_expression::get_constructor_tree(Translate_context* context, - tree type_tree) -{ - VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc, - (this->vals_ == NULL - ? 0 - : this->vals_->size())); - Type* element_type = this->type_->array_type()->element_type(); - bool is_constant = true; - if (this->vals_ != NULL) - { - size_t i = 0; - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv, ++i) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, values, NULL); - elt->index = size_int(i); - if (*pv == NULL) - elt->value = element_type->get_init_tree(context->gogo(), false); - else - { - tree value_tree = (*pv)->get_tree(context); - elt->value = Expression::convert_for_assignment(context, - element_type, - (*pv)->type(), - value_tree, - this->location()); - } - if (elt->value == error_mark_node) - return error_mark_node; - if (!TREE_CONSTANT(elt->value)) - is_constant = false; - } - } - - tree ret = build_constructor(type_tree, values); - if (is_constant) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Export an array construction. - -void -Array_construction_expression::do_export(Export* exp) const -{ - exp->write_c_string("convert("); - exp->write_type(this->type_); - if (this->vals_ != NULL) - { - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - exp->write_c_string(", "); - if (*pv != NULL) - (*pv)->export_expression(exp); - } - } - exp->write_c_string(")"); -} - -// Construct a fixed array. - -class Fixed_array_construction_expression : - public Array_construction_expression -{ - public: - Fixed_array_construction_expression(Type* type, Expression_list* vals, - source_location location) - : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION, - type, vals, location) - { - gcc_assert(type->array_type() != NULL - && type->array_type()->length() != NULL); - } - - protected: - Expression* - do_copy() - { - return new Fixed_array_construction_expression(this->type(), - (this->vals() == NULL - ? NULL - : this->vals()->copy()), - this->location()); - } - - tree - do_get_tree(Translate_context*); -}; - -// Return a tree for constructing a fixed array. - -tree -Fixed_array_construction_expression::do_get_tree(Translate_context* context) -{ - return this->get_constructor_tree(context, - this->type()->get_tree(context->gogo())); -} - -// Construct an open array. - -class Open_array_construction_expression : public Array_construction_expression -{ - public: - Open_array_construction_expression(Type* type, Expression_list* vals, - source_location location) - : Array_construction_expression(EXPRESSION_OPEN_ARRAY_CONSTRUCTION, - type, vals, location) - { - gcc_assert(type->array_type() != NULL - && type->array_type()->length() == NULL); - } - - protected: - // Note that taking the address of an open array literal is invalid. - - Expression* - do_copy() - { - return new Open_array_construction_expression(this->type(), - (this->vals() == NULL - ? NULL - : this->vals()->copy()), - this->location()); - } - - tree - do_get_tree(Translate_context*); -}; - -// Return a tree for constructing an open array. - -tree -Open_array_construction_expression::do_get_tree(Translate_context* context) -{ - Array_type* array_type = this->type()->array_type(); - if (array_type == NULL) - { - gcc_assert(this->type()->is_error_type()); - return error_mark_node; - } - - Type* element_type = array_type->element_type(); - tree element_type_tree = element_type->get_tree(context->gogo()); - if (element_type_tree == error_mark_node) - return error_mark_node; - - tree values; - tree length_tree; - if (this->vals() == NULL || this->vals()->empty()) - { - // We need to create a unique value. - tree max = size_int(0); - tree constructor_type = build_array_type(element_type_tree, - build_index_type(max)); - if (constructor_type == error_mark_node) - return error_mark_node; - VEC(constructor_elt,gc)* vec = VEC_alloc(constructor_elt, gc, 1); - constructor_elt* elt = VEC_quick_push(constructor_elt, vec, NULL); - elt->index = size_int(0); - elt->value = element_type->get_init_tree(context->gogo(), false); - values = build_constructor(constructor_type, vec); - if (TREE_CONSTANT(elt->value)) - TREE_CONSTANT(values) = 1; - length_tree = size_int(0); - } - else - { - tree max = size_int(this->vals()->size() - 1); - tree constructor_type = build_array_type(element_type_tree, - build_index_type(max)); - if (constructor_type == error_mark_node) - return error_mark_node; - values = this->get_constructor_tree(context, constructor_type); - length_tree = size_int(this->vals()->size()); - } - - if (values == error_mark_node) - return error_mark_node; - - bool is_constant_initializer = TREE_CONSTANT(values); - - // We have to copy the initial values into heap memory if we are in - // a function or if the values are not constants. We also have to - // copy them if they may contain pointers in a non-constant context, - // as otherwise the garbage collector won't see them. - bool copy_to_heap = (context->function() != NULL - || !is_constant_initializer - || (element_type->has_pointer() - && !context->is_const())); - - if (is_constant_initializer) - { - tree tmp = build_decl(this->location(), VAR_DECL, - create_tmp_var_name("C"), TREE_TYPE(values)); - DECL_EXTERNAL(tmp) = 0; - TREE_PUBLIC(tmp) = 0; - TREE_STATIC(tmp) = 1; - DECL_ARTIFICIAL(tmp) = 1; - if (copy_to_heap) - { - // If we are not copying the value to the heap, we will only - // initialize the value once, so we can use this directly - // rather than copying it. In that case we can't make it - // read-only, because the program is permitted to change it. - TREE_READONLY(tmp) = 1; - TREE_CONSTANT(tmp) = 1; - } - DECL_INITIAL(tmp) = values; - rest_of_decl_compilation(tmp, 1, 0); - values = tmp; - } - - tree space; - tree set; - if (!copy_to_heap) - { - // the initializer will only run once. - space = build_fold_addr_expr(values); - set = NULL_TREE; - } - else - { - tree memsize = TYPE_SIZE_UNIT(TREE_TYPE(values)); - space = context->gogo()->allocate_memory(element_type, memsize, - this->location()); - space = save_expr(space); - - tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space); - tree ref = build_fold_indirect_ref_loc(this->location(), s); - TREE_THIS_NOTRAP(ref) = 1; - set = build2(MODIFY_EXPR, void_type_node, ref, values); - } - - // Build a constructor for the open array. - - tree type_tree = this->type()->get_tree(context->gogo()); - if (type_tree == error_mark_node) - return error_mark_node; - gcc_assert(TREE_CODE(type_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(type_tree); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), space); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), length_tree); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), length_tree); - - tree constructor = build_constructor(type_tree, init); - if (constructor == error_mark_node) - return error_mark_node; - if (!copy_to_heap) - TREE_CONSTANT(constructor) = 1; - - if (set == NULL_TREE) - return constructor; - else - return build2(COMPOUND_EXPR, type_tree, set, constructor); -} - -// Make a slice composite literal. This is used by the type -// descriptor code. - -Expression* -Expression::make_slice_composite_literal(Type* type, Expression_list* vals, - source_location location) -{ - gcc_assert(type->is_open_array_type()); - return new Open_array_construction_expression(type, vals, location); -} - -// Construct a map. - -class Map_construction_expression : public Expression -{ - public: - Map_construction_expression(Type* type, Expression_list* vals, - source_location location) - : Expression(EXPRESSION_MAP_CONSTRUCTION, location), - type_(type), vals_(vals) - { gcc_assert(vals == NULL || vals->size() % 2 == 0); } - - protected: - int - do_traverse(Traverse* traverse); - - Type* - do_type() - { return this->type_; } - - void - do_determine_type(const Type_context*); - - void - do_check_types(Gogo*); - - Expression* - do_copy() - { - return new Map_construction_expression(this->type_, this->vals_->copy(), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - void - do_export(Export*) const; - - private: - // The type of the map to construct. - Type* type_; - // The list of values. - Expression_list* vals_; -}; - -// Traversal. - -int -Map_construction_expression::do_traverse(Traverse* traverse) -{ - if (this->vals_ != NULL - && this->vals_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Final type determination. - -void -Map_construction_expression::do_determine_type(const Type_context*) -{ - if (this->vals_ == NULL) - return; - - Map_type* mt = this->type_->map_type(); - Type_context key_context(mt->key_type(), false); - Type_context val_context(mt->val_type(), false); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - (*pv)->determine_type(&key_context); - ++pv; - (*pv)->determine_type(&val_context); - } -} - -// Check types. - -void -Map_construction_expression::do_check_types(Gogo*) -{ - if (this->vals_ == NULL) - return; - - Map_type* mt = this->type_->map_type(); - int i = 0; - Type* key_type = mt->key_type(); - Type* val_type = mt->val_type(); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv, ++i) - { - if (!Type::are_assignable(key_type, (*pv)->type(), NULL)) - { - error_at((*pv)->location(), - "incompatible type for element %d key in map construction", - i + 1); - this->set_is_error(); - } - ++pv; - if (!Type::are_assignable(val_type, (*pv)->type(), NULL)) - { - error_at((*pv)->location(), - ("incompatible type for element %d value " - "in map construction"), - i + 1); - this->set_is_error(); - } - } -} - -// Return a tree for constructing a map. - -tree -Map_construction_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - source_location loc = this->location(); - - Map_type* mt = this->type_->map_type(); - - // Build a struct to hold the key and value. - tree struct_type = make_node(RECORD_TYPE); - - Type* key_type = mt->key_type(); - tree id = get_identifier("__key"); - tree key_type_tree = key_type->get_tree(gogo); - if (key_type_tree == error_mark_node) - return error_mark_node; - tree key_field = build_decl(loc, FIELD_DECL, id, key_type_tree); - DECL_CONTEXT(key_field) = struct_type; - TYPE_FIELDS(struct_type) = key_field; - - Type* val_type = mt->val_type(); - id = get_identifier("__val"); - tree val_type_tree = val_type->get_tree(gogo); - if (val_type_tree == error_mark_node) - return error_mark_node; - tree val_field = build_decl(loc, FIELD_DECL, id, val_type_tree); - DECL_CONTEXT(val_field) = struct_type; - DECL_CHAIN(key_field) = val_field; - - layout_type(struct_type); - - bool is_constant = true; - size_t i = 0; - tree valaddr; - tree make_tmp; - - if (this->vals_ == NULL || this->vals_->empty()) - { - valaddr = null_pointer_node; - make_tmp = NULL_TREE; - } - else - { - VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc, - this->vals_->size() / 2); - - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv, ++i) - { - bool one_is_constant = true; - - VEC(constructor_elt,gc)* one = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, one, NULL); - elt->index = key_field; - tree val_tree = (*pv)->get_tree(context); - elt->value = Expression::convert_for_assignment(context, key_type, - (*pv)->type(), - val_tree, loc); - if (elt->value == error_mark_node) - return error_mark_node; - if (!TREE_CONSTANT(elt->value)) - one_is_constant = false; - - ++pv; - - elt = VEC_quick_push(constructor_elt, one, NULL); - elt->index = val_field; - val_tree = (*pv)->get_tree(context); - elt->value = Expression::convert_for_assignment(context, val_type, - (*pv)->type(), - val_tree, loc); - if (elt->value == error_mark_node) - return error_mark_node; - if (!TREE_CONSTANT(elt->value)) - one_is_constant = false; - - elt = VEC_quick_push(constructor_elt, values, NULL); - elt->index = size_int(i); - elt->value = build_constructor(struct_type, one); - if (one_is_constant) - TREE_CONSTANT(elt->value) = 1; - else - is_constant = false; - } - - tree index_type = build_index_type(size_int(i - 1)); - tree array_type = build_array_type(struct_type, index_type); - tree init = build_constructor(array_type, values); - if (is_constant) - TREE_CONSTANT(init) = 1; - tree tmp; - if (current_function_decl != NULL) - { - tmp = create_tmp_var(array_type, get_name(array_type)); - DECL_INITIAL(tmp) = init; - make_tmp = fold_build1_loc(loc, DECL_EXPR, void_type_node, tmp); - TREE_ADDRESSABLE(tmp) = 1; - } - else - { - tmp = build_decl(loc, VAR_DECL, create_tmp_var_name("M"), array_type); - DECL_EXTERNAL(tmp) = 0; - TREE_PUBLIC(tmp) = 0; - TREE_STATIC(tmp) = 1; - DECL_ARTIFICIAL(tmp) = 1; - if (!TREE_CONSTANT(init)) - make_tmp = fold_build2_loc(loc, INIT_EXPR, void_type_node, tmp, - init); - else - { - TREE_READONLY(tmp) = 1; - TREE_CONSTANT(tmp) = 1; - DECL_INITIAL(tmp) = init; - make_tmp = NULL_TREE; - } - rest_of_decl_compilation(tmp, 1, 0); - } - - valaddr = build_fold_addr_expr(tmp); - } - - tree descriptor = gogo->map_descriptor(mt); - - tree type_tree = this->type_->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - - static tree construct_map_fndecl; - tree call = Gogo::call_builtin(&construct_map_fndecl, - loc, - "__go_construct_map", - 6, - type_tree, - TREE_TYPE(descriptor), - descriptor, - sizetype, - size_int(i), - sizetype, - TYPE_SIZE_UNIT(struct_type), - sizetype, - byte_position(val_field), - sizetype, - TYPE_SIZE_UNIT(TREE_TYPE(val_field)), - const_ptr_type_node, - fold_convert(const_ptr_type_node, valaddr)); - if (call == error_mark_node) - return error_mark_node; - - tree ret; - if (make_tmp == NULL) - ret = call; - else - ret = fold_build2_loc(loc, COMPOUND_EXPR, type_tree, make_tmp, call); - return ret; -} - -// Export an array construction. - -void -Map_construction_expression::do_export(Export* exp) const -{ - exp->write_c_string("convert("); - exp->write_type(this->type_); - for (Expression_list::const_iterator pv = this->vals_->begin(); - pv != this->vals_->end(); - ++pv) - { - exp->write_c_string(", "); - (*pv)->export_expression(exp); - } - exp->write_c_string(")"); -} - -// A general composite literal. This is lowered to a type specific -// version. - -class Composite_literal_expression : public Parser_expression -{ - public: - Composite_literal_expression(Type* type, int depth, bool has_keys, - Expression_list* vals, source_location location) - : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location), - type_(type), depth_(depth), vals_(vals), has_keys_(has_keys) - { } - - protected: - int - do_traverse(Traverse* traverse); - - Expression* - do_lower(Gogo*, Named_object*, int); - - Expression* - do_copy() - { - return new Composite_literal_expression(this->type_, this->depth_, - this->has_keys_, - (this->vals_ == NULL - ? NULL - : this->vals_->copy()), - this->location()); - } - - private: - Expression* - lower_struct(Gogo*, Type*); - - Expression* - lower_array(Type*); - - Expression* - make_array(Type*, Expression_list*); - - Expression* - lower_map(Gogo*, Named_object*, Type*); - - // The type of the composite literal. - Type* type_; - // The depth within a list of composite literals within a composite - // literal, when the type is omitted. - int depth_; - // The values to put in the composite literal. - Expression_list* vals_; - // If this is true, then VALS_ is a list of pairs: a key and a - // value. In an array initializer, a missing key will be NULL. - bool has_keys_; -}; - -// Traversal. - -int -Composite_literal_expression::do_traverse(Traverse* traverse) -{ - if (this->vals_ != NULL - && this->vals_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return Type::traverse(this->type_, traverse); -} - -// Lower a generic composite literal into a specific version based on -// the type. - -Expression* -Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function, int) -{ - Type* type = this->type_; - - for (int depth = this->depth_; depth > 0; --depth) - { - if (type->array_type() != NULL) - type = type->array_type()->element_type(); - else if (type->map_type() != NULL) - type = type->map_type()->val_type(); - else - { - if (!type->is_error_type()) - error_at(this->location(), - ("may only omit types within composite literals " - "of slice, array, or map type")); - return Expression::make_error(this->location()); - } - } - - if (type->is_error_type()) - return Expression::make_error(this->location()); - else if (type->struct_type() != NULL) - return this->lower_struct(gogo, type); - else if (type->array_type() != NULL) - return this->lower_array(type); - else if (type->map_type() != NULL) - return this->lower_map(gogo, function, type); - else - { - error_at(this->location(), - ("expected struct, slice, array, or map type " - "for composite literal")); - return Expression::make_error(this->location()); - } -} - -// Lower a struct composite literal. - -Expression* -Composite_literal_expression::lower_struct(Gogo* gogo, Type* type) -{ - source_location location = this->location(); - Struct_type* st = type->struct_type(); - if (this->vals_ == NULL || !this->has_keys_) - return new Struct_construction_expression(type, this->vals_, location); - - size_t field_count = st->field_count(); - std::vector vals(field_count); - Expression_list::const_iterator p = this->vals_->begin(); - while (p != this->vals_->end()) - { - Expression* name_expr = *p; - - ++p; - gcc_assert(p != this->vals_->end()); - Expression* val = *p; - - ++p; - - if (name_expr == NULL) - { - error_at(val->location(), "mixture of field and value initializers"); - return Expression::make_error(location); - } - - bool bad_key = false; - std::string name; - const Named_object* no = NULL; - switch (name_expr->classification()) - { - case EXPRESSION_UNKNOWN_REFERENCE: - name = name_expr->unknown_expression()->name(); - break; - - case EXPRESSION_CONST_REFERENCE: - no = static_cast(name_expr)->named_object(); - break; - - case EXPRESSION_TYPE: - { - Type* t = name_expr->type(); - Named_type* nt = t->named_type(); - if (nt == NULL) - bad_key = true; - else - no = nt->named_object(); - } - break; - - case EXPRESSION_VAR_REFERENCE: - no = name_expr->var_expression()->named_object(); - break; - - case EXPRESSION_FUNC_REFERENCE: - no = name_expr->func_expression()->named_object(); - break; - - case EXPRESSION_UNARY: - // If there is a local variable around with the same name as - // the field, and this occurs in the closure, then the - // parser may turn the field reference into an indirection - // through the closure. FIXME: This is a mess. - { - bad_key = true; - Unary_expression* ue = static_cast(name_expr); - if (ue->op() == OPERATOR_MULT) - { - Field_reference_expression* fre = - ue->operand()->field_reference_expression(); - if (fre != NULL) - { - Struct_type* st = - fre->expr()->type()->deref()->struct_type(); - if (st != NULL) - { - const Struct_field* sf = st->field(fre->field_index()); - name = sf->field_name(); - char buf[20]; - snprintf(buf, sizeof buf, "%u", fre->field_index()); - size_t buflen = strlen(buf); - if (name.compare(name.length() - buflen, buflen, buf) - == 0) - { - name = name.substr(0, name.length() - buflen); - bad_key = false; - } - } - } - } - } - break; - - default: - bad_key = true; - break; - } - if (bad_key) - { - error_at(name_expr->location(), "expected struct field name"); - return Expression::make_error(location); - } - - if (no != NULL) - { - name = no->name(); - - // A predefined name won't be packed. If it starts with a - // lower case letter we need to check for that case, because - // the field name will be packed. - if (!Gogo::is_hidden_name(name) - && name[0] >= 'a' - && name[0] <= 'z') - { - Named_object* gno = gogo->lookup_global(name.c_str()); - if (gno == no) - name = gogo->pack_hidden_name(name, false); - } - } - - unsigned int index; - const Struct_field* sf = st->find_local_field(name, &index); - if (sf == NULL) - { - error_at(name_expr->location(), "unknown field %qs in %qs", - Gogo::message_name(name).c_str(), - (type->named_type() != NULL - ? type->named_type()->message_name().c_str() - : "unnamed struct")); - return Expression::make_error(location); - } - if (vals[index] != NULL) - { - error_at(name_expr->location(), - "duplicate value for field %qs in %qs", - Gogo::message_name(name).c_str(), - (type->named_type() != NULL - ? type->named_type()->message_name().c_str() - : "unnamed struct")); - return Expression::make_error(location); - } - - vals[index] = val; - } - - Expression_list* list = new Expression_list; - list->reserve(field_count); - for (size_t i = 0; i < field_count; ++i) - list->push_back(vals[i]); - - return new Struct_construction_expression(type, list, location); -} - -// Lower an array composite literal. - -Expression* -Composite_literal_expression::lower_array(Type* type) -{ - source_location location = this->location(); - if (this->vals_ == NULL || !this->has_keys_) - return this->make_array(type, this->vals_); - - std::vector vals; - vals.reserve(this->vals_->size()); - unsigned long index = 0; - Expression_list::const_iterator p = this->vals_->begin(); - while (p != this->vals_->end()) - { - Expression* index_expr = *p; - - ++p; - gcc_assert(p != this->vals_->end()); - Expression* val = *p; - - ++p; - - if (index_expr != NULL) - { - mpz_t ival; - mpz_init(ival); - - Type* dummy; - if (!index_expr->integer_constant_value(true, ival, &dummy)) - { - mpz_clear(ival); - error_at(index_expr->location(), - "index expression is not integer constant"); - return Expression::make_error(location); - } - - if (mpz_sgn(ival) < 0) - { - mpz_clear(ival); - error_at(index_expr->location(), "index expression is negative"); - return Expression::make_error(location); - } - - index = mpz_get_ui(ival); - if (mpz_cmp_ui(ival, index) != 0) - { - mpz_clear(ival); - error_at(index_expr->location(), "index value overflow"); - return Expression::make_error(location); - } - - Named_type* ntype = Type::lookup_integer_type("int"); - Integer_type* inttype = ntype->integer_type(); - mpz_t max; - mpz_init_set_ui(max, 1); - mpz_mul_2exp(max, max, inttype->bits() - 1); - bool ok = mpz_cmp(ival, max) < 0; - mpz_clear(max); - if (!ok) - { - mpz_clear(ival); - error_at(index_expr->location(), "index value overflow"); - return Expression::make_error(location); - } - - mpz_clear(ival); - - // FIXME: Our representation isn't very good; this avoids - // thrashing. - if (index > 0x1000000) - { - error_at(index_expr->location(), "index too large for compiler"); - return Expression::make_error(location); - } - } - - if (index == vals.size()) - vals.push_back(val); - else - { - if (index > vals.size()) - { - vals.reserve(index + 32); - vals.resize(index + 1, static_cast(NULL)); - } - if (vals[index] != NULL) - { - error_at((index_expr != NULL - ? index_expr->location() - : val->location()), - "duplicate value for index %lu", - index); - return Expression::make_error(location); - } - vals[index] = val; - } - - ++index; - } - - size_t size = vals.size(); - Expression_list* list = new Expression_list; - list->reserve(size); - for (size_t i = 0; i < size; ++i) - list->push_back(vals[i]); - - return this->make_array(type, list); -} - -// Actually build the array composite literal. This handles -// [...]{...}. - -Expression* -Composite_literal_expression::make_array(Type* type, Expression_list* vals) -{ - source_location location = this->location(); - Array_type* at = type->array_type(); - if (at->length() != NULL && at->length()->is_nil_expression()) - { - size_t size = vals == NULL ? 0 : vals->size(); - mpz_t vlen; - mpz_init_set_ui(vlen, size); - Expression* elen = Expression::make_integer(&vlen, NULL, location); - mpz_clear(vlen); - at = Type::make_array_type(at->element_type(), elen); - type = at; - } - if (at->length() != NULL) - return new Fixed_array_construction_expression(type, vals, location); - else - return new Open_array_construction_expression(type, vals, location); -} - -// Lower a map composite literal. - -Expression* -Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function, - Type* type) -{ - source_location location = this->location(); - if (this->vals_ != NULL) - { - if (!this->has_keys_) - { - error_at(location, "map composite literal must have keys"); - return Expression::make_error(location); - } - - for (Expression_list::iterator p = this->vals_->begin(); - p != this->vals_->end(); - p += 2) - { - if (*p == NULL) - { - ++p; - error_at((*p)->location(), - "map composite literal must have keys for every value"); - return Expression::make_error(location); - } - // Make sure we have lowered the key; it may not have been - // lowered in order to handle keys for struct composite - // literals. Lower it now to get the right error message. - if ((*p)->unknown_expression() != NULL) - { - (*p)->unknown_expression()->clear_is_composite_literal_key(); - gogo->lower_expression(function, &*p); - gcc_assert((*p)->is_error_expression()); - return Expression::make_error(location); - } - } - } - - return new Map_construction_expression(type, this->vals_, location); -} - -// Make a composite literal expression. - -Expression* -Expression::make_composite_literal(Type* type, int depth, bool has_keys, - Expression_list* vals, - source_location location) -{ - return new Composite_literal_expression(type, depth, has_keys, vals, - location); -} - -// Return whether this expression is a composite literal. - -bool -Expression::is_composite_literal() const -{ - switch (this->classification_) - { - case EXPRESSION_COMPOSITE_LITERAL: - case EXPRESSION_STRUCT_CONSTRUCTION: - case EXPRESSION_FIXED_ARRAY_CONSTRUCTION: - case EXPRESSION_OPEN_ARRAY_CONSTRUCTION: - case EXPRESSION_MAP_CONSTRUCTION: - return true; - default: - return false; - } -} - -// Return whether this expression is a composite literal which is not -// constant. - -bool -Expression::is_nonconstant_composite_literal() const -{ - switch (this->classification_) - { - case EXPRESSION_STRUCT_CONSTRUCTION: - { - const Struct_construction_expression *psce = - static_cast(this); - return !psce->is_constant_struct(); - } - case EXPRESSION_FIXED_ARRAY_CONSTRUCTION: - { - const Fixed_array_construction_expression *pace = - static_cast(this); - return !pace->is_constant_array(); - } - case EXPRESSION_OPEN_ARRAY_CONSTRUCTION: - { - const Open_array_construction_expression *pace = - static_cast(this); - return !pace->is_constant_array(); - } - case EXPRESSION_MAP_CONSTRUCTION: - return true; - default: - return false; - } -} - -// Return true if this is a reference to a local variable. - -bool -Expression::is_local_variable() const -{ - const Var_expression* ve = this->var_expression(); - if (ve == NULL) - return false; - const Named_object* no = ve->named_object(); - return (no->is_result_variable() - || (no->is_variable() && !no->var_value()->is_global())); -} - -// Class Type_guard_expression. - -// Traversal. - -int -Type_guard_expression::do_traverse(Traverse* traverse) -{ - if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT - || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Check types of a type guard expression. The expression must have -// an interface type, but the actual type conversion is checked at run -// time. - -void -Type_guard_expression::do_check_types(Gogo*) -{ - // 6g permits using a type guard with unsafe.pointer; we are - // compatible. - Type* expr_type = this->expr_->type(); - if (expr_type->is_unsafe_pointer_type()) - { - if (this->type_->points_to() == NULL - && (this->type_->integer_type() == NULL - || (this->type_->forwarded() - != Type::lookup_integer_type("uintptr")))) - this->report_error(_("invalid unsafe.Pointer conversion")); - } - else if (this->type_->is_unsafe_pointer_type()) - { - if (expr_type->points_to() == NULL - && (expr_type->integer_type() == NULL - || (expr_type->forwarded() - != Type::lookup_integer_type("uintptr")))) - this->report_error(_("invalid unsafe.Pointer conversion")); - } - else if (expr_type->interface_type() == NULL) - { - if (!expr_type->is_error_type() && !this->type_->is_error_type()) - this->report_error(_("type assertion only valid for interface types")); - this->set_is_error(); - } - else if (this->type_->interface_type() == NULL) - { - std::string reason; - if (!expr_type->interface_type()->implements_interface(this->type_, - &reason)) - { - if (!this->type_->is_error_type()) - { - if (reason.empty()) - this->report_error(_("impossible type assertion: " - "type does not implement interface")); - else - error_at(this->location(), - ("impossible type assertion: " - "type does not implement interface (%s)"), - reason.c_str()); - } - this->set_is_error(); - } - } -} - -// Return a tree for a type guard expression. - -tree -Type_guard_expression::do_get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - tree expr_tree = this->expr_->get_tree(context); - if (expr_tree == error_mark_node) - return error_mark_node; - Type* expr_type = this->expr_->type(); - if ((this->type_->is_unsafe_pointer_type() - && (expr_type->points_to() != NULL - || expr_type->integer_type() != NULL)) - || (expr_type->is_unsafe_pointer_type() - && this->type_->points_to() != NULL)) - return convert_to_pointer(this->type_->get_tree(gogo), expr_tree); - else if (expr_type->is_unsafe_pointer_type() - && this->type_->integer_type() != NULL) - return convert_to_integer(this->type_->get_tree(gogo), expr_tree); - else if (this->type_->interface_type() != NULL) - return Expression::convert_interface_to_interface(context, this->type_, - this->expr_->type(), - expr_tree, true, - this->location()); - else - return Expression::convert_for_assignment(context, this->type_, - this->expr_->type(), expr_tree, - this->location()); -} - -// Make a type guard expression. - -Expression* -Expression::make_type_guard(Expression* expr, Type* type, - source_location location) -{ - return new Type_guard_expression(expr, type, location); -} - -// Class Heap_composite_expression. - -// When you take the address of a composite literal, it is allocated -// on the heap. This class implements that. - -class Heap_composite_expression : public Expression -{ - public: - Heap_composite_expression(Expression* expr, source_location location) - : Expression(EXPRESSION_HEAP_COMPOSITE, location), - expr_(expr) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return Expression::traverse(&this->expr_, traverse); } - - Type* - do_type() - { return Type::make_pointer_type(this->expr_->type()); } - - void - do_determine_type(const Type_context*) - { this->expr_->determine_type_no_context(); } - - Expression* - do_copy() - { - return Expression::make_heap_composite(this->expr_->copy(), - this->location()); - } - - tree - do_get_tree(Translate_context*); - - // We only export global objects, and the parser does not generate - // this in global scope. - void - do_export(Export*) const - { gcc_unreachable(); } - - private: - // The composite literal which is being put on the heap. - Expression* expr_; -}; - -// Return a tree which allocates a composite literal on the heap. - -tree -Heap_composite_expression::do_get_tree(Translate_context* context) -{ - tree expr_tree = this->expr_->get_tree(context); - if (expr_tree == error_mark_node) - return error_mark_node; - tree expr_size = TYPE_SIZE_UNIT(TREE_TYPE(expr_tree)); - gcc_assert(TREE_CODE(expr_size) == INTEGER_CST); - tree space = context->gogo()->allocate_memory(this->expr_->type(), - expr_size, this->location()); - space = fold_convert(build_pointer_type(TREE_TYPE(expr_tree)), space); - space = save_expr(space); - tree ref = build_fold_indirect_ref_loc(this->location(), space); - TREE_THIS_NOTRAP(ref) = 1; - tree ret = build2(COMPOUND_EXPR, TREE_TYPE(space), - build2(MODIFY_EXPR, void_type_node, ref, expr_tree), - space); - SET_EXPR_LOCATION(ret, this->location()); - return ret; -} - -// Allocate a composite literal on the heap. - -Expression* -Expression::make_heap_composite(Expression* expr, source_location location) -{ - return new Heap_composite_expression(expr, location); -} - -// Class Receive_expression. - -// Return the type of a receive expression. - -Type* -Receive_expression::do_type() -{ - Channel_type* channel_type = this->channel_->type()->channel_type(); - if (channel_type == NULL) - return Type::make_error_type(); - return channel_type->element_type(); -} - -// Check types for a receive expression. - -void -Receive_expression::do_check_types(Gogo*) -{ - Type* type = this->channel_->type(); - if (type->is_error_type()) - { - this->set_is_error(); - return; - } - if (type->channel_type() == NULL) - { - this->report_error(_("expected channel")); - return; - } - if (!type->channel_type()->may_receive()) - { - this->report_error(_("invalid receive on send-only channel")); - return; - } -} - -// Get a tree for a receive expression. - -tree -Receive_expression::do_get_tree(Translate_context* context) -{ - Channel_type* channel_type = this->channel_->type()->channel_type(); - if (channel_type == NULL) - { - gcc_assert(this->channel_->type()->is_error_type()); - return error_mark_node; - } - Type* element_type = channel_type->element_type(); - tree element_type_tree = element_type->get_tree(context->gogo()); - - tree channel = this->channel_->get_tree(context); - if (element_type_tree == error_mark_node || channel == error_mark_node) - return error_mark_node; - - return Gogo::receive_from_channel(element_type_tree, channel, - this->for_select_, this->location()); -} - -// Make a receive expression. - -Receive_expression* -Expression::make_receive(Expression* channel, source_location location) -{ - return new Receive_expression(channel, location); -} - -// An expression which evaluates to a pointer to the type descriptor -// of a type. - -class Type_descriptor_expression : public Expression -{ - public: - Type_descriptor_expression(Type* type, source_location location) - : Expression(EXPRESSION_TYPE_DESCRIPTOR, location), - type_(type) - { } - - protected: - Type* - do_type() - { return Type::make_type_descriptor_ptr_type(); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context* context) - { return this->type_->type_descriptor_pointer(context->gogo()); } - - private: - // The type for which this is the descriptor. - Type* type_; -}; - -// Make a type descriptor expression. - -Expression* -Expression::make_type_descriptor(Type* type, source_location location) -{ - return new Type_descriptor_expression(type, location); -} - -// An expression which evaluates to some characteristic of a type. -// This is only used to initialize fields of a type descriptor. Using -// a new expression class is slightly inefficient but gives us a good -// separation between the frontend and the middle-end with regard to -// how types are laid out. - -class Type_info_expression : public Expression -{ - public: - Type_info_expression(Type* type, Type_info type_info) - : Expression(EXPRESSION_TYPE_INFO, BUILTINS_LOCATION), - type_(type), type_info_(type_info) - { } - - protected: - Type* - do_type(); - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context* context); - - private: - // The type for which we are getting information. - Type* type_; - // What information we want. - Type_info type_info_; -}; - -// The type is chosen to match what the type descriptor struct -// expects. - -Type* -Type_info_expression::do_type() -{ - switch (this->type_info_) - { - case TYPE_INFO_SIZE: - return Type::lookup_integer_type("uintptr"); - case TYPE_INFO_ALIGNMENT: - case TYPE_INFO_FIELD_ALIGNMENT: - return Type::lookup_integer_type("uint8"); - default: - gcc_unreachable(); - } -} - -// Return type information in GENERIC. - -tree -Type_info_expression::do_get_tree(Translate_context* context) -{ - tree type_tree = this->type_->get_tree(context->gogo()); - if (type_tree == error_mark_node) - return error_mark_node; - - tree val_type_tree = this->type()->get_tree(context->gogo()); - gcc_assert(val_type_tree != error_mark_node); - - if (this->type_info_ == TYPE_INFO_SIZE) - return fold_convert_loc(BUILTINS_LOCATION, val_type_tree, - TYPE_SIZE_UNIT(type_tree)); - else - { - unsigned int val; - if (this->type_info_ == TYPE_INFO_ALIGNMENT) - val = go_type_alignment(type_tree); - else - val = go_field_alignment(type_tree); - return build_int_cstu(val_type_tree, val); - } -} - -// Make a type info expression. - -Expression* -Expression::make_type_info(Type* type, Type_info type_info) -{ - return new Type_info_expression(type, type_info); -} - -// An expression which evaluates to the offset of a field within a -// struct. This, like Type_info_expression, q.v., is only used to -// initialize fields of a type descriptor. - -class Struct_field_offset_expression : public Expression -{ - public: - Struct_field_offset_expression(Struct_type* type, const Struct_field* field) - : Expression(EXPRESSION_STRUCT_FIELD_OFFSET, BUILTINS_LOCATION), - type_(type), field_(field) - { } - - protected: - Type* - do_type() - { return Type::lookup_integer_type("uintptr"); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return this; } - - tree - do_get_tree(Translate_context* context); - - private: - // The type of the struct. - Struct_type* type_; - // The field. - const Struct_field* field_; -}; - -// Return a struct field offset in GENERIC. - -tree -Struct_field_offset_expression::do_get_tree(Translate_context* context) -{ - tree type_tree = this->type_->get_tree(context->gogo()); - if (type_tree == error_mark_node) - return error_mark_node; - - tree val_type_tree = this->type()->get_tree(context->gogo()); - gcc_assert(val_type_tree != error_mark_node); - - const Struct_field_list* fields = this->type_->fields(); - tree struct_field_tree = TYPE_FIELDS(type_tree); - Struct_field_list::const_iterator p; - for (p = fields->begin(); - p != fields->end(); - ++p, struct_field_tree = DECL_CHAIN(struct_field_tree)) - { - gcc_assert(struct_field_tree != NULL_TREE); - if (&*p == this->field_) - break; - } - gcc_assert(&*p == this->field_); - - return fold_convert_loc(BUILTINS_LOCATION, val_type_tree, - byte_position(struct_field_tree)); -} - -// Make an expression for a struct field offset. - -Expression* -Expression::make_struct_field_offset(Struct_type* type, - const Struct_field* field) -{ - return new Struct_field_offset_expression(type, field); -} - -// An expression which evaluates to the address of an unnamed label. - -class Label_addr_expression : public Expression -{ - public: - Label_addr_expression(Label* label, source_location location) - : Expression(EXPRESSION_LABEL_ADDR, location), - label_(label) - { } - - protected: - Type* - do_type() - { return Type::make_pointer_type(Type::make_void_type()); } - - void - do_determine_type(const Type_context*) - { } - - Expression* - do_copy() - { return new Label_addr_expression(this->label_, this->location()); } - - tree - do_get_tree(Translate_context*) - { return this->label_->get_addr(this->location()); } - - private: - // The label whose address we are taking. - Label* label_; -}; - -// Make an expression for the address of an unnamed label. - -Expression* -Expression::make_label_addr(Label* label, source_location location) -{ - return new Label_addr_expression(label, location); -} - -// Import an expression. This comes at the end in order to see the -// various class definitions. - -Expression* -Expression::import_expression(Import* imp) -{ - int c = imp->peek_char(); - if (imp->match_c_string("- ") - || imp->match_c_string("! ") - || imp->match_c_string("^ ")) - return Unary_expression::do_import(imp); - else if (c == '(') - return Binary_expression::do_import(imp); - else if (imp->match_c_string("true") - || imp->match_c_string("false")) - return Boolean_expression::do_import(imp); - else if (c == '"') - return String_expression::do_import(imp); - else if (c == '-' || (c >= '0' && c <= '9')) - { - // This handles integers, floats and complex constants. - return Integer_expression::do_import(imp); - } - else if (imp->match_c_string("nil")) - return Nil_expression::do_import(imp); - else if (imp->match_c_string("convert")) - return Type_conversion_expression::do_import(imp); - else - { - error_at(imp->location(), "import error: expected expression"); - return Expression::make_error(imp->location()); - } -} - -// Class Expression_list. - -// Traverse the list. - -int -Expression_list::traverse(Traverse* traverse) -{ - for (Expression_list::iterator p = this->begin(); - p != this->end(); - ++p) - { - if (*p != NULL) - { - if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - return TRAVERSE_CONTINUE; -} - -// Copy the list. - -Expression_list* -Expression_list::copy() -{ - Expression_list* ret = new Expression_list(); - for (Expression_list::iterator p = this->begin(); - p != this->end(); - ++p) - { - if (*p == NULL) - ret->push_back(NULL); - else - ret->push_back((*p)->copy()); - } - return ret; -} - -// Return whether an expression list has an error expression. - -bool -Expression_list::contains_error() const -{ - for (Expression_list::const_iterator p = this->begin(); - p != this->end(); - ++p) - if (*p != NULL && (*p)->is_error_expression()) - return true; - return false; -} diff --git a/gcc/go/gofrontend/go.cc.merge-left.r167407 b/gcc/go/gofrontend/go.cc.merge-left.r167407 deleted file mode 100644 index c756084a1dc..00000000000 --- a/gcc/go/gofrontend/go.cc.merge-left.r167407 +++ /dev/null @@ -1,153 +0,0 @@ -// go.cc -- Go frontend main file for gcc. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include "go-c.h" - -#include "lex.h" -#include "parse.h" -#include "gogo.h" - -// The unique prefix to use for exported symbols. This is set during -// option processing. - -static std::string unique_prefix; - -// The data structures we build to represent the file. -static Gogo* gogo; - -// Create the main IR data structure. - -GO_EXTERN_C -void -go_create_gogo(int int_type_size, int float_type_size, int pointer_size) -{ - gcc_assert(::gogo == NULL); - ::gogo = new Gogo(int_type_size, float_type_size, pointer_size); - if (!unique_prefix.empty()) - ::gogo->set_unique_prefix(unique_prefix); -} - -// Set the unique prefix we use for exported symbols. - -GO_EXTERN_C -void -go_set_prefix(const char* arg) -{ - unique_prefix = arg; - for (size_t i = 0; i < unique_prefix.length(); ++i) - { - char c = unique_prefix[i]; - if ((c >= 'a' && c <= 'z') - || (c >= 'A' && c <= 'Z') - || (c >= '0' && c <= '9') - || c == '_') - ; - else - unique_prefix[i] = '_'; - } -} - -// Parse the input files. - -GO_EXTERN_C -void -go_parse_input_files(const char** filenames, unsigned int filename_count, - bool only_check_syntax, bool require_return_statement) -{ - gcc_assert(filename_count > 0); - for (unsigned int i = 0; i < filename_count; ++i) - { - if (i > 0) - ::gogo->clear_file_scope(); - - const char* filename = filenames[i]; - FILE* file; - if (strcmp(filename, "-") == 0) - file = stdin; - else - { - file = fopen(filename, "r"); - if (file == NULL) - fatal_error("cannot open %s: %m", filename); - } - - Lex lexer(filename, file); - - Parse parse(&lexer, ::gogo); - parse.program(); - - if (strcmp(filename, "-") != 0) - fclose(file); - } - - ::gogo->clear_file_scope(); - - // If the global predeclared names are referenced but not defined, - // define them now. - ::gogo->define_global_names(); - - // Finalize method lists and build stub methods for named types. - ::gogo->finalize_methods(); - - // Now that we have seen all the names, lower the parse tree into a - // form which is easier to use. - ::gogo->lower_parse_tree(); - - // Now that we have seen all the names, verify that types are - // correct. - ::gogo->verify_types(); - - // Work out types of unspecified constants and variables. - ::gogo->determine_types(); - - // Check types and issue errors as appropriate. - ::gogo->check_types(); - - if (only_check_syntax) - return; - - // Check that functions have return statements. - if (require_return_statement) - ::gogo->check_return_statements(); - - // Export global identifiers as appropriate. - ::gogo->do_exports(); - - // Build required interface method tables. - ::gogo->build_interface_method_tables(); - - // Turn short-cut operators (&&, ||) into explicit if statements. - ::gogo->remove_shortcuts(); - - // Use temporary variables to force order of evaluation. - ::gogo->order_evaluations(); - - // Build thunks for functions which call recover. - ::gogo->build_recover_thunks(); - - // Convert complicated go and defer statements into simpler ones. - ::gogo->simplify_thunk_statements(); -} - -// Write out globals. - -GO_EXTERN_C -void -go_write_globals() -{ - return ::gogo->write_globals(); -} - -// Return the global IR structure. This is used by some of the -// langhooks to pass to other code. - -Gogo* -go_get_gogo() -{ - return ::gogo; -} diff --git a/gcc/go/gofrontend/go.cc.merge-right.r172891 b/gcc/go/gofrontend/go.cc.merge-right.r172891 deleted file mode 100644 index 3da1404129b..00000000000 --- a/gcc/go/gofrontend/go.cc.merge-right.r172891 +++ /dev/null @@ -1,151 +0,0 @@ -// go.cc -- Go frontend main file for gcc. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include "go-c.h" - -#include "lex.h" -#include "parse.h" -#include "backend.h" -#include "gogo.h" - -// The unique prefix to use for exported symbols. This is set during -// option processing. - -static std::string unique_prefix; - -// The data structures we build to represent the file. -static Gogo* gogo; - -// Create the main IR data structure. - -GO_EXTERN_C -void -go_create_gogo(int int_type_size, int pointer_size) -{ - go_assert(::gogo == NULL); - ::gogo = new Gogo(go_get_backend(), int_type_size, pointer_size); - if (!unique_prefix.empty()) - ::gogo->set_unique_prefix(unique_prefix); -} - -// Set the unique prefix we use for exported symbols. - -GO_EXTERN_C -void -go_set_prefix(const char* arg) -{ - unique_prefix = arg; - for (size_t i = 0; i < unique_prefix.length(); ++i) - { - char c = unique_prefix[i]; - if ((c >= 'a' && c <= 'z') - || (c >= 'A' && c <= 'Z') - || (c >= '0' && c <= '9') - || c == '_') - ; - else - unique_prefix[i] = '_'; - } -} - -// Parse the input files. - -GO_EXTERN_C -void -go_parse_input_files(const char** filenames, unsigned int filename_count, - bool only_check_syntax, bool require_return_statement) -{ - go_assert(filename_count > 0); - for (unsigned int i = 0; i < filename_count; ++i) - { - if (i > 0) - ::gogo->clear_file_scope(); - - const char* filename = filenames[i]; - FILE* file; - if (strcmp(filename, "-") == 0) - file = stdin; - else - { - file = fopen(filename, "r"); - if (file == NULL) - fatal_error("cannot open %s: %m", filename); - } - - Lex lexer(filename, file); - - Parse parse(&lexer, ::gogo); - parse.program(); - - if (strcmp(filename, "-") != 0) - fclose(file); - } - - ::gogo->clear_file_scope(); - - // If the global predeclared names are referenced but not defined, - // define them now. - ::gogo->define_global_names(); - - // Finalize method lists and build stub methods for named types. - ::gogo->finalize_methods(); - - // Now that we have seen all the names, lower the parse tree into a - // form which is easier to use. - ::gogo->lower_parse_tree(); - - // Now that we have seen all the names, verify that types are - // correct. - ::gogo->verify_types(); - - // Work out types of unspecified constants and variables. - ::gogo->determine_types(); - - // Check types and issue errors as appropriate. - ::gogo->check_types(); - - if (only_check_syntax) - return; - - // Check that functions have return statements. - if (require_return_statement) - ::gogo->check_return_statements(); - - // Export global identifiers as appropriate. - ::gogo->do_exports(); - - // Turn short-cut operators (&&, ||) into explicit if statements. - ::gogo->remove_shortcuts(); - - // Use temporary variables to force order of evaluation. - ::gogo->order_evaluations(); - - // Build thunks for functions which call recover. - ::gogo->build_recover_thunks(); - - // Convert complicated go and defer statements into simpler ones. - ::gogo->simplify_thunk_statements(); -} - -// Write out globals. - -GO_EXTERN_C -void -go_write_globals() -{ - return ::gogo->write_globals(); -} - -// Return the global IR structure. This is used by some of the -// langhooks to pass to other code. - -Gogo* -go_get_gogo() -{ - return ::gogo; -} diff --git a/gcc/go/gofrontend/go.cc.working b/gcc/go/gofrontend/go.cc.working deleted file mode 100644 index 7b1fd7eccbb..00000000000 --- a/gcc/go/gofrontend/go.cc.working +++ /dev/null @@ -1,150 +0,0 @@ -// go.cc -- Go frontend main file for gcc. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include "go-c.h" - -#include "lex.h" -#include "parse.h" -#include "gogo.h" - -// The unique prefix to use for exported symbols. This is set during -// option processing. - -static std::string unique_prefix; - -// The data structures we build to represent the file. -static Gogo* gogo; - -// Create the main IR data structure. - -GO_EXTERN_C -void -go_create_gogo(int int_type_size, int pointer_size) -{ - gcc_assert(::gogo == NULL); - ::gogo = new Gogo(int_type_size, pointer_size); - if (!unique_prefix.empty()) - ::gogo->set_unique_prefix(unique_prefix); -} - -// Set the unique prefix we use for exported symbols. - -GO_EXTERN_C -void -go_set_prefix(const char* arg) -{ - unique_prefix = arg; - for (size_t i = 0; i < unique_prefix.length(); ++i) - { - char c = unique_prefix[i]; - if ((c >= 'a' && c <= 'z') - || (c >= 'A' && c <= 'Z') - || (c >= '0' && c <= '9') - || c == '_') - ; - else - unique_prefix[i] = '_'; - } -} - -// Parse the input files. - -GO_EXTERN_C -void -go_parse_input_files(const char** filenames, unsigned int filename_count, - bool only_check_syntax, bool require_return_statement) -{ - gcc_assert(filename_count > 0); - for (unsigned int i = 0; i < filename_count; ++i) - { - if (i > 0) - ::gogo->clear_file_scope(); - - const char* filename = filenames[i]; - FILE* file; - if (strcmp(filename, "-") == 0) - file = stdin; - else - { - file = fopen(filename, "r"); - if (file == NULL) - fatal_error("cannot open %s: %m", filename); - } - - Lex lexer(filename, file); - - Parse parse(&lexer, ::gogo); - parse.program(); - - if (strcmp(filename, "-") != 0) - fclose(file); - } - - ::gogo->clear_file_scope(); - - // If the global predeclared names are referenced but not defined, - // define them now. - ::gogo->define_global_names(); - - // Finalize method lists and build stub methods for named types. - ::gogo->finalize_methods(); - - // Now that we have seen all the names, lower the parse tree into a - // form which is easier to use. - ::gogo->lower_parse_tree(); - - // Now that we have seen all the names, verify that types are - // correct. - ::gogo->verify_types(); - - // Work out types of unspecified constants and variables. - ::gogo->determine_types(); - - // Check types and issue errors as appropriate. - ::gogo->check_types(); - - if (only_check_syntax) - return; - - // Check that functions have return statements. - if (require_return_statement) - ::gogo->check_return_statements(); - - // Export global identifiers as appropriate. - ::gogo->do_exports(); - - // Turn short-cut operators (&&, ||) into explicit if statements. - ::gogo->remove_shortcuts(); - - // Use temporary variables to force order of evaluation. - ::gogo->order_evaluations(); - - // Build thunks for functions which call recover. - ::gogo->build_recover_thunks(); - - // Convert complicated go and defer statements into simpler ones. - ::gogo->simplify_thunk_statements(); -} - -// Write out globals. - -GO_EXTERN_C -void -go_write_globals() -{ - return ::gogo->write_globals(); -} - -// Return the global IR structure. This is used by some of the -// langhooks to pass to other code. - -Gogo* -go_get_gogo() -{ - return ::gogo; -} diff --git a/gcc/go/gofrontend/gogo-tree.cc.merge-left.r167407 b/gcc/go/gofrontend/gogo-tree.cc.merge-left.r167407 deleted file mode 100644 index 755a0e9c784..00000000000 --- a/gcc/go/gofrontend/gogo-tree.cc.merge-left.r167407 +++ /dev/null @@ -1,3105 +0,0 @@ -// gogo-tree.cc -- convert Go frontend Gogo IR to gcc trees. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include - -#ifndef ENABLE_BUILD_WITH_CXX -extern "C" -{ -#endif - -#include "tm.h" -#include "toplev.h" -#include "tree.h" -#include "gimple.h" -#include "tree-iterator.h" -#include "cgraph.h" -#include "langhooks.h" -#include "convert.h" -#include "output.h" -#include "diagnostic.h" -#include "rtl.h" - -#ifndef ENABLE_BUILD_WITH_CXX -} -#endif - -#include "go-c.h" -#include "types.h" -#include "expressions.h" -#include "statements.h" -#include "gogo.h" - -// Whether we have seen any errors. - -bool -saw_errors() -{ - return errorcount != 0 || sorrycount != 0; -} - -// A helper function. - -static inline tree -get_identifier_from_string(const std::string& str) -{ - return get_identifier_with_length(str.data(), str.length()); -} - -// Builtin functions. - -static std::map builtin_functions; - -// Define a builtin function. BCODE is the builtin function code -// defined by builtins.def. NAME is the name of the builtin function. -// LIBNAME is the name of the corresponding library function, and is -// NULL if there isn't one. FNTYPE is the type of the function. -// CONST_P is true if the function has the const attribute. - -static void -define_builtin(built_in_function bcode, const char* name, const char* libname, - tree fntype, bool const_p) -{ - tree decl = add_builtin_function(name, fntype, bcode, BUILT_IN_NORMAL, - libname, NULL_TREE); - if (const_p) - TREE_READONLY(decl) = 1; - built_in_decls[bcode] = decl; - implicit_built_in_decls[bcode] = decl; - builtin_functions[name] = decl; - if (libname != NULL) - { - decl = add_builtin_function(libname, fntype, bcode, BUILT_IN_NORMAL, - NULL, NULL_TREE); - if (const_p) - TREE_READONLY(decl) = 1; - builtin_functions[libname] = decl; - } -} - -// Create trees for implicit builtin functions. - -void -Gogo::define_builtin_function_trees() -{ - /* We need to define the fetch_and_add functions, since we use them - for ++ and --. */ - tree t = go_type_for_size(BITS_PER_UNIT, 1); - tree p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE)); - define_builtin(BUILT_IN_ADD_AND_FETCH_1, "__sync_fetch_and_add_1", NULL, - build_function_type_list(t, p, t, NULL_TREE), false); - - t = go_type_for_size(BITS_PER_UNIT * 2, 1); - p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE)); - define_builtin (BUILT_IN_ADD_AND_FETCH_2, "__sync_fetch_and_add_2", NULL, - build_function_type_list(t, p, t, NULL_TREE), false); - - t = go_type_for_size(BITS_PER_UNIT * 4, 1); - p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE)); - define_builtin(BUILT_IN_ADD_AND_FETCH_4, "__sync_fetch_and_add_4", NULL, - build_function_type_list(t, p, t, NULL_TREE), false); - - t = go_type_for_size(BITS_PER_UNIT * 8, 1); - p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE)); - define_builtin(BUILT_IN_ADD_AND_FETCH_8, "__sync_fetch_and_add_8", NULL, - build_function_type_list(t, p, t, NULL_TREE), false); - - // We use __builtin_expect for magic import functions. - define_builtin(BUILT_IN_EXPECT, "__builtin_expect", NULL, - build_function_type_list(long_integer_type_node, - long_integer_type_node, - long_integer_type_node, - NULL_TREE), - true); - - // We use __builtin_memmove for the predeclared copy function. - define_builtin(BUILT_IN_MEMMOVE, "__builtin_memmove", "memmove", - build_function_type_list(ptr_type_node, - ptr_type_node, - const_ptr_type_node, - size_type_node, - NULL_TREE), - false); - - // We provide sqrt for the math library. - define_builtin(BUILT_IN_SQRT, "__builtin_sqrt", "sqrt", - build_function_type_list(double_type_node, - double_type_node, - NULL_TREE), - true); - define_builtin(BUILT_IN_SQRTL, "__builtin_sqrtl", "sqrtl", - build_function_type_list(long_double_type_node, - long_double_type_node, - NULL_TREE), - true); - - // We use __builtin_return_address in the thunk we build for - // functions which call recover. - define_builtin(BUILT_IN_RETURN_ADDRESS, "__builtin_return_address", NULL, - build_function_type_list(ptr_type_node, - unsigned_type_node, - NULL_TREE), - false); - - // The compiler uses __builtin_trap for some exception handling - // cases. - define_builtin(BUILT_IN_TRAP, "__builtin_trap", NULL, - build_function_type(void_type_node, void_list_node), - false); -} - -// Get the name to use for the import control function. If there is a -// global function or variable, then we know that that name must be -// unique in the link, and we use it as the basis for our name. - -const std::string& -Gogo::get_init_fn_name() -{ - if (this->init_fn_name_.empty()) - { - gcc_assert(this->package_ != NULL); - if (this->package_name() == "main") - { - // Use a name which the runtime knows. - this->init_fn_name_ = "__go_init_main"; - } - else - { - std::string s = this->unique_prefix(); - s.append(1, '.'); - s.append(this->package_name()); - s.append("..import"); - this->init_fn_name_ = s; - } - } - - return this->init_fn_name_; -} - -// Add statements to INIT_STMT_LIST which run the initialization -// functions for imported packages. This is only used for the "main" -// package. - -void -Gogo::init_imports(tree* init_stmt_list) -{ - gcc_assert(this->package_name() == "main"); - - if (this->imported_init_fns_.empty()) - return; - - tree fntype = build_function_type(void_type_node, void_list_node); - - // We must call them in increasing priority order. - std::vector v; - for (std::set::const_iterator p = - this->imported_init_fns_.begin(); - p != this->imported_init_fns_.end(); - ++p) - v.push_back(*p); - std::sort(v.begin(), v.end()); - - for (std::vector::const_iterator p = v.begin(); - p != v.end(); - ++p) - { - std::string user_name = p->package_name() + ".init"; - tree decl = build_decl(UNKNOWN_LOCATION, FUNCTION_DECL, - get_identifier_from_string(user_name), - fntype); - const std::string& init_name(p->init_name()); - SET_DECL_ASSEMBLER_NAME(decl, get_identifier_from_string(init_name)); - TREE_PUBLIC(decl) = 1; - DECL_EXTERNAL(decl) = 1; - append_to_statement_list(build_call_expr(decl, 0), init_stmt_list); - } -} - -// Register global variables with the garbage collector. We need to -// register all variables which can hold a pointer value. They become -// roots during the mark phase. We build a struct that is easy to -// hook into a list of roots. - -// struct __go_gc_root_list -// { -// struct __go_gc_root_list* __next; -// struct __go_gc_root -// { -// void* __decl; -// size_t __size; -// } __roots[]; -// }; - -// The last entry in the roots array has a NULL decl field. - -void -Gogo::register_gc_vars(const std::vector& var_gc, - tree* init_stmt_list) -{ - if (var_gc.empty()) - return; - - size_t count = var_gc.size(); - - tree root_type = Gogo::builtin_struct(NULL, "__go_gc_root", NULL_TREE, 2, - "__next", - ptr_type_node, - "__size", - sizetype); - - tree index_type = build_index_type(size_int(count)); - tree array_type = build_array_type(root_type, index_type); - - tree root_list_type = make_node(RECORD_TYPE); - root_list_type = Gogo::builtin_struct(NULL, "__go_gc_root_list", - root_list_type, 2, - "__next", - build_pointer_type(root_list_type), - "__roots", - array_type); - - // Build an initialier for the __roots array. - - VEC(constructor_elt,gc)* roots_init = VEC_alloc(constructor_elt, gc, - count + 1); - - size_t i = 0; - for (std::vector::const_iterator p = var_gc.begin(); - p != var_gc.end(); - ++p, ++i) - { - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(root_type); - elt->index = field; - tree decl = (*p)->get_tree(this, NULL); - gcc_assert(TREE_CODE(decl) == VAR_DECL); - elt->value = build_fold_addr_expr(decl); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - elt->index = field; - elt->value = DECL_SIZE_UNIT(decl); - - elt = VEC_quick_push(constructor_elt, roots_init, NULL); - elt->index = size_int(i); - elt->value = build_constructor(root_type, init); - } - - // The list ends with a NULL entry. - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(root_type); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), null_pointer_node); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - elt->index = field; - elt->value = size_zero_node; - - elt = VEC_quick_push(constructor_elt, roots_init, NULL); - elt->index = size_int(i); - elt->value = build_constructor(root_type, init); - - // Build a constructor for the struct. - - VEC(constructor_elt,gc*) root_list_init = VEC_alloc(constructor_elt, gc, 2); - - elt = VEC_quick_push(constructor_elt, root_list_init, NULL); - field = TYPE_FIELDS(root_list_type); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), null_pointer_node); - - elt = VEC_quick_push(constructor_elt, root_list_init, NULL); - field = DECL_CHAIN(field); - elt->index = field; - elt->value = build_constructor(array_type, roots_init); - - // Build a decl to register. - - tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, - create_tmp_var_name("gc"), root_list_type); - DECL_EXTERNAL(decl) = 0; - TREE_PUBLIC(decl) = 0; - TREE_STATIC(decl) = 1; - DECL_ARTIFICIAL(decl) = 1; - DECL_INITIAL(decl) = build_constructor(root_list_type, root_list_init); - rest_of_decl_compilation(decl, 1, 0); - - static tree register_gc_fndecl; - tree call = Gogo::call_builtin(®ister_gc_fndecl, BUILTINS_LOCATION, - "__go_register_gc_roots", - 1, - void_type_node, - build_pointer_type(root_list_type), - build_fold_addr_expr(decl)); - append_to_statement_list(call, init_stmt_list); -} - -// Build the decl for the initialization function. - -tree -Gogo::initialization_function_decl() -{ - // The tedious details of building your own function. There doesn't - // seem to be a helper function for this. - std::string name = this->package_name() + ".init"; - tree fndecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL, - get_identifier_from_string(name), - build_function_type(void_type_node, - void_list_node)); - const std::string& asm_name(this->get_init_fn_name()); - SET_DECL_ASSEMBLER_NAME(fndecl, get_identifier_from_string(asm_name)); - - tree resdecl = build_decl(BUILTINS_LOCATION, RESULT_DECL, NULL_TREE, - void_type_node); - DECL_ARTIFICIAL(resdecl) = 1; - DECL_CONTEXT(resdecl) = fndecl; - DECL_RESULT(fndecl) = resdecl; - - TREE_STATIC(fndecl) = 1; - TREE_USED(fndecl) = 1; - DECL_ARTIFICIAL(fndecl) = 1; - TREE_PUBLIC(fndecl) = 1; - - DECL_INITIAL(fndecl) = make_node(BLOCK); - TREE_USED(DECL_INITIAL(fndecl)) = 1; - - return fndecl; -} - -// Create the magic initialization function. INIT_STMT_LIST is the -// code that it needs to run. - -void -Gogo::write_initialization_function(tree fndecl, tree init_stmt_list) -{ - // Make sure that we thought we needed an initialization function, - // as otherwise we will not have reported it in the export data. - gcc_assert(this->package_name() == "main" || this->need_init_fn_); - - if (fndecl == NULL_TREE) - fndecl = this->initialization_function_decl(); - - DECL_SAVED_TREE(fndecl) = init_stmt_list; - - current_function_decl = fndecl; - if (DECL_STRUCT_FUNCTION(fndecl) == NULL) - push_struct_function(fndecl); - else - push_cfun(DECL_STRUCT_FUNCTION(fndecl)); - cfun->function_end_locus = BUILTINS_LOCATION; - - gimplify_function_tree(fndecl); - - cgraph_add_new_function(fndecl, false); - cgraph_mark_needed_node(cgraph_node(fndecl)); - - current_function_decl = NULL_TREE; - pop_cfun(); -} - -// Search for references to VAR in any statements or called functions. - -class Find_var : public Traverse -{ - public: - // A hash table we use to avoid looping. The index is the name of a - // named object. We only look through objects defined in this - // package. - typedef Unordered_set(std::string) Seen_objects; - - Find_var(Named_object* var, Seen_objects* seen_objects) - : Traverse(traverse_expressions), - var_(var), seen_objects_(seen_objects), found_(false) - { } - - // Whether the variable was found. - bool - found() const - { return this->found_; } - - int - expression(Expression**); - - private: - // The variable we are looking for. - Named_object* var_; - // Names of objects we have already seen. - Seen_objects* seen_objects_; - // True if the variable was found. - bool found_; -}; - -// See if EXPR refers to VAR, looking through function calls and -// variable initializations. - -int -Find_var::expression(Expression** pexpr) -{ - Expression* e = *pexpr; - - Var_expression* ve = e->var_expression(); - if (ve != NULL) - { - Named_object* v = ve->named_object(); - if (v == this->var_) - { - this->found_ = true; - return TRAVERSE_EXIT; - } - - if (v->is_variable() && v->package() == NULL) - { - Expression* init = v->var_value()->init(); - if (init != NULL) - { - std::pair ins = - this->seen_objects_->insert(v->name()); - if (ins.second) - { - // This is the first time we have seen this name. - if (Expression::traverse(&init, this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - } - } - - // We traverse the code of any function we see. Note that this - // means that we will traverse the code of a function whose address - // is taken even if it is not called. - Func_expression* fe = e->func_expression(); - if (fe != NULL) - { - const Named_object* f = fe->named_object(); - if (f->is_function() && f->package() == NULL) - { - std::pair ins = - this->seen_objects_->insert(f->name()); - if (ins.second) - { - // This is the first time we have seen this name. - if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - } - - return TRAVERSE_CONTINUE; -} - -// Return true if EXPR refers to VAR. - -static bool -expression_requires(Expression* expr, Block* preinit, Named_object* var) -{ - Find_var::Seen_objects seen_objects; - Find_var find_var(var, &seen_objects); - if (expr != NULL) - Expression::traverse(&expr, &find_var); - if (preinit != NULL) - preinit->traverse(&find_var); - - return find_var.found(); -} - -// Sort variable initializations. If the initialization expression -// for variable A refers directly or indirectly to the initialization -// expression for variable B, then we must initialize B before A. - -class Var_init -{ - public: - Var_init() - : var_(NULL), init_(NULL_TREE), waiting_(0) - { } - - Var_init(Named_object* var, tree init) - : var_(var), init_(init), waiting_(0) - { } - - // Return the variable. - Named_object* - var() const - { return this->var_; } - - // Return the initialization expression. - tree - init() const - { return this->init_; } - - // Return the number of variables waiting for this one to be - // initialized. - size_t - waiting() const - { return this->waiting_; } - - // Increment the number waiting. - void - increment_waiting() - { ++this->waiting_; } - - private: - // The variable being initialized. - Named_object* var_; - // The initialization expression to run. - tree init_; - // The number of variables which are waiting for this one. - size_t waiting_; -}; - -typedef std::list Var_inits; - -// Sort the variable initializations. The rule we follow is that we -// emit them in the order they appear in the array, except that if the -// initialization expression for a variable V1 depends upon another -// variable V2 then we initialize V1 after V2. - -static void -sort_var_inits(Var_inits* var_inits) -{ - Var_inits ready; - while (!var_inits->empty()) - { - Var_inits::iterator p1 = var_inits->begin(); - Named_object* var = p1->var(); - Expression* init = var->var_value()->init(); - Block* preinit = var->var_value()->preinit(); - - // Start walking through the list to see which variables VAR - // needs to wait for. We can skip P1->WAITING variables--that - // is the number we've already checked. - Var_inits::iterator p2 = p1; - ++p2; - for (size_t i = p1->waiting(); i > 0; --i) - ++p2; - - for (; p2 != var_inits->end(); ++p2) - { - if (expression_requires(init, preinit, p2->var())) - { - // Check for cycles. - if (expression_requires(p2->var()->var_value()->init(), - p2->var()->var_value()->preinit(), - var)) - { - error_at(var->location(), - ("initialization expressions for %qs and " - "%qs depend upon each other"), - var->message_name().c_str(), - p2->var()->message_name().c_str()); - inform(p2->var()->location(), "%qs defined here", - p2->var()->message_name().c_str()); - p2 = var_inits->end(); - } - else - { - // We can't emit P1 until P2 is emitted. Move P1. - // Note that the WAITING loop always executes at - // least once, which is what we want. - p2->increment_waiting(); - Var_inits::iterator p3 = p2; - for (size_t i = p2->waiting(); i > 0; --i) - ++p3; - var_inits->splice(p3, *var_inits, p1); - } - break; - } - } - - if (p2 == var_inits->end()) - { - // VAR does not depends upon any other initialization expressions. - - // Check for a loop of VAR on itself. We only do this if - // INIT is not NULL; when INIT is NULL, it means that - // PREINIT sets VAR, which we will interpret as a loop. - if (init != NULL && expression_requires(init, preinit, var)) - error_at(var->location(), - "initialization expression for %qs depends upon itself", - var->message_name().c_str()); - ready.splice(ready.end(), *var_inits, p1); - } - } - - // Now READY is the list in the desired initialization order. - var_inits->swap(ready); -} - -// Write out the global definitions. - -void -Gogo::write_globals() -{ - Bindings* bindings = this->current_bindings(); - size_t count = bindings->size_definitions(); - - tree* vec = new tree[count]; - - tree init_fndecl = NULL_TREE; - tree init_stmt_list = NULL_TREE; - - if (this->package_name() == "main") - this->init_imports(&init_stmt_list); - - // A list of variable initializations. - Var_inits var_inits; - - // A list of variables which need to be registered with the garbage - // collector. - std::vector var_gc; - var_gc.reserve(count); - - tree var_init_stmt_list = NULL_TREE; - size_t i = 0; - for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); - p != bindings->end_definitions(); - ++p, ++i) - { - Named_object* no = *p; - - gcc_assert(!no->is_type_declaration() && !no->is_function_declaration()); - // There is nothing to do for a package. - if (no->is_package()) - { - --i; - --count; - continue; - } - - // There is nothing to do for an object which was imported from - // a different package into the global scope. - if (no->package() != NULL) - { - --i; - --count; - continue; - } - - // There is nothing useful we can output for constants which - // have ideal or non-integeral type. - if (no->is_const()) - { - Type* type = no->const_value()->type(); - if (type == NULL) - type = no->const_value()->expr()->type(); - if (type->is_abstract() || type->integer_type() == NULL) - { - --i; - --count; - continue; - } - } - - vec[i] = no->get_tree(this, NULL); - - if (vec[i] == error_mark_node) - { - gcc_assert(saw_errors()); - --i; - --count; - continue; - } - - // If a variable is initialized to a non-constant value, do the - // initialization in an initialization function. - if (TREE_CODE(vec[i]) == VAR_DECL) - { - gcc_assert(no->is_variable()); - - // Check for a sink variable, which may be used to run - // an initializer purely for its side effects. - bool is_sink = no->name()[0] == '_' && no->name()[1] == '.'; - - tree var_init_tree = NULL_TREE; - if (!no->var_value()->has_pre_init()) - { - tree init = no->var_value()->get_init_tree(this, NULL); - if (init == error_mark_node) - gcc_assert(saw_errors()); - else if (init == NULL_TREE) - ; - else if (TREE_CONSTANT(init)) - DECL_INITIAL(vec[i]) = init; - else if (is_sink) - var_init_tree = init; - else - var_init_tree = fold_build2_loc(no->location(), MODIFY_EXPR, - void_type_node, vec[i], init); - } - else - { - // We are going to create temporary variables which - // means that we need an fndecl. - if (init_fndecl == NULL_TREE) - init_fndecl = this->initialization_function_decl(); - current_function_decl = init_fndecl; - if (DECL_STRUCT_FUNCTION(init_fndecl) == NULL) - push_struct_function(init_fndecl); - else - push_cfun(DECL_STRUCT_FUNCTION(init_fndecl)); - - tree var_decl = is_sink ? NULL_TREE : vec[i]; - var_init_tree = no->var_value()->get_init_block(this, NULL, - var_decl); - - current_function_decl = NULL_TREE; - pop_cfun(); - } - - if (var_init_tree != NULL_TREE) - { - if (no->var_value()->init() == NULL - && !no->var_value()->has_pre_init()) - append_to_statement_list(var_init_tree, &var_init_stmt_list); - else - var_inits.push_back(Var_init(no, var_init_tree)); - } - - if (!is_sink && no->var_value()->type()->has_pointer()) - var_gc.push_back(no); - } - } - - // Register global variables with the garbage collector. - this->register_gc_vars(var_gc, &init_stmt_list); - - // Simple variable initializations, after all variables are - // registered. - append_to_statement_list(var_init_stmt_list, &init_stmt_list); - - // Complex variable initializations, first sorting them into a - // workable order. - if (!var_inits.empty()) - { - sort_var_inits(&var_inits); - for (Var_inits::const_iterator p = var_inits.begin(); - p != var_inits.end(); - ++p) - append_to_statement_list(p->init(), &init_stmt_list); - } - - // After all the variables are initialized, call the "init" - // functions if there are any. - for (std::vector::const_iterator p = - this->init_functions_.begin(); - p != this->init_functions_.end(); - ++p) - { - tree decl = (*p)->get_tree(this, NULL); - tree call = build_call_expr(decl, 0); - append_to_statement_list(call, &init_stmt_list); - } - - // Set up a magic function to do all the initialization actions. - // This will be called if this package is imported. - if (init_stmt_list != NULL_TREE - || this->need_init_fn_ - || this->package_name() == "main") - this->write_initialization_function(init_fndecl, init_stmt_list); - - // Pass everything back to the middle-end. - - if (this->imported_unsafe_) - { - // Importing the "unsafe" package automatically disables TBAA. - flag_strict_aliasing = false; - - // This is a real hack. init_varasm_once has already grabbed an - // alias set, which we don't want when we aren't going strict - // aliasing. We reinitialize to make it do it again. FIXME. - init_varasm_once(); - } - - wrapup_global_declarations(vec, count); - - cgraph_finalize_compilation_unit(); - - check_global_declarations(vec, count); - emit_debug_global_declarations(vec, count); - - delete[] vec; -} - -// Get a tree for the identifier for a named object. - -tree -Named_object::get_id(Gogo* gogo) -{ - std::string decl_name; - if (this->is_function_declaration() - && !this->func_declaration_value()->asm_name().empty()) - decl_name = this->func_declaration_value()->asm_name(); - else if ((this->is_variable() && !this->var_value()->is_global()) - || (this->is_type() - && this->type_value()->location() == BUILTINS_LOCATION)) - { - // We don't need the package name for local variables or builtin - // types. - decl_name = Gogo::unpack_hidden_name(this->name_); - } - else if (this->is_function() - && !this->func_value()->is_method() - && this->package_ == NULL - && Gogo::unpack_hidden_name(this->name_) == "init") - { - // A single package can have multiple "init" functions, which - // means that we need to give them different names. - static int init_index; - char buf[20]; - snprintf(buf, sizeof buf, "%d", init_index); - ++init_index; - decl_name = gogo->package_name() + ".init." + buf; - } - else - { - std::string package_name; - if (this->package_ == NULL) - package_name = gogo->package_name(); - else - package_name = this->package_->name(); - - decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_); - - Function_type* fntype; - if (this->is_function()) - fntype = this->func_value()->type(); - else if (this->is_function_declaration()) - fntype = this->func_declaration_value()->type(); - else - fntype = NULL; - if (fntype != NULL && fntype->is_method()) - { - decl_name.push_back('.'); - decl_name.append(fntype->receiver()->type()->mangled_name(gogo)); - } - } - if (this->is_type()) - { - const Named_object* in_function = this->type_value()->in_function(); - if (in_function != NULL) - decl_name += '$' + in_function->name(); - } - return get_identifier_from_string(decl_name); -} - -// Get a tree for a named object. - -tree -Named_object::get_tree(Gogo* gogo, Named_object* function) -{ - if (this->tree_ != NULL_TREE) - { - // If this is a variable whose address is taken, we must rebuild - // the INDIRECT_REF each time to avoid invalid sharing. - tree ret = this->tree_; - if (((this->classification_ == NAMED_OBJECT_VAR - && this->var_value()->is_in_heap()) - || (this->classification_ == NAMED_OBJECT_RESULT_VAR - && this->result_var_value()->is_in_heap())) - && ret != error_mark_node) - { - gcc_assert(TREE_CODE(ret) == INDIRECT_REF); - ret = build_fold_indirect_ref(TREE_OPERAND(ret, 0)); - TREE_THIS_NOTRAP(ret) = 1; - } - return ret; - } - - tree name; - if (this->classification_ == NAMED_OBJECT_TYPE) - name = NULL_TREE; - else - name = this->get_id(gogo); - tree decl; - switch (this->classification_) - { - case NAMED_OBJECT_CONST: - { - Named_constant* named_constant = this->u_.const_value; - Translate_context subcontext(gogo, function, NULL, NULL_TREE); - tree expr_tree = named_constant->expr()->get_tree(&subcontext); - if (expr_tree == error_mark_node) - decl = error_mark_node; - else - { - Type* type = named_constant->type(); - if (type != NULL && !type->is_abstract()) - expr_tree = fold_convert(type->get_tree(gogo), expr_tree); - if (expr_tree == error_mark_node) - decl = error_mark_node; - else if (INTEGRAL_TYPE_P(TREE_TYPE(expr_tree))) - { - decl = build_decl(named_constant->location(), CONST_DECL, - name, TREE_TYPE(expr_tree)); - DECL_INITIAL(decl) = expr_tree; - TREE_CONSTANT(decl) = 1; - TREE_READONLY(decl) = 1; - } - else - { - // A CONST_DECL is only for an enum constant, so we - // shouldn't use for non-integral types. Instead we - // just return the constant itself, rather than a - // decl. - decl = expr_tree; - } - } - } - break; - - case NAMED_OBJECT_TYPE: - { - Named_type* named_type = this->u_.type_value; - tree type_tree = named_type->get_tree(gogo); - if (type_tree == error_mark_node) - decl = error_mark_node; - else - { - decl = TYPE_NAME(type_tree); - gcc_assert(decl != NULL_TREE); - - // We need to produce a type descriptor for every named - // type, and for a pointer to every named type, since - // other files or packages might refer to them. We need - // to do this even for hidden types, because they might - // still be returned by some function. Simply calling the - // type_descriptor method is enough to create the type - // descriptor, even though we don't do anything with it. - if (this->package_ == NULL) - { - named_type->type_descriptor_pointer(gogo); - Type* pn = Type::make_pointer_type(named_type); - pn->type_descriptor_pointer(gogo); - } - } - } - break; - - case NAMED_OBJECT_TYPE_DECLARATION: - error("reference to undefined type %qs", - this->message_name().c_str()); - return error_mark_node; - - case NAMED_OBJECT_VAR: - { - Variable* var = this->u_.var_value; - Type* type = var->type(); - if (type->is_error_type() - || (type->is_undefined() - && (!var->is_global() || this->package() == NULL))) - { - // Force the error for an undefined type, just in case. - type->base(); - decl = error_mark_node; - } - else - { - tree var_type = type->get_tree(gogo); - bool is_parameter = var->is_parameter(); - if (var->is_receiver() && type->points_to() == NULL) - is_parameter = false; - if (var->is_in_heap()) - { - is_parameter = false; - var_type = build_pointer_type(var_type); - } - decl = build_decl(var->location(), - is_parameter ? PARM_DECL : VAR_DECL, - name, var_type); - if (!var->is_global()) - { - tree fnid = function->get_id(gogo); - tree fndecl = function->func_value()->get_or_make_decl(gogo, - function, - fnid); - DECL_CONTEXT(decl) = fndecl; - } - if (is_parameter) - DECL_ARG_TYPE(decl) = TREE_TYPE(decl); - - if (var->is_global()) - { - const Package* package = this->package(); - if (package == NULL) - TREE_STATIC(decl) = 1; - else - DECL_EXTERNAL(decl) = 1; - if (!Gogo::is_hidden_name(this->name_)) - { - TREE_PUBLIC(decl) = 1; - std::string asm_name = (package == NULL - ? gogo->unique_prefix() - : package->unique_prefix()); - asm_name.append(1, '.'); - asm_name.append(IDENTIFIER_POINTER(name), - IDENTIFIER_LENGTH(name)); - tree asm_id = get_identifier_from_string(asm_name); - SET_DECL_ASSEMBLER_NAME(decl, asm_id); - } - } - - // FIXME: We should only set this for variables which are - // actually used somewhere. - TREE_USED(decl) = 1; - } - } - break; - - case NAMED_OBJECT_RESULT_VAR: - { - Result_variable* result = this->u_.result_var_value; - Type* type = result->type(); - if (type->is_error_type() || type->is_undefined()) - { - // Force the error. - type->base(); - decl = error_mark_node; - } - else - { - gcc_assert(result->function() == function->func_value()); - source_location loc = function->location(); - tree result_type = type->get_tree(gogo); - tree init; - if (!result->is_in_heap()) - init = type->get_init_tree(gogo, false); - else - { - tree space = gogo->allocate_memory(type, - TYPE_SIZE_UNIT(result_type), - loc); - result_type = build_pointer_type(result_type); - tree subinit = type->get_init_tree(gogo, true); - if (subinit == NULL_TREE) - init = fold_convert_loc(loc, result_type, space); - else - { - space = save_expr(space); - space = fold_convert_loc(loc, result_type, space); - tree spaceref = build_fold_indirect_ref_loc(loc, space); - TREE_THIS_NOTRAP(spaceref) = 1; - tree set = fold_build2_loc(loc, MODIFY_EXPR, void_type_node, - spaceref, subinit); - init = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(space), - set, space); - } - } - decl = build_decl(loc, VAR_DECL, name, result_type); - tree fnid = function->get_id(gogo); - tree fndecl = function->func_value()->get_or_make_decl(gogo, - function, - fnid); - DECL_CONTEXT(decl) = fndecl; - DECL_INITIAL(decl) = init; - TREE_USED(decl) = 1; - } - } - break; - - case NAMED_OBJECT_SINK: - gcc_unreachable(); - - case NAMED_OBJECT_FUNC: - { - Function* func = this->u_.func_value; - decl = func->get_or_make_decl(gogo, this, name); - if (decl != error_mark_node) - { - if (func->block() != NULL) - { - if (DECL_STRUCT_FUNCTION(decl) == NULL) - push_struct_function(decl); - else - push_cfun(DECL_STRUCT_FUNCTION(decl)); - - cfun->function_end_locus = func->block()->end_location(); - - current_function_decl = decl; - - func->build_tree(gogo, this); - - gimplify_function_tree(decl); - - cgraph_finalize_function(decl, true); - - current_function_decl = NULL_TREE; - pop_cfun(); - } - } - } - break; - - default: - gcc_unreachable(); - } - - if (TREE_TYPE(decl) == error_mark_node) - decl = error_mark_node; - - tree ret = decl; - - // If this is a local variable whose address is taken, then we - // actually store it in the heap. For uses of the variable we need - // to return a reference to that heap location. - if (((this->classification_ == NAMED_OBJECT_VAR - && this->var_value()->is_in_heap()) - || (this->classification_ == NAMED_OBJECT_RESULT_VAR - && this->result_var_value()->is_in_heap())) - && ret != error_mark_node) - { - gcc_assert(POINTER_TYPE_P(TREE_TYPE(ret))); - ret = build_fold_indirect_ref(ret); - TREE_THIS_NOTRAP(ret) = 1; - } - - this->tree_ = ret; - - if (ret != error_mark_node) - go_preserve_from_gc(ret); - - return ret; -} - -// Get the initial value of a variable as a tree. This does not -// consider whether the variable is in the heap--it returns the -// initial value as though it were always stored in the stack. - -tree -Variable::get_init_tree(Gogo* gogo, Named_object* function) -{ - gcc_assert(this->preinit_ == NULL); - if (this->init_ == NULL) - { - gcc_assert(!this->is_parameter_); - return this->type_->get_init_tree(gogo, this->is_global_); - } - else - { - Translate_context context(gogo, function, NULL, NULL_TREE); - tree rhs_tree = this->init_->get_tree(&context); - return Expression::convert_for_assignment(&context, this->type(), - this->init_->type(), - rhs_tree, this->location()); - } -} - -// Get the initial value of a variable when a block is required. -// VAR_DECL is the decl to set; it may be NULL for a sink variable. - -tree -Variable::get_init_block(Gogo* gogo, Named_object* function, tree var_decl) -{ - gcc_assert(this->preinit_ != NULL); - - // We want to add the variable assignment to the end of the preinit - // block. The preinit block may have a TRY_FINALLY_EXPR and a - // TRY_CATCH_EXPR; if it does, we want to add to the end of the - // regular statements. - - Translate_context context(gogo, function, NULL, NULL_TREE); - tree block_tree = this->preinit_->get_tree(&context); - gcc_assert(TREE_CODE(block_tree) == BIND_EXPR); - tree statements = BIND_EXPR_BODY(block_tree); - while (TREE_CODE(statements) == TRY_FINALLY_EXPR - || TREE_CODE(statements) == TRY_CATCH_EXPR) - statements = TREE_OPERAND(statements, 0); - - // It's possible to have pre-init statements without an initializer - // if the pre-init statements set the variable. - if (this->init_ != NULL) - { - tree rhs_tree = this->init_->get_tree(&context); - if (var_decl == NULL_TREE) - append_to_statement_list(rhs_tree, &statements); - else - { - tree val = Expression::convert_for_assignment(&context, this->type(), - this->init_->type(), - rhs_tree, - this->location()); - tree set = fold_build2_loc(this->location(), MODIFY_EXPR, - void_type_node, var_decl, val); - append_to_statement_list(set, &statements); - } - } - - return block_tree; -} - -// Get a tree for a function decl. - -tree -Function::get_or_make_decl(Gogo* gogo, Named_object* no, tree id) -{ - if (this->fndecl_ == NULL_TREE) - { - tree functype = this->type_->get_tree(gogo); - if (functype == error_mark_node) - this->fndecl_ = error_mark_node; - else - { - // The type of a function comes back as a pointer, but we - // want the real function type for a function declaration. - gcc_assert(POINTER_TYPE_P(functype)); - functype = TREE_TYPE(functype); - tree decl = build_decl(this->location(), FUNCTION_DECL, id, functype); - - this->fndecl_ = decl; - - gcc_assert(no->package() == NULL); - if (this->enclosing_ != NULL || Gogo::is_thunk(no)) - ; - else if (Gogo::unpack_hidden_name(no->name()) == "init" - && !this->type_->is_method()) - ; - else if (Gogo::unpack_hidden_name(no->name()) == "main" - && gogo->package_name() == "main") - TREE_PUBLIC(decl) = 1; - // Methods have to be public even if they are hidden because - // they can be pulled into type descriptors when using - // anonymous fields. - else if (!Gogo::is_hidden_name(no->name()) - || this->type_->is_method()) - { - TREE_PUBLIC(decl) = 1; - std::string asm_name = gogo->unique_prefix(); - asm_name.append(1, '.'); - asm_name.append(IDENTIFIER_POINTER(id), IDENTIFIER_LENGTH(id)); - SET_DECL_ASSEMBLER_NAME(decl, - get_identifier_from_string(asm_name)); - } - - // Why do we have to do this in the frontend? - tree restype = TREE_TYPE(functype); - tree resdecl = build_decl(this->location(), RESULT_DECL, NULL_TREE, - restype); - DECL_ARTIFICIAL(resdecl) = 1; - DECL_IGNORED_P(resdecl) = 1; - DECL_CONTEXT(resdecl) = decl; - DECL_RESULT(decl) = resdecl; - - if (this->enclosing_ != NULL) - DECL_STATIC_CHAIN(decl) = 1; - - // If a function calls the predeclared recover function, we - // can't inline it, because recover behaves differently in a - // function passed directly to defer. - if (this->calls_recover_ && !this->is_recover_thunk_) - DECL_UNINLINABLE(decl) = 1; - - // If this is a thunk created to call a function which calls - // the predeclared recover function, we need to disable - // stack splitting for the thunk. - if (this->is_recover_thunk_) - { - tree attr = get_identifier("__no_split_stack__"); - DECL_ATTRIBUTES(decl) = tree_cons(attr, NULL_TREE, NULL_TREE); - } - - go_preserve_from_gc(decl); - - if (this->closure_var_ != NULL) - { - push_struct_function(decl); - - tree closure_decl = this->closure_var_->get_tree(gogo, no); - - DECL_ARTIFICIAL(closure_decl) = 1; - DECL_IGNORED_P(closure_decl) = 1; - TREE_USED(closure_decl) = 1; - DECL_ARG_TYPE(closure_decl) = TREE_TYPE(closure_decl); - TREE_READONLY(closure_decl) = 1; - - DECL_STRUCT_FUNCTION(decl)->static_chain_decl = closure_decl; - pop_cfun(); - } - } - } - return this->fndecl_; -} - -// Get a tree for a function declaration. - -tree -Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no, tree id) -{ - if (this->fndecl_ == NULL_TREE) - { - // Let Go code use an asm declaration to pick up a builtin - // function. - if (!this->asm_name_.empty()) - { - std::map::const_iterator p = - builtin_functions.find(this->asm_name_); - if (p != builtin_functions.end()) - { - this->fndecl_ = p->second; - return this->fndecl_; - } - } - - tree functype = this->fntype_->get_tree(gogo); - tree decl; - if (functype == error_mark_node) - decl = error_mark_node; - else - { - // The type of a function comes back as a pointer, but we - // want the real function type for a function declaration. - gcc_assert(POINTER_TYPE_P(functype)); - functype = TREE_TYPE(functype); - decl = build_decl(this->location(), FUNCTION_DECL, id, functype); - TREE_PUBLIC(decl) = 1; - DECL_EXTERNAL(decl) = 1; - - if (this->asm_name_.empty()) - { - std::string asm_name = (no->package() == NULL - ? gogo->unique_prefix() - : no->package()->unique_prefix()); - asm_name.append(1, '.'); - asm_name.append(IDENTIFIER_POINTER(id), IDENTIFIER_LENGTH(id)); - SET_DECL_ASSEMBLER_NAME(decl, - get_identifier_from_string(asm_name)); - } - } - this->fndecl_ = decl; - go_preserve_from_gc(decl); - } - return this->fndecl_; -} - -// We always pass the receiver to a method as a pointer. If the -// receiver is actually declared as a non-pointer type, then we copy -// the value into a local variable, so that it has the right type. In -// this function we create the real PARM_DECL to use, and set -// DEC_INITIAL of the var_decl to be the value passed in. - -tree -Function::make_receiver_parm_decl(Gogo* gogo, Named_object* no, tree var_decl) -{ - // If the function takes the address of a receiver which is passed - // by value, then we will have an INDIRECT_REF here. We need to get - // the real variable. - bool is_in_heap = no->var_value()->is_in_heap(); - tree val_type; - if (TREE_CODE(var_decl) != INDIRECT_REF) - { - gcc_assert(!is_in_heap); - val_type = TREE_TYPE(var_decl); - } - else - { - gcc_assert(is_in_heap); - var_decl = TREE_OPERAND(var_decl, 0); - gcc_assert(POINTER_TYPE_P(TREE_TYPE(var_decl))); - val_type = TREE_TYPE(TREE_TYPE(var_decl)); - } - gcc_assert(TREE_CODE(var_decl) == VAR_DECL); - source_location loc = DECL_SOURCE_LOCATION(var_decl); - std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl)); - name += ".pointer"; - tree id = get_identifier_from_string(name); - tree parm_decl = build_decl(loc, PARM_DECL, id, build_pointer_type(val_type)); - DECL_CONTEXT(parm_decl) = current_function_decl; - DECL_ARG_TYPE(parm_decl) = TREE_TYPE(parm_decl); - - gcc_assert(DECL_INITIAL(var_decl) == NULL_TREE); - // The receiver might be passed as a null pointer. - tree check = fold_build2_loc(loc, NE_EXPR, boolean_type_node, parm_decl, - fold_convert_loc(loc, TREE_TYPE(parm_decl), - null_pointer_node)); - tree ind = build_fold_indirect_ref_loc(loc, parm_decl); - TREE_THIS_NOTRAP(ind) = 1; - tree zero_init = no->var_value()->type()->get_init_tree(gogo, false); - tree init = fold_build3_loc(loc, COND_EXPR, TREE_TYPE(ind), - check, ind, zero_init); - - if (is_in_heap) - { - tree size = TYPE_SIZE_UNIT(val_type); - tree space = gogo->allocate_memory(no->var_value()->type(), size, - no->location()); - space = save_expr(space); - space = fold_convert(build_pointer_type(val_type), space); - tree spaceref = build_fold_indirect_ref_loc(no->location(), space); - TREE_THIS_NOTRAP(spaceref) = 1; - tree check = fold_build2_loc(loc, NE_EXPR, boolean_type_node, - parm_decl, - fold_convert_loc(loc, TREE_TYPE(parm_decl), - null_pointer_node)); - tree parmref = build_fold_indirect_ref_loc(no->location(), parm_decl); - TREE_THIS_NOTRAP(parmref) = 1; - tree set = fold_build2_loc(loc, MODIFY_EXPR, void_type_node, - spaceref, parmref); - init = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(space), - build3(COND_EXPR, void_type_node, - check, set, NULL_TREE), - space); - } - - DECL_INITIAL(var_decl) = init; - - return parm_decl; -} - -// If we take the address of a parameter, then we need to copy it into -// the heap. We will access it as a local variable via an -// indirection. - -tree -Function::copy_parm_to_heap(Gogo* gogo, Named_object* no, tree ref) -{ - gcc_assert(TREE_CODE(ref) == INDIRECT_REF); - - tree var_decl = TREE_OPERAND(ref, 0); - gcc_assert(TREE_CODE(var_decl) == VAR_DECL); - source_location loc = DECL_SOURCE_LOCATION(var_decl); - - std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl)); - name += ".param"; - tree id = get_identifier_from_string(name); - - tree type = TREE_TYPE(var_decl); - gcc_assert(POINTER_TYPE_P(type)); - type = TREE_TYPE(type); - - tree parm_decl = build_decl(loc, PARM_DECL, id, type); - DECL_CONTEXT(parm_decl) = current_function_decl; - DECL_ARG_TYPE(parm_decl) = type; - - tree size = TYPE_SIZE_UNIT(type); - tree space = gogo->allocate_memory(no->var_value()->type(), size, loc); - space = save_expr(space); - space = fold_convert(TREE_TYPE(var_decl), space); - tree spaceref = build_fold_indirect_ref_loc(loc, space); - TREE_THIS_NOTRAP(spaceref) = 1; - tree init = build2(COMPOUND_EXPR, TREE_TYPE(space), - build2(MODIFY_EXPR, void_type_node, spaceref, parm_decl), - space); - DECL_INITIAL(var_decl) = init; - - return parm_decl; -} - -// Get a tree for function code. - -void -Function::build_tree(Gogo* gogo, Named_object* named_function) -{ - tree fndecl = this->fndecl_; - gcc_assert(fndecl != NULL_TREE); - - tree params = NULL_TREE; - tree* pp = ¶ms; - - tree declare_vars = NULL_TREE; - for (Bindings::const_definitions_iterator p = - this->block_->bindings()->begin_definitions(); - p != this->block_->bindings()->end_definitions(); - ++p) - { - if ((*p)->is_variable() && (*p)->var_value()->is_parameter()) - { - *pp = (*p)->get_tree(gogo, named_function); - - // We always pass the receiver to a method as a pointer. If - // the receiver is declared as a non-pointer type, then we - // copy the value into a local variable. - if ((*p)->var_value()->is_receiver() - && (*p)->var_value()->type()->points_to() == NULL) - { - tree parm_decl = this->make_receiver_parm_decl(gogo, *p, *pp); - tree var = *pp; - if (TREE_CODE(var) == INDIRECT_REF) - var = TREE_OPERAND(var, 0); - gcc_assert(TREE_CODE(var) == VAR_DECL); - DECL_CHAIN(var) = declare_vars; - declare_vars = var; - *pp = parm_decl; - } - else if ((*p)->var_value()->is_in_heap()) - { - // If we take the address of a parameter, then we need - // to copy it into the heap. - tree parm_decl = this->copy_parm_to_heap(gogo, *p, *pp); - gcc_assert(TREE_CODE(*pp) == INDIRECT_REF); - tree var_decl = TREE_OPERAND(*pp, 0); - gcc_assert(TREE_CODE(var_decl) == VAR_DECL); - DECL_CHAIN(var_decl) = declare_vars; - declare_vars = var_decl; - *pp = parm_decl; - } - - if (*pp != error_mark_node) - { - gcc_assert(TREE_CODE(*pp) == PARM_DECL); - pp = &DECL_CHAIN(*pp); - } - } - else if ((*p)->is_result_variable()) - { - tree var_decl = (*p)->get_tree(gogo, named_function); - if ((*p)->result_var_value()->is_in_heap()) - { - gcc_assert(TREE_CODE(var_decl) == INDIRECT_REF); - var_decl = TREE_OPERAND(var_decl, 0); - } - gcc_assert(TREE_CODE(var_decl) == VAR_DECL); - DECL_CHAIN(var_decl) = declare_vars; - declare_vars = var_decl; - } - } - *pp = NULL_TREE; - - DECL_ARGUMENTS(fndecl) = params; - - if (this->block_ != NULL) - { - gcc_assert(DECL_INITIAL(fndecl) == NULL_TREE); - - // Declare variables if necessary. - tree bind = NULL_TREE; - if (declare_vars != NULL_TREE) - { - tree block = make_node(BLOCK); - BLOCK_SUPERCONTEXT(block) = fndecl; - DECL_INITIAL(fndecl) = block; - BLOCK_VARS(block) = declare_vars; - TREE_USED(block) = 1; - bind = build3(BIND_EXPR, void_type_node, BLOCK_VARS(block), - NULL_TREE, block); - TREE_SIDE_EFFECTS(bind) = 1; - } - - // Build the trees for all the statements in the function. - Translate_context context(gogo, named_function, NULL, NULL_TREE); - tree code = this->block_->get_tree(&context); - - tree init = NULL_TREE; - tree except = NULL_TREE; - tree fini = NULL_TREE; - - // Initialize variables if necessary. - for (tree v = declare_vars; v != NULL_TREE; v = DECL_CHAIN(v)) - { - tree dv = build1(DECL_EXPR, void_type_node, v); - SET_EXPR_LOCATION(dv, DECL_SOURCE_LOCATION(v)); - append_to_statement_list(dv, &init); - } - - // If we have a defer stack, initialize it at the start of a - // function. - if (this->defer_stack_ != NULL_TREE) - { - tree defer_init = build1(DECL_EXPR, void_type_node, - this->defer_stack_); - SET_EXPR_LOCATION(defer_init, this->block_->start_location()); - append_to_statement_list(defer_init, &init); - - // Clean up the defer stack when we leave the function. - this->build_defer_wrapper(gogo, named_function, &except, &fini); - } - - if (code != NULL_TREE && code != error_mark_node) - { - if (init != NULL_TREE) - code = build2(COMPOUND_EXPR, void_type_node, init, code); - if (except != NULL_TREE) - code = build2(TRY_CATCH_EXPR, void_type_node, code, - build2(CATCH_EXPR, void_type_node, NULL, except)); - if (fini != NULL_TREE) - code = build2(TRY_FINALLY_EXPR, void_type_node, code, fini); - } - - // Stick the code into the block we built for the receiver, if - // we built on. - if (bind != NULL_TREE && code != NULL_TREE && code != error_mark_node) - { - BIND_EXPR_BODY(bind) = code; - code = bind; - } - - DECL_SAVED_TREE(fndecl) = code; - } -} - -// Build the wrappers around function code needed if the function has -// any defer statements. This sets *EXCEPT to an exception handler -// and *FINI to a finally handler. - -void -Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function, - tree *except, tree *fini) -{ - source_location end_loc = this->block_->end_location(); - - // Add an exception handler. This is used if a panic occurs. Its - // purpose is to stop the stack unwinding if a deferred function - // calls recover. There are more details in - // libgo/runtime/go-unwind.c. - tree stmt_list = NULL_TREE; - static tree check_fndecl; - tree call = Gogo::call_builtin(&check_fndecl, - end_loc, - "__go_check_defer", - 1, - void_type_node, - ptr_type_node, - this->defer_stack(end_loc)); - append_to_statement_list(call, &stmt_list); - - tree retval = this->return_value(gogo, named_function, end_loc, &stmt_list); - tree set; - if (retval == NULL_TREE) - set = NULL_TREE; - else - set = fold_build2_loc(end_loc, MODIFY_EXPR, void_type_node, - DECL_RESULT(this->fndecl_), retval); - tree ret_stmt = fold_build1_loc(end_loc, RETURN_EXPR, void_type_node, set); - append_to_statement_list(ret_stmt, &stmt_list); - - gcc_assert(*except == NULL_TREE); - *except = stmt_list; - - // Add some finally code to run the defer functions. This is used - // both in the normal case, when no panic occurs, and also if a - // panic occurs to run any further defer functions. Of course, it - // is possible for a defer function to call panic which should be - // caught by another defer function. To handle that we use a loop. - // finish: - // try { __go_undefer(); } catch { __go_check_defer(); goto finish; } - // if (return values are named) return named_vals; - - stmt_list = NULL; - - tree label = create_artificial_label(end_loc); - tree define_label = fold_build1_loc(end_loc, LABEL_EXPR, void_type_node, - label); - append_to_statement_list(define_label, &stmt_list); - - static tree undefer_fndecl; - tree undefer = Gogo::call_builtin(&undefer_fndecl, - end_loc, - "__go_undefer", - 1, - void_type_node, - ptr_type_node, - this->defer_stack(end_loc)); - TREE_NOTHROW(undefer_fndecl) = 0; - - tree defer = Gogo::call_builtin(&check_fndecl, - end_loc, - "__go_check_defer", - 1, - void_type_node, - ptr_type_node, - this->defer_stack(end_loc)); - tree jump = fold_build1_loc(end_loc, GOTO_EXPR, void_type_node, label); - tree catch_body = build2(COMPOUND_EXPR, void_type_node, defer, jump); - catch_body = build2(CATCH_EXPR, void_type_node, NULL, catch_body); - tree try_catch = build2(TRY_CATCH_EXPR, void_type_node, undefer, catch_body); - - append_to_statement_list(try_catch, &stmt_list); - - if (this->type_->results() != NULL - && !this->type_->results()->empty() - && !this->type_->results()->front().name().empty()) - { - // If the result variables are named, we need to return them - // again, because they might have been changed by a defer - // function. - retval = this->return_value(gogo, named_function, end_loc, - &stmt_list); - set = fold_build2_loc(end_loc, MODIFY_EXPR, void_type_node, - DECL_RESULT(this->fndecl_), retval); - ret_stmt = fold_build1_loc(end_loc, RETURN_EXPR, void_type_node, set); - append_to_statement_list(ret_stmt, &stmt_list); - } - - gcc_assert(*fini == NULL_TREE); - *fini = stmt_list; -} - -// Return the value to assign to DECL_RESULT(this->fndecl_). This may -// also add statements to STMT_LIST, which need to be executed before -// the assignment. This is used for a return statement with no -// explicit values. - -tree -Function::return_value(Gogo* gogo, Named_object* named_function, - source_location location, tree* stmt_list) const -{ - const Typed_identifier_list* results = this->type_->results(); - if (results == NULL || results->empty()) - return NULL_TREE; - - // In the case of an exception handler created for functions with - // defer statements, the result variables may be unnamed. - bool is_named = !results->front().name().empty(); - if (is_named) - gcc_assert(this->named_results_ != NULL - && this->named_results_->size() == results->size()); - - tree retval; - if (results->size() == 1) - { - if (is_named) - return this->named_results_->front()->get_tree(gogo, named_function); - else - return results->front().type()->get_init_tree(gogo, false); - } - else - { - tree rettype = TREE_TYPE(DECL_RESULT(this->fndecl_)); - retval = create_tmp_var(rettype, "RESULT"); - tree field = TYPE_FIELDS(rettype); - int index = 0; - for (Typed_identifier_list::const_iterator pr = results->begin(); - pr != results->end(); - ++pr, ++index, field = DECL_CHAIN(field)) - { - gcc_assert(field != NULL); - tree val; - if (is_named) - val = (*this->named_results_)[index]->get_tree(gogo, - named_function); - else - val = pr->type()->get_init_tree(gogo, false); - tree set = fold_build2_loc(location, MODIFY_EXPR, void_type_node, - build3(COMPONENT_REF, TREE_TYPE(field), - retval, field, NULL_TREE), - val); - append_to_statement_list(set, stmt_list); - } - return retval; - } -} - -// Get the tree for the variable holding the defer stack for this -// function. At least at present, the value of this variable is not -// used. However, a pointer to this variable is used as a marker for -// the functions on the defer stack associated with this function. -// Doing things this way permits inlining a function which uses defer. - -tree -Function::defer_stack(source_location location) -{ - if (this->defer_stack_ == NULL_TREE) - { - tree var = create_tmp_var(ptr_type_node, "DEFER"); - DECL_INITIAL(var) = null_pointer_node; - DECL_SOURCE_LOCATION(var) = location; - TREE_ADDRESSABLE(var) = 1; - this->defer_stack_ = var; - } - return fold_convert_loc(location, ptr_type_node, - build_fold_addr_expr_loc(location, - this->defer_stack_)); -} - -// Get a tree for the statements in a block. - -tree -Block::get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - - tree block = make_node(BLOCK); - - // Put the new block into the block tree. - - if (context->block() == NULL) - { - tree fndecl; - if (context->function() != NULL) - fndecl = context->function()->func_value()->get_decl(); - else - fndecl = current_function_decl; - gcc_assert(fndecl != NULL_TREE); - - // We may have already created a block for the receiver. - if (DECL_INITIAL(fndecl) == NULL_TREE) - { - BLOCK_SUPERCONTEXT(block) = fndecl; - DECL_INITIAL(fndecl) = block; - } - else - { - tree superblock_tree = DECL_INITIAL(fndecl); - BLOCK_SUPERCONTEXT(block) = superblock_tree; - gcc_assert(BLOCK_CHAIN(block) == NULL_TREE); - BLOCK_CHAIN(block) = block; - } - } - else - { - tree superblock_tree = context->block_tree(); - BLOCK_SUPERCONTEXT(block) = superblock_tree; - tree* pp; - for (pp = &BLOCK_SUBBLOCKS(superblock_tree); - *pp != NULL_TREE; - pp = &BLOCK_CHAIN(*pp)) - ; - *pp = block; - } - - // Expand local variables in the block. - - tree* pp = &BLOCK_VARS(block); - for (Bindings::const_definitions_iterator pv = - this->bindings_->begin_definitions(); - pv != this->bindings_->end_definitions(); - ++pv) - { - if ((!(*pv)->is_variable() || !(*pv)->var_value()->is_parameter()) - && !(*pv)->is_result_variable() - && !(*pv)->is_const()) - { - tree var = (*pv)->get_tree(gogo, context->function()); - if (var != error_mark_node && TREE_TYPE(var) != error_mark_node) - { - if ((*pv)->is_variable() && (*pv)->var_value()->is_in_heap()) - { - gcc_assert(TREE_CODE(var) == INDIRECT_REF); - var = TREE_OPERAND(var, 0); - gcc_assert(TREE_CODE(var) == VAR_DECL); - } - *pp = var; - pp = &DECL_CHAIN(*pp); - } - } - } - *pp = NULL_TREE; - - Translate_context subcontext(context->gogo(), context->function(), - this, block); - - tree statements = NULL_TREE; - - // Expand the statements. - - for (std::vector::const_iterator p = this->statements_.begin(); - p != this->statements_.end(); - ++p) - { - tree statement = (*p)->get_tree(&subcontext); - if (statement != error_mark_node) - append_to_statement_list(statement, &statements); - } - - TREE_USED(block) = 1; - - tree bind = build3(BIND_EXPR, void_type_node, BLOCK_VARS(block), statements, - block); - TREE_SIDE_EFFECTS(bind) = 1; - - return bind; -} - -// Get the LABEL_DECL for a label. - -tree -Label::get_decl() -{ - if (this->decl_ == NULL) - { - tree id = get_identifier_from_string(this->name_); - this->decl_ = build_decl(this->location_, LABEL_DECL, id, void_type_node); - DECL_CONTEXT(this->decl_) = current_function_decl; - } - return this->decl_; -} - -// Return an expression for the address of this label. - -tree -Label::get_addr(source_location location) -{ - tree decl = this->get_decl(); - TREE_USED(decl) = 1; - TREE_ADDRESSABLE(decl) = 1; - return fold_convert_loc(location, ptr_type_node, - build_fold_addr_expr_loc(location, decl)); -} - -// Get the LABEL_DECL for an unnamed label. - -tree -Unnamed_label::get_decl() -{ - if (this->decl_ == NULL) - this->decl_ = create_artificial_label(this->location_); - return this->decl_; -} - -// Get the LABEL_EXPR for an unnamed label. - -tree -Unnamed_label::get_definition() -{ - tree t = build1(LABEL_EXPR, void_type_node, this->get_decl()); - SET_EXPR_LOCATION(t, this->location_); - return t; -} - -// Return a goto to this label. - -tree -Unnamed_label::get_goto(source_location location) -{ - tree t = build1(GOTO_EXPR, void_type_node, this->get_decl()); - SET_EXPR_LOCATION(t, location); - return t; -} - -// Return the integer type to use for a size. - -GO_EXTERN_C -tree -go_type_for_size(unsigned int bits, int unsignedp) -{ - const char* name; - switch (bits) - { - case 8: - name = unsignedp ? "uint8" : "int8"; - break; - case 16: - name = unsignedp ? "uint16" : "int16"; - break; - case 32: - name = unsignedp ? "uint32" : "int32"; - break; - case 64: - name = unsignedp ? "uint64" : "int64"; - break; - default: - if (bits == POINTER_SIZE && unsignedp) - name = "uintptr"; - else - return NULL_TREE; - } - Type* type = Type::lookup_integer_type(name); - return type->get_tree(go_get_gogo()); -} - -// Return the type to use for a mode. - -GO_EXTERN_C -tree -go_type_for_mode(enum machine_mode mode, int unsignedp) -{ - // FIXME: This static_cast should be in machmode.h. - enum mode_class mc = static_cast(GET_MODE_CLASS(mode)); - if (mc == MODE_INT) - return go_type_for_size(GET_MODE_BITSIZE(mode), unsignedp); - else if (mc == MODE_FLOAT) - { - Type* type; - switch (GET_MODE_BITSIZE (mode)) - { - case 32: - type = Type::lookup_float_type("float32"); - break; - case 64: - type = Type::lookup_float_type("float64"); - break; - default: - // We have to check for long double in order to support - // i386 excess precision. - if (mode == TYPE_MODE(long_double_type_node)) - return long_double_type_node; - return NULL_TREE; - } - return type->float_type()->type_tree(); - } - else if (mc == MODE_COMPLEX_FLOAT) - { - Type *type; - switch (GET_MODE_BITSIZE (mode)) - { - case 64: - type = Type::lookup_complex_type("complex64"); - break; - case 128: - type = Type::lookup_complex_type("complex128"); - break; - default: - // We have to check for long double in order to support - // i386 excess precision. - if (mode == TYPE_MODE(complex_long_double_type_node)) - return complex_long_double_type_node; - return NULL_TREE; - } - return type->complex_type()->type_tree(); - } - else - return NULL_TREE; -} - -// Return a tree which allocates SIZE bytes which will holds value of -// type TYPE. - -tree -Gogo::allocate_memory(Type* type, tree size, source_location location) -{ - // If the package imports unsafe, then it may play games with - // pointers that look like integers. - if (this->imported_unsafe_ || type->has_pointer()) - { - static tree new_fndecl; - return Gogo::call_builtin(&new_fndecl, - location, - "__go_new", - 1, - ptr_type_node, - sizetype, - size); - } - else - { - static tree new_nopointers_fndecl; - return Gogo::call_builtin(&new_nopointers_fndecl, - location, - "__go_new_nopointers", - 1, - ptr_type_node, - sizetype, - size); - } -} - -// Build a builtin struct with a list of fields. The name is -// STRUCT_NAME. STRUCT_TYPE is NULL_TREE or an empty RECORD_TYPE -// node; this exists so that the struct can have fields which point to -// itself. If PTYPE is not NULL, store the result in *PTYPE. There -// are NFIELDS fields. Each field is a name (a const char*) followed -// by a type (a tree). - -tree -Gogo::builtin_struct(tree* ptype, const char* struct_name, tree struct_type, - int nfields, ...) -{ - if (ptype != NULL && *ptype != NULL_TREE) - return *ptype; - - va_list ap; - va_start(ap, nfields); - - tree fields = NULL_TREE; - for (int i = 0; i < nfields; ++i) - { - const char* field_name = va_arg(ap, const char*); - tree type = va_arg(ap, tree); - if (type == error_mark_node) - { - if (ptype != NULL) - *ptype = error_mark_node; - return error_mark_node; - } - tree field = build_decl(BUILTINS_LOCATION, FIELD_DECL, - get_identifier(field_name), type); - DECL_CHAIN(field) = fields; - fields = field; - } - - va_end(ap); - - if (struct_type == NULL_TREE) - struct_type = make_node(RECORD_TYPE); - finish_builtin_struct(struct_type, struct_name, fields, NULL_TREE); - - if (ptype != NULL) - { - go_preserve_from_gc(struct_type); - *ptype = struct_type; - } - - return struct_type; -} - -// Return a type to use for pointer to const char for a string. - -tree -Gogo::const_char_pointer_type_tree() -{ - static tree type; - if (type == NULL_TREE) - { - tree const_char_type = build_qualified_type(unsigned_char_type_node, - TYPE_QUAL_CONST); - type = build_pointer_type(const_char_type); - go_preserve_from_gc(type); - } - return type; -} - -// Return a tree for a string constant. - -tree -Gogo::string_constant_tree(const std::string& val) -{ - tree index_type = build_index_type(size_int(val.length())); - tree const_char_type = build_qualified_type(unsigned_char_type_node, - TYPE_QUAL_CONST); - tree string_type = build_array_type(const_char_type, index_type); - string_type = build_variant_type_copy(string_type); - TYPE_STRING_FLAG(string_type) = 1; - tree string_val = build_string(val.length(), val.data()); - TREE_TYPE(string_val) = string_type; - return string_val; -} - -// Return a tree for a Go string constant. - -tree -Gogo::go_string_constant_tree(const std::string& val) -{ - tree string_type = Type::make_string_type()->get_tree(this); - - VEC(constructor_elt, gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(string_type); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__data") == 0); - elt->index = field; - tree str = Gogo::string_constant_tree(val); - elt->value = fold_convert(TREE_TYPE(field), - build_fold_addr_expr(str)); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__length") == 0); - elt->index = field; - elt->value = build_int_cst_type(TREE_TYPE(field), val.length()); - - tree constructor = build_constructor(string_type, init); - TREE_READONLY(constructor) = 1; - TREE_CONSTANT(constructor) = 1; - - return constructor; -} - -// Return a tree for a pointer to a Go string constant. This is only -// used for type descriptors, so we return a pointer to a constant -// decl. - -tree -Gogo::ptr_go_string_constant_tree(const std::string& val) -{ - tree pval = this->go_string_constant_tree(val); - - tree decl = build_decl(UNKNOWN_LOCATION, VAR_DECL, - create_tmp_var_name("SP"), TREE_TYPE(pval)); - DECL_EXTERNAL(decl) = 0; - TREE_PUBLIC(decl) = 0; - TREE_USED(decl) = 1; - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - TREE_STATIC(decl) = 1; - DECL_ARTIFICIAL(decl) = 1; - DECL_INITIAL(decl) = pval; - rest_of_decl_compilation(decl, 1, 0); - - return build_fold_addr_expr(decl); -} - -// Build the type of the struct that holds a slice for the given -// element type. - -tree -Gogo::slice_type_tree(tree element_type_tree) -{ - // We use int for the count and capacity fields in a slice header. - // This matches 6g. The language definition guarantees that we - // can't allocate space of a size which does not fit in int - // anyhow. FIXME: integer_type_node is the the C type "int" but is - // not necessarily the Go type "int". They will differ when the C - // type "int" has fewer than 32 bits. - return Gogo::builtin_struct(NULL, "__go_slice", NULL_TREE, 3, - "__values", - build_pointer_type(element_type_tree), - "__count", - integer_type_node, - "__capacity", - integer_type_node); -} - -// Given the tree for a slice type, return the tree for the type of -// the elements of the slice. - -tree -Gogo::slice_element_type_tree(tree slice_type_tree) -{ - gcc_assert(TREE_CODE(slice_type_tree) == RECORD_TYPE - && POINTER_TYPE_P(TREE_TYPE(TYPE_FIELDS(slice_type_tree)))); - return TREE_TYPE(TREE_TYPE(TYPE_FIELDS(slice_type_tree))); -} - -// Build a constructor for a slice. SLICE_TYPE_TREE is the type of -// the slice. VALUES is the value pointer and COUNT is the number of -// entries. If CAPACITY is not NULL, it is the capacity; otherwise -// the capacity and the count are the same. - -tree -Gogo::slice_constructor(tree slice_type_tree, tree values, tree count, - tree capacity) -{ - gcc_assert(TREE_CODE(slice_type_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - tree field = TYPE_FIELDS(slice_type_tree); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0); - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - gcc_assert(TYPE_MAIN_VARIANT(TREE_TYPE(field)) - == TYPE_MAIN_VARIANT(TREE_TYPE(values))); - elt->value = values; - - count = fold_convert(sizetype, count); - if (capacity == NULL_TREE) - { - count = save_expr(count); - capacity = count; - } - - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0); - elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), count); - - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0); - elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), capacity); - - return build_constructor(slice_type_tree, init); -} - -// Build a constructor for an empty slice. - -tree -Gogo::empty_slice_constructor(tree slice_type_tree) -{ - tree element_field = TYPE_FIELDS(slice_type_tree); - tree ret = Gogo::slice_constructor(slice_type_tree, - fold_convert(TREE_TYPE(element_field), - null_pointer_node), - size_zero_node, - size_zero_node); - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Build a map descriptor for a map of type MAPTYPE. - -tree -Gogo::map_descriptor(Map_type* maptype) -{ - if (this->map_descriptors_ == NULL) - this->map_descriptors_ = new Map_descriptors(10); - - std::pair val(maptype, NULL); - std::pair ins = - this->map_descriptors_->insert(val); - Map_descriptors::iterator p = ins.first; - if (!ins.second) - { - gcc_assert(p->second != NULL_TREE && DECL_P(p->second)); - return build_fold_addr_expr(p->second); - } - - Type* keytype = maptype->key_type(); - Type* valtype = maptype->val_type(); - - std::string mangled_name = ("__go_map_" + maptype->mangled_name(this)); - - tree id = get_identifier_from_string(mangled_name); - - // Get the type of the map descriptor. This is __go_map_descriptor - // in libgo/map.h. - - tree struct_type = this->map_descriptor_type(); - - // The map entry type is a struct with three fields. This struct is - // specific to MAPTYPE. Build it. - - tree map_entry_type = make_node(RECORD_TYPE); - - map_entry_type = Gogo::builtin_struct(NULL, "__map", map_entry_type, 3, - "__next", - build_pointer_type(map_entry_type), - "__key", - keytype->get_tree(this), - "__val", - valtype->get_tree(this)); - if (map_entry_type == error_mark_node) - return error_mark_node; - - tree map_entry_key_field = DECL_CHAIN(TYPE_FIELDS(map_entry_type)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_entry_key_field)), - "__key") == 0); - - tree map_entry_val_field = DECL_CHAIN(map_entry_key_field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_entry_val_field)), - "__val") == 0); - - // Initialize the entries. - - tree map_descriptor_field = TYPE_FIELDS(struct_type); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_descriptor_field)), - "__map_descriptor") == 0); - tree entry_size_field = DECL_CHAIN(map_descriptor_field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(entry_size_field)), - "__entry_size") == 0); - tree key_offset_field = DECL_CHAIN(entry_size_field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(key_offset_field)), - "__key_offset") == 0); - tree val_offset_field = DECL_CHAIN(key_offset_field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(val_offset_field)), - "__val_offset") == 0); - - VEC(constructor_elt, gc)* descriptor = VEC_alloc(constructor_elt, gc, 6); - - constructor_elt* elt = VEC_quick_push(constructor_elt, descriptor, NULL); - elt->index = map_descriptor_field; - elt->value = maptype->type_descriptor_pointer(this); - - elt = VEC_quick_push(constructor_elt, descriptor, NULL); - elt->index = entry_size_field; - elt->value = TYPE_SIZE_UNIT(map_entry_type); - - elt = VEC_quick_push(constructor_elt, descriptor, NULL); - elt->index = key_offset_field; - elt->value = byte_position(map_entry_key_field); - - elt = VEC_quick_push(constructor_elt, descriptor, NULL); - elt->index = val_offset_field; - elt->value = byte_position(map_entry_val_field); - - tree constructor = build_constructor(struct_type, descriptor); - - tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, struct_type); - TREE_STATIC(decl) = 1; - TREE_USED(decl) = 1; - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - DECL_INITIAL(decl) = constructor; - make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl)); - resolve_unique_section(decl, 1, 0); - - rest_of_decl_compilation(decl, 1, 0); - - go_preserve_from_gc(decl); - p->second = decl; - - return build_fold_addr_expr(decl); -} - -// Return a tree for the type of a map descriptor. This is struct -// __go_map_descriptor in libgo/runtime/map.h. This is the same for -// all map types. - -tree -Gogo::map_descriptor_type() -{ - static tree struct_type; - tree dtype = Type::make_type_descriptor_type()->get_tree(this); - dtype = build_qualified_type(dtype, TYPE_QUAL_CONST); - return Gogo::builtin_struct(&struct_type, "__go_map_descriptor", NULL_TREE, - 4, - "__map_descriptor", - build_pointer_type(dtype), - "__entry_size", - sizetype, - "__key_offset", - sizetype, - "__val_offset", - sizetype); -} - -// Return the name to use for a type descriptor decl for TYPE. This -// is used when TYPE does not have a name. - -std::string -Gogo::unnamed_type_descriptor_decl_name(const Type* type) -{ - return "__go_td_" + type->mangled_name(this); -} - -// Return the name to use for a type descriptor decl for a type named -// NAME, defined in the function IN_FUNCTION. IN_FUNCTION will -// normally be NULL. - -std::string -Gogo::type_descriptor_decl_name(const Named_object* no, - const Named_object* in_function) -{ - std::string ret = "__go_tdn_"; - if (no->type_value()->is_builtin()) - gcc_assert(in_function == NULL); - else - { - const std::string& unique_prefix(no->package() == NULL - ? this->unique_prefix() - : no->package()->unique_prefix()); - const std::string& package_name(no->package() == NULL - ? this->package_name() - : no->package()->name()); - ret.append(unique_prefix); - ret.append(1, '.'); - ret.append(package_name); - ret.append(1, '.'); - if (in_function != NULL) - { - ret.append(Gogo::unpack_hidden_name(in_function->name())); - ret.append(1, '.'); - } - } - ret.append(no->name()); - return ret; -} - -// Where a type descriptor decl should be defined. - -Gogo::Type_descriptor_location -Gogo::type_descriptor_location(const Type* type) -{ - const Named_type* name = type->named_type(); - if (name != NULL) - { - if (name->named_object()->package() != NULL) - { - // This is a named type defined in a different package. The - // descriptor should be defined in that package. - return TYPE_DESCRIPTOR_UNDEFINED; - } - else if (name->is_builtin()) - { - // We create the descriptor for a builtin type whenever we - // need it. - return TYPE_DESCRIPTOR_COMMON; - } - else - { - // This is a named type defined in this package. The - // descriptor should be defined here. - return TYPE_DESCRIPTOR_DEFINED; - } - } - else - { - if (type->points_to() != NULL - && type->points_to()->named_type() != NULL - && type->points_to()->named_type()->named_object()->package() != NULL) - { - // This is an unnamed pointer to a named type defined in a - // different package. The descriptor should be defined in - // that package. - return TYPE_DESCRIPTOR_UNDEFINED; - } - else - { - // This is an unnamed type. The descriptor could be defined - // in any package where it is needed, and the linker will - // pick one descriptor to keep. - return TYPE_DESCRIPTOR_COMMON; - } - } -} - -// Build a type descriptor decl for TYPE. INITIALIZER is a struct -// composite literal which initializers the type descriptor. - -void -Gogo::build_type_descriptor_decl(const Type* type, Expression* initializer, - tree* pdecl) -{ - const Named_type* name = type->named_type(); - - // We can have multiple instances of unnamed types, but we only want - // to emit the type descriptor once. We use a hash table to handle - // this. This is not necessary for named types, as they are unique, - // and we store the type descriptor decl in the type itself. - tree* phash = NULL; - if (name == NULL) - { - if (this->type_descriptor_decls_ == NULL) - this->type_descriptor_decls_ = new Type_descriptor_decls(10); - - std::pair ins = - this->type_descriptor_decls_->insert(std::make_pair(type, NULL_TREE)); - if (!ins.second) - { - // We've already built a type descriptor for this type. - *pdecl = ins.first->second; - return; - } - phash = &ins.first->second; - } - - std::string decl_name; - if (name == NULL) - decl_name = this->unnamed_type_descriptor_decl_name(type); - else - decl_name = this->type_descriptor_decl_name(name->named_object(), - name->in_function()); - tree id = get_identifier_from_string(decl_name); - tree descriptor_type_tree = initializer->type()->get_tree(this); - if (descriptor_type_tree == error_mark_node) - { - *pdecl = error_mark_node; - return; - } - tree decl = build_decl(name == NULL ? BUILTINS_LOCATION : name->location(), - VAR_DECL, id, - build_qualified_type(descriptor_type_tree, - TYPE_QUAL_CONST)); - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - DECL_ARTIFICIAL(decl) = 1; - - go_preserve_from_gc(decl); - if (phash != NULL) - *phash = decl; - - // We store the new DECL now because we may need to refer to it when - // expanding INITIALIZER. - *pdecl = decl; - - // If appropriate, just refer to the exported type identifier. - Gogo::Type_descriptor_location type_descriptor_location = - this->type_descriptor_location(type); - if (type_descriptor_location == TYPE_DESCRIPTOR_UNDEFINED) - { - TREE_PUBLIC(decl) = 1; - DECL_EXTERNAL(decl) = 1; - return; - } - - TREE_STATIC(decl) = 1; - TREE_USED(decl) = 1; - - Translate_context context(this, NULL, NULL, NULL); - context.set_is_const(); - tree constructor = initializer->get_tree(&context); - - if (constructor == error_mark_node) - gcc_assert(saw_errors()); - - DECL_INITIAL(decl) = constructor; - - if (type_descriptor_location == TYPE_DESCRIPTOR_COMMON) - { - make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl)); - resolve_unique_section(decl, 1, 0); - } - else - { -#ifdef OBJECT_FORMAT_ELF - // Give the decl protected visibility. This avoids out-of-range - // references with shared libraries with the x86_64 small model - // when the type descriptor gets a COPY reloc into the main - // executable. There is no need to have unique pointers to type - // descriptors, as the runtime code compares reflection strings - // if necessary. - DECL_VISIBILITY(decl) = VISIBILITY_PROTECTED; - DECL_VISIBILITY_SPECIFIED(decl) = 1; -#endif - - TREE_PUBLIC(decl) = 1; - } - - rest_of_decl_compilation(decl, 1, 0); -} - -// Build an interface method table for a type: a list of function -// pointers, one for each interface method. This is used for -// interfaces. - -tree -Gogo::interface_method_table_for_type(const Interface_type* interface, - Named_type* type, - bool is_pointer) -{ - const Typed_identifier_list* interface_methods = interface->methods(); - gcc_assert(!interface_methods->empty()); - - std::string mangled_name = ((is_pointer ? "__go_pimt__" : "__go_imt_") - + interface->mangled_name(this) - + "__" - + type->mangled_name(this)); - - tree id = get_identifier_from_string(mangled_name); - - // See whether this interface has any hidden methods. - bool has_hidden_methods = false; - for (Typed_identifier_list::const_iterator p = interface_methods->begin(); - p != interface_methods->end(); - ++p) - { - if (Gogo::is_hidden_name(p->name())) - { - has_hidden_methods = true; - break; - } - } - - // We already know that the named type is convertible to the - // interface. If the interface has hidden methods, and the named - // type is defined in a different package, then the interface - // conversion table will be defined by that other package. - if (has_hidden_methods && type->named_object()->package() != NULL) - { - tree array_type = build_array_type(const_ptr_type_node, NULL); - tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type); - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - TREE_PUBLIC(decl) = 1; - DECL_EXTERNAL(decl) = 1; - go_preserve_from_gc(decl); - return decl; - } - - size_t count = interface_methods->size(); - VEC(constructor_elt, gc)* pointers = VEC_alloc(constructor_elt, gc, - count + 1); - - // The first element is the type descriptor. - constructor_elt* elt = VEC_quick_push(constructor_elt, pointers, NULL); - elt->index = size_zero_node; - Type* td_type; - if (!is_pointer) - td_type = type; - else - td_type = Type::make_pointer_type(type); - elt->value = fold_convert(const_ptr_type_node, - td_type->type_descriptor_pointer(this)); - - size_t i = 1; - for (Typed_identifier_list::const_iterator p = interface_methods->begin(); - p != interface_methods->end(); - ++p, ++i) - { - bool is_ambiguous; - Method* m = type->method_function(p->name(), &is_ambiguous); - gcc_assert(m != NULL); - - Named_object* no = m->named_object(); - - tree fnid = no->get_id(this); - - tree fndecl; - if (no->is_function()) - fndecl = no->func_value()->get_or_make_decl(this, no, fnid); - else if (no->is_function_declaration()) - fndecl = no->func_declaration_value()->get_or_make_decl(this, no, - fnid); - else - gcc_unreachable(); - fndecl = build_fold_addr_expr(fndecl); - - elt = VEC_quick_push(constructor_elt, pointers, NULL); - elt->index = size_int(i); - elt->value = fold_convert(const_ptr_type_node, fndecl); - } - gcc_assert(i == count + 1); - - tree array_type = build_array_type(const_ptr_type_node, - build_index_type(size_int(count))); - tree constructor = build_constructor(array_type, pointers); - - tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type); - TREE_STATIC(decl) = 1; - TREE_USED(decl) = 1; - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - DECL_INITIAL(decl) = constructor; - - // If the interface type has hidden methods, then this is the only - // definition of the table. Otherwise it is a comdat table which - // may be defined in multiple packages. - if (has_hidden_methods) - { -#ifdef OBJECT_FORMAT_ELF - // Give the decl protected visibility. This avoids out-of-range - // references with shared libraries with the x86_64 small model - // when the table gets a COPY reloc into the main executable. - DECL_VISIBILITY(decl) = VISIBILITY_PROTECTED; - DECL_VISIBILITY_SPECIFIED(decl) = 1; -#endif - - TREE_PUBLIC(decl) = 1; - } - else - { - make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl)); - resolve_unique_section(decl, 1, 0); - } - - rest_of_decl_compilation(decl, 1, 0); - - go_preserve_from_gc(decl); - - return decl; -} - -// Mark a function as a builtin library function. - -void -Gogo::mark_fndecl_as_builtin_library(tree fndecl) -{ - DECL_EXTERNAL(fndecl) = 1; - TREE_PUBLIC(fndecl) = 1; - DECL_ARTIFICIAL(fndecl) = 1; - TREE_NOTHROW(fndecl) = 1; - DECL_VISIBILITY(fndecl) = VISIBILITY_DEFAULT; - DECL_VISIBILITY_SPECIFIED(fndecl) = 1; -} - -// Build a call to a builtin function. - -tree -Gogo::call_builtin(tree* pdecl, source_location location, const char* name, - int nargs, tree rettype, ...) -{ - if (rettype == error_mark_node) - return error_mark_node; - - tree* types = new tree[nargs]; - tree* args = new tree[nargs]; - - va_list ap; - va_start(ap, rettype); - for (int i = 0; i < nargs; ++i) - { - types[i] = va_arg(ap, tree); - args[i] = va_arg(ap, tree); - if (types[i] == error_mark_node || args[i] == error_mark_node) - return error_mark_node; - } - va_end(ap); - - if (*pdecl == NULL_TREE) - { - tree fnid = get_identifier(name); - - tree argtypes = NULL_TREE; - tree* pp = &argtypes; - for (int i = 0; i < nargs; ++i) - { - *pp = tree_cons(NULL_TREE, types[i], NULL_TREE); - pp = &TREE_CHAIN(*pp); - } - *pp = void_list_node; - - tree fntype = build_function_type(rettype, argtypes); - - *pdecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL, fnid, fntype); - Gogo::mark_fndecl_as_builtin_library(*pdecl); - go_preserve_from_gc(*pdecl); - } - - tree fnptr = build_fold_addr_expr(*pdecl); - if (CAN_HAVE_LOCATION_P(fnptr)) - SET_EXPR_LOCATION(fnptr, location); - - tree ret = build_call_array(rettype, fnptr, nargs, args); - SET_EXPR_LOCATION(ret, location); - - delete[] types; - delete[] args; - - return ret; -} - -// Build a call to the runtime error function. - -tree -Gogo::runtime_error(int code, source_location location) -{ - static tree runtime_error_fndecl; - tree ret = Gogo::call_builtin(&runtime_error_fndecl, - location, - "__go_runtime_error", - 1, - void_type_node, - integer_type_node, - build_int_cst(integer_type_node, code)); - // The runtime error function panics and does not return. - TREE_NOTHROW(runtime_error_fndecl) = 0; - TREE_THIS_VOLATILE(runtime_error_fndecl) = 1; - return ret; -} - -// Send VAL on CHANNEL. If BLOCKING is true, the resulting tree has a -// void type. If BLOCKING is false, the resulting tree has a boolean -// type, and it will evaluate as true if the value was sent. If -// FOR_SELECT is true, this is being done because it was chosen in a -// select statement. - -tree -Gogo::send_on_channel(tree channel, tree val, bool blocking, bool for_select, - source_location location) -{ - if (int_size_in_bytes(TREE_TYPE(val)) <= 8 - && !AGGREGATE_TYPE_P(TREE_TYPE(val)) - && !FLOAT_TYPE_P(TREE_TYPE(val))) - { - val = convert_to_integer(uint64_type_node, val); - if (blocking) - { - static tree send_small_fndecl; - tree ret = Gogo::call_builtin(&send_small_fndecl, - location, - "__go_send_small", - 3, - void_type_node, - ptr_type_node, - channel, - uint64_type_node, - val, - boolean_type_node, - (for_select - ? boolean_true_node - : boolean_false_node)); - // This can panic if there are too many operations on a - // closed channel. - TREE_NOTHROW(send_small_fndecl) = 0; - return ret; - } - else - { - gcc_assert(!for_select); - static tree send_nonblocking_small_fndecl; - tree ret = Gogo::call_builtin(&send_nonblocking_small_fndecl, - location, - "__go_send_nonblocking_small", - 2, - boolean_type_node, - ptr_type_node, - channel, - uint64_type_node, - val); - // This can panic if there are too many operations on a - // closed channel. - TREE_NOTHROW(send_nonblocking_small_fndecl) = 0; - return ret; - } - } - else - { - tree make_tmp; - if (TREE_ADDRESSABLE(TREE_TYPE(val)) || TREE_CODE(val) == VAR_DECL) - { - make_tmp = NULL_TREE; - val = build_fold_addr_expr(val); - if (DECL_P(val)) - TREE_ADDRESSABLE(val) = 1; - } - else - { - tree tmp = create_tmp_var(TREE_TYPE(val), get_name(val)); - DECL_IGNORED_P(tmp) = 0; - DECL_INITIAL(tmp) = val; - TREE_ADDRESSABLE(tmp) = 1; - make_tmp = build1(DECL_EXPR, void_type_node, tmp); - SET_EXPR_LOCATION(make_tmp, location); - val = build_fold_addr_expr(tmp); - } - val = fold_convert(ptr_type_node, val); - - tree call; - if (blocking) - { - static tree send_big_fndecl; - call = Gogo::call_builtin(&send_big_fndecl, - location, - "__go_send_big", - 3, - void_type_node, - ptr_type_node, - channel, - ptr_type_node, - val, - boolean_type_node, - (for_select - ? boolean_true_node - : boolean_false_node)); - // This can panic if there are too many operations on a - // closed channel. - TREE_NOTHROW(send_big_fndecl) = 0; - } - else - { - gcc_assert(!for_select); - static tree send_nonblocking_big_fndecl; - call = Gogo::call_builtin(&send_nonblocking_big_fndecl, - location, - "__go_send_nonblocking_big", - 2, - boolean_type_node, - ptr_type_node, - channel, - ptr_type_node, - val); - // This can panic if there are too many operations on a - // closed channel. - TREE_NOTHROW(send_nonblocking_big_fndecl) = 0; - } - - if (make_tmp == NULL_TREE) - return call; - else - { - tree ret = build2(COMPOUND_EXPR, TREE_TYPE(call), make_tmp, call); - SET_EXPR_LOCATION(ret, location); - return ret; - } - } -} - -// Return a tree for receiving a value of type TYPE_TREE on CHANNEL. -// This does a blocking receive and returns the value read from the -// channel. If FOR_SELECT is true, this is being done because it was -// chosen in a select statement. - -tree -Gogo::receive_from_channel(tree type_tree, tree channel, bool for_select, - source_location location) -{ - if (int_size_in_bytes(type_tree) <= 8 - && !AGGREGATE_TYPE_P(type_tree) - && !FLOAT_TYPE_P(type_tree)) - { - static tree receive_small_fndecl; - tree call = Gogo::call_builtin(&receive_small_fndecl, - location, - "__go_receive_small", - 2, - uint64_type_node, - ptr_type_node, - channel, - boolean_type_node, - (for_select - ? boolean_true_node - : boolean_false_node)); - // This can panic if there are too many operations on a closed - // channel. - TREE_NOTHROW(receive_small_fndecl) = 0; - int bitsize = GET_MODE_BITSIZE(TYPE_MODE(type_tree)); - tree int_type_tree = go_type_for_size(bitsize, 1); - return fold_convert_loc(location, type_tree, - fold_convert_loc(location, int_type_tree, - call)); - } - else - { - tree tmp = create_tmp_var(type_tree, get_name(type_tree)); - DECL_IGNORED_P(tmp) = 0; - TREE_ADDRESSABLE(tmp) = 1; - tree make_tmp = build1(DECL_EXPR, void_type_node, tmp); - SET_EXPR_LOCATION(make_tmp, location); - tree tmpaddr = build_fold_addr_expr(tmp); - tmpaddr = fold_convert(ptr_type_node, tmpaddr); - static tree receive_big_fndecl; - tree call = Gogo::call_builtin(&receive_big_fndecl, - location, - "__go_receive_big", - 3, - void_type_node, - ptr_type_node, - channel, - ptr_type_node, - tmpaddr, - boolean_type_node, - (for_select - ? boolean_true_node - : boolean_false_node)); - // This can panic if there are too many operations on a closed - // channel. - TREE_NOTHROW(receive_big_fndecl) = 0; - return build2(COMPOUND_EXPR, type_tree, make_tmp, - build2(COMPOUND_EXPR, type_tree, call, tmp)); - } -} - -// Return the type of a function trampoline. This is like -// get_trampoline_type in tree-nested.c. - -tree -Gogo::trampoline_type_tree() -{ - static tree type_tree; - if (type_tree == NULL_TREE) - { - unsigned int align = TRAMPOLINE_ALIGNMENT; - unsigned int size = TRAMPOLINE_SIZE; - tree t = build_index_type(build_int_cst(integer_type_node, size - 1)); - t = build_array_type(char_type_node, t); - - type_tree = Gogo::builtin_struct(NULL, "__go_trampoline", NULL_TREE, 1, - "__data", t); - t = TYPE_FIELDS(type_tree); - DECL_ALIGN(t) = align; - DECL_USER_ALIGN(t) = 1; - - go_preserve_from_gc(type_tree); - } - return type_tree; -} - -// Make a trampoline which calls FNADDR passing CLOSURE. - -tree -Gogo::make_trampoline(tree fnaddr, tree closure, source_location location) -{ - tree trampoline_type = Gogo::trampoline_type_tree(); - tree trampoline_size = TYPE_SIZE_UNIT(trampoline_type); - - closure = save_expr(closure); - - // We allocate the trampoline using a special function which will - // mark it as executable. - static tree trampoline_fndecl; - tree x = Gogo::call_builtin(&trampoline_fndecl, - location, - "__go_allocate_trampoline", - 2, - ptr_type_node, - size_type_node, - trampoline_size, - ptr_type_node, - fold_convert_loc(location, ptr_type_node, - closure)); - - x = save_expr(x); - - // Initialize the trampoline. - tree ini = build_call_expr(implicit_built_in_decls[BUILT_IN_INIT_TRAMPOLINE], - 3, x, fnaddr, closure); - - // On some targets the trampoline address needs to be adjusted. For - // example, when compiling in Thumb mode on the ARM, the address - // needs to have the low bit set. - x = build_call_expr(implicit_built_in_decls[BUILT_IN_ADJUST_TRAMPOLINE], - 1, x); - x = fold_convert(TREE_TYPE(fnaddr), x); - - return build2(COMPOUND_EXPR, TREE_TYPE(x), ini, x); -} diff --git a/gcc/go/gofrontend/gogo-tree.cc.merge-right.r172891 b/gcc/go/gofrontend/gogo-tree.cc.merge-right.r172891 deleted file mode 100644 index c24ff98fbd4..00000000000 --- a/gcc/go/gofrontend/gogo-tree.cc.merge-right.r172891 +++ /dev/null @@ -1,2697 +0,0 @@ -// gogo-tree.cc -- convert Go frontend Gogo IR to gcc trees. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include - -#ifndef ENABLE_BUILD_WITH_CXX -extern "C" -{ -#endif - -#include "toplev.h" -#include "tree.h" -#include "gimple.h" -#include "tree-iterator.h" -#include "cgraph.h" -#include "langhooks.h" -#include "convert.h" -#include "output.h" -#include "diagnostic.h" - -#ifndef ENABLE_BUILD_WITH_CXX -} -#endif - -#include "go-c.h" -#include "types.h" -#include "expressions.h" -#include "statements.h" -#include "runtime.h" -#include "backend.h" -#include "gogo.h" - -// Whether we have seen any errors. - -bool -saw_errors() -{ - return errorcount != 0 || sorrycount != 0; -} - -// A helper function. - -static inline tree -get_identifier_from_string(const std::string& str) -{ - return get_identifier_with_length(str.data(), str.length()); -} - -// Builtin functions. - -static std::map builtin_functions; - -// Define a builtin function. BCODE is the builtin function code -// defined by builtins.def. NAME is the name of the builtin function. -// LIBNAME is the name of the corresponding library function, and is -// NULL if there isn't one. FNTYPE is the type of the function. -// CONST_P is true if the function has the const attribute. - -static void -define_builtin(built_in_function bcode, const char* name, const char* libname, - tree fntype, bool const_p) -{ - tree decl = add_builtin_function(name, fntype, bcode, BUILT_IN_NORMAL, - libname, NULL_TREE); - if (const_p) - TREE_READONLY(decl) = 1; - built_in_decls[bcode] = decl; - implicit_built_in_decls[bcode] = decl; - builtin_functions[name] = decl; - if (libname != NULL) - { - decl = add_builtin_function(libname, fntype, bcode, BUILT_IN_NORMAL, - NULL, NULL_TREE); - if (const_p) - TREE_READONLY(decl) = 1; - builtin_functions[libname] = decl; - } -} - -// Create trees for implicit builtin functions. - -void -Gogo::define_builtin_function_trees() -{ - /* We need to define the fetch_and_add functions, since we use them - for ++ and --. */ - tree t = go_type_for_size(BITS_PER_UNIT, 1); - tree p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE)); - define_builtin(BUILT_IN_ADD_AND_FETCH_1, "__sync_fetch_and_add_1", NULL, - build_function_type_list(t, p, t, NULL_TREE), false); - - t = go_type_for_size(BITS_PER_UNIT * 2, 1); - p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE)); - define_builtin (BUILT_IN_ADD_AND_FETCH_2, "__sync_fetch_and_add_2", NULL, - build_function_type_list(t, p, t, NULL_TREE), false); - - t = go_type_for_size(BITS_PER_UNIT * 4, 1); - p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE)); - define_builtin(BUILT_IN_ADD_AND_FETCH_4, "__sync_fetch_and_add_4", NULL, - build_function_type_list(t, p, t, NULL_TREE), false); - - t = go_type_for_size(BITS_PER_UNIT * 8, 1); - p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE)); - define_builtin(BUILT_IN_ADD_AND_FETCH_8, "__sync_fetch_and_add_8", NULL, - build_function_type_list(t, p, t, NULL_TREE), false); - - // We use __builtin_expect for magic import functions. - define_builtin(BUILT_IN_EXPECT, "__builtin_expect", NULL, - build_function_type_list(long_integer_type_node, - long_integer_type_node, - long_integer_type_node, - NULL_TREE), - true); - - // We use __builtin_memmove for the predeclared copy function. - define_builtin(BUILT_IN_MEMMOVE, "__builtin_memmove", "memmove", - build_function_type_list(ptr_type_node, - ptr_type_node, - const_ptr_type_node, - size_type_node, - NULL_TREE), - false); - - // We provide sqrt for the math library. - define_builtin(BUILT_IN_SQRT, "__builtin_sqrt", "sqrt", - build_function_type_list(double_type_node, - double_type_node, - NULL_TREE), - true); - define_builtin(BUILT_IN_SQRTL, "__builtin_sqrtl", "sqrtl", - build_function_type_list(long_double_type_node, - long_double_type_node, - NULL_TREE), - true); - - // We use __builtin_return_address in the thunk we build for - // functions which call recover. - define_builtin(BUILT_IN_RETURN_ADDRESS, "__builtin_return_address", NULL, - build_function_type_list(ptr_type_node, - unsigned_type_node, - NULL_TREE), - false); - - // The compiler uses __builtin_trap for some exception handling - // cases. - define_builtin(BUILT_IN_TRAP, "__builtin_trap", NULL, - build_function_type(void_type_node, void_list_node), - false); -} - -// Get the name to use for the import control function. If there is a -// global function or variable, then we know that that name must be -// unique in the link, and we use it as the basis for our name. - -const std::string& -Gogo::get_init_fn_name() -{ - if (this->init_fn_name_.empty()) - { - go_assert(this->package_ != NULL); - if (this->is_main_package()) - { - // Use a name which the runtime knows. - this->init_fn_name_ = "__go_init_main"; - } - else - { - std::string s = this->unique_prefix(); - s.append(1, '.'); - s.append(this->package_name()); - s.append("..import"); - this->init_fn_name_ = s; - } - } - - return this->init_fn_name_; -} - -// Add statements to INIT_STMT_LIST which run the initialization -// functions for imported packages. This is only used for the "main" -// package. - -void -Gogo::init_imports(tree* init_stmt_list) -{ - go_assert(this->is_main_package()); - - if (this->imported_init_fns_.empty()) - return; - - tree fntype = build_function_type(void_type_node, void_list_node); - - // We must call them in increasing priority order. - std::vector v; - for (std::set::const_iterator p = - this->imported_init_fns_.begin(); - p != this->imported_init_fns_.end(); - ++p) - v.push_back(*p); - std::sort(v.begin(), v.end()); - - for (std::vector::const_iterator p = v.begin(); - p != v.end(); - ++p) - { - std::string user_name = p->package_name() + ".init"; - tree decl = build_decl(UNKNOWN_LOCATION, FUNCTION_DECL, - get_identifier_from_string(user_name), - fntype); - const std::string& init_name(p->init_name()); - SET_DECL_ASSEMBLER_NAME(decl, get_identifier_from_string(init_name)); - TREE_PUBLIC(decl) = 1; - DECL_EXTERNAL(decl) = 1; - append_to_statement_list(build_call_expr(decl, 0), init_stmt_list); - } -} - -// Register global variables with the garbage collector. We need to -// register all variables which can hold a pointer value. They become -// roots during the mark phase. We build a struct that is easy to -// hook into a list of roots. - -// struct __go_gc_root_list -// { -// struct __go_gc_root_list* __next; -// struct __go_gc_root -// { -// void* __decl; -// size_t __size; -// } __roots[]; -// }; - -// The last entry in the roots array has a NULL decl field. - -void -Gogo::register_gc_vars(const std::vector& var_gc, - tree* init_stmt_list) -{ - if (var_gc.empty()) - return; - - size_t count = var_gc.size(); - - tree root_type = Gogo::builtin_struct(NULL, "__go_gc_root", NULL_TREE, 2, - "__next", - ptr_type_node, - "__size", - sizetype); - - tree index_type = build_index_type(size_int(count)); - tree array_type = build_array_type(root_type, index_type); - - tree root_list_type = make_node(RECORD_TYPE); - root_list_type = Gogo::builtin_struct(NULL, "__go_gc_root_list", - root_list_type, 2, - "__next", - build_pointer_type(root_list_type), - "__roots", - array_type); - - // Build an initialier for the __roots array. - - VEC(constructor_elt,gc)* roots_init = VEC_alloc(constructor_elt, gc, - count + 1); - - size_t i = 0; - for (std::vector::const_iterator p = var_gc.begin(); - p != var_gc.end(); - ++p, ++i) - { - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(root_type); - elt->index = field; - Bvariable* bvar = (*p)->get_backend_variable(this, NULL); - tree decl = var_to_tree(bvar); - go_assert(TREE_CODE(decl) == VAR_DECL); - elt->value = build_fold_addr_expr(decl); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - elt->index = field; - elt->value = DECL_SIZE_UNIT(decl); - - elt = VEC_quick_push(constructor_elt, roots_init, NULL); - elt->index = size_int(i); - elt->value = build_constructor(root_type, init); - } - - // The list ends with a NULL entry. - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(root_type); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), null_pointer_node); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - elt->index = field; - elt->value = size_zero_node; - - elt = VEC_quick_push(constructor_elt, roots_init, NULL); - elt->index = size_int(i); - elt->value = build_constructor(root_type, init); - - // Build a constructor for the struct. - - VEC(constructor_elt,gc*) root_list_init = VEC_alloc(constructor_elt, gc, 2); - - elt = VEC_quick_push(constructor_elt, root_list_init, NULL); - field = TYPE_FIELDS(root_list_type); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), null_pointer_node); - - elt = VEC_quick_push(constructor_elt, root_list_init, NULL); - field = DECL_CHAIN(field); - elt->index = field; - elt->value = build_constructor(array_type, roots_init); - - // Build a decl to register. - - tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, - create_tmp_var_name("gc"), root_list_type); - DECL_EXTERNAL(decl) = 0; - TREE_PUBLIC(decl) = 0; - TREE_STATIC(decl) = 1; - DECL_ARTIFICIAL(decl) = 1; - DECL_INITIAL(decl) = build_constructor(root_list_type, root_list_init); - rest_of_decl_compilation(decl, 1, 0); - - static tree register_gc_fndecl; - tree call = Gogo::call_builtin(®ister_gc_fndecl, BUILTINS_LOCATION, - "__go_register_gc_roots", - 1, - void_type_node, - build_pointer_type(root_list_type), - build_fold_addr_expr(decl)); - if (call != error_mark_node) - append_to_statement_list(call, init_stmt_list); -} - -// Build the decl for the initialization function. - -tree -Gogo::initialization_function_decl() -{ - // The tedious details of building your own function. There doesn't - // seem to be a helper function for this. - std::string name = this->package_name() + ".init"; - tree fndecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL, - get_identifier_from_string(name), - build_function_type(void_type_node, - void_list_node)); - const std::string& asm_name(this->get_init_fn_name()); - SET_DECL_ASSEMBLER_NAME(fndecl, get_identifier_from_string(asm_name)); - - tree resdecl = build_decl(BUILTINS_LOCATION, RESULT_DECL, NULL_TREE, - void_type_node); - DECL_ARTIFICIAL(resdecl) = 1; - DECL_CONTEXT(resdecl) = fndecl; - DECL_RESULT(fndecl) = resdecl; - - TREE_STATIC(fndecl) = 1; - TREE_USED(fndecl) = 1; - DECL_ARTIFICIAL(fndecl) = 1; - TREE_PUBLIC(fndecl) = 1; - - DECL_INITIAL(fndecl) = make_node(BLOCK); - TREE_USED(DECL_INITIAL(fndecl)) = 1; - - return fndecl; -} - -// Create the magic initialization function. INIT_STMT_LIST is the -// code that it needs to run. - -void -Gogo::write_initialization_function(tree fndecl, tree init_stmt_list) -{ - // Make sure that we thought we needed an initialization function, - // as otherwise we will not have reported it in the export data. - go_assert(this->is_main_package() || this->need_init_fn_); - - if (fndecl == NULL_TREE) - fndecl = this->initialization_function_decl(); - - DECL_SAVED_TREE(fndecl) = init_stmt_list; - - current_function_decl = fndecl; - if (DECL_STRUCT_FUNCTION(fndecl) == NULL) - push_struct_function(fndecl); - else - push_cfun(DECL_STRUCT_FUNCTION(fndecl)); - cfun->function_end_locus = BUILTINS_LOCATION; - - gimplify_function_tree(fndecl); - - cgraph_add_new_function(fndecl, false); - cgraph_mark_needed_node(cgraph_get_node(fndecl)); - - current_function_decl = NULL_TREE; - pop_cfun(); -} - -// Search for references to VAR in any statements or called functions. - -class Find_var : public Traverse -{ - public: - // A hash table we use to avoid looping. The index is the name of a - // named object. We only look through objects defined in this - // package. - typedef Unordered_set(std::string) Seen_objects; - - Find_var(Named_object* var, Seen_objects* seen_objects) - : Traverse(traverse_expressions), - var_(var), seen_objects_(seen_objects), found_(false) - { } - - // Whether the variable was found. - bool - found() const - { return this->found_; } - - int - expression(Expression**); - - private: - // The variable we are looking for. - Named_object* var_; - // Names of objects we have already seen. - Seen_objects* seen_objects_; - // True if the variable was found. - bool found_; -}; - -// See if EXPR refers to VAR, looking through function calls and -// variable initializations. - -int -Find_var::expression(Expression** pexpr) -{ - Expression* e = *pexpr; - - Var_expression* ve = e->var_expression(); - if (ve != NULL) - { - Named_object* v = ve->named_object(); - if (v == this->var_) - { - this->found_ = true; - return TRAVERSE_EXIT; - } - - if (v->is_variable() && v->package() == NULL) - { - Expression* init = v->var_value()->init(); - if (init != NULL) - { - std::pair ins = - this->seen_objects_->insert(v->name()); - if (ins.second) - { - // This is the first time we have seen this name. - if (Expression::traverse(&init, this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - } - } - - // We traverse the code of any function we see. Note that this - // means that we will traverse the code of a function whose address - // is taken even if it is not called. - Func_expression* fe = e->func_expression(); - if (fe != NULL) - { - const Named_object* f = fe->named_object(); - if (f->is_function() && f->package() == NULL) - { - std::pair ins = - this->seen_objects_->insert(f->name()); - if (ins.second) - { - // This is the first time we have seen this name. - if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - } - - return TRAVERSE_CONTINUE; -} - -// Return true if EXPR refers to VAR. - -static bool -expression_requires(Expression* expr, Block* preinit, Named_object* var) -{ - Find_var::Seen_objects seen_objects; - Find_var find_var(var, &seen_objects); - if (expr != NULL) - Expression::traverse(&expr, &find_var); - if (preinit != NULL) - preinit->traverse(&find_var); - - return find_var.found(); -} - -// Sort variable initializations. If the initialization expression -// for variable A refers directly or indirectly to the initialization -// expression for variable B, then we must initialize B before A. - -class Var_init -{ - public: - Var_init() - : var_(NULL), init_(NULL_TREE), waiting_(0) - { } - - Var_init(Named_object* var, tree init) - : var_(var), init_(init), waiting_(0) - { } - - // Return the variable. - Named_object* - var() const - { return this->var_; } - - // Return the initialization expression. - tree - init() const - { return this->init_; } - - // Return the number of variables waiting for this one to be - // initialized. - size_t - waiting() const - { return this->waiting_; } - - // Increment the number waiting. - void - increment_waiting() - { ++this->waiting_; } - - private: - // The variable being initialized. - Named_object* var_; - // The initialization expression to run. - tree init_; - // The number of variables which are waiting for this one. - size_t waiting_; -}; - -typedef std::list Var_inits; - -// Sort the variable initializations. The rule we follow is that we -// emit them in the order they appear in the array, except that if the -// initialization expression for a variable V1 depends upon another -// variable V2 then we initialize V1 after V2. - -static void -sort_var_inits(Var_inits* var_inits) -{ - Var_inits ready; - while (!var_inits->empty()) - { - Var_inits::iterator p1 = var_inits->begin(); - Named_object* var = p1->var(); - Expression* init = var->var_value()->init(); - Block* preinit = var->var_value()->preinit(); - - // Start walking through the list to see which variables VAR - // needs to wait for. We can skip P1->WAITING variables--that - // is the number we've already checked. - Var_inits::iterator p2 = p1; - ++p2; - for (size_t i = p1->waiting(); i > 0; --i) - ++p2; - - for (; p2 != var_inits->end(); ++p2) - { - if (expression_requires(init, preinit, p2->var())) - { - // Check for cycles. - if (expression_requires(p2->var()->var_value()->init(), - p2->var()->var_value()->preinit(), - var)) - { - error_at(var->location(), - ("initialization expressions for %qs and " - "%qs depend upon each other"), - var->message_name().c_str(), - p2->var()->message_name().c_str()); - inform(p2->var()->location(), "%qs defined here", - p2->var()->message_name().c_str()); - p2 = var_inits->end(); - } - else - { - // We can't emit P1 until P2 is emitted. Move P1. - // Note that the WAITING loop always executes at - // least once, which is what we want. - p2->increment_waiting(); - Var_inits::iterator p3 = p2; - for (size_t i = p2->waiting(); i > 0; --i) - ++p3; - var_inits->splice(p3, *var_inits, p1); - } - break; - } - } - - if (p2 == var_inits->end()) - { - // VAR does not depends upon any other initialization expressions. - - // Check for a loop of VAR on itself. We only do this if - // INIT is not NULL; when INIT is NULL, it means that - // PREINIT sets VAR, which we will interpret as a loop. - if (init != NULL && expression_requires(init, preinit, var)) - error_at(var->location(), - "initialization expression for %qs depends upon itself", - var->message_name().c_str()); - ready.splice(ready.end(), *var_inits, p1); - } - } - - // Now READY is the list in the desired initialization order. - var_inits->swap(ready); -} - -// Write out the global definitions. - -void -Gogo::write_globals() -{ - this->convert_named_types(); - this->build_interface_method_tables(); - - Bindings* bindings = this->current_bindings(); - size_t count = bindings->size_definitions(); - - tree* vec = new tree[count]; - - tree init_fndecl = NULL_TREE; - tree init_stmt_list = NULL_TREE; - - if (this->is_main_package()) - this->init_imports(&init_stmt_list); - - // A list of variable initializations. - Var_inits var_inits; - - // A list of variables which need to be registered with the garbage - // collector. - std::vector var_gc; - var_gc.reserve(count); - - tree var_init_stmt_list = NULL_TREE; - size_t i = 0; - for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); - p != bindings->end_definitions(); - ++p, ++i) - { - Named_object* no = *p; - - go_assert(!no->is_type_declaration() && !no->is_function_declaration()); - // There is nothing to do for a package. - if (no->is_package()) - { - --i; - --count; - continue; - } - - // There is nothing to do for an object which was imported from - // a different package into the global scope. - if (no->package() != NULL) - { - --i; - --count; - continue; - } - - // There is nothing useful we can output for constants which - // have ideal or non-integeral type. - if (no->is_const()) - { - Type* type = no->const_value()->type(); - if (type == NULL) - type = no->const_value()->expr()->type(); - if (type->is_abstract() || type->integer_type() == NULL) - { - --i; - --count; - continue; - } - } - - if (!no->is_variable()) - { - vec[i] = no->get_tree(this, NULL); - if (vec[i] == error_mark_node) - { - go_assert(saw_errors()); - --i; - --count; - continue; - } - } - else - { - Bvariable* var = no->get_backend_variable(this, NULL); - vec[i] = var_to_tree(var); - if (vec[i] == error_mark_node) - { - go_assert(saw_errors()); - --i; - --count; - continue; - } - - // Check for a sink variable, which may be used to run an - // initializer purely for its side effects. - bool is_sink = no->name()[0] == '_' && no->name()[1] == '.'; - - tree var_init_tree = NULL_TREE; - if (!no->var_value()->has_pre_init()) - { - tree init = no->var_value()->get_init_tree(this, NULL); - if (init == error_mark_node) - go_assert(saw_errors()); - else if (init == NULL_TREE) - ; - else if (TREE_CONSTANT(init)) - this->backend()->global_variable_set_init(var, - tree_to_expr(init)); - else if (is_sink) - var_init_tree = init; - else - var_init_tree = fold_build2_loc(no->location(), MODIFY_EXPR, - void_type_node, vec[i], init); - } - else - { - // We are going to create temporary variables which - // means that we need an fndecl. - if (init_fndecl == NULL_TREE) - init_fndecl = this->initialization_function_decl(); - current_function_decl = init_fndecl; - if (DECL_STRUCT_FUNCTION(init_fndecl) == NULL) - push_struct_function(init_fndecl); - else - push_cfun(DECL_STRUCT_FUNCTION(init_fndecl)); - - tree var_decl = is_sink ? NULL_TREE : vec[i]; - var_init_tree = no->var_value()->get_init_block(this, NULL, - var_decl); - - current_function_decl = NULL_TREE; - pop_cfun(); - } - - if (var_init_tree != NULL_TREE && var_init_tree != error_mark_node) - { - if (no->var_value()->init() == NULL - && !no->var_value()->has_pre_init()) - append_to_statement_list(var_init_tree, &var_init_stmt_list); - else - var_inits.push_back(Var_init(no, var_init_tree)); - } - - if (!is_sink && no->var_value()->type()->has_pointer()) - var_gc.push_back(no); - } - } - - // Register global variables with the garbage collector. - this->register_gc_vars(var_gc, &init_stmt_list); - - // Simple variable initializations, after all variables are - // registered. - append_to_statement_list(var_init_stmt_list, &init_stmt_list); - - // Complex variable initializations, first sorting them into a - // workable order. - if (!var_inits.empty()) - { - sort_var_inits(&var_inits); - for (Var_inits::const_iterator p = var_inits.begin(); - p != var_inits.end(); - ++p) - append_to_statement_list(p->init(), &init_stmt_list); - } - - // After all the variables are initialized, call the "init" - // functions if there are any. - for (std::vector::const_iterator p = - this->init_functions_.begin(); - p != this->init_functions_.end(); - ++p) - { - tree decl = (*p)->get_tree(this, NULL); - tree call = build_call_expr(decl, 0); - append_to_statement_list(call, &init_stmt_list); - } - - // Set up a magic function to do all the initialization actions. - // This will be called if this package is imported. - if (init_stmt_list != NULL_TREE - || this->need_init_fn_ - || this->is_main_package()) - this->write_initialization_function(init_fndecl, init_stmt_list); - - // Pass everything back to the middle-end. - - wrapup_global_declarations(vec, count); - - cgraph_finalize_compilation_unit(); - - check_global_declarations(vec, count); - emit_debug_global_declarations(vec, count); - - delete[] vec; -} - -// Get a tree for the identifier for a named object. - -tree -Named_object::get_id(Gogo* gogo) -{ - go_assert(!this->is_variable() && !this->is_result_variable()); - std::string decl_name; - if (this->is_function_declaration() - && !this->func_declaration_value()->asm_name().empty()) - decl_name = this->func_declaration_value()->asm_name(); - else if (this->is_type() - && this->type_value()->location() == BUILTINS_LOCATION) - { - // We don't need the package name for builtin types. - decl_name = Gogo::unpack_hidden_name(this->name_); - } - else - { - std::string package_name; - if (this->package_ == NULL) - package_name = gogo->package_name(); - else - package_name = this->package_->name(); - - decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_); - - Function_type* fntype; - if (this->is_function()) - fntype = this->func_value()->type(); - else if (this->is_function_declaration()) - fntype = this->func_declaration_value()->type(); - else - fntype = NULL; - if (fntype != NULL && fntype->is_method()) - { - decl_name.push_back('.'); - decl_name.append(fntype->receiver()->type()->mangled_name(gogo)); - } - } - if (this->is_type()) - { - const Named_object* in_function = this->type_value()->in_function(); - if (in_function != NULL) - decl_name += '$' + in_function->name(); - } - return get_identifier_from_string(decl_name); -} - -// Get a tree for a named object. - -tree -Named_object::get_tree(Gogo* gogo, Named_object* function) -{ - if (this->tree_ != NULL_TREE) - return this->tree_; - - tree name; - if (this->classification_ == NAMED_OBJECT_TYPE) - name = NULL_TREE; - else - name = this->get_id(gogo); - tree decl; - switch (this->classification_) - { - case NAMED_OBJECT_CONST: - { - Named_constant* named_constant = this->u_.const_value; - Translate_context subcontext(gogo, function, NULL, NULL); - tree expr_tree = named_constant->expr()->get_tree(&subcontext); - if (expr_tree == error_mark_node) - decl = error_mark_node; - else - { - Type* type = named_constant->type(); - if (type != NULL && !type->is_abstract()) - { - if (!type->is_error()) - expr_tree = fold_convert(type->get_tree(gogo), expr_tree); - else - expr_tree = error_mark_node; - } - if (expr_tree == error_mark_node) - decl = error_mark_node; - else if (INTEGRAL_TYPE_P(TREE_TYPE(expr_tree))) - { - decl = build_decl(named_constant->location(), CONST_DECL, - name, TREE_TYPE(expr_tree)); - DECL_INITIAL(decl) = expr_tree; - TREE_CONSTANT(decl) = 1; - TREE_READONLY(decl) = 1; - } - else - { - // A CONST_DECL is only for an enum constant, so we - // shouldn't use for non-integral types. Instead we - // just return the constant itself, rather than a - // decl. - decl = expr_tree; - } - } - } - break; - - case NAMED_OBJECT_TYPE: - { - Named_type* named_type = this->u_.type_value; - tree type_tree = named_type->get_tree(gogo); - if (type_tree == error_mark_node) - decl = error_mark_node; - else - { - decl = TYPE_NAME(type_tree); - go_assert(decl != NULL_TREE); - - // We need to produce a type descriptor for every named - // type, and for a pointer to every named type, since - // other files or packages might refer to them. We need - // to do this even for hidden types, because they might - // still be returned by some function. Simply calling the - // type_descriptor method is enough to create the type - // descriptor, even though we don't do anything with it. - if (this->package_ == NULL) - { - named_type->type_descriptor_pointer(gogo); - Type* pn = Type::make_pointer_type(named_type); - pn->type_descriptor_pointer(gogo); - } - } - } - break; - - case NAMED_OBJECT_TYPE_DECLARATION: - error("reference to undefined type %qs", - this->message_name().c_str()); - return error_mark_node; - - case NAMED_OBJECT_VAR: - case NAMED_OBJECT_RESULT_VAR: - case NAMED_OBJECT_SINK: - go_unreachable(); - - case NAMED_OBJECT_FUNC: - { - Function* func = this->u_.func_value; - decl = func->get_or_make_decl(gogo, this, name); - if (decl != error_mark_node) - { - if (func->block() != NULL) - { - if (DECL_STRUCT_FUNCTION(decl) == NULL) - push_struct_function(decl); - else - push_cfun(DECL_STRUCT_FUNCTION(decl)); - - cfun->function_end_locus = func->block()->end_location(); - - current_function_decl = decl; - - func->build_tree(gogo, this); - - gimplify_function_tree(decl); - - cgraph_finalize_function(decl, true); - - current_function_decl = NULL_TREE; - pop_cfun(); - } - } - } - break; - - default: - go_unreachable(); - } - - if (TREE_TYPE(decl) == error_mark_node) - decl = error_mark_node; - - tree ret = decl; - - this->tree_ = ret; - - if (ret != error_mark_node) - go_preserve_from_gc(ret); - - return ret; -} - -// Get the initial value of a variable as a tree. This does not -// consider whether the variable is in the heap--it returns the -// initial value as though it were always stored in the stack. - -tree -Variable::get_init_tree(Gogo* gogo, Named_object* function) -{ - go_assert(this->preinit_ == NULL); - if (this->init_ == NULL) - { - go_assert(!this->is_parameter_); - return this->type_->get_init_tree(gogo, - (this->is_global_ - || this->is_in_heap())); - } - else - { - Translate_context context(gogo, function, NULL, NULL); - tree rhs_tree = this->init_->get_tree(&context); - return Expression::convert_for_assignment(&context, this->type(), - this->init_->type(), - rhs_tree, this->location()); - } -} - -// Get the initial value of a variable when a block is required. -// VAR_DECL is the decl to set; it may be NULL for a sink variable. - -tree -Variable::get_init_block(Gogo* gogo, Named_object* function, tree var_decl) -{ - go_assert(this->preinit_ != NULL); - - // We want to add the variable assignment to the end of the preinit - // block. The preinit block may have a TRY_FINALLY_EXPR and a - // TRY_CATCH_EXPR; if it does, we want to add to the end of the - // regular statements. - - Translate_context context(gogo, function, NULL, NULL); - Bblock* bblock = this->preinit_->get_backend(&context); - tree block_tree = block_to_tree(bblock); - if (block_tree == error_mark_node) - return error_mark_node; - go_assert(TREE_CODE(block_tree) == BIND_EXPR); - tree statements = BIND_EXPR_BODY(block_tree); - while (statements != NULL_TREE - && (TREE_CODE(statements) == TRY_FINALLY_EXPR - || TREE_CODE(statements) == TRY_CATCH_EXPR)) - statements = TREE_OPERAND(statements, 0); - - // It's possible to have pre-init statements without an initializer - // if the pre-init statements set the variable. - if (this->init_ != NULL) - { - tree rhs_tree = this->init_->get_tree(&context); - if (rhs_tree == error_mark_node) - return error_mark_node; - if (var_decl == NULL_TREE) - append_to_statement_list(rhs_tree, &statements); - else - { - tree val = Expression::convert_for_assignment(&context, this->type(), - this->init_->type(), - rhs_tree, - this->location()); - if (val == error_mark_node) - return error_mark_node; - tree set = fold_build2_loc(this->location(), MODIFY_EXPR, - void_type_node, var_decl, val); - append_to_statement_list(set, &statements); - } - } - - return block_tree; -} - -// Get a tree for a function decl. - -tree -Function::get_or_make_decl(Gogo* gogo, Named_object* no, tree id) -{ - if (this->fndecl_ == NULL_TREE) - { - tree functype = this->type_->get_tree(gogo); - if (functype == error_mark_node) - this->fndecl_ = error_mark_node; - else - { - // The type of a function comes back as a pointer, but we - // want the real function type for a function declaration. - go_assert(POINTER_TYPE_P(functype)); - functype = TREE_TYPE(functype); - tree decl = build_decl(this->location(), FUNCTION_DECL, id, functype); - - this->fndecl_ = decl; - - if (no->package() != NULL) - ; - else if (this->enclosing_ != NULL || Gogo::is_thunk(no)) - ; - else if (Gogo::unpack_hidden_name(no->name()) == "init" - && !this->type_->is_method()) - ; - else if (Gogo::unpack_hidden_name(no->name()) == "main" - && gogo->is_main_package()) - TREE_PUBLIC(decl) = 1; - // Methods have to be public even if they are hidden because - // they can be pulled into type descriptors when using - // anonymous fields. - else if (!Gogo::is_hidden_name(no->name()) - || this->type_->is_method()) - { - TREE_PUBLIC(decl) = 1; - std::string asm_name = gogo->unique_prefix(); - asm_name.append(1, '.'); - asm_name.append(IDENTIFIER_POINTER(id), IDENTIFIER_LENGTH(id)); - SET_DECL_ASSEMBLER_NAME(decl, - get_identifier_from_string(asm_name)); - } - - // Why do we have to do this in the frontend? - tree restype = TREE_TYPE(functype); - tree resdecl = build_decl(this->location(), RESULT_DECL, NULL_TREE, - restype); - DECL_ARTIFICIAL(resdecl) = 1; - DECL_IGNORED_P(resdecl) = 1; - DECL_CONTEXT(resdecl) = decl; - DECL_RESULT(decl) = resdecl; - - if (this->enclosing_ != NULL) - DECL_STATIC_CHAIN(decl) = 1; - - // If a function calls the predeclared recover function, we - // can't inline it, because recover behaves differently in a - // function passed directly to defer. - if (this->calls_recover_ && !this->is_recover_thunk_) - DECL_UNINLINABLE(decl) = 1; - - // If this is a thunk created to call a function which calls - // the predeclared recover function, we need to disable - // stack splitting for the thunk. - if (this->is_recover_thunk_) - { - tree attr = get_identifier("__no_split_stack__"); - DECL_ATTRIBUTES(decl) = tree_cons(attr, NULL_TREE, NULL_TREE); - } - - go_preserve_from_gc(decl); - - if (this->closure_var_ != NULL) - { - push_struct_function(decl); - - Bvariable* bvar = this->closure_var_->get_backend_variable(gogo, - no); - tree closure_decl = var_to_tree(bvar); - if (closure_decl == error_mark_node) - this->fndecl_ = error_mark_node; - else - { - DECL_ARTIFICIAL(closure_decl) = 1; - DECL_IGNORED_P(closure_decl) = 1; - TREE_USED(closure_decl) = 1; - DECL_ARG_TYPE(closure_decl) = TREE_TYPE(closure_decl); - TREE_READONLY(closure_decl) = 1; - - DECL_STRUCT_FUNCTION(decl)->static_chain_decl = closure_decl; - } - - pop_cfun(); - } - } - } - return this->fndecl_; -} - -// Get a tree for a function declaration. - -tree -Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no, tree id) -{ - if (this->fndecl_ == NULL_TREE) - { - // Let Go code use an asm declaration to pick up a builtin - // function. - if (!this->asm_name_.empty()) - { - std::map::const_iterator p = - builtin_functions.find(this->asm_name_); - if (p != builtin_functions.end()) - { - this->fndecl_ = p->second; - return this->fndecl_; - } - } - - tree functype = this->fntype_->get_tree(gogo); - tree decl; - if (functype == error_mark_node) - decl = error_mark_node; - else - { - // The type of a function comes back as a pointer, but we - // want the real function type for a function declaration. - go_assert(POINTER_TYPE_P(functype)); - functype = TREE_TYPE(functype); - decl = build_decl(this->location(), FUNCTION_DECL, id, functype); - TREE_PUBLIC(decl) = 1; - DECL_EXTERNAL(decl) = 1; - - if (this->asm_name_.empty()) - { - std::string asm_name = (no->package() == NULL - ? gogo->unique_prefix() - : no->package()->unique_prefix()); - asm_name.append(1, '.'); - asm_name.append(IDENTIFIER_POINTER(id), IDENTIFIER_LENGTH(id)); - SET_DECL_ASSEMBLER_NAME(decl, - get_identifier_from_string(asm_name)); - } - } - this->fndecl_ = decl; - go_preserve_from_gc(decl); - } - return this->fndecl_; -} - -// We always pass the receiver to a method as a pointer. If the -// receiver is actually declared as a non-pointer type, then we copy -// the value into a local variable, so that it has the right type. In -// this function we create the real PARM_DECL to use, and set -// DEC_INITIAL of the var_decl to be the value passed in. - -tree -Function::make_receiver_parm_decl(Gogo* gogo, Named_object* no, tree var_decl) -{ - if (var_decl == error_mark_node) - return error_mark_node; - go_assert(TREE_CODE(var_decl) == VAR_DECL); - tree val_type = TREE_TYPE(var_decl); - bool is_in_heap = no->var_value()->is_in_heap(); - if (is_in_heap) - { - go_assert(POINTER_TYPE_P(val_type)); - val_type = TREE_TYPE(val_type); - } - - source_location loc = DECL_SOURCE_LOCATION(var_decl); - std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl)); - name += ".pointer"; - tree id = get_identifier_from_string(name); - tree parm_decl = build_decl(loc, PARM_DECL, id, build_pointer_type(val_type)); - DECL_CONTEXT(parm_decl) = current_function_decl; - DECL_ARG_TYPE(parm_decl) = TREE_TYPE(parm_decl); - - go_assert(DECL_INITIAL(var_decl) == NULL_TREE); - // The receiver might be passed as a null pointer. - tree check = fold_build2_loc(loc, NE_EXPR, boolean_type_node, parm_decl, - fold_convert_loc(loc, TREE_TYPE(parm_decl), - null_pointer_node)); - tree ind = build_fold_indirect_ref_loc(loc, parm_decl); - TREE_THIS_NOTRAP(ind) = 1; - tree zero_init = no->var_value()->type()->get_init_tree(gogo, false); - tree init = fold_build3_loc(loc, COND_EXPR, TREE_TYPE(ind), - check, ind, zero_init); - - if (is_in_heap) - { - tree size = TYPE_SIZE_UNIT(val_type); - tree space = gogo->allocate_memory(no->var_value()->type(), size, - no->location()); - space = save_expr(space); - space = fold_convert(build_pointer_type(val_type), space); - tree spaceref = build_fold_indirect_ref_loc(no->location(), space); - TREE_THIS_NOTRAP(spaceref) = 1; - tree check = fold_build2_loc(loc, NE_EXPR, boolean_type_node, - parm_decl, - fold_convert_loc(loc, TREE_TYPE(parm_decl), - null_pointer_node)); - tree parmref = build_fold_indirect_ref_loc(no->location(), parm_decl); - TREE_THIS_NOTRAP(parmref) = 1; - tree set = fold_build2_loc(loc, MODIFY_EXPR, void_type_node, - spaceref, parmref); - init = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(space), - build3(COND_EXPR, void_type_node, - check, set, NULL_TREE), - space); - } - - DECL_INITIAL(var_decl) = init; - - return parm_decl; -} - -// If we take the address of a parameter, then we need to copy it into -// the heap. We will access it as a local variable via an -// indirection. - -tree -Function::copy_parm_to_heap(Gogo* gogo, Named_object* no, tree var_decl) -{ - if (var_decl == error_mark_node) - return error_mark_node; - go_assert(TREE_CODE(var_decl) == VAR_DECL); - source_location loc = DECL_SOURCE_LOCATION(var_decl); - - std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl)); - name += ".param"; - tree id = get_identifier_from_string(name); - - tree type = TREE_TYPE(var_decl); - go_assert(POINTER_TYPE_P(type)); - type = TREE_TYPE(type); - - tree parm_decl = build_decl(loc, PARM_DECL, id, type); - DECL_CONTEXT(parm_decl) = current_function_decl; - DECL_ARG_TYPE(parm_decl) = type; - - tree size = TYPE_SIZE_UNIT(type); - tree space = gogo->allocate_memory(no->var_value()->type(), size, loc); - space = save_expr(space); - space = fold_convert(TREE_TYPE(var_decl), space); - tree spaceref = build_fold_indirect_ref_loc(loc, space); - TREE_THIS_NOTRAP(spaceref) = 1; - tree init = build2(COMPOUND_EXPR, TREE_TYPE(space), - build2(MODIFY_EXPR, void_type_node, spaceref, parm_decl), - space); - DECL_INITIAL(var_decl) = init; - - return parm_decl; -} - -// Get a tree for function code. - -void -Function::build_tree(Gogo* gogo, Named_object* named_function) -{ - tree fndecl = this->fndecl_; - go_assert(fndecl != NULL_TREE); - - tree params = NULL_TREE; - tree* pp = ¶ms; - - tree declare_vars = NULL_TREE; - for (Bindings::const_definitions_iterator p = - this->block_->bindings()->begin_definitions(); - p != this->block_->bindings()->end_definitions(); - ++p) - { - if ((*p)->is_variable() && (*p)->var_value()->is_parameter()) - { - Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function); - *pp = var_to_tree(bvar); - - // We always pass the receiver to a method as a pointer. If - // the receiver is declared as a non-pointer type, then we - // copy the value into a local variable. - if ((*p)->var_value()->is_receiver() - && (*p)->var_value()->type()->points_to() == NULL) - { - tree parm_decl = this->make_receiver_parm_decl(gogo, *p, *pp); - tree var = *pp; - if (var != error_mark_node) - { - go_assert(TREE_CODE(var) == VAR_DECL); - DECL_CHAIN(var) = declare_vars; - declare_vars = var; - } - *pp = parm_decl; - } - else if ((*p)->var_value()->is_in_heap()) - { - // If we take the address of a parameter, then we need - // to copy it into the heap. - tree parm_decl = this->copy_parm_to_heap(gogo, *p, *pp); - tree var = *pp; - if (var != error_mark_node) - { - go_assert(TREE_CODE(var) == VAR_DECL); - DECL_CHAIN(var) = declare_vars; - declare_vars = var; - } - *pp = parm_decl; - } - - if (*pp != error_mark_node) - { - go_assert(TREE_CODE(*pp) == PARM_DECL); - pp = &DECL_CHAIN(*pp); - } - } - else if ((*p)->is_result_variable()) - { - Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function); - tree var_decl = var_to_tree(bvar); - - Type* type = (*p)->result_var_value()->type(); - tree init; - if (!(*p)->result_var_value()->is_in_heap()) - init = type->get_init_tree(gogo, false); - else - { - source_location loc = (*p)->location(); - tree type_tree = type->get_tree(gogo); - tree space = gogo->allocate_memory(type, - TYPE_SIZE_UNIT(type_tree), - loc); - tree ptr_type_tree = build_pointer_type(type_tree); - tree subinit = type->get_init_tree(gogo, true); - if (subinit == NULL_TREE) - init = fold_convert_loc(loc, ptr_type_tree, space); - else - { - space = save_expr(space); - space = fold_convert_loc(loc, ptr_type_tree, space); - tree spaceref = build_fold_indirect_ref_loc(loc, space); - TREE_THIS_NOTRAP(spaceref) = 1; - tree set = fold_build2_loc(loc, MODIFY_EXPR, void_type_node, - spaceref, subinit); - init = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(space), - set, space); - } - } - - if (var_decl != error_mark_node) - { - go_assert(TREE_CODE(var_decl) == VAR_DECL); - DECL_INITIAL(var_decl) = init; - DECL_CHAIN(var_decl) = declare_vars; - declare_vars = var_decl; - } - } - } - *pp = NULL_TREE; - - DECL_ARGUMENTS(fndecl) = params; - - if (this->block_ != NULL) - { - go_assert(DECL_INITIAL(fndecl) == NULL_TREE); - - // Declare variables if necessary. - tree bind = NULL_TREE; - tree defer_init = NULL_TREE; - if (declare_vars != NULL_TREE || this->defer_stack_ != NULL) - { - tree block = make_node(BLOCK); - BLOCK_SUPERCONTEXT(block) = fndecl; - DECL_INITIAL(fndecl) = block; - BLOCK_VARS(block) = declare_vars; - TREE_USED(block) = 1; - - bind = build3(BIND_EXPR, void_type_node, BLOCK_VARS(block), - NULL_TREE, block); - TREE_SIDE_EFFECTS(bind) = 1; - - if (this->defer_stack_ != NULL) - { - Translate_context dcontext(gogo, named_function, this->block_, - tree_to_block(bind)); - Bstatement* bdi = this->defer_stack_->get_backend(&dcontext); - defer_init = stat_to_tree(bdi); - } - } - - // Build the trees for all the statements in the function. - Translate_context context(gogo, named_function, NULL, NULL); - Bblock* bblock = this->block_->get_backend(&context); - tree code = block_to_tree(bblock); - - tree init = NULL_TREE; - tree except = NULL_TREE; - tree fini = NULL_TREE; - - // Initialize variables if necessary. - for (tree v = declare_vars; v != NULL_TREE; v = DECL_CHAIN(v)) - { - tree dv = build1(DECL_EXPR, void_type_node, v); - SET_EXPR_LOCATION(dv, DECL_SOURCE_LOCATION(v)); - append_to_statement_list(dv, &init); - } - - // If we have a defer stack, initialize it at the start of a - // function. - if (defer_init != NULL_TREE && defer_init != error_mark_node) - { - SET_EXPR_LOCATION(defer_init, this->block_->start_location()); - append_to_statement_list(defer_init, &init); - - // Clean up the defer stack when we leave the function. - this->build_defer_wrapper(gogo, named_function, &except, &fini); - } - - if (code != NULL_TREE && code != error_mark_node) - { - if (init != NULL_TREE) - code = build2(COMPOUND_EXPR, void_type_node, init, code); - if (except != NULL_TREE) - code = build2(TRY_CATCH_EXPR, void_type_node, code, - build2(CATCH_EXPR, void_type_node, NULL, except)); - if (fini != NULL_TREE) - code = build2(TRY_FINALLY_EXPR, void_type_node, code, fini); - } - - // Stick the code into the block we built for the receiver, if - // we built on. - if (bind != NULL_TREE && code != NULL_TREE && code != error_mark_node) - { - BIND_EXPR_BODY(bind) = code; - code = bind; - } - - DECL_SAVED_TREE(fndecl) = code; - } -} - -// Build the wrappers around function code needed if the function has -// any defer statements. This sets *EXCEPT to an exception handler -// and *FINI to a finally handler. - -void -Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function, - tree *except, tree *fini) -{ - source_location end_loc = this->block_->end_location(); - - // Add an exception handler. This is used if a panic occurs. Its - // purpose is to stop the stack unwinding if a deferred function - // calls recover. There are more details in - // libgo/runtime/go-unwind.c. - - tree stmt_list = NULL_TREE; - - Expression* call = Runtime::make_call(Runtime::CHECK_DEFER, end_loc, 1, - this->defer_stack(end_loc)); - Translate_context context(gogo, named_function, NULL, NULL); - tree call_tree = call->get_tree(&context); - if (call_tree != error_mark_node) - append_to_statement_list(call_tree, &stmt_list); - - tree retval = this->return_value(gogo, named_function, end_loc, &stmt_list); - tree set; - if (retval == NULL_TREE) - set = NULL_TREE; - else - set = fold_build2_loc(end_loc, MODIFY_EXPR, void_type_node, - DECL_RESULT(this->fndecl_), retval); - tree ret_stmt = fold_build1_loc(end_loc, RETURN_EXPR, void_type_node, set); - append_to_statement_list(ret_stmt, &stmt_list); - - go_assert(*except == NULL_TREE); - *except = stmt_list; - - // Add some finally code to run the defer functions. This is used - // both in the normal case, when no panic occurs, and also if a - // panic occurs to run any further defer functions. Of course, it - // is possible for a defer function to call panic which should be - // caught by another defer function. To handle that we use a loop. - // finish: - // try { __go_undefer(); } catch { __go_check_defer(); goto finish; } - // if (return values are named) return named_vals; - - stmt_list = NULL; - - tree label = create_artificial_label(end_loc); - tree define_label = fold_build1_loc(end_loc, LABEL_EXPR, void_type_node, - label); - append_to_statement_list(define_label, &stmt_list); - - call = Runtime::make_call(Runtime::UNDEFER, end_loc, 1, - this->defer_stack(end_loc)); - tree undefer = call->get_tree(&context); - - call = Runtime::make_call(Runtime::CHECK_DEFER, end_loc, 1, - this->defer_stack(end_loc)); - tree defer = call->get_tree(&context); - - if (undefer == error_mark_node || defer == error_mark_node) - return; - - tree jump = fold_build1_loc(end_loc, GOTO_EXPR, void_type_node, label); - tree catch_body = build2(COMPOUND_EXPR, void_type_node, defer, jump); - catch_body = build2(CATCH_EXPR, void_type_node, NULL, catch_body); - tree try_catch = build2(TRY_CATCH_EXPR, void_type_node, undefer, catch_body); - - append_to_statement_list(try_catch, &stmt_list); - - if (this->type_->results() != NULL - && !this->type_->results()->empty() - && !this->type_->results()->front().name().empty()) - { - // If the result variables are named, we need to return them - // again, because they might have been changed by a defer - // function. - retval = this->return_value(gogo, named_function, end_loc, - &stmt_list); - set = fold_build2_loc(end_loc, MODIFY_EXPR, void_type_node, - DECL_RESULT(this->fndecl_), retval); - ret_stmt = fold_build1_loc(end_loc, RETURN_EXPR, void_type_node, set); - append_to_statement_list(ret_stmt, &stmt_list); - } - - go_assert(*fini == NULL_TREE); - *fini = stmt_list; -} - -// Return the value to assign to DECL_RESULT(this->fndecl_). This may -// also add statements to STMT_LIST, which need to be executed before -// the assignment. This is used for a return statement with no -// explicit values. - -tree -Function::return_value(Gogo* gogo, Named_object* named_function, - source_location location, tree* stmt_list) const -{ - const Typed_identifier_list* results = this->type_->results(); - if (results == NULL || results->empty()) - return NULL_TREE; - - go_assert(this->results_ != NULL); - if (this->results_->size() != results->size()) - { - go_assert(saw_errors()); - return error_mark_node; - } - - tree retval; - if (results->size() == 1) - { - Bvariable* bvar = - this->results_->front()->get_backend_variable(gogo, - named_function); - tree ret = var_to_tree(bvar); - if (this->results_->front()->result_var_value()->is_in_heap()) - ret = build_fold_indirect_ref_loc(location, ret); - return ret; - } - else - { - tree rettype = TREE_TYPE(DECL_RESULT(this->fndecl_)); - retval = create_tmp_var(rettype, "RESULT"); - tree field = TYPE_FIELDS(rettype); - int index = 0; - for (Typed_identifier_list::const_iterator pr = results->begin(); - pr != results->end(); - ++pr, ++index, field = DECL_CHAIN(field)) - { - go_assert(field != NULL); - Named_object* no = (*this->results_)[index]; - Bvariable* bvar = no->get_backend_variable(gogo, named_function); - tree val = var_to_tree(bvar); - if (no->result_var_value()->is_in_heap()) - val = build_fold_indirect_ref_loc(location, val); - tree set = fold_build2_loc(location, MODIFY_EXPR, void_type_node, - build3(COMPONENT_REF, TREE_TYPE(field), - retval, field, NULL_TREE), - val); - append_to_statement_list(set, stmt_list); - } - return retval; - } -} - -// Return the integer type to use for a size. - -GO_EXTERN_C -tree -go_type_for_size(unsigned int bits, int unsignedp) -{ - const char* name; - switch (bits) - { - case 8: - name = unsignedp ? "uint8" : "int8"; - break; - case 16: - name = unsignedp ? "uint16" : "int16"; - break; - case 32: - name = unsignedp ? "uint32" : "int32"; - break; - case 64: - name = unsignedp ? "uint64" : "int64"; - break; - default: - if (bits == POINTER_SIZE && unsignedp) - name = "uintptr"; - else - return NULL_TREE; - } - Type* type = Type::lookup_integer_type(name); - return type->get_tree(go_get_gogo()); -} - -// Return the type to use for a mode. - -GO_EXTERN_C -tree -go_type_for_mode(enum machine_mode mode, int unsignedp) -{ - // FIXME: This static_cast should be in machmode.h. - enum mode_class mc = static_cast(GET_MODE_CLASS(mode)); - if (mc == MODE_INT) - return go_type_for_size(GET_MODE_BITSIZE(mode), unsignedp); - else if (mc == MODE_FLOAT) - { - Type* type; - switch (GET_MODE_BITSIZE (mode)) - { - case 32: - type = Type::lookup_float_type("float32"); - break; - case 64: - type = Type::lookup_float_type("float64"); - break; - default: - // We have to check for long double in order to support - // i386 excess precision. - if (mode == TYPE_MODE(long_double_type_node)) - return long_double_type_node; - return NULL_TREE; - } - return type->float_type()->type_tree(); - } - else if (mc == MODE_COMPLEX_FLOAT) - { - Type *type; - switch (GET_MODE_BITSIZE (mode)) - { - case 64: - type = Type::lookup_complex_type("complex64"); - break; - case 128: - type = Type::lookup_complex_type("complex128"); - break; - default: - // We have to check for long double in order to support - // i386 excess precision. - if (mode == TYPE_MODE(complex_long_double_type_node)) - return complex_long_double_type_node; - return NULL_TREE; - } - return type->complex_type()->type_tree(); - } - else - return NULL_TREE; -} - -// Return a tree which allocates SIZE bytes which will holds value of -// type TYPE. - -tree -Gogo::allocate_memory(Type* type, tree size, source_location location) -{ - // If the package imports unsafe, then it may play games with - // pointers that look like integers. - if (this->imported_unsafe_ || type->has_pointer()) - { - static tree new_fndecl; - return Gogo::call_builtin(&new_fndecl, - location, - "__go_new", - 1, - ptr_type_node, - sizetype, - size); - } - else - { - static tree new_nopointers_fndecl; - return Gogo::call_builtin(&new_nopointers_fndecl, - location, - "__go_new_nopointers", - 1, - ptr_type_node, - sizetype, - size); - } -} - -// Build a builtin struct with a list of fields. The name is -// STRUCT_NAME. STRUCT_TYPE is NULL_TREE or an empty RECORD_TYPE -// node; this exists so that the struct can have fields which point to -// itself. If PTYPE is not NULL, store the result in *PTYPE. There -// are NFIELDS fields. Each field is a name (a const char*) followed -// by a type (a tree). - -tree -Gogo::builtin_struct(tree* ptype, const char* struct_name, tree struct_type, - int nfields, ...) -{ - if (ptype != NULL && *ptype != NULL_TREE) - return *ptype; - - va_list ap; - va_start(ap, nfields); - - tree fields = NULL_TREE; - for (int i = 0; i < nfields; ++i) - { - const char* field_name = va_arg(ap, const char*); - tree type = va_arg(ap, tree); - if (type == error_mark_node) - { - if (ptype != NULL) - *ptype = error_mark_node; - return error_mark_node; - } - tree field = build_decl(BUILTINS_LOCATION, FIELD_DECL, - get_identifier(field_name), type); - DECL_CHAIN(field) = fields; - fields = field; - } - - va_end(ap); - - if (struct_type == NULL_TREE) - struct_type = make_node(RECORD_TYPE); - finish_builtin_struct(struct_type, struct_name, fields, NULL_TREE); - - if (ptype != NULL) - { - go_preserve_from_gc(struct_type); - *ptype = struct_type; - } - - return struct_type; -} - -// Return a type to use for pointer to const char for a string. - -tree -Gogo::const_char_pointer_type_tree() -{ - static tree type; - if (type == NULL_TREE) - { - tree const_char_type = build_qualified_type(unsigned_char_type_node, - TYPE_QUAL_CONST); - type = build_pointer_type(const_char_type); - go_preserve_from_gc(type); - } - return type; -} - -// Return a tree for a string constant. - -tree -Gogo::string_constant_tree(const std::string& val) -{ - tree index_type = build_index_type(size_int(val.length())); - tree const_char_type = build_qualified_type(unsigned_char_type_node, - TYPE_QUAL_CONST); - tree string_type = build_array_type(const_char_type, index_type); - string_type = build_variant_type_copy(string_type); - TYPE_STRING_FLAG(string_type) = 1; - tree string_val = build_string(val.length(), val.data()); - TREE_TYPE(string_val) = string_type; - return string_val; -} - -// Return a tree for a Go string constant. - -tree -Gogo::go_string_constant_tree(const std::string& val) -{ - tree string_type = Type::make_string_type()->get_tree(this); - - VEC(constructor_elt, gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(string_type); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__data") == 0); - elt->index = field; - tree str = Gogo::string_constant_tree(val); - elt->value = fold_convert(TREE_TYPE(field), - build_fold_addr_expr(str)); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__length") == 0); - elt->index = field; - elt->value = build_int_cst_type(TREE_TYPE(field), val.length()); - - tree constructor = build_constructor(string_type, init); - TREE_READONLY(constructor) = 1; - TREE_CONSTANT(constructor) = 1; - - return constructor; -} - -// Return a tree for a pointer to a Go string constant. This is only -// used for type descriptors, so we return a pointer to a constant -// decl. - -tree -Gogo::ptr_go_string_constant_tree(const std::string& val) -{ - tree pval = this->go_string_constant_tree(val); - - tree decl = build_decl(UNKNOWN_LOCATION, VAR_DECL, - create_tmp_var_name("SP"), TREE_TYPE(pval)); - DECL_EXTERNAL(decl) = 0; - TREE_PUBLIC(decl) = 0; - TREE_USED(decl) = 1; - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - TREE_STATIC(decl) = 1; - DECL_ARTIFICIAL(decl) = 1; - DECL_INITIAL(decl) = pval; - rest_of_decl_compilation(decl, 1, 0); - - return build_fold_addr_expr(decl); -} - -// Build the type of the struct that holds a slice for the given -// element type. - -tree -Gogo::slice_type_tree(tree element_type_tree) -{ - // We use int for the count and capacity fields in a slice header. - // This matches 6g. The language definition guarantees that we - // can't allocate space of a size which does not fit in int - // anyhow. FIXME: integer_type_node is the the C type "int" but is - // not necessarily the Go type "int". They will differ when the C - // type "int" has fewer than 32 bits. - return Gogo::builtin_struct(NULL, "__go_slice", NULL_TREE, 3, - "__values", - build_pointer_type(element_type_tree), - "__count", - integer_type_node, - "__capacity", - integer_type_node); -} - -// Given the tree for a slice type, return the tree for the type of -// the elements of the slice. - -tree -Gogo::slice_element_type_tree(tree slice_type_tree) -{ - go_assert(TREE_CODE(slice_type_tree) == RECORD_TYPE - && POINTER_TYPE_P(TREE_TYPE(TYPE_FIELDS(slice_type_tree)))); - return TREE_TYPE(TREE_TYPE(TYPE_FIELDS(slice_type_tree))); -} - -// Build a constructor for a slice. SLICE_TYPE_TREE is the type of -// the slice. VALUES is the value pointer and COUNT is the number of -// entries. If CAPACITY is not NULL, it is the capacity; otherwise -// the capacity and the count are the same. - -tree -Gogo::slice_constructor(tree slice_type_tree, tree values, tree count, - tree capacity) -{ - go_assert(TREE_CODE(slice_type_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - tree field = TYPE_FIELDS(slice_type_tree); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0); - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(field)) - == TYPE_MAIN_VARIANT(TREE_TYPE(values))); - elt->value = values; - - count = fold_convert(sizetype, count); - if (capacity == NULL_TREE) - { - count = save_expr(count); - capacity = count; - } - - field = DECL_CHAIN(field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0); - elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), count); - - field = DECL_CHAIN(field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0); - elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), capacity); - - return build_constructor(slice_type_tree, init); -} - -// Build a constructor for an empty slice. - -tree -Gogo::empty_slice_constructor(tree slice_type_tree) -{ - tree element_field = TYPE_FIELDS(slice_type_tree); - tree ret = Gogo::slice_constructor(slice_type_tree, - fold_convert(TREE_TYPE(element_field), - null_pointer_node), - size_zero_node, - size_zero_node); - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Build a map descriptor for a map of type MAPTYPE. - -tree -Gogo::map_descriptor(Map_type* maptype) -{ - if (this->map_descriptors_ == NULL) - this->map_descriptors_ = new Map_descriptors(10); - - std::pair val(maptype, NULL); - std::pair ins = - this->map_descriptors_->insert(val); - Map_descriptors::iterator p = ins.first; - if (!ins.second) - { - if (p->second == error_mark_node) - return error_mark_node; - go_assert(p->second != NULL_TREE && DECL_P(p->second)); - return build_fold_addr_expr(p->second); - } - - Type* keytype = maptype->key_type(); - Type* valtype = maptype->val_type(); - - std::string mangled_name = ("__go_map_" + maptype->mangled_name(this)); - - tree id = get_identifier_from_string(mangled_name); - - // Get the type of the map descriptor. This is __go_map_descriptor - // in libgo/map.h. - - tree struct_type = this->map_descriptor_type(); - - // The map entry type is a struct with three fields. This struct is - // specific to MAPTYPE. Build it. - - tree map_entry_type = make_node(RECORD_TYPE); - - map_entry_type = Gogo::builtin_struct(NULL, "__map", map_entry_type, 3, - "__next", - build_pointer_type(map_entry_type), - "__key", - keytype->get_tree(this), - "__val", - valtype->get_tree(this)); - if (map_entry_type == error_mark_node) - { - p->second = error_mark_node; - return error_mark_node; - } - - tree map_entry_key_field = DECL_CHAIN(TYPE_FIELDS(map_entry_type)); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_entry_key_field)), - "__key") == 0); - - tree map_entry_val_field = DECL_CHAIN(map_entry_key_field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_entry_val_field)), - "__val") == 0); - - // Initialize the entries. - - tree map_descriptor_field = TYPE_FIELDS(struct_type); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_descriptor_field)), - "__map_descriptor") == 0); - tree entry_size_field = DECL_CHAIN(map_descriptor_field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(entry_size_field)), - "__entry_size") == 0); - tree key_offset_field = DECL_CHAIN(entry_size_field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(key_offset_field)), - "__key_offset") == 0); - tree val_offset_field = DECL_CHAIN(key_offset_field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(val_offset_field)), - "__val_offset") == 0); - - VEC(constructor_elt, gc)* descriptor = VEC_alloc(constructor_elt, gc, 6); - - constructor_elt* elt = VEC_quick_push(constructor_elt, descriptor, NULL); - elt->index = map_descriptor_field; - elt->value = maptype->type_descriptor_pointer(this); - - elt = VEC_quick_push(constructor_elt, descriptor, NULL); - elt->index = entry_size_field; - elt->value = TYPE_SIZE_UNIT(map_entry_type); - - elt = VEC_quick_push(constructor_elt, descriptor, NULL); - elt->index = key_offset_field; - elt->value = byte_position(map_entry_key_field); - - elt = VEC_quick_push(constructor_elt, descriptor, NULL); - elt->index = val_offset_field; - elt->value = byte_position(map_entry_val_field); - - tree constructor = build_constructor(struct_type, descriptor); - - tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, struct_type); - TREE_STATIC(decl) = 1; - TREE_USED(decl) = 1; - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - DECL_INITIAL(decl) = constructor; - make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl)); - resolve_unique_section(decl, 1, 0); - - rest_of_decl_compilation(decl, 1, 0); - - go_preserve_from_gc(decl); - p->second = decl; - - return build_fold_addr_expr(decl); -} - -// Return a tree for the type of a map descriptor. This is struct -// __go_map_descriptor in libgo/runtime/map.h. This is the same for -// all map types. - -tree -Gogo::map_descriptor_type() -{ - static tree struct_type; - tree dtype = Type::make_type_descriptor_type()->get_tree(this); - dtype = build_qualified_type(dtype, TYPE_QUAL_CONST); - return Gogo::builtin_struct(&struct_type, "__go_map_descriptor", NULL_TREE, - 4, - "__map_descriptor", - build_pointer_type(dtype), - "__entry_size", - sizetype, - "__key_offset", - sizetype, - "__val_offset", - sizetype); -} - -// Return the name to use for a type descriptor decl for TYPE. This -// is used when TYPE does not have a name. - -std::string -Gogo::unnamed_type_descriptor_decl_name(const Type* type) -{ - return "__go_td_" + type->mangled_name(this); -} - -// Return the name to use for a type descriptor decl for a type named -// NAME, defined in the function IN_FUNCTION. IN_FUNCTION will -// normally be NULL. - -std::string -Gogo::type_descriptor_decl_name(const Named_object* no, - const Named_object* in_function) -{ - std::string ret = "__go_tdn_"; - if (no->type_value()->is_builtin()) - go_assert(in_function == NULL); - else - { - const std::string& unique_prefix(no->package() == NULL - ? this->unique_prefix() - : no->package()->unique_prefix()); - const std::string& package_name(no->package() == NULL - ? this->package_name() - : no->package()->name()); - ret.append(unique_prefix); - ret.append(1, '.'); - ret.append(package_name); - ret.append(1, '.'); - if (in_function != NULL) - { - ret.append(Gogo::unpack_hidden_name(in_function->name())); - ret.append(1, '.'); - } - } - ret.append(no->name()); - return ret; -} - -// Where a type descriptor decl should be defined. - -Gogo::Type_descriptor_location -Gogo::type_descriptor_location(const Type* type) -{ - const Named_type* name = type->named_type(); - if (name != NULL) - { - if (name->named_object()->package() != NULL) - { - // This is a named type defined in a different package. The - // descriptor should be defined in that package. - return TYPE_DESCRIPTOR_UNDEFINED; - } - else if (name->is_builtin()) - { - // We create the descriptor for a builtin type whenever we - // need it. - return TYPE_DESCRIPTOR_COMMON; - } - else - { - // This is a named type defined in this package. The - // descriptor should be defined here. - return TYPE_DESCRIPTOR_DEFINED; - } - } - else - { - if (type->points_to() != NULL - && type->points_to()->named_type() != NULL - && type->points_to()->named_type()->named_object()->package() != NULL) - { - // This is an unnamed pointer to a named type defined in a - // different package. The descriptor should be defined in - // that package. - return TYPE_DESCRIPTOR_UNDEFINED; - } - else - { - // This is an unnamed type. The descriptor could be defined - // in any package where it is needed, and the linker will - // pick one descriptor to keep. - return TYPE_DESCRIPTOR_COMMON; - } - } -} - -// Build a type descriptor decl for TYPE. INITIALIZER is a struct -// composite literal which initializers the type descriptor. - -void -Gogo::build_type_descriptor_decl(const Type* type, Expression* initializer, - tree* pdecl) -{ - const Named_type* name = type->named_type(); - - // We can have multiple instances of unnamed types, but we only want - // to emit the type descriptor once. We use a hash table to handle - // this. This is not necessary for named types, as they are unique, - // and we store the type descriptor decl in the type itself. - tree* phash = NULL; - if (name == NULL) - { - if (this->type_descriptor_decls_ == NULL) - this->type_descriptor_decls_ = new Type_descriptor_decls(10); - - std::pair ins = - this->type_descriptor_decls_->insert(std::make_pair(type, NULL_TREE)); - if (!ins.second) - { - // We've already built a type descriptor for this type. - *pdecl = ins.first->second; - return; - } - phash = &ins.first->second; - } - - std::string decl_name; - if (name == NULL) - decl_name = this->unnamed_type_descriptor_decl_name(type); - else - decl_name = this->type_descriptor_decl_name(name->named_object(), - name->in_function()); - tree id = get_identifier_from_string(decl_name); - tree descriptor_type_tree = initializer->type()->get_tree(this); - if (descriptor_type_tree == error_mark_node) - { - *pdecl = error_mark_node; - return; - } - tree decl = build_decl(name == NULL ? BUILTINS_LOCATION : name->location(), - VAR_DECL, id, - build_qualified_type(descriptor_type_tree, - TYPE_QUAL_CONST)); - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - DECL_ARTIFICIAL(decl) = 1; - - go_preserve_from_gc(decl); - if (phash != NULL) - *phash = decl; - - // We store the new DECL now because we may need to refer to it when - // expanding INITIALIZER. - *pdecl = decl; - - // If appropriate, just refer to the exported type identifier. - Gogo::Type_descriptor_location type_descriptor_location = - this->type_descriptor_location(type); - if (type_descriptor_location == TYPE_DESCRIPTOR_UNDEFINED) - { - TREE_PUBLIC(decl) = 1; - DECL_EXTERNAL(decl) = 1; - return; - } - - TREE_STATIC(decl) = 1; - TREE_USED(decl) = 1; - - Translate_context context(this, NULL, NULL, NULL); - context.set_is_const(); - tree constructor = initializer->get_tree(&context); - - if (constructor == error_mark_node) - go_assert(saw_errors()); - - DECL_INITIAL(decl) = constructor; - - if (type_descriptor_location == TYPE_DESCRIPTOR_DEFINED) - TREE_PUBLIC(decl) = 1; - else - { - go_assert(type_descriptor_location == TYPE_DESCRIPTOR_COMMON); - make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl)); - resolve_unique_section(decl, 1, 0); - } - - rest_of_decl_compilation(decl, 1, 0); -} - -// Build an interface method table for a type: a list of function -// pointers, one for each interface method. This is used for -// interfaces. - -tree -Gogo::interface_method_table_for_type(const Interface_type* interface, - Named_type* type, - bool is_pointer) -{ - const Typed_identifier_list* interface_methods = interface->methods(); - go_assert(!interface_methods->empty()); - - std::string mangled_name = ((is_pointer ? "__go_pimt__" : "__go_imt_") - + interface->mangled_name(this) - + "__" - + type->mangled_name(this)); - - tree id = get_identifier_from_string(mangled_name); - - // See whether this interface has any hidden methods. - bool has_hidden_methods = false; - for (Typed_identifier_list::const_iterator p = interface_methods->begin(); - p != interface_methods->end(); - ++p) - { - if (Gogo::is_hidden_name(p->name())) - { - has_hidden_methods = true; - break; - } - } - - // We already know that the named type is convertible to the - // interface. If the interface has hidden methods, and the named - // type is defined in a different package, then the interface - // conversion table will be defined by that other package. - if (has_hidden_methods && type->named_object()->package() != NULL) - { - tree array_type = build_array_type(const_ptr_type_node, NULL); - tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type); - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - TREE_PUBLIC(decl) = 1; - DECL_EXTERNAL(decl) = 1; - go_preserve_from_gc(decl); - return decl; - } - - size_t count = interface_methods->size(); - VEC(constructor_elt, gc)* pointers = VEC_alloc(constructor_elt, gc, - count + 1); - - // The first element is the type descriptor. - constructor_elt* elt = VEC_quick_push(constructor_elt, pointers, NULL); - elt->index = size_zero_node; - Type* td_type; - if (!is_pointer) - td_type = type; - else - td_type = Type::make_pointer_type(type); - elt->value = fold_convert(const_ptr_type_node, - td_type->type_descriptor_pointer(this)); - - size_t i = 1; - for (Typed_identifier_list::const_iterator p = interface_methods->begin(); - p != interface_methods->end(); - ++p, ++i) - { - bool is_ambiguous; - Method* m = type->method_function(p->name(), &is_ambiguous); - go_assert(m != NULL); - - Named_object* no = m->named_object(); - - tree fnid = no->get_id(this); - - tree fndecl; - if (no->is_function()) - fndecl = no->func_value()->get_or_make_decl(this, no, fnid); - else if (no->is_function_declaration()) - fndecl = no->func_declaration_value()->get_or_make_decl(this, no, - fnid); - else - go_unreachable(); - fndecl = build_fold_addr_expr(fndecl); - - elt = VEC_quick_push(constructor_elt, pointers, NULL); - elt->index = size_int(i); - elt->value = fold_convert(const_ptr_type_node, fndecl); - } - go_assert(i == count + 1); - - tree array_type = build_array_type(const_ptr_type_node, - build_index_type(size_int(count))); - tree constructor = build_constructor(array_type, pointers); - - tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type); - TREE_STATIC(decl) = 1; - TREE_USED(decl) = 1; - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - DECL_INITIAL(decl) = constructor; - - // If the interface type has hidden methods, then this is the only - // definition of the table. Otherwise it is a comdat table which - // may be defined in multiple packages. - if (has_hidden_methods) - TREE_PUBLIC(decl) = 1; - else - { - make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl)); - resolve_unique_section(decl, 1, 0); - } - - rest_of_decl_compilation(decl, 1, 0); - - go_preserve_from_gc(decl); - - return decl; -} - -// Mark a function as a builtin library function. - -void -Gogo::mark_fndecl_as_builtin_library(tree fndecl) -{ - DECL_EXTERNAL(fndecl) = 1; - TREE_PUBLIC(fndecl) = 1; - DECL_ARTIFICIAL(fndecl) = 1; - TREE_NOTHROW(fndecl) = 1; - DECL_VISIBILITY(fndecl) = VISIBILITY_DEFAULT; - DECL_VISIBILITY_SPECIFIED(fndecl) = 1; -} - -// Build a call to a builtin function. - -tree -Gogo::call_builtin(tree* pdecl, source_location location, const char* name, - int nargs, tree rettype, ...) -{ - if (rettype == error_mark_node) - return error_mark_node; - - tree* types = new tree[nargs]; - tree* args = new tree[nargs]; - - va_list ap; - va_start(ap, rettype); - for (int i = 0; i < nargs; ++i) - { - types[i] = va_arg(ap, tree); - args[i] = va_arg(ap, tree); - if (types[i] == error_mark_node || args[i] == error_mark_node) - { - delete[] types; - delete[] args; - return error_mark_node; - } - } - va_end(ap); - - if (*pdecl == NULL_TREE) - { - tree fnid = get_identifier(name); - - tree argtypes = NULL_TREE; - tree* pp = &argtypes; - for (int i = 0; i < nargs; ++i) - { - *pp = tree_cons(NULL_TREE, types[i], NULL_TREE); - pp = &TREE_CHAIN(*pp); - } - *pp = void_list_node; - - tree fntype = build_function_type(rettype, argtypes); - - *pdecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL, fnid, fntype); - Gogo::mark_fndecl_as_builtin_library(*pdecl); - go_preserve_from_gc(*pdecl); - } - - tree fnptr = build_fold_addr_expr(*pdecl); - if (CAN_HAVE_LOCATION_P(fnptr)) - SET_EXPR_LOCATION(fnptr, location); - - tree ret = build_call_array(rettype, fnptr, nargs, args); - SET_EXPR_LOCATION(ret, location); - - delete[] types; - delete[] args; - - return ret; -} - -// Build a call to the runtime error function. - -tree -Gogo::runtime_error(int code, source_location location) -{ - static tree runtime_error_fndecl; - tree ret = Gogo::call_builtin(&runtime_error_fndecl, - location, - "__go_runtime_error", - 1, - void_type_node, - integer_type_node, - build_int_cst(integer_type_node, code)); - if (ret == error_mark_node) - return error_mark_node; - // The runtime error function panics and does not return. - TREE_NOTHROW(runtime_error_fndecl) = 0; - TREE_THIS_VOLATILE(runtime_error_fndecl) = 1; - return ret; -} - -// Return a tree for receiving a value of type TYPE_TREE on CHANNEL. -// This does a blocking receive and returns the value read from the -// channel. If FOR_SELECT is true, this is being done because it was -// chosen in a select statement. - -tree -Gogo::receive_from_channel(tree type_tree, tree channel, bool for_select, - source_location location) -{ - if (type_tree == error_mark_node || channel == error_mark_node) - return error_mark_node; - - if (int_size_in_bytes(type_tree) <= 8 - && !AGGREGATE_TYPE_P(type_tree) - && !FLOAT_TYPE_P(type_tree)) - { - static tree receive_small_fndecl; - tree call = Gogo::call_builtin(&receive_small_fndecl, - location, - "__go_receive_small", - 2, - uint64_type_node, - ptr_type_node, - channel, - boolean_type_node, - (for_select - ? boolean_true_node - : boolean_false_node)); - if (call == error_mark_node) - return error_mark_node; - // This can panic if there are too many operations on a closed - // channel. - TREE_NOTHROW(receive_small_fndecl) = 0; - int bitsize = GET_MODE_BITSIZE(TYPE_MODE(type_tree)); - tree int_type_tree = go_type_for_size(bitsize, 1); - return fold_convert_loc(location, type_tree, - fold_convert_loc(location, int_type_tree, - call)); - } - else - { - tree tmp = create_tmp_var(type_tree, get_name(type_tree)); - DECL_IGNORED_P(tmp) = 0; - TREE_ADDRESSABLE(tmp) = 1; - tree make_tmp = build1(DECL_EXPR, void_type_node, tmp); - SET_EXPR_LOCATION(make_tmp, location); - tree tmpaddr = build_fold_addr_expr(tmp); - tmpaddr = fold_convert(ptr_type_node, tmpaddr); - static tree receive_big_fndecl; - tree call = Gogo::call_builtin(&receive_big_fndecl, - location, - "__go_receive_big", - 3, - boolean_type_node, - ptr_type_node, - channel, - ptr_type_node, - tmpaddr, - boolean_type_node, - (for_select - ? boolean_true_node - : boolean_false_node)); - if (call == error_mark_node) - return error_mark_node; - // This can panic if there are too many operations on a closed - // channel. - TREE_NOTHROW(receive_big_fndecl) = 0; - return build2(COMPOUND_EXPR, type_tree, make_tmp, - build2(COMPOUND_EXPR, type_tree, call, tmp)); - } -} - -// Return the type of a function trampoline. This is like -// get_trampoline_type in tree-nested.c. - -tree -Gogo::trampoline_type_tree() -{ - static tree type_tree; - if (type_tree == NULL_TREE) - { - unsigned int size; - unsigned int align; - go_trampoline_info(&size, &align); - tree t = build_index_type(build_int_cst(integer_type_node, size - 1)); - t = build_array_type(char_type_node, t); - - type_tree = Gogo::builtin_struct(NULL, "__go_trampoline", NULL_TREE, 1, - "__data", t); - t = TYPE_FIELDS(type_tree); - DECL_ALIGN(t) = align; - DECL_USER_ALIGN(t) = 1; - - go_preserve_from_gc(type_tree); - } - return type_tree; -} - -// Make a trampoline which calls FNADDR passing CLOSURE. - -tree -Gogo::make_trampoline(tree fnaddr, tree closure, source_location location) -{ - tree trampoline_type = Gogo::trampoline_type_tree(); - tree trampoline_size = TYPE_SIZE_UNIT(trampoline_type); - - closure = save_expr(closure); - - // We allocate the trampoline using a special function which will - // mark it as executable. - static tree trampoline_fndecl; - tree x = Gogo::call_builtin(&trampoline_fndecl, - location, - "__go_allocate_trampoline", - 2, - ptr_type_node, - size_type_node, - trampoline_size, - ptr_type_node, - fold_convert_loc(location, ptr_type_node, - closure)); - if (x == error_mark_node) - return error_mark_node; - - x = save_expr(x); - - // Initialize the trampoline. - tree ini = build_call_expr(implicit_built_in_decls[BUILT_IN_INIT_TRAMPOLINE], - 3, x, fnaddr, closure); - - // On some targets the trampoline address needs to be adjusted. For - // example, when compiling in Thumb mode on the ARM, the address - // needs to have the low bit set. - x = build_call_expr(implicit_built_in_decls[BUILT_IN_ADJUST_TRAMPOLINE], - 1, x); - x = fold_convert(TREE_TYPE(fnaddr), x); - - return build2(COMPOUND_EXPR, TREE_TYPE(x), ini, x); -} diff --git a/gcc/go/gofrontend/gogo-tree.cc.working b/gcc/go/gofrontend/gogo-tree.cc.working deleted file mode 100644 index 238a0d72487..00000000000 --- a/gcc/go/gofrontend/gogo-tree.cc.working +++ /dev/null @@ -1,3145 +0,0 @@ -// gogo-tree.cc -- convert Go frontend Gogo IR to gcc trees. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include - -#ifndef ENABLE_BUILD_WITH_CXX -extern "C" -{ -#endif - -#include "toplev.h" -#include "tree.h" -#include "gimple.h" -#include "tree-iterator.h" -#include "cgraph.h" -#include "langhooks.h" -#include "convert.h" -#include "output.h" -#include "diagnostic.h" - -#ifndef ENABLE_BUILD_WITH_CXX -} -#endif - -#include "go-c.h" -#include "types.h" -#include "expressions.h" -#include "statements.h" -#include "gogo.h" - -// Whether we have seen any errors. - -bool -saw_errors() -{ - return errorcount != 0 || sorrycount != 0; -} - -// A helper function. - -static inline tree -get_identifier_from_string(const std::string& str) -{ - return get_identifier_with_length(str.data(), str.length()); -} - -// Builtin functions. - -static std::map builtin_functions; - -// Define a builtin function. BCODE is the builtin function code -// defined by builtins.def. NAME is the name of the builtin function. -// LIBNAME is the name of the corresponding library function, and is -// NULL if there isn't one. FNTYPE is the type of the function. -// CONST_P is true if the function has the const attribute. - -static void -define_builtin(built_in_function bcode, const char* name, const char* libname, - tree fntype, bool const_p) -{ - tree decl = add_builtin_function(name, fntype, bcode, BUILT_IN_NORMAL, - libname, NULL_TREE); - if (const_p) - TREE_READONLY(decl) = 1; - built_in_decls[bcode] = decl; - implicit_built_in_decls[bcode] = decl; - builtin_functions[name] = decl; - if (libname != NULL) - { - decl = add_builtin_function(libname, fntype, bcode, BUILT_IN_NORMAL, - NULL, NULL_TREE); - if (const_p) - TREE_READONLY(decl) = 1; - builtin_functions[libname] = decl; - } -} - -// Create trees for implicit builtin functions. - -void -Gogo::define_builtin_function_trees() -{ - /* We need to define the fetch_and_add functions, since we use them - for ++ and --. */ - tree t = go_type_for_size(BITS_PER_UNIT, 1); - tree p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE)); - define_builtin(BUILT_IN_ADD_AND_FETCH_1, "__sync_fetch_and_add_1", NULL, - build_function_type_list(t, p, t, NULL_TREE), false); - - t = go_type_for_size(BITS_PER_UNIT * 2, 1); - p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE)); - define_builtin (BUILT_IN_ADD_AND_FETCH_2, "__sync_fetch_and_add_2", NULL, - build_function_type_list(t, p, t, NULL_TREE), false); - - t = go_type_for_size(BITS_PER_UNIT * 4, 1); - p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE)); - define_builtin(BUILT_IN_ADD_AND_FETCH_4, "__sync_fetch_and_add_4", NULL, - build_function_type_list(t, p, t, NULL_TREE), false); - - t = go_type_for_size(BITS_PER_UNIT * 8, 1); - p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE)); - define_builtin(BUILT_IN_ADD_AND_FETCH_8, "__sync_fetch_and_add_8", NULL, - build_function_type_list(t, p, t, NULL_TREE), false); - - // We use __builtin_expect for magic import functions. - define_builtin(BUILT_IN_EXPECT, "__builtin_expect", NULL, - build_function_type_list(long_integer_type_node, - long_integer_type_node, - long_integer_type_node, - NULL_TREE), - true); - - // We use __builtin_memmove for the predeclared copy function. - define_builtin(BUILT_IN_MEMMOVE, "__builtin_memmove", "memmove", - build_function_type_list(ptr_type_node, - ptr_type_node, - const_ptr_type_node, - size_type_node, - NULL_TREE), - false); - - // We provide sqrt for the math library. - define_builtin(BUILT_IN_SQRT, "__builtin_sqrt", "sqrt", - build_function_type_list(double_type_node, - double_type_node, - NULL_TREE), - true); - define_builtin(BUILT_IN_SQRTL, "__builtin_sqrtl", "sqrtl", - build_function_type_list(long_double_type_node, - long_double_type_node, - NULL_TREE), - true); - - // We use __builtin_return_address in the thunk we build for - // functions which call recover. - define_builtin(BUILT_IN_RETURN_ADDRESS, "__builtin_return_address", NULL, - build_function_type_list(ptr_type_node, - unsigned_type_node, - NULL_TREE), - false); - - // The compiler uses __builtin_trap for some exception handling - // cases. - define_builtin(BUILT_IN_TRAP, "__builtin_trap", NULL, - build_function_type(void_type_node, void_list_node), - false); -} - -// Get the name to use for the import control function. If there is a -// global function or variable, then we know that that name must be -// unique in the link, and we use it as the basis for our name. - -const std::string& -Gogo::get_init_fn_name() -{ - if (this->init_fn_name_.empty()) - { - gcc_assert(this->package_ != NULL); - if (this->is_main_package()) - { - // Use a name which the runtime knows. - this->init_fn_name_ = "__go_init_main"; - } - else - { - std::string s = this->unique_prefix(); - s.append(1, '.'); - s.append(this->package_name()); - s.append("..import"); - this->init_fn_name_ = s; - } - } - - return this->init_fn_name_; -} - -// Add statements to INIT_STMT_LIST which run the initialization -// functions for imported packages. This is only used for the "main" -// package. - -void -Gogo::init_imports(tree* init_stmt_list) -{ - gcc_assert(this->is_main_package()); - - if (this->imported_init_fns_.empty()) - return; - - tree fntype = build_function_type(void_type_node, void_list_node); - - // We must call them in increasing priority order. - std::vector v; - for (std::set::const_iterator p = - this->imported_init_fns_.begin(); - p != this->imported_init_fns_.end(); - ++p) - v.push_back(*p); - std::sort(v.begin(), v.end()); - - for (std::vector::const_iterator p = v.begin(); - p != v.end(); - ++p) - { - std::string user_name = p->package_name() + ".init"; - tree decl = build_decl(UNKNOWN_LOCATION, FUNCTION_DECL, - get_identifier_from_string(user_name), - fntype); - const std::string& init_name(p->init_name()); - SET_DECL_ASSEMBLER_NAME(decl, get_identifier_from_string(init_name)); - TREE_PUBLIC(decl) = 1; - DECL_EXTERNAL(decl) = 1; - append_to_statement_list(build_call_expr(decl, 0), init_stmt_list); - } -} - -// Register global variables with the garbage collector. We need to -// register all variables which can hold a pointer value. They become -// roots during the mark phase. We build a struct that is easy to -// hook into a list of roots. - -// struct __go_gc_root_list -// { -// struct __go_gc_root_list* __next; -// struct __go_gc_root -// { -// void* __decl; -// size_t __size; -// } __roots[]; -// }; - -// The last entry in the roots array has a NULL decl field. - -void -Gogo::register_gc_vars(const std::vector& var_gc, - tree* init_stmt_list) -{ - if (var_gc.empty()) - return; - - size_t count = var_gc.size(); - - tree root_type = Gogo::builtin_struct(NULL, "__go_gc_root", NULL_TREE, 2, - "__next", - ptr_type_node, - "__size", - sizetype); - - tree index_type = build_index_type(size_int(count)); - tree array_type = build_array_type(root_type, index_type); - - tree root_list_type = make_node(RECORD_TYPE); - root_list_type = Gogo::builtin_struct(NULL, "__go_gc_root_list", - root_list_type, 2, - "__next", - build_pointer_type(root_list_type), - "__roots", - array_type); - - // Build an initialier for the __roots array. - - VEC(constructor_elt,gc)* roots_init = VEC_alloc(constructor_elt, gc, - count + 1); - - size_t i = 0; - for (std::vector::const_iterator p = var_gc.begin(); - p != var_gc.end(); - ++p, ++i) - { - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(root_type); - elt->index = field; - tree decl = (*p)->get_tree(this, NULL); - gcc_assert(TREE_CODE(decl) == VAR_DECL); - elt->value = build_fold_addr_expr(decl); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - elt->index = field; - elt->value = DECL_SIZE_UNIT(decl); - - elt = VEC_quick_push(constructor_elt, roots_init, NULL); - elt->index = size_int(i); - elt->value = build_constructor(root_type, init); - } - - // The list ends with a NULL entry. - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(root_type); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), null_pointer_node); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - elt->index = field; - elt->value = size_zero_node; - - elt = VEC_quick_push(constructor_elt, roots_init, NULL); - elt->index = size_int(i); - elt->value = build_constructor(root_type, init); - - // Build a constructor for the struct. - - VEC(constructor_elt,gc*) root_list_init = VEC_alloc(constructor_elt, gc, 2); - - elt = VEC_quick_push(constructor_elt, root_list_init, NULL); - field = TYPE_FIELDS(root_list_type); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), null_pointer_node); - - elt = VEC_quick_push(constructor_elt, root_list_init, NULL); - field = DECL_CHAIN(field); - elt->index = field; - elt->value = build_constructor(array_type, roots_init); - - // Build a decl to register. - - tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, - create_tmp_var_name("gc"), root_list_type); - DECL_EXTERNAL(decl) = 0; - TREE_PUBLIC(decl) = 0; - TREE_STATIC(decl) = 1; - DECL_ARTIFICIAL(decl) = 1; - DECL_INITIAL(decl) = build_constructor(root_list_type, root_list_init); - rest_of_decl_compilation(decl, 1, 0); - - static tree register_gc_fndecl; - tree call = Gogo::call_builtin(®ister_gc_fndecl, BUILTINS_LOCATION, - "__go_register_gc_roots", - 1, - void_type_node, - build_pointer_type(root_list_type), - build_fold_addr_expr(decl)); - if (call != error_mark_node) - append_to_statement_list(call, init_stmt_list); -} - -// Build the decl for the initialization function. - -tree -Gogo::initialization_function_decl() -{ - // The tedious details of building your own function. There doesn't - // seem to be a helper function for this. - std::string name = this->package_name() + ".init"; - tree fndecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL, - get_identifier_from_string(name), - build_function_type(void_type_node, - void_list_node)); - const std::string& asm_name(this->get_init_fn_name()); - SET_DECL_ASSEMBLER_NAME(fndecl, get_identifier_from_string(asm_name)); - - tree resdecl = build_decl(BUILTINS_LOCATION, RESULT_DECL, NULL_TREE, - void_type_node); - DECL_ARTIFICIAL(resdecl) = 1; - DECL_CONTEXT(resdecl) = fndecl; - DECL_RESULT(fndecl) = resdecl; - - TREE_STATIC(fndecl) = 1; - TREE_USED(fndecl) = 1; - DECL_ARTIFICIAL(fndecl) = 1; - TREE_PUBLIC(fndecl) = 1; - - DECL_INITIAL(fndecl) = make_node(BLOCK); - TREE_USED(DECL_INITIAL(fndecl)) = 1; - - return fndecl; -} - -// Create the magic initialization function. INIT_STMT_LIST is the -// code that it needs to run. - -void -Gogo::write_initialization_function(tree fndecl, tree init_stmt_list) -{ - // Make sure that we thought we needed an initialization function, - // as otherwise we will not have reported it in the export data. - gcc_assert(this->is_main_package() || this->need_init_fn_); - - if (fndecl == NULL_TREE) - fndecl = this->initialization_function_decl(); - - DECL_SAVED_TREE(fndecl) = init_stmt_list; - - current_function_decl = fndecl; - if (DECL_STRUCT_FUNCTION(fndecl) == NULL) - push_struct_function(fndecl); - else - push_cfun(DECL_STRUCT_FUNCTION(fndecl)); - cfun->function_end_locus = BUILTINS_LOCATION; - - gimplify_function_tree(fndecl); - - cgraph_add_new_function(fndecl, false); - cgraph_mark_needed_node(cgraph_node(fndecl)); - - current_function_decl = NULL_TREE; - pop_cfun(); -} - -// Search for references to VAR in any statements or called functions. - -class Find_var : public Traverse -{ - public: - // A hash table we use to avoid looping. The index is the name of a - // named object. We only look through objects defined in this - // package. - typedef Unordered_set(std::string) Seen_objects; - - Find_var(Named_object* var, Seen_objects* seen_objects) - : Traverse(traverse_expressions), - var_(var), seen_objects_(seen_objects), found_(false) - { } - - // Whether the variable was found. - bool - found() const - { return this->found_; } - - int - expression(Expression**); - - private: - // The variable we are looking for. - Named_object* var_; - // Names of objects we have already seen. - Seen_objects* seen_objects_; - // True if the variable was found. - bool found_; -}; - -// See if EXPR refers to VAR, looking through function calls and -// variable initializations. - -int -Find_var::expression(Expression** pexpr) -{ - Expression* e = *pexpr; - - Var_expression* ve = e->var_expression(); - if (ve != NULL) - { - Named_object* v = ve->named_object(); - if (v == this->var_) - { - this->found_ = true; - return TRAVERSE_EXIT; - } - - if (v->is_variable() && v->package() == NULL) - { - Expression* init = v->var_value()->init(); - if (init != NULL) - { - std::pair ins = - this->seen_objects_->insert(v->name()); - if (ins.second) - { - // This is the first time we have seen this name. - if (Expression::traverse(&init, this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - } - } - - // We traverse the code of any function we see. Note that this - // means that we will traverse the code of a function whose address - // is taken even if it is not called. - Func_expression* fe = e->func_expression(); - if (fe != NULL) - { - const Named_object* f = fe->named_object(); - if (f->is_function() && f->package() == NULL) - { - std::pair ins = - this->seen_objects_->insert(f->name()); - if (ins.second) - { - // This is the first time we have seen this name. - if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - } - - return TRAVERSE_CONTINUE; -} - -// Return true if EXPR refers to VAR. - -static bool -expression_requires(Expression* expr, Block* preinit, Named_object* var) -{ - Find_var::Seen_objects seen_objects; - Find_var find_var(var, &seen_objects); - if (expr != NULL) - Expression::traverse(&expr, &find_var); - if (preinit != NULL) - preinit->traverse(&find_var); - - return find_var.found(); -} - -// Sort variable initializations. If the initialization expression -// for variable A refers directly or indirectly to the initialization -// expression for variable B, then we must initialize B before A. - -class Var_init -{ - public: - Var_init() - : var_(NULL), init_(NULL_TREE), waiting_(0) - { } - - Var_init(Named_object* var, tree init) - : var_(var), init_(init), waiting_(0) - { } - - // Return the variable. - Named_object* - var() const - { return this->var_; } - - // Return the initialization expression. - tree - init() const - { return this->init_; } - - // Return the number of variables waiting for this one to be - // initialized. - size_t - waiting() const - { return this->waiting_; } - - // Increment the number waiting. - void - increment_waiting() - { ++this->waiting_; } - - private: - // The variable being initialized. - Named_object* var_; - // The initialization expression to run. - tree init_; - // The number of variables which are waiting for this one. - size_t waiting_; -}; - -typedef std::list Var_inits; - -// Sort the variable initializations. The rule we follow is that we -// emit them in the order they appear in the array, except that if the -// initialization expression for a variable V1 depends upon another -// variable V2 then we initialize V1 after V2. - -static void -sort_var_inits(Var_inits* var_inits) -{ - Var_inits ready; - while (!var_inits->empty()) - { - Var_inits::iterator p1 = var_inits->begin(); - Named_object* var = p1->var(); - Expression* init = var->var_value()->init(); - Block* preinit = var->var_value()->preinit(); - - // Start walking through the list to see which variables VAR - // needs to wait for. We can skip P1->WAITING variables--that - // is the number we've already checked. - Var_inits::iterator p2 = p1; - ++p2; - for (size_t i = p1->waiting(); i > 0; --i) - ++p2; - - for (; p2 != var_inits->end(); ++p2) - { - if (expression_requires(init, preinit, p2->var())) - { - // Check for cycles. - if (expression_requires(p2->var()->var_value()->init(), - p2->var()->var_value()->preinit(), - var)) - { - error_at(var->location(), - ("initialization expressions for %qs and " - "%qs depend upon each other"), - var->message_name().c_str(), - p2->var()->message_name().c_str()); - inform(p2->var()->location(), "%qs defined here", - p2->var()->message_name().c_str()); - p2 = var_inits->end(); - } - else - { - // We can't emit P1 until P2 is emitted. Move P1. - // Note that the WAITING loop always executes at - // least once, which is what we want. - p2->increment_waiting(); - Var_inits::iterator p3 = p2; - for (size_t i = p2->waiting(); i > 0; --i) - ++p3; - var_inits->splice(p3, *var_inits, p1); - } - break; - } - } - - if (p2 == var_inits->end()) - { - // VAR does not depends upon any other initialization expressions. - - // Check for a loop of VAR on itself. We only do this if - // INIT is not NULL; when INIT is NULL, it means that - // PREINIT sets VAR, which we will interpret as a loop. - if (init != NULL && expression_requires(init, preinit, var)) - error_at(var->location(), - "initialization expression for %qs depends upon itself", - var->message_name().c_str()); - ready.splice(ready.end(), *var_inits, p1); - } - } - - // Now READY is the list in the desired initialization order. - var_inits->swap(ready); -} - -// Write out the global definitions. - -void -Gogo::write_globals() -{ - this->convert_named_types(); - this->build_interface_method_tables(); - - Bindings* bindings = this->current_bindings(); - size_t count = bindings->size_definitions(); - - tree* vec = new tree[count]; - - tree init_fndecl = NULL_TREE; - tree init_stmt_list = NULL_TREE; - - if (this->is_main_package()) - this->init_imports(&init_stmt_list); - - // A list of variable initializations. - Var_inits var_inits; - - // A list of variables which need to be registered with the garbage - // collector. - std::vector var_gc; - var_gc.reserve(count); - - tree var_init_stmt_list = NULL_TREE; - size_t i = 0; - for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); - p != bindings->end_definitions(); - ++p, ++i) - { - Named_object* no = *p; - - gcc_assert(!no->is_type_declaration() && !no->is_function_declaration()); - // There is nothing to do for a package. - if (no->is_package()) - { - --i; - --count; - continue; - } - - // There is nothing to do for an object which was imported from - // a different package into the global scope. - if (no->package() != NULL) - { - --i; - --count; - continue; - } - - // There is nothing useful we can output for constants which - // have ideal or non-integeral type. - if (no->is_const()) - { - Type* type = no->const_value()->type(); - if (type == NULL) - type = no->const_value()->expr()->type(); - if (type->is_abstract() || type->integer_type() == NULL) - { - --i; - --count; - continue; - } - } - - vec[i] = no->get_tree(this, NULL); - - if (vec[i] == error_mark_node) - { - gcc_assert(saw_errors()); - --i; - --count; - continue; - } - - // If a variable is initialized to a non-constant value, do the - // initialization in an initialization function. - if (TREE_CODE(vec[i]) == VAR_DECL) - { - gcc_assert(no->is_variable()); - - // Check for a sink variable, which may be used to run - // an initializer purely for its side effects. - bool is_sink = no->name()[0] == '_' && no->name()[1] == '.'; - - tree var_init_tree = NULL_TREE; - if (!no->var_value()->has_pre_init()) - { - tree init = no->var_value()->get_init_tree(this, NULL); - if (init == error_mark_node) - gcc_assert(saw_errors()); - else if (init == NULL_TREE) - ; - else if (TREE_CONSTANT(init)) - DECL_INITIAL(vec[i]) = init; - else if (is_sink) - var_init_tree = init; - else - var_init_tree = fold_build2_loc(no->location(), MODIFY_EXPR, - void_type_node, vec[i], init); - } - else - { - // We are going to create temporary variables which - // means that we need an fndecl. - if (init_fndecl == NULL_TREE) - init_fndecl = this->initialization_function_decl(); - current_function_decl = init_fndecl; - if (DECL_STRUCT_FUNCTION(init_fndecl) == NULL) - push_struct_function(init_fndecl); - else - push_cfun(DECL_STRUCT_FUNCTION(init_fndecl)); - - tree var_decl = is_sink ? NULL_TREE : vec[i]; - var_init_tree = no->var_value()->get_init_block(this, NULL, - var_decl); - - current_function_decl = NULL_TREE; - pop_cfun(); - } - - if (var_init_tree != NULL_TREE && var_init_tree != error_mark_node) - { - if (no->var_value()->init() == NULL - && !no->var_value()->has_pre_init()) - append_to_statement_list(var_init_tree, &var_init_stmt_list); - else - var_inits.push_back(Var_init(no, var_init_tree)); - } - - if (!is_sink && no->var_value()->type()->has_pointer()) - var_gc.push_back(no); - } - } - - // Register global variables with the garbage collector. - this->register_gc_vars(var_gc, &init_stmt_list); - - // Simple variable initializations, after all variables are - // registered. - append_to_statement_list(var_init_stmt_list, &init_stmt_list); - - // Complex variable initializations, first sorting them into a - // workable order. - if (!var_inits.empty()) - { - sort_var_inits(&var_inits); - for (Var_inits::const_iterator p = var_inits.begin(); - p != var_inits.end(); - ++p) - append_to_statement_list(p->init(), &init_stmt_list); - } - - // After all the variables are initialized, call the "init" - // functions if there are any. - for (std::vector::const_iterator p = - this->init_functions_.begin(); - p != this->init_functions_.end(); - ++p) - { - tree decl = (*p)->get_tree(this, NULL); - tree call = build_call_expr(decl, 0); - append_to_statement_list(call, &init_stmt_list); - } - - // Set up a magic function to do all the initialization actions. - // This will be called if this package is imported. - if (init_stmt_list != NULL_TREE - || this->need_init_fn_ - || this->is_main_package()) - this->write_initialization_function(init_fndecl, init_stmt_list); - - // Pass everything back to the middle-end. - - wrapup_global_declarations(vec, count); - - cgraph_finalize_compilation_unit(); - - check_global_declarations(vec, count); - emit_debug_global_declarations(vec, count); - - delete[] vec; -} - -// Get a tree for the identifier for a named object. - -tree -Named_object::get_id(Gogo* gogo) -{ - std::string decl_name; - if (this->is_function_declaration() - && !this->func_declaration_value()->asm_name().empty()) - decl_name = this->func_declaration_value()->asm_name(); - else if ((this->is_variable() && !this->var_value()->is_global()) - || (this->is_type() - && this->type_value()->location() == BUILTINS_LOCATION)) - { - // We don't need the package name for local variables or builtin - // types. - decl_name = Gogo::unpack_hidden_name(this->name_); - } - else - { - std::string package_name; - if (this->package_ == NULL) - package_name = gogo->package_name(); - else - package_name = this->package_->name(); - - decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_); - - Function_type* fntype; - if (this->is_function()) - fntype = this->func_value()->type(); - else if (this->is_function_declaration()) - fntype = this->func_declaration_value()->type(); - else - fntype = NULL; - if (fntype != NULL && fntype->is_method()) - { - decl_name.push_back('.'); - decl_name.append(fntype->receiver()->type()->mangled_name(gogo)); - } - } - if (this->is_type()) - { - const Named_object* in_function = this->type_value()->in_function(); - if (in_function != NULL) - decl_name += '$' + in_function->name(); - } - return get_identifier_from_string(decl_name); -} - -// Get a tree for a named object. - -tree -Named_object::get_tree(Gogo* gogo, Named_object* function) -{ - if (this->tree_ != NULL_TREE) - { - // If this is a variable whose address is taken, we must rebuild - // the INDIRECT_REF each time to avoid invalid sharing. - tree ret = this->tree_; - if (((this->classification_ == NAMED_OBJECT_VAR - && this->var_value()->is_in_heap()) - || (this->classification_ == NAMED_OBJECT_RESULT_VAR - && this->result_var_value()->is_in_heap())) - && ret != error_mark_node) - { - gcc_assert(TREE_CODE(ret) == INDIRECT_REF); - ret = build_fold_indirect_ref(TREE_OPERAND(ret, 0)); - TREE_THIS_NOTRAP(ret) = 1; - } - return ret; - } - - tree name; - if (this->classification_ == NAMED_OBJECT_TYPE) - name = NULL_TREE; - else - name = this->get_id(gogo); - tree decl; - switch (this->classification_) - { - case NAMED_OBJECT_CONST: - { - Named_constant* named_constant = this->u_.const_value; - Translate_context subcontext(gogo, function, NULL, NULL_TREE); - tree expr_tree = named_constant->expr()->get_tree(&subcontext); - if (expr_tree == error_mark_node) - decl = error_mark_node; - else - { - Type* type = named_constant->type(); - if (type != NULL && !type->is_abstract()) - { - if (!type->is_undefined()) - expr_tree = fold_convert(type->get_tree(gogo), expr_tree); - else - { - // Make sure we report the error. - type->base(); - expr_tree = error_mark_node; - } - } - if (expr_tree == error_mark_node) - decl = error_mark_node; - else if (INTEGRAL_TYPE_P(TREE_TYPE(expr_tree))) - { - decl = build_decl(named_constant->location(), CONST_DECL, - name, TREE_TYPE(expr_tree)); - DECL_INITIAL(decl) = expr_tree; - TREE_CONSTANT(decl) = 1; - TREE_READONLY(decl) = 1; - } - else - { - // A CONST_DECL is only for an enum constant, so we - // shouldn't use for non-integral types. Instead we - // just return the constant itself, rather than a - // decl. - decl = expr_tree; - } - } - } - break; - - case NAMED_OBJECT_TYPE: - { - Named_type* named_type = this->u_.type_value; - tree type_tree = named_type->get_tree(gogo); - if (type_tree == error_mark_node) - decl = error_mark_node; - else - { - decl = TYPE_NAME(type_tree); - gcc_assert(decl != NULL_TREE); - - // We need to produce a type descriptor for every named - // type, and for a pointer to every named type, since - // other files or packages might refer to them. We need - // to do this even for hidden types, because they might - // still be returned by some function. Simply calling the - // type_descriptor method is enough to create the type - // descriptor, even though we don't do anything with it. - if (this->package_ == NULL) - { - named_type->type_descriptor_pointer(gogo); - Type* pn = Type::make_pointer_type(named_type); - pn->type_descriptor_pointer(gogo); - } - } - } - break; - - case NAMED_OBJECT_TYPE_DECLARATION: - error("reference to undefined type %qs", - this->message_name().c_str()); - return error_mark_node; - - case NAMED_OBJECT_VAR: - { - Variable* var = this->u_.var_value; - Type* type = var->type(); - if (type->is_error_type() - || (type->is_undefined() - && (!var->is_global() || this->package() == NULL))) - { - // Force the error for an undefined type, just in case. - type->base(); - decl = error_mark_node; - } - else - { - tree var_type = type->get_tree(gogo); - bool is_parameter = var->is_parameter(); - if (var->is_receiver() && type->points_to() == NULL) - is_parameter = false; - if (var->is_in_heap()) - { - is_parameter = false; - var_type = build_pointer_type(var_type); - } - decl = build_decl(var->location(), - is_parameter ? PARM_DECL : VAR_DECL, - name, var_type); - if (!var->is_global()) - { - tree fnid = function->get_id(gogo); - tree fndecl = function->func_value()->get_or_make_decl(gogo, - function, - fnid); - DECL_CONTEXT(decl) = fndecl; - } - if (is_parameter) - DECL_ARG_TYPE(decl) = TREE_TYPE(decl); - - if (var->is_global()) - { - const Package* package = this->package(); - if (package == NULL) - TREE_STATIC(decl) = 1; - else - DECL_EXTERNAL(decl) = 1; - if (!Gogo::is_hidden_name(this->name_)) - { - TREE_PUBLIC(decl) = 1; - std::string asm_name = (package == NULL - ? gogo->unique_prefix() - : package->unique_prefix()); - asm_name.append(1, '.'); - asm_name.append(IDENTIFIER_POINTER(name), - IDENTIFIER_LENGTH(name)); - tree asm_id = get_identifier_from_string(asm_name); - SET_DECL_ASSEMBLER_NAME(decl, asm_id); - } - } - - // FIXME: We should only set this for variables which are - // actually used somewhere. - TREE_USED(decl) = 1; - } - } - break; - - case NAMED_OBJECT_RESULT_VAR: - { - Result_variable* result = this->u_.result_var_value; - Type* type = result->type(); - if (type->is_error_type() || type->is_undefined()) - { - // Force the error. - type->base(); - decl = error_mark_node; - } - else - { - gcc_assert(result->function() == function->func_value()); - source_location loc = function->location(); - tree result_type = type->get_tree(gogo); - tree init; - if (!result->is_in_heap()) - init = type->get_init_tree(gogo, false); - else - { - tree space = gogo->allocate_memory(type, - TYPE_SIZE_UNIT(result_type), - loc); - result_type = build_pointer_type(result_type); - tree subinit = type->get_init_tree(gogo, true); - if (subinit == NULL_TREE) - init = fold_convert_loc(loc, result_type, space); - else - { - space = save_expr(space); - space = fold_convert_loc(loc, result_type, space); - tree spaceref = build_fold_indirect_ref_loc(loc, space); - TREE_THIS_NOTRAP(spaceref) = 1; - tree set = fold_build2_loc(loc, MODIFY_EXPR, void_type_node, - spaceref, subinit); - init = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(space), - set, space); - } - } - decl = build_decl(loc, VAR_DECL, name, result_type); - tree fnid = function->get_id(gogo); - tree fndecl = function->func_value()->get_or_make_decl(gogo, - function, - fnid); - DECL_CONTEXT(decl) = fndecl; - DECL_INITIAL(decl) = init; - TREE_USED(decl) = 1; - } - } - break; - - case NAMED_OBJECT_SINK: - gcc_unreachable(); - - case NAMED_OBJECT_FUNC: - { - Function* func = this->u_.func_value; - decl = func->get_or_make_decl(gogo, this, name); - if (decl != error_mark_node) - { - if (func->block() != NULL) - { - if (DECL_STRUCT_FUNCTION(decl) == NULL) - push_struct_function(decl); - else - push_cfun(DECL_STRUCT_FUNCTION(decl)); - - cfun->function_end_locus = func->block()->end_location(); - - current_function_decl = decl; - - func->build_tree(gogo, this); - - gimplify_function_tree(decl); - - cgraph_finalize_function(decl, true); - - current_function_decl = NULL_TREE; - pop_cfun(); - } - } - } - break; - - default: - gcc_unreachable(); - } - - if (TREE_TYPE(decl) == error_mark_node) - decl = error_mark_node; - - tree ret = decl; - - // If this is a local variable whose address is taken, then we - // actually store it in the heap. For uses of the variable we need - // to return a reference to that heap location. - if (((this->classification_ == NAMED_OBJECT_VAR - && this->var_value()->is_in_heap()) - || (this->classification_ == NAMED_OBJECT_RESULT_VAR - && this->result_var_value()->is_in_heap())) - && ret != error_mark_node) - { - gcc_assert(POINTER_TYPE_P(TREE_TYPE(ret))); - ret = build_fold_indirect_ref(ret); - TREE_THIS_NOTRAP(ret) = 1; - } - - this->tree_ = ret; - - if (ret != error_mark_node) - go_preserve_from_gc(ret); - - return ret; -} - -// Get the initial value of a variable as a tree. This does not -// consider whether the variable is in the heap--it returns the -// initial value as though it were always stored in the stack. - -tree -Variable::get_init_tree(Gogo* gogo, Named_object* function) -{ - gcc_assert(this->preinit_ == NULL); - if (this->init_ == NULL) - { - gcc_assert(!this->is_parameter_); - return this->type_->get_init_tree(gogo, this->is_global_); - } - else - { - Translate_context context(gogo, function, NULL, NULL_TREE); - tree rhs_tree = this->init_->get_tree(&context); - return Expression::convert_for_assignment(&context, this->type(), - this->init_->type(), - rhs_tree, this->location()); - } -} - -// Get the initial value of a variable when a block is required. -// VAR_DECL is the decl to set; it may be NULL for a sink variable. - -tree -Variable::get_init_block(Gogo* gogo, Named_object* function, tree var_decl) -{ - gcc_assert(this->preinit_ != NULL); - - // We want to add the variable assignment to the end of the preinit - // block. The preinit block may have a TRY_FINALLY_EXPR and a - // TRY_CATCH_EXPR; if it does, we want to add to the end of the - // regular statements. - - Translate_context context(gogo, function, NULL, NULL_TREE); - tree block_tree = this->preinit_->get_tree(&context); - if (block_tree == error_mark_node) - return error_mark_node; - gcc_assert(TREE_CODE(block_tree) == BIND_EXPR); - tree statements = BIND_EXPR_BODY(block_tree); - while (statements != NULL_TREE - && (TREE_CODE(statements) == TRY_FINALLY_EXPR - || TREE_CODE(statements) == TRY_CATCH_EXPR)) - statements = TREE_OPERAND(statements, 0); - - // It's possible to have pre-init statements without an initializer - // if the pre-init statements set the variable. - if (this->init_ != NULL) - { - tree rhs_tree = this->init_->get_tree(&context); - if (rhs_tree == error_mark_node) - return error_mark_node; - if (var_decl == NULL_TREE) - append_to_statement_list(rhs_tree, &statements); - else - { - tree val = Expression::convert_for_assignment(&context, this->type(), - this->init_->type(), - rhs_tree, - this->location()); - if (val == error_mark_node) - return error_mark_node; - tree set = fold_build2_loc(this->location(), MODIFY_EXPR, - void_type_node, var_decl, val); - append_to_statement_list(set, &statements); - } - } - - return block_tree; -} - -// Get a tree for a function decl. - -tree -Function::get_or_make_decl(Gogo* gogo, Named_object* no, tree id) -{ - if (this->fndecl_ == NULL_TREE) - { - tree functype = this->type_->get_tree(gogo); - if (functype == error_mark_node) - this->fndecl_ = error_mark_node; - else - { - // The type of a function comes back as a pointer, but we - // want the real function type for a function declaration. - gcc_assert(POINTER_TYPE_P(functype)); - functype = TREE_TYPE(functype); - tree decl = build_decl(this->location(), FUNCTION_DECL, id, functype); - - this->fndecl_ = decl; - - if (no->package() != NULL) - ; - else if (this->enclosing_ != NULL || Gogo::is_thunk(no)) - ; - else if (Gogo::unpack_hidden_name(no->name()) == "init" - && !this->type_->is_method()) - ; - else if (Gogo::unpack_hidden_name(no->name()) == "main" - && gogo->is_main_package()) - TREE_PUBLIC(decl) = 1; - // Methods have to be public even if they are hidden because - // they can be pulled into type descriptors when using - // anonymous fields. - else if (!Gogo::is_hidden_name(no->name()) - || this->type_->is_method()) - { - TREE_PUBLIC(decl) = 1; - std::string asm_name = gogo->unique_prefix(); - asm_name.append(1, '.'); - asm_name.append(IDENTIFIER_POINTER(id), IDENTIFIER_LENGTH(id)); - SET_DECL_ASSEMBLER_NAME(decl, - get_identifier_from_string(asm_name)); - } - - // Why do we have to do this in the frontend? - tree restype = TREE_TYPE(functype); - tree resdecl = build_decl(this->location(), RESULT_DECL, NULL_TREE, - restype); - DECL_ARTIFICIAL(resdecl) = 1; - DECL_IGNORED_P(resdecl) = 1; - DECL_CONTEXT(resdecl) = decl; - DECL_RESULT(decl) = resdecl; - - if (this->enclosing_ != NULL) - DECL_STATIC_CHAIN(decl) = 1; - - // If a function calls the predeclared recover function, we - // can't inline it, because recover behaves differently in a - // function passed directly to defer. - if (this->calls_recover_ && !this->is_recover_thunk_) - DECL_UNINLINABLE(decl) = 1; - - // If this is a thunk created to call a function which calls - // the predeclared recover function, we need to disable - // stack splitting for the thunk. - if (this->is_recover_thunk_) - { - tree attr = get_identifier("__no_split_stack__"); - DECL_ATTRIBUTES(decl) = tree_cons(attr, NULL_TREE, NULL_TREE); - } - - go_preserve_from_gc(decl); - - if (this->closure_var_ != NULL) - { - push_struct_function(decl); - - tree closure_decl = this->closure_var_->get_tree(gogo, no); - if (closure_decl == error_mark_node) - this->fndecl_ = error_mark_node; - else - { - DECL_ARTIFICIAL(closure_decl) = 1; - DECL_IGNORED_P(closure_decl) = 1; - TREE_USED(closure_decl) = 1; - DECL_ARG_TYPE(closure_decl) = TREE_TYPE(closure_decl); - TREE_READONLY(closure_decl) = 1; - - DECL_STRUCT_FUNCTION(decl)->static_chain_decl = closure_decl; - } - - pop_cfun(); - } - } - } - return this->fndecl_; -} - -// Get a tree for a function declaration. - -tree -Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no, tree id) -{ - if (this->fndecl_ == NULL_TREE) - { - // Let Go code use an asm declaration to pick up a builtin - // function. - if (!this->asm_name_.empty()) - { - std::map::const_iterator p = - builtin_functions.find(this->asm_name_); - if (p != builtin_functions.end()) - { - this->fndecl_ = p->second; - return this->fndecl_; - } - } - - tree functype = this->fntype_->get_tree(gogo); - tree decl; - if (functype == error_mark_node) - decl = error_mark_node; - else - { - // The type of a function comes back as a pointer, but we - // want the real function type for a function declaration. - gcc_assert(POINTER_TYPE_P(functype)); - functype = TREE_TYPE(functype); - decl = build_decl(this->location(), FUNCTION_DECL, id, functype); - TREE_PUBLIC(decl) = 1; - DECL_EXTERNAL(decl) = 1; - - if (this->asm_name_.empty()) - { - std::string asm_name = (no->package() == NULL - ? gogo->unique_prefix() - : no->package()->unique_prefix()); - asm_name.append(1, '.'); - asm_name.append(IDENTIFIER_POINTER(id), IDENTIFIER_LENGTH(id)); - SET_DECL_ASSEMBLER_NAME(decl, - get_identifier_from_string(asm_name)); - } - } - this->fndecl_ = decl; - go_preserve_from_gc(decl); - } - return this->fndecl_; -} - -// We always pass the receiver to a method as a pointer. If the -// receiver is actually declared as a non-pointer type, then we copy -// the value into a local variable, so that it has the right type. In -// this function we create the real PARM_DECL to use, and set -// DEC_INITIAL of the var_decl to be the value passed in. - -tree -Function::make_receiver_parm_decl(Gogo* gogo, Named_object* no, tree var_decl) -{ - if (var_decl == error_mark_node) - return error_mark_node; - // If the function takes the address of a receiver which is passed - // by value, then we will have an INDIRECT_REF here. We need to get - // the real variable. - bool is_in_heap = no->var_value()->is_in_heap(); - tree val_type; - if (TREE_CODE(var_decl) != INDIRECT_REF) - { - gcc_assert(!is_in_heap); - val_type = TREE_TYPE(var_decl); - } - else - { - gcc_assert(is_in_heap); - var_decl = TREE_OPERAND(var_decl, 0); - if (var_decl == error_mark_node) - return error_mark_node; - gcc_assert(POINTER_TYPE_P(TREE_TYPE(var_decl))); - val_type = TREE_TYPE(TREE_TYPE(var_decl)); - } - gcc_assert(TREE_CODE(var_decl) == VAR_DECL); - source_location loc = DECL_SOURCE_LOCATION(var_decl); - std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl)); - name += ".pointer"; - tree id = get_identifier_from_string(name); - tree parm_decl = build_decl(loc, PARM_DECL, id, build_pointer_type(val_type)); - DECL_CONTEXT(parm_decl) = current_function_decl; - DECL_ARG_TYPE(parm_decl) = TREE_TYPE(parm_decl); - - gcc_assert(DECL_INITIAL(var_decl) == NULL_TREE); - // The receiver might be passed as a null pointer. - tree check = fold_build2_loc(loc, NE_EXPR, boolean_type_node, parm_decl, - fold_convert_loc(loc, TREE_TYPE(parm_decl), - null_pointer_node)); - tree ind = build_fold_indirect_ref_loc(loc, parm_decl); - TREE_THIS_NOTRAP(ind) = 1; - tree zero_init = no->var_value()->type()->get_init_tree(gogo, false); - tree init = fold_build3_loc(loc, COND_EXPR, TREE_TYPE(ind), - check, ind, zero_init); - - if (is_in_heap) - { - tree size = TYPE_SIZE_UNIT(val_type); - tree space = gogo->allocate_memory(no->var_value()->type(), size, - no->location()); - space = save_expr(space); - space = fold_convert(build_pointer_type(val_type), space); - tree spaceref = build_fold_indirect_ref_loc(no->location(), space); - TREE_THIS_NOTRAP(spaceref) = 1; - tree check = fold_build2_loc(loc, NE_EXPR, boolean_type_node, - parm_decl, - fold_convert_loc(loc, TREE_TYPE(parm_decl), - null_pointer_node)); - tree parmref = build_fold_indirect_ref_loc(no->location(), parm_decl); - TREE_THIS_NOTRAP(parmref) = 1; - tree set = fold_build2_loc(loc, MODIFY_EXPR, void_type_node, - spaceref, parmref); - init = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(space), - build3(COND_EXPR, void_type_node, - check, set, NULL_TREE), - space); - } - - DECL_INITIAL(var_decl) = init; - - return parm_decl; -} - -// If we take the address of a parameter, then we need to copy it into -// the heap. We will access it as a local variable via an -// indirection. - -tree -Function::copy_parm_to_heap(Gogo* gogo, Named_object* no, tree ref) -{ - if (ref == error_mark_node) - return error_mark_node; - - gcc_assert(TREE_CODE(ref) == INDIRECT_REF); - - tree var_decl = TREE_OPERAND(ref, 0); - if (var_decl == error_mark_node) - return error_mark_node; - gcc_assert(TREE_CODE(var_decl) == VAR_DECL); - source_location loc = DECL_SOURCE_LOCATION(var_decl); - - std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl)); - name += ".param"; - tree id = get_identifier_from_string(name); - - tree type = TREE_TYPE(var_decl); - gcc_assert(POINTER_TYPE_P(type)); - type = TREE_TYPE(type); - - tree parm_decl = build_decl(loc, PARM_DECL, id, type); - DECL_CONTEXT(parm_decl) = current_function_decl; - DECL_ARG_TYPE(parm_decl) = type; - - tree size = TYPE_SIZE_UNIT(type); - tree space = gogo->allocate_memory(no->var_value()->type(), size, loc); - space = save_expr(space); - space = fold_convert(TREE_TYPE(var_decl), space); - tree spaceref = build_fold_indirect_ref_loc(loc, space); - TREE_THIS_NOTRAP(spaceref) = 1; - tree init = build2(COMPOUND_EXPR, TREE_TYPE(space), - build2(MODIFY_EXPR, void_type_node, spaceref, parm_decl), - space); - DECL_INITIAL(var_decl) = init; - - return parm_decl; -} - -// Get a tree for function code. - -void -Function::build_tree(Gogo* gogo, Named_object* named_function) -{ - tree fndecl = this->fndecl_; - gcc_assert(fndecl != NULL_TREE); - - tree params = NULL_TREE; - tree* pp = ¶ms; - - tree declare_vars = NULL_TREE; - for (Bindings::const_definitions_iterator p = - this->block_->bindings()->begin_definitions(); - p != this->block_->bindings()->end_definitions(); - ++p) - { - if ((*p)->is_variable() && (*p)->var_value()->is_parameter()) - { - *pp = (*p)->get_tree(gogo, named_function); - - // We always pass the receiver to a method as a pointer. If - // the receiver is declared as a non-pointer type, then we - // copy the value into a local variable. - if ((*p)->var_value()->is_receiver() - && (*p)->var_value()->type()->points_to() == NULL) - { - tree parm_decl = this->make_receiver_parm_decl(gogo, *p, *pp); - tree var = *pp; - if (TREE_CODE(var) == INDIRECT_REF) - var = TREE_OPERAND(var, 0); - if (var != error_mark_node) - { - gcc_assert(TREE_CODE(var) == VAR_DECL); - DECL_CHAIN(var) = declare_vars; - declare_vars = var; - } - *pp = parm_decl; - } - else if ((*p)->var_value()->is_in_heap()) - { - // If we take the address of a parameter, then we need - // to copy it into the heap. - tree parm_decl = this->copy_parm_to_heap(gogo, *p, *pp); - if (*pp != error_mark_node) - { - gcc_assert(TREE_CODE(*pp) == INDIRECT_REF); - tree var_decl = TREE_OPERAND(*pp, 0); - if (var_decl != error_mark_node) - { - gcc_assert(TREE_CODE(var_decl) == VAR_DECL); - DECL_CHAIN(var_decl) = declare_vars; - declare_vars = var_decl; - } - } - *pp = parm_decl; - } - - if (*pp != error_mark_node) - { - gcc_assert(TREE_CODE(*pp) == PARM_DECL); - pp = &DECL_CHAIN(*pp); - } - } - else if ((*p)->is_result_variable()) - { - tree var_decl = (*p)->get_tree(gogo, named_function); - if (var_decl != error_mark_node - && (*p)->result_var_value()->is_in_heap()) - { - gcc_assert(TREE_CODE(var_decl) == INDIRECT_REF); - var_decl = TREE_OPERAND(var_decl, 0); - } - if (var_decl != error_mark_node) - { - gcc_assert(TREE_CODE(var_decl) == VAR_DECL); - DECL_CHAIN(var_decl) = declare_vars; - declare_vars = var_decl; - } - } - } - *pp = NULL_TREE; - - DECL_ARGUMENTS(fndecl) = params; - - if (this->block_ != NULL) - { - gcc_assert(DECL_INITIAL(fndecl) == NULL_TREE); - - // Declare variables if necessary. - tree bind = NULL_TREE; - if (declare_vars != NULL_TREE) - { - tree block = make_node(BLOCK); - BLOCK_SUPERCONTEXT(block) = fndecl; - DECL_INITIAL(fndecl) = block; - BLOCK_VARS(block) = declare_vars; - TREE_USED(block) = 1; - bind = build3(BIND_EXPR, void_type_node, BLOCK_VARS(block), - NULL_TREE, block); - TREE_SIDE_EFFECTS(bind) = 1; - } - - // Build the trees for all the statements in the function. - Translate_context context(gogo, named_function, NULL, NULL_TREE); - tree code = this->block_->get_tree(&context); - - tree init = NULL_TREE; - tree except = NULL_TREE; - tree fini = NULL_TREE; - - // Initialize variables if necessary. - for (tree v = declare_vars; v != NULL_TREE; v = DECL_CHAIN(v)) - { - tree dv = build1(DECL_EXPR, void_type_node, v); - SET_EXPR_LOCATION(dv, DECL_SOURCE_LOCATION(v)); - append_to_statement_list(dv, &init); - } - - // If we have a defer stack, initialize it at the start of a - // function. - if (this->defer_stack_ != NULL_TREE) - { - tree defer_init = build1(DECL_EXPR, void_type_node, - this->defer_stack_); - SET_EXPR_LOCATION(defer_init, this->block_->start_location()); - append_to_statement_list(defer_init, &init); - - // Clean up the defer stack when we leave the function. - this->build_defer_wrapper(gogo, named_function, &except, &fini); - } - - if (code != NULL_TREE && code != error_mark_node) - { - if (init != NULL_TREE) - code = build2(COMPOUND_EXPR, void_type_node, init, code); - if (except != NULL_TREE) - code = build2(TRY_CATCH_EXPR, void_type_node, code, - build2(CATCH_EXPR, void_type_node, NULL, except)); - if (fini != NULL_TREE) - code = build2(TRY_FINALLY_EXPR, void_type_node, code, fini); - } - - // Stick the code into the block we built for the receiver, if - // we built on. - if (bind != NULL_TREE && code != NULL_TREE && code != error_mark_node) - { - BIND_EXPR_BODY(bind) = code; - code = bind; - } - - DECL_SAVED_TREE(fndecl) = code; - } -} - -// Build the wrappers around function code needed if the function has -// any defer statements. This sets *EXCEPT to an exception handler -// and *FINI to a finally handler. - -void -Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function, - tree *except, tree *fini) -{ - source_location end_loc = this->block_->end_location(); - - // Add an exception handler. This is used if a panic occurs. Its - // purpose is to stop the stack unwinding if a deferred function - // calls recover. There are more details in - // libgo/runtime/go-unwind.c. - tree stmt_list = NULL_TREE; - static tree check_fndecl; - tree call = Gogo::call_builtin(&check_fndecl, - end_loc, - "__go_check_defer", - 1, - void_type_node, - ptr_type_node, - this->defer_stack(end_loc)); - if (call != error_mark_node) - append_to_statement_list(call, &stmt_list); - - tree retval = this->return_value(gogo, named_function, end_loc, &stmt_list); - tree set; - if (retval == NULL_TREE) - set = NULL_TREE; - else - set = fold_build2_loc(end_loc, MODIFY_EXPR, void_type_node, - DECL_RESULT(this->fndecl_), retval); - tree ret_stmt = fold_build1_loc(end_loc, RETURN_EXPR, void_type_node, set); - append_to_statement_list(ret_stmt, &stmt_list); - - gcc_assert(*except == NULL_TREE); - *except = stmt_list; - - // Add some finally code to run the defer functions. This is used - // both in the normal case, when no panic occurs, and also if a - // panic occurs to run any further defer functions. Of course, it - // is possible for a defer function to call panic which should be - // caught by another defer function. To handle that we use a loop. - // finish: - // try { __go_undefer(); } catch { __go_check_defer(); goto finish; } - // if (return values are named) return named_vals; - - stmt_list = NULL; - - tree label = create_artificial_label(end_loc); - tree define_label = fold_build1_loc(end_loc, LABEL_EXPR, void_type_node, - label); - append_to_statement_list(define_label, &stmt_list); - - static tree undefer_fndecl; - tree undefer = Gogo::call_builtin(&undefer_fndecl, - end_loc, - "__go_undefer", - 1, - void_type_node, - ptr_type_node, - this->defer_stack(end_loc)); - if (undefer_fndecl != NULL_TREE) - TREE_NOTHROW(undefer_fndecl) = 0; - - tree defer = Gogo::call_builtin(&check_fndecl, - end_loc, - "__go_check_defer", - 1, - void_type_node, - ptr_type_node, - this->defer_stack(end_loc)); - tree jump = fold_build1_loc(end_loc, GOTO_EXPR, void_type_node, label); - tree catch_body = build2(COMPOUND_EXPR, void_type_node, defer, jump); - catch_body = build2(CATCH_EXPR, void_type_node, NULL, catch_body); - tree try_catch = build2(TRY_CATCH_EXPR, void_type_node, undefer, catch_body); - - append_to_statement_list(try_catch, &stmt_list); - - if (this->type_->results() != NULL - && !this->type_->results()->empty() - && !this->type_->results()->front().name().empty()) - { - // If the result variables are named, we need to return them - // again, because they might have been changed by a defer - // function. - retval = this->return_value(gogo, named_function, end_loc, - &stmt_list); - set = fold_build2_loc(end_loc, MODIFY_EXPR, void_type_node, - DECL_RESULT(this->fndecl_), retval); - ret_stmt = fold_build1_loc(end_loc, RETURN_EXPR, void_type_node, set); - append_to_statement_list(ret_stmt, &stmt_list); - } - - gcc_assert(*fini == NULL_TREE); - *fini = stmt_list; -} - -// Return the value to assign to DECL_RESULT(this->fndecl_). This may -// also add statements to STMT_LIST, which need to be executed before -// the assignment. This is used for a return statement with no -// explicit values. - -tree -Function::return_value(Gogo* gogo, Named_object* named_function, - source_location location, tree* stmt_list) const -{ - const Typed_identifier_list* results = this->type_->results(); - if (results == NULL || results->empty()) - return NULL_TREE; - - // In the case of an exception handler created for functions with - // defer statements, the result variables may be unnamed. - bool is_named = !results->front().name().empty(); - if (is_named) - { - gcc_assert(this->named_results_ != NULL); - if (this->named_results_->size() != results->size()) - { - gcc_assert(saw_errors()); - return error_mark_node; - } - } - - tree retval; - if (results->size() == 1) - { - if (is_named) - return this->named_results_->front()->get_tree(gogo, named_function); - else - return results->front().type()->get_init_tree(gogo, false); - } - else - { - tree rettype = TREE_TYPE(DECL_RESULT(this->fndecl_)); - retval = create_tmp_var(rettype, "RESULT"); - tree field = TYPE_FIELDS(rettype); - int index = 0; - for (Typed_identifier_list::const_iterator pr = results->begin(); - pr != results->end(); - ++pr, ++index, field = DECL_CHAIN(field)) - { - gcc_assert(field != NULL); - tree val; - if (is_named) - val = (*this->named_results_)[index]->get_tree(gogo, - named_function); - else - val = pr->type()->get_init_tree(gogo, false); - tree set = fold_build2_loc(location, MODIFY_EXPR, void_type_node, - build3(COMPONENT_REF, TREE_TYPE(field), - retval, field, NULL_TREE), - val); - append_to_statement_list(set, stmt_list); - } - return retval; - } -} - -// Get the tree for the variable holding the defer stack for this -// function. At least at present, the value of this variable is not -// used. However, a pointer to this variable is used as a marker for -// the functions on the defer stack associated with this function. -// Doing things this way permits inlining a function which uses defer. - -tree -Function::defer_stack(source_location location) -{ - if (this->defer_stack_ == NULL_TREE) - { - tree var = create_tmp_var(ptr_type_node, "DEFER"); - DECL_INITIAL(var) = null_pointer_node; - DECL_SOURCE_LOCATION(var) = location; - TREE_ADDRESSABLE(var) = 1; - this->defer_stack_ = var; - } - return fold_convert_loc(location, ptr_type_node, - build_fold_addr_expr_loc(location, - this->defer_stack_)); -} - -// Get a tree for the statements in a block. - -tree -Block::get_tree(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - - tree block = make_node(BLOCK); - - // Put the new block into the block tree. - - if (context->block() == NULL) - { - tree fndecl; - if (context->function() != NULL) - fndecl = context->function()->func_value()->get_decl(); - else - fndecl = current_function_decl; - gcc_assert(fndecl != NULL_TREE); - - // We may have already created a block for the receiver. - if (DECL_INITIAL(fndecl) == NULL_TREE) - { - BLOCK_SUPERCONTEXT(block) = fndecl; - DECL_INITIAL(fndecl) = block; - } - else - { - tree superblock_tree = DECL_INITIAL(fndecl); - BLOCK_SUPERCONTEXT(block) = superblock_tree; - gcc_assert(BLOCK_CHAIN(block) == NULL_TREE); - BLOCK_CHAIN(block) = block; - } - } - else - { - tree superblock_tree = context->block_tree(); - BLOCK_SUPERCONTEXT(block) = superblock_tree; - tree* pp; - for (pp = &BLOCK_SUBBLOCKS(superblock_tree); - *pp != NULL_TREE; - pp = &BLOCK_CHAIN(*pp)) - ; - *pp = block; - } - - // Expand local variables in the block. - - tree* pp = &BLOCK_VARS(block); - for (Bindings::const_definitions_iterator pv = - this->bindings_->begin_definitions(); - pv != this->bindings_->end_definitions(); - ++pv) - { - if ((!(*pv)->is_variable() || !(*pv)->var_value()->is_parameter()) - && !(*pv)->is_result_variable() - && !(*pv)->is_const()) - { - tree var = (*pv)->get_tree(gogo, context->function()); - if (var != error_mark_node && TREE_TYPE(var) != error_mark_node) - { - if ((*pv)->is_variable() && (*pv)->var_value()->is_in_heap()) - { - gcc_assert(TREE_CODE(var) == INDIRECT_REF); - var = TREE_OPERAND(var, 0); - gcc_assert(TREE_CODE(var) == VAR_DECL); - } - *pp = var; - pp = &DECL_CHAIN(*pp); - } - } - } - *pp = NULL_TREE; - - Translate_context subcontext(context->gogo(), context->function(), - this, block); - - tree statements = NULL_TREE; - - // Expand the statements. - - for (std::vector::const_iterator p = this->statements_.begin(); - p != this->statements_.end(); - ++p) - { - tree statement = (*p)->get_tree(&subcontext); - if (statement != error_mark_node) - append_to_statement_list(statement, &statements); - } - - TREE_USED(block) = 1; - - tree bind = build3(BIND_EXPR, void_type_node, BLOCK_VARS(block), statements, - block); - TREE_SIDE_EFFECTS(bind) = 1; - - return bind; -} - -// Get the LABEL_DECL for a label. - -tree -Label::get_decl() -{ - if (this->decl_ == NULL) - { - tree id = get_identifier_from_string(this->name_); - this->decl_ = build_decl(this->location_, LABEL_DECL, id, void_type_node); - DECL_CONTEXT(this->decl_) = current_function_decl; - } - return this->decl_; -} - -// Return an expression for the address of this label. - -tree -Label::get_addr(source_location location) -{ - tree decl = this->get_decl(); - TREE_USED(decl) = 1; - TREE_ADDRESSABLE(decl) = 1; - return fold_convert_loc(location, ptr_type_node, - build_fold_addr_expr_loc(location, decl)); -} - -// Get the LABEL_DECL for an unnamed label. - -tree -Unnamed_label::get_decl() -{ - if (this->decl_ == NULL) - this->decl_ = create_artificial_label(this->location_); - return this->decl_; -} - -// Get the LABEL_EXPR for an unnamed label. - -tree -Unnamed_label::get_definition() -{ - tree t = build1(LABEL_EXPR, void_type_node, this->get_decl()); - SET_EXPR_LOCATION(t, this->location_); - return t; -} - -// Return a goto to this label. - -tree -Unnamed_label::get_goto(source_location location) -{ - tree t = build1(GOTO_EXPR, void_type_node, this->get_decl()); - SET_EXPR_LOCATION(t, location); - return t; -} - -// Return the integer type to use for a size. - -GO_EXTERN_C -tree -go_type_for_size(unsigned int bits, int unsignedp) -{ - const char* name; - switch (bits) - { - case 8: - name = unsignedp ? "uint8" : "int8"; - break; - case 16: - name = unsignedp ? "uint16" : "int16"; - break; - case 32: - name = unsignedp ? "uint32" : "int32"; - break; - case 64: - name = unsignedp ? "uint64" : "int64"; - break; - default: - if (bits == POINTER_SIZE && unsignedp) - name = "uintptr"; - else - return NULL_TREE; - } - Type* type = Type::lookup_integer_type(name); - return type->get_tree(go_get_gogo()); -} - -// Return the type to use for a mode. - -GO_EXTERN_C -tree -go_type_for_mode(enum machine_mode mode, int unsignedp) -{ - // FIXME: This static_cast should be in machmode.h. - enum mode_class mc = static_cast(GET_MODE_CLASS(mode)); - if (mc == MODE_INT) - return go_type_for_size(GET_MODE_BITSIZE(mode), unsignedp); - else if (mc == MODE_FLOAT) - { - Type* type; - switch (GET_MODE_BITSIZE (mode)) - { - case 32: - type = Type::lookup_float_type("float32"); - break; - case 64: - type = Type::lookup_float_type("float64"); - break; - default: - // We have to check for long double in order to support - // i386 excess precision. - if (mode == TYPE_MODE(long_double_type_node)) - return long_double_type_node; - return NULL_TREE; - } - return type->float_type()->type_tree(); - } - else if (mc == MODE_COMPLEX_FLOAT) - { - Type *type; - switch (GET_MODE_BITSIZE (mode)) - { - case 64: - type = Type::lookup_complex_type("complex64"); - break; - case 128: - type = Type::lookup_complex_type("complex128"); - break; - default: - // We have to check for long double in order to support - // i386 excess precision. - if (mode == TYPE_MODE(complex_long_double_type_node)) - return complex_long_double_type_node; - return NULL_TREE; - } - return type->complex_type()->type_tree(); - } - else - return NULL_TREE; -} - -// Return a tree which allocates SIZE bytes which will holds value of -// type TYPE. - -tree -Gogo::allocate_memory(Type* type, tree size, source_location location) -{ - // If the package imports unsafe, then it may play games with - // pointers that look like integers. - if (this->imported_unsafe_ || type->has_pointer()) - { - static tree new_fndecl; - return Gogo::call_builtin(&new_fndecl, - location, - "__go_new", - 1, - ptr_type_node, - sizetype, - size); - } - else - { - static tree new_nopointers_fndecl; - return Gogo::call_builtin(&new_nopointers_fndecl, - location, - "__go_new_nopointers", - 1, - ptr_type_node, - sizetype, - size); - } -} - -// Build a builtin struct with a list of fields. The name is -// STRUCT_NAME. STRUCT_TYPE is NULL_TREE or an empty RECORD_TYPE -// node; this exists so that the struct can have fields which point to -// itself. If PTYPE is not NULL, store the result in *PTYPE. There -// are NFIELDS fields. Each field is a name (a const char*) followed -// by a type (a tree). - -tree -Gogo::builtin_struct(tree* ptype, const char* struct_name, tree struct_type, - int nfields, ...) -{ - if (ptype != NULL && *ptype != NULL_TREE) - return *ptype; - - va_list ap; - va_start(ap, nfields); - - tree fields = NULL_TREE; - for (int i = 0; i < nfields; ++i) - { - const char* field_name = va_arg(ap, const char*); - tree type = va_arg(ap, tree); - if (type == error_mark_node) - { - if (ptype != NULL) - *ptype = error_mark_node; - return error_mark_node; - } - tree field = build_decl(BUILTINS_LOCATION, FIELD_DECL, - get_identifier(field_name), type); - DECL_CHAIN(field) = fields; - fields = field; - } - - va_end(ap); - - if (struct_type == NULL_TREE) - struct_type = make_node(RECORD_TYPE); - finish_builtin_struct(struct_type, struct_name, fields, NULL_TREE); - - if (ptype != NULL) - { - go_preserve_from_gc(struct_type); - *ptype = struct_type; - } - - return struct_type; -} - -// Return a type to use for pointer to const char for a string. - -tree -Gogo::const_char_pointer_type_tree() -{ - static tree type; - if (type == NULL_TREE) - { - tree const_char_type = build_qualified_type(unsigned_char_type_node, - TYPE_QUAL_CONST); - type = build_pointer_type(const_char_type); - go_preserve_from_gc(type); - } - return type; -} - -// Return a tree for a string constant. - -tree -Gogo::string_constant_tree(const std::string& val) -{ - tree index_type = build_index_type(size_int(val.length())); - tree const_char_type = build_qualified_type(unsigned_char_type_node, - TYPE_QUAL_CONST); - tree string_type = build_array_type(const_char_type, index_type); - string_type = build_variant_type_copy(string_type); - TYPE_STRING_FLAG(string_type) = 1; - tree string_val = build_string(val.length(), val.data()); - TREE_TYPE(string_val) = string_type; - return string_val; -} - -// Return a tree for a Go string constant. - -tree -Gogo::go_string_constant_tree(const std::string& val) -{ - tree string_type = Type::make_string_type()->get_tree(this); - - VEC(constructor_elt, gc)* init = VEC_alloc(constructor_elt, gc, 2); - - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - tree field = TYPE_FIELDS(string_type); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__data") == 0); - elt->index = field; - tree str = Gogo::string_constant_tree(val); - elt->value = fold_convert(TREE_TYPE(field), - build_fold_addr_expr(str)); - - elt = VEC_quick_push(constructor_elt, init, NULL); - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__length") == 0); - elt->index = field; - elt->value = build_int_cst_type(TREE_TYPE(field), val.length()); - - tree constructor = build_constructor(string_type, init); - TREE_READONLY(constructor) = 1; - TREE_CONSTANT(constructor) = 1; - - return constructor; -} - -// Return a tree for a pointer to a Go string constant. This is only -// used for type descriptors, so we return a pointer to a constant -// decl. - -tree -Gogo::ptr_go_string_constant_tree(const std::string& val) -{ - tree pval = this->go_string_constant_tree(val); - - tree decl = build_decl(UNKNOWN_LOCATION, VAR_DECL, - create_tmp_var_name("SP"), TREE_TYPE(pval)); - DECL_EXTERNAL(decl) = 0; - TREE_PUBLIC(decl) = 0; - TREE_USED(decl) = 1; - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - TREE_STATIC(decl) = 1; - DECL_ARTIFICIAL(decl) = 1; - DECL_INITIAL(decl) = pval; - rest_of_decl_compilation(decl, 1, 0); - - return build_fold_addr_expr(decl); -} - -// Build the type of the struct that holds a slice for the given -// element type. - -tree -Gogo::slice_type_tree(tree element_type_tree) -{ - // We use int for the count and capacity fields in a slice header. - // This matches 6g. The language definition guarantees that we - // can't allocate space of a size which does not fit in int - // anyhow. FIXME: integer_type_node is the the C type "int" but is - // not necessarily the Go type "int". They will differ when the C - // type "int" has fewer than 32 bits. - return Gogo::builtin_struct(NULL, "__go_slice", NULL_TREE, 3, - "__values", - build_pointer_type(element_type_tree), - "__count", - integer_type_node, - "__capacity", - integer_type_node); -} - -// Given the tree for a slice type, return the tree for the type of -// the elements of the slice. - -tree -Gogo::slice_element_type_tree(tree slice_type_tree) -{ - gcc_assert(TREE_CODE(slice_type_tree) == RECORD_TYPE - && POINTER_TYPE_P(TREE_TYPE(TYPE_FIELDS(slice_type_tree)))); - return TREE_TYPE(TREE_TYPE(TYPE_FIELDS(slice_type_tree))); -} - -// Build a constructor for a slice. SLICE_TYPE_TREE is the type of -// the slice. VALUES is the value pointer and COUNT is the number of -// entries. If CAPACITY is not NULL, it is the capacity; otherwise -// the capacity and the count are the same. - -tree -Gogo::slice_constructor(tree slice_type_tree, tree values, tree count, - tree capacity) -{ - gcc_assert(TREE_CODE(slice_type_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - tree field = TYPE_FIELDS(slice_type_tree); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0); - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - gcc_assert(TYPE_MAIN_VARIANT(TREE_TYPE(field)) - == TYPE_MAIN_VARIANT(TREE_TYPE(values))); - elt->value = values; - - count = fold_convert(sizetype, count); - if (capacity == NULL_TREE) - { - count = save_expr(count); - capacity = count; - } - - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0); - elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), count); - - field = DECL_CHAIN(field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0); - elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), capacity); - - return build_constructor(slice_type_tree, init); -} - -// Build a constructor for an empty slice. - -tree -Gogo::empty_slice_constructor(tree slice_type_tree) -{ - tree element_field = TYPE_FIELDS(slice_type_tree); - tree ret = Gogo::slice_constructor(slice_type_tree, - fold_convert(TREE_TYPE(element_field), - null_pointer_node), - size_zero_node, - size_zero_node); - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Build a map descriptor for a map of type MAPTYPE. - -tree -Gogo::map_descriptor(Map_type* maptype) -{ - if (this->map_descriptors_ == NULL) - this->map_descriptors_ = new Map_descriptors(10); - - std::pair val(maptype, NULL); - std::pair ins = - this->map_descriptors_->insert(val); - Map_descriptors::iterator p = ins.first; - if (!ins.second) - { - if (p->second == error_mark_node) - return error_mark_node; - gcc_assert(p->second != NULL_TREE && DECL_P(p->second)); - return build_fold_addr_expr(p->second); - } - - Type* keytype = maptype->key_type(); - Type* valtype = maptype->val_type(); - - std::string mangled_name = ("__go_map_" + maptype->mangled_name(this)); - - tree id = get_identifier_from_string(mangled_name); - - // Get the type of the map descriptor. This is __go_map_descriptor - // in libgo/map.h. - - tree struct_type = this->map_descriptor_type(); - - // The map entry type is a struct with three fields. This struct is - // specific to MAPTYPE. Build it. - - tree map_entry_type = make_node(RECORD_TYPE); - - map_entry_type = Gogo::builtin_struct(NULL, "__map", map_entry_type, 3, - "__next", - build_pointer_type(map_entry_type), - "__key", - keytype->get_tree(this), - "__val", - valtype->get_tree(this)); - if (map_entry_type == error_mark_node) - { - p->second = error_mark_node; - return error_mark_node; - } - - tree map_entry_key_field = DECL_CHAIN(TYPE_FIELDS(map_entry_type)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_entry_key_field)), - "__key") == 0); - - tree map_entry_val_field = DECL_CHAIN(map_entry_key_field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_entry_val_field)), - "__val") == 0); - - // Initialize the entries. - - tree map_descriptor_field = TYPE_FIELDS(struct_type); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(map_descriptor_field)), - "__map_descriptor") == 0); - tree entry_size_field = DECL_CHAIN(map_descriptor_field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(entry_size_field)), - "__entry_size") == 0); - tree key_offset_field = DECL_CHAIN(entry_size_field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(key_offset_field)), - "__key_offset") == 0); - tree val_offset_field = DECL_CHAIN(key_offset_field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(val_offset_field)), - "__val_offset") == 0); - - VEC(constructor_elt, gc)* descriptor = VEC_alloc(constructor_elt, gc, 6); - - constructor_elt* elt = VEC_quick_push(constructor_elt, descriptor, NULL); - elt->index = map_descriptor_field; - elt->value = maptype->type_descriptor_pointer(this); - - elt = VEC_quick_push(constructor_elt, descriptor, NULL); - elt->index = entry_size_field; - elt->value = TYPE_SIZE_UNIT(map_entry_type); - - elt = VEC_quick_push(constructor_elt, descriptor, NULL); - elt->index = key_offset_field; - elt->value = byte_position(map_entry_key_field); - - elt = VEC_quick_push(constructor_elt, descriptor, NULL); - elt->index = val_offset_field; - elt->value = byte_position(map_entry_val_field); - - tree constructor = build_constructor(struct_type, descriptor); - - tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, struct_type); - TREE_STATIC(decl) = 1; - TREE_USED(decl) = 1; - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - DECL_INITIAL(decl) = constructor; - make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl)); - resolve_unique_section(decl, 1, 0); - - rest_of_decl_compilation(decl, 1, 0); - - go_preserve_from_gc(decl); - p->second = decl; - - return build_fold_addr_expr(decl); -} - -// Return a tree for the type of a map descriptor. This is struct -// __go_map_descriptor in libgo/runtime/map.h. This is the same for -// all map types. - -tree -Gogo::map_descriptor_type() -{ - static tree struct_type; - tree dtype = Type::make_type_descriptor_type()->get_tree(this); - dtype = build_qualified_type(dtype, TYPE_QUAL_CONST); - return Gogo::builtin_struct(&struct_type, "__go_map_descriptor", NULL_TREE, - 4, - "__map_descriptor", - build_pointer_type(dtype), - "__entry_size", - sizetype, - "__key_offset", - sizetype, - "__val_offset", - sizetype); -} - -// Return the name to use for a type descriptor decl for TYPE. This -// is used when TYPE does not have a name. - -std::string -Gogo::unnamed_type_descriptor_decl_name(const Type* type) -{ - return "__go_td_" + type->mangled_name(this); -} - -// Return the name to use for a type descriptor decl for a type named -// NAME, defined in the function IN_FUNCTION. IN_FUNCTION will -// normally be NULL. - -std::string -Gogo::type_descriptor_decl_name(const Named_object* no, - const Named_object* in_function) -{ - std::string ret = "__go_tdn_"; - if (no->type_value()->is_builtin()) - gcc_assert(in_function == NULL); - else - { - const std::string& unique_prefix(no->package() == NULL - ? this->unique_prefix() - : no->package()->unique_prefix()); - const std::string& package_name(no->package() == NULL - ? this->package_name() - : no->package()->name()); - ret.append(unique_prefix); - ret.append(1, '.'); - ret.append(package_name); - ret.append(1, '.'); - if (in_function != NULL) - { - ret.append(Gogo::unpack_hidden_name(in_function->name())); - ret.append(1, '.'); - } - } - ret.append(no->name()); - return ret; -} - -// Where a type descriptor decl should be defined. - -Gogo::Type_descriptor_location -Gogo::type_descriptor_location(const Type* type) -{ - const Named_type* name = type->named_type(); - if (name != NULL) - { - if (name->named_object()->package() != NULL) - { - // This is a named type defined in a different package. The - // descriptor should be defined in that package. - return TYPE_DESCRIPTOR_UNDEFINED; - } - else if (name->is_builtin()) - { - // We create the descriptor for a builtin type whenever we - // need it. - return TYPE_DESCRIPTOR_COMMON; - } - else - { - // This is a named type defined in this package. The - // descriptor should be defined here. - return TYPE_DESCRIPTOR_DEFINED; - } - } - else - { - if (type->points_to() != NULL - && type->points_to()->named_type() != NULL - && type->points_to()->named_type()->named_object()->package() != NULL) - { - // This is an unnamed pointer to a named type defined in a - // different package. The descriptor should be defined in - // that package. - return TYPE_DESCRIPTOR_UNDEFINED; - } - else - { - // This is an unnamed type. The descriptor could be defined - // in any package where it is needed, and the linker will - // pick one descriptor to keep. - return TYPE_DESCRIPTOR_COMMON; - } - } -} - -// Build a type descriptor decl for TYPE. INITIALIZER is a struct -// composite literal which initializers the type descriptor. - -void -Gogo::build_type_descriptor_decl(const Type* type, Expression* initializer, - tree* pdecl) -{ - const Named_type* name = type->named_type(); - - // We can have multiple instances of unnamed types, but we only want - // to emit the type descriptor once. We use a hash table to handle - // this. This is not necessary for named types, as they are unique, - // and we store the type descriptor decl in the type itself. - tree* phash = NULL; - if (name == NULL) - { - if (this->type_descriptor_decls_ == NULL) - this->type_descriptor_decls_ = new Type_descriptor_decls(10); - - std::pair ins = - this->type_descriptor_decls_->insert(std::make_pair(type, NULL_TREE)); - if (!ins.second) - { - // We've already built a type descriptor for this type. - *pdecl = ins.first->second; - return; - } - phash = &ins.first->second; - } - - std::string decl_name; - if (name == NULL) - decl_name = this->unnamed_type_descriptor_decl_name(type); - else - decl_name = this->type_descriptor_decl_name(name->named_object(), - name->in_function()); - tree id = get_identifier_from_string(decl_name); - tree descriptor_type_tree = initializer->type()->get_tree(this); - if (descriptor_type_tree == error_mark_node) - { - *pdecl = error_mark_node; - return; - } - tree decl = build_decl(name == NULL ? BUILTINS_LOCATION : name->location(), - VAR_DECL, id, - build_qualified_type(descriptor_type_tree, - TYPE_QUAL_CONST)); - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - DECL_ARTIFICIAL(decl) = 1; - - go_preserve_from_gc(decl); - if (phash != NULL) - *phash = decl; - - // We store the new DECL now because we may need to refer to it when - // expanding INITIALIZER. - *pdecl = decl; - - // If appropriate, just refer to the exported type identifier. - Gogo::Type_descriptor_location type_descriptor_location = - this->type_descriptor_location(type); - if (type_descriptor_location == TYPE_DESCRIPTOR_UNDEFINED) - { - TREE_PUBLIC(decl) = 1; - DECL_EXTERNAL(decl) = 1; - return; - } - - TREE_STATIC(decl) = 1; - TREE_USED(decl) = 1; - - Translate_context context(this, NULL, NULL, NULL); - context.set_is_const(); - tree constructor = initializer->get_tree(&context); - - if (constructor == error_mark_node) - gcc_assert(saw_errors()); - - DECL_INITIAL(decl) = constructor; - - if (type_descriptor_location == TYPE_DESCRIPTOR_DEFINED) - TREE_PUBLIC(decl) = 1; - else - { - gcc_assert(type_descriptor_location == TYPE_DESCRIPTOR_COMMON); - make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl)); - resolve_unique_section(decl, 1, 0); - } - - rest_of_decl_compilation(decl, 1, 0); -} - -// Build an interface method table for a type: a list of function -// pointers, one for each interface method. This is used for -// interfaces. - -tree -Gogo::interface_method_table_for_type(const Interface_type* interface, - Named_type* type, - bool is_pointer) -{ - const Typed_identifier_list* interface_methods = interface->methods(); - gcc_assert(!interface_methods->empty()); - - std::string mangled_name = ((is_pointer ? "__go_pimt__" : "__go_imt_") - + interface->mangled_name(this) - + "__" - + type->mangled_name(this)); - - tree id = get_identifier_from_string(mangled_name); - - // See whether this interface has any hidden methods. - bool has_hidden_methods = false; - for (Typed_identifier_list::const_iterator p = interface_methods->begin(); - p != interface_methods->end(); - ++p) - { - if (Gogo::is_hidden_name(p->name())) - { - has_hidden_methods = true; - break; - } - } - - // We already know that the named type is convertible to the - // interface. If the interface has hidden methods, and the named - // type is defined in a different package, then the interface - // conversion table will be defined by that other package. - if (has_hidden_methods && type->named_object()->package() != NULL) - { - tree array_type = build_array_type(const_ptr_type_node, NULL); - tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type); - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - TREE_PUBLIC(decl) = 1; - DECL_EXTERNAL(decl) = 1; - go_preserve_from_gc(decl); - return decl; - } - - size_t count = interface_methods->size(); - VEC(constructor_elt, gc)* pointers = VEC_alloc(constructor_elt, gc, - count + 1); - - // The first element is the type descriptor. - constructor_elt* elt = VEC_quick_push(constructor_elt, pointers, NULL); - elt->index = size_zero_node; - Type* td_type; - if (!is_pointer) - td_type = type; - else - td_type = Type::make_pointer_type(type); - elt->value = fold_convert(const_ptr_type_node, - td_type->type_descriptor_pointer(this)); - - size_t i = 1; - for (Typed_identifier_list::const_iterator p = interface_methods->begin(); - p != interface_methods->end(); - ++p, ++i) - { - bool is_ambiguous; - Method* m = type->method_function(p->name(), &is_ambiguous); - gcc_assert(m != NULL); - - Named_object* no = m->named_object(); - - tree fnid = no->get_id(this); - - tree fndecl; - if (no->is_function()) - fndecl = no->func_value()->get_or_make_decl(this, no, fnid); - else if (no->is_function_declaration()) - fndecl = no->func_declaration_value()->get_or_make_decl(this, no, - fnid); - else - gcc_unreachable(); - fndecl = build_fold_addr_expr(fndecl); - - elt = VEC_quick_push(constructor_elt, pointers, NULL); - elt->index = size_int(i); - elt->value = fold_convert(const_ptr_type_node, fndecl); - } - gcc_assert(i == count + 1); - - tree array_type = build_array_type(const_ptr_type_node, - build_index_type(size_int(count))); - tree constructor = build_constructor(array_type, pointers); - - tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type); - TREE_STATIC(decl) = 1; - TREE_USED(decl) = 1; - TREE_READONLY(decl) = 1; - TREE_CONSTANT(decl) = 1; - DECL_INITIAL(decl) = constructor; - - // If the interface type has hidden methods, then this is the only - // definition of the table. Otherwise it is a comdat table which - // may be defined in multiple packages. - if (has_hidden_methods) - TREE_PUBLIC(decl) = 1; - else - { - make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl)); - resolve_unique_section(decl, 1, 0); - } - - rest_of_decl_compilation(decl, 1, 0); - - go_preserve_from_gc(decl); - - return decl; -} - -// Mark a function as a builtin library function. - -void -Gogo::mark_fndecl_as_builtin_library(tree fndecl) -{ - DECL_EXTERNAL(fndecl) = 1; - TREE_PUBLIC(fndecl) = 1; - DECL_ARTIFICIAL(fndecl) = 1; - TREE_NOTHROW(fndecl) = 1; - DECL_VISIBILITY(fndecl) = VISIBILITY_DEFAULT; - DECL_VISIBILITY_SPECIFIED(fndecl) = 1; -} - -// Build a call to a builtin function. - -tree -Gogo::call_builtin(tree* pdecl, source_location location, const char* name, - int nargs, tree rettype, ...) -{ - if (rettype == error_mark_node) - return error_mark_node; - - tree* types = new tree[nargs]; - tree* args = new tree[nargs]; - - va_list ap; - va_start(ap, rettype); - for (int i = 0; i < nargs; ++i) - { - types[i] = va_arg(ap, tree); - args[i] = va_arg(ap, tree); - if (types[i] == error_mark_node || args[i] == error_mark_node) - { - delete[] types; - delete[] args; - return error_mark_node; - } - } - va_end(ap); - - if (*pdecl == NULL_TREE) - { - tree fnid = get_identifier(name); - - tree argtypes = NULL_TREE; - tree* pp = &argtypes; - for (int i = 0; i < nargs; ++i) - { - *pp = tree_cons(NULL_TREE, types[i], NULL_TREE); - pp = &TREE_CHAIN(*pp); - } - *pp = void_list_node; - - tree fntype = build_function_type(rettype, argtypes); - - *pdecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL, fnid, fntype); - Gogo::mark_fndecl_as_builtin_library(*pdecl); - go_preserve_from_gc(*pdecl); - } - - tree fnptr = build_fold_addr_expr(*pdecl); - if (CAN_HAVE_LOCATION_P(fnptr)) - SET_EXPR_LOCATION(fnptr, location); - - tree ret = build_call_array(rettype, fnptr, nargs, args); - SET_EXPR_LOCATION(ret, location); - - delete[] types; - delete[] args; - - return ret; -} - -// Build a call to the runtime error function. - -tree -Gogo::runtime_error(int code, source_location location) -{ - static tree runtime_error_fndecl; - tree ret = Gogo::call_builtin(&runtime_error_fndecl, - location, - "__go_runtime_error", - 1, - void_type_node, - integer_type_node, - build_int_cst(integer_type_node, code)); - if (ret == error_mark_node) - return error_mark_node; - // The runtime error function panics and does not return. - TREE_NOTHROW(runtime_error_fndecl) = 0; - TREE_THIS_VOLATILE(runtime_error_fndecl) = 1; - return ret; -} - -// Send VAL on CHANNEL. If BLOCKING is true, the resulting tree has a -// void type. If BLOCKING is false, the resulting tree has a boolean -// type, and it will evaluate as true if the value was sent. If -// FOR_SELECT is true, this is being done because it was chosen in a -// select statement. - -tree -Gogo::send_on_channel(tree channel, tree val, bool blocking, bool for_select, - source_location location) -{ - if (channel == error_mark_node || val == error_mark_node) - return error_mark_node; - - if (int_size_in_bytes(TREE_TYPE(val)) <= 8 - && !AGGREGATE_TYPE_P(TREE_TYPE(val)) - && !FLOAT_TYPE_P(TREE_TYPE(val))) - { - val = convert_to_integer(uint64_type_node, val); - if (blocking) - { - static tree send_small_fndecl; - tree ret = Gogo::call_builtin(&send_small_fndecl, - location, - "__go_send_small", - 3, - void_type_node, - ptr_type_node, - channel, - uint64_type_node, - val, - boolean_type_node, - (for_select - ? boolean_true_node - : boolean_false_node)); - if (ret == error_mark_node) - return error_mark_node; - // This can panic if there are too many operations on a - // closed channel. - TREE_NOTHROW(send_small_fndecl) = 0; - return ret; - } - else - { - gcc_assert(!for_select); - static tree send_nonblocking_small_fndecl; - tree ret = Gogo::call_builtin(&send_nonblocking_small_fndecl, - location, - "__go_send_nonblocking_small", - 2, - boolean_type_node, - ptr_type_node, - channel, - uint64_type_node, - val); - if (ret == error_mark_node) - return error_mark_node; - // This can panic if there are too many operations on a - // closed channel. - TREE_NOTHROW(send_nonblocking_small_fndecl) = 0; - return ret; - } - } - else - { - tree make_tmp; - if (TREE_ADDRESSABLE(TREE_TYPE(val)) || TREE_CODE(val) == VAR_DECL) - { - make_tmp = NULL_TREE; - val = build_fold_addr_expr(val); - if (DECL_P(val)) - TREE_ADDRESSABLE(val) = 1; - } - else - { - tree tmp = create_tmp_var(TREE_TYPE(val), get_name(val)); - DECL_IGNORED_P(tmp) = 0; - DECL_INITIAL(tmp) = val; - TREE_ADDRESSABLE(tmp) = 1; - make_tmp = build1(DECL_EXPR, void_type_node, tmp); - SET_EXPR_LOCATION(make_tmp, location); - val = build_fold_addr_expr(tmp); - } - val = fold_convert(ptr_type_node, val); - - tree call; - if (blocking) - { - static tree send_big_fndecl; - call = Gogo::call_builtin(&send_big_fndecl, - location, - "__go_send_big", - 3, - void_type_node, - ptr_type_node, - channel, - ptr_type_node, - val, - boolean_type_node, - (for_select - ? boolean_true_node - : boolean_false_node)); - if (call == error_mark_node) - return error_mark_node; - // This can panic if there are too many operations on a - // closed channel. - TREE_NOTHROW(send_big_fndecl) = 0; - } - else - { - gcc_assert(!for_select); - static tree send_nonblocking_big_fndecl; - call = Gogo::call_builtin(&send_nonblocking_big_fndecl, - location, - "__go_send_nonblocking_big", - 2, - boolean_type_node, - ptr_type_node, - channel, - ptr_type_node, - val); - if (call == error_mark_node) - return error_mark_node; - // This can panic if there are too many operations on a - // closed channel. - TREE_NOTHROW(send_nonblocking_big_fndecl) = 0; - } - - if (make_tmp == NULL_TREE) - return call; - else - { - tree ret = build2(COMPOUND_EXPR, TREE_TYPE(call), make_tmp, call); - SET_EXPR_LOCATION(ret, location); - return ret; - } - } -} - -// Return a tree for receiving a value of type TYPE_TREE on CHANNEL. -// This does a blocking receive and returns the value read from the -// channel. If FOR_SELECT is true, this is being done because it was -// chosen in a select statement. - -tree -Gogo::receive_from_channel(tree type_tree, tree channel, bool for_select, - source_location location) -{ - if (type_tree == error_mark_node || channel == error_mark_node) - return error_mark_node; - - if (int_size_in_bytes(type_tree) <= 8 - && !AGGREGATE_TYPE_P(type_tree) - && !FLOAT_TYPE_P(type_tree)) - { - static tree receive_small_fndecl; - tree call = Gogo::call_builtin(&receive_small_fndecl, - location, - "__go_receive_small", - 2, - uint64_type_node, - ptr_type_node, - channel, - boolean_type_node, - (for_select - ? boolean_true_node - : boolean_false_node)); - if (call == error_mark_node) - return error_mark_node; - // This can panic if there are too many operations on a closed - // channel. - TREE_NOTHROW(receive_small_fndecl) = 0; - int bitsize = GET_MODE_BITSIZE(TYPE_MODE(type_tree)); - tree int_type_tree = go_type_for_size(bitsize, 1); - return fold_convert_loc(location, type_tree, - fold_convert_loc(location, int_type_tree, - call)); - } - else - { - tree tmp = create_tmp_var(type_tree, get_name(type_tree)); - DECL_IGNORED_P(tmp) = 0; - TREE_ADDRESSABLE(tmp) = 1; - tree make_tmp = build1(DECL_EXPR, void_type_node, tmp); - SET_EXPR_LOCATION(make_tmp, location); - tree tmpaddr = build_fold_addr_expr(tmp); - tmpaddr = fold_convert(ptr_type_node, tmpaddr); - static tree receive_big_fndecl; - tree call = Gogo::call_builtin(&receive_big_fndecl, - location, - "__go_receive_big", - 3, - boolean_type_node, - ptr_type_node, - channel, - ptr_type_node, - tmpaddr, - boolean_type_node, - (for_select - ? boolean_true_node - : boolean_false_node)); - if (call == error_mark_node) - return error_mark_node; - // This can panic if there are too many operations on a closed - // channel. - TREE_NOTHROW(receive_big_fndecl) = 0; - return build2(COMPOUND_EXPR, type_tree, make_tmp, - build2(COMPOUND_EXPR, type_tree, call, tmp)); - } -} - -// Return the type of a function trampoline. This is like -// get_trampoline_type in tree-nested.c. - -tree -Gogo::trampoline_type_tree() -{ - static tree type_tree; - if (type_tree == NULL_TREE) - { - unsigned int size; - unsigned int align; - go_trampoline_info(&size, &align); - tree t = build_index_type(build_int_cst(integer_type_node, size - 1)); - t = build_array_type(char_type_node, t); - - type_tree = Gogo::builtin_struct(NULL, "__go_trampoline", NULL_TREE, 1, - "__data", t); - t = TYPE_FIELDS(type_tree); - DECL_ALIGN(t) = align; - DECL_USER_ALIGN(t) = 1; - - go_preserve_from_gc(type_tree); - } - return type_tree; -} - -// Make a trampoline which calls FNADDR passing CLOSURE. - -tree -Gogo::make_trampoline(tree fnaddr, tree closure, source_location location) -{ - tree trampoline_type = Gogo::trampoline_type_tree(); - tree trampoline_size = TYPE_SIZE_UNIT(trampoline_type); - - closure = save_expr(closure); - - // We allocate the trampoline using a special function which will - // mark it as executable. - static tree trampoline_fndecl; - tree x = Gogo::call_builtin(&trampoline_fndecl, - location, - "__go_allocate_trampoline", - 2, - ptr_type_node, - size_type_node, - trampoline_size, - ptr_type_node, - fold_convert_loc(location, ptr_type_node, - closure)); - if (x == error_mark_node) - return error_mark_node; - - x = save_expr(x); - - // Initialize the trampoline. - tree ini = build_call_expr(implicit_built_in_decls[BUILT_IN_INIT_TRAMPOLINE], - 3, x, fnaddr, closure); - - // On some targets the trampoline address needs to be adjusted. For - // example, when compiling in Thumb mode on the ARM, the address - // needs to have the low bit set. - x = build_call_expr(implicit_built_in_decls[BUILT_IN_ADJUST_TRAMPOLINE], - 1, x); - x = fold_convert(TREE_TYPE(fnaddr), x); - - return build2(COMPOUND_EXPR, TREE_TYPE(x), ini, x); -} diff --git a/gcc/go/gofrontend/gogo.cc.merge-left.r167407 b/gcc/go/gofrontend/gogo.cc.merge-left.r167407 deleted file mode 100644 index 0216d6c6b09..00000000000 --- a/gcc/go/gofrontend/gogo.cc.merge-left.r167407 +++ /dev/null @@ -1,4274 +0,0 @@ -// gogo.cc -- Go frontend parsed representation. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include "go-c.h" -#include "go-dump.h" -#include "lex.h" -#include "types.h" -#include "statements.h" -#include "expressions.h" -#include "dataflow.h" -#include "import.h" -#include "export.h" -#include "gogo.h" - -// Class Gogo. - -Gogo::Gogo(int int_type_size, int float_type_size, int pointer_size) - : package_(NULL), - functions_(), - globals_(new Bindings(NULL)), - imports_(), - imported_unsafe_(false), - packages_(), - map_descriptors_(NULL), - type_descriptor_decls_(NULL), - init_functions_(), - need_init_fn_(false), - init_fn_name_(), - imported_init_fns_(), - unique_prefix_(), - interface_types_() -{ - const source_location loc = BUILTINS_LOCATION; - - Named_type* uint8_type = Type::make_integer_type("uint8", true, 8, - RUNTIME_TYPE_KIND_UINT8); - this->add_named_type(uint8_type); - this->add_named_type(Type::make_integer_type("uint16", true, 16, - RUNTIME_TYPE_KIND_UINT16)); - this->add_named_type(Type::make_integer_type("uint32", true, 32, - RUNTIME_TYPE_KIND_UINT32)); - this->add_named_type(Type::make_integer_type("uint64", true, 64, - RUNTIME_TYPE_KIND_UINT64)); - - this->add_named_type(Type::make_integer_type("int8", false, 8, - RUNTIME_TYPE_KIND_INT8)); - this->add_named_type(Type::make_integer_type("int16", false, 16, - RUNTIME_TYPE_KIND_INT16)); - this->add_named_type(Type::make_integer_type("int32", false, 32, - RUNTIME_TYPE_KIND_INT32)); - this->add_named_type(Type::make_integer_type("int64", false, 64, - RUNTIME_TYPE_KIND_INT64)); - - this->add_named_type(Type::make_float_type("float32", 32, - RUNTIME_TYPE_KIND_FLOAT32)); - this->add_named_type(Type::make_float_type("float64", 64, - RUNTIME_TYPE_KIND_FLOAT64)); - - this->add_named_type(Type::make_complex_type("complex64", 64, - RUNTIME_TYPE_KIND_COMPLEX64)); - this->add_named_type(Type::make_complex_type("complex128", 128, - RUNTIME_TYPE_KIND_COMPLEX128)); - - if (int_type_size < 32) - int_type_size = 32; - this->add_named_type(Type::make_integer_type("uint", true, - int_type_size, - RUNTIME_TYPE_KIND_UINT)); - Named_type* int_type = Type::make_integer_type("int", false, int_type_size, - RUNTIME_TYPE_KIND_INT); - this->add_named_type(int_type); - - // "byte" is an alias for "uint8". Construct a Named_object which - // points to UINT8_TYPE. Note that this breaks the normal pairing - // in which a Named_object points to a Named_type which points back - // to the same Named_object. - Named_object* byte_type = this->declare_type("byte", loc); - byte_type->set_type_value(uint8_type); - - this->add_named_type(Type::make_integer_type("uintptr", true, - pointer_size, - RUNTIME_TYPE_KIND_UINTPTR)); - - this->add_named_type(Type::make_float_type("float", float_type_size, - RUNTIME_TYPE_KIND_FLOAT)); - - this->add_named_type(Type::make_complex_type("complex", float_type_size * 2, - RUNTIME_TYPE_KIND_COMPLEX)); - - this->add_named_type(Type::make_named_bool_type()); - - this->add_named_type(Type::make_named_string_type()); - - this->globals_->add_constant(Typed_identifier("true", - Type::make_boolean_type(), - loc), - NULL, - Expression::make_boolean(true, loc), - 0); - this->globals_->add_constant(Typed_identifier("false", - Type::make_boolean_type(), - loc), - NULL, - Expression::make_boolean(false, loc), - 0); - - this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(), - loc), - NULL, - Expression::make_nil(loc), - 0); - - Type* abstract_int_type = Type::make_abstract_integer_type(); - this->globals_->add_constant(Typed_identifier("iota", abstract_int_type, - loc), - NULL, - Expression::make_iota(), - 0); - - Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc); - new_type->set_is_varargs(); - new_type->set_is_builtin(); - this->globals_->add_function_declaration("new", NULL, new_type, loc); - - Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc); - make_type->set_is_varargs(); - make_type->set_is_builtin(); - this->globals_->add_function_declaration("make", NULL, make_type, loc); - - Typed_identifier_list* len_result = new Typed_identifier_list(); - len_result->push_back(Typed_identifier("", int_type, loc)); - Function_type* len_type = Type::make_function_type(NULL, NULL, len_result, - loc); - len_type->set_is_builtin(); - this->globals_->add_function_declaration("len", NULL, len_type, loc); - - Typed_identifier_list* cap_result = new Typed_identifier_list(); - cap_result->push_back(Typed_identifier("", int_type, loc)); - Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result, - loc); - cap_type->set_is_builtin(); - this->globals_->add_function_declaration("cap", NULL, cap_type, loc); - - Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc); - print_type->set_is_varargs(); - print_type->set_is_builtin(); - this->globals_->add_function_declaration("print", NULL, print_type, loc); - - print_type = Type::make_function_type(NULL, NULL, NULL, loc); - print_type->set_is_varargs(); - print_type->set_is_builtin(); - this->globals_->add_function_declaration("println", NULL, print_type, loc); - - Type *empty = Type::make_interface_type(NULL, loc); - Typed_identifier_list* panic_parms = new Typed_identifier_list(); - panic_parms->push_back(Typed_identifier("e", empty, loc)); - Function_type *panic_type = Type::make_function_type(NULL, panic_parms, - NULL, loc); - panic_type->set_is_builtin(); - this->globals_->add_function_declaration("panic", NULL, panic_type, loc); - - Typed_identifier_list* recover_result = new Typed_identifier_list(); - recover_result->push_back(Typed_identifier("", empty, loc)); - Function_type* recover_type = Type::make_function_type(NULL, NULL, - recover_result, - loc); - recover_type->set_is_builtin(); - this->globals_->add_function_declaration("recover", NULL, recover_type, loc); - - Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc); - close_type->set_is_varargs(); - close_type->set_is_builtin(); - this->globals_->add_function_declaration("close", NULL, close_type, loc); - - Typed_identifier_list* closed_result = new Typed_identifier_list(); - closed_result->push_back(Typed_identifier("", Type::lookup_bool_type(), - loc)); - Function_type* closed_type = Type::make_function_type(NULL, NULL, - closed_result, loc); - closed_type->set_is_varargs(); - closed_type->set_is_builtin(); - this->globals_->add_function_declaration("closed", NULL, closed_type, loc); - - Typed_identifier_list* copy_result = new Typed_identifier_list(); - copy_result->push_back(Typed_identifier("", int_type, loc)); - Function_type* copy_type = Type::make_function_type(NULL, NULL, - copy_result, loc); - copy_type->set_is_varargs(); - copy_type->set_is_builtin(); - this->globals_->add_function_declaration("copy", NULL, copy_type, loc); - - Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc); - append_type->set_is_varargs(); - append_type->set_is_builtin(); - this->globals_->add_function_declaration("append", NULL, append_type, loc); - - Function_type* cmplx_type = Type::make_function_type(NULL, NULL, NULL, loc); - cmplx_type->set_is_varargs(); - cmplx_type->set_is_builtin(); - this->globals_->add_function_declaration("cmplx", NULL, cmplx_type, loc); - - Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc); - real_type->set_is_varargs(); - real_type->set_is_builtin(); - this->globals_->add_function_declaration("real", NULL, real_type, loc); - - Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc); - imag_type->set_is_varargs(); - imag_type->set_is_builtin(); - this->globals_->add_function_declaration("imag", NULL, cmplx_type, loc); - - this->define_builtin_function_trees(); - - // Declare "init", to ensure that it is not defined with parameters - // or return values. - this->declare_function("init", - Type::make_function_type(NULL, NULL, NULL, loc), - loc); -} - -// Munge name for use in an error message. - -std::string -Gogo::message_name(const std::string& name) -{ - return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str()); -} - -// Get the package name. - -const std::string& -Gogo::package_name() const -{ - gcc_assert(this->package_ != NULL); - return this->package_->name(); -} - -// Set the package name. - -void -Gogo::set_package_name(const std::string& package_name, - source_location location) -{ - if (this->package_ != NULL && this->package_->name() != package_name) - { - error_at(location, "expected package %<%s%>", - Gogo::message_name(this->package_->name()).c_str()); - return; - } - - // If the user did not specify a unique prefix, we always use "go". - // This in effect requires that the package name be unique. - if (this->unique_prefix_.empty()) - this->unique_prefix_ = "go"; - - this->package_ = this->register_package(package_name, this->unique_prefix_, - location); - - // We used to permit people to qualify symbols with the current - // package name (e.g., P.x), but we no longer do. - // this->globals_->add_package(package_name, this->package_); - - if (package_name == "main") - { - // Declare "main" as a function which takes no parameters and - // returns no value. - this->declare_function("main", - Type::make_function_type(NULL, NULL, NULL, - BUILTINS_LOCATION), - BUILTINS_LOCATION); - } -} - -// Import a package. - -void -Gogo::import_package(const std::string& filename, - const std::string& local_name, - bool is_local_name_exported, - source_location location) -{ - if (filename == "unsafe") - { - this->import_unsafe(local_name, is_local_name_exported, location); - return; - } - - Imports::const_iterator p = this->imports_.find(filename); - if (p != this->imports_.end()) - { - Package* package = p->second; - package->set_location(location); - package->set_is_imported(); - std::string ln = local_name; - bool is_ln_exported = is_local_name_exported; - if (ln.empty()) - { - ln = package->name(); - is_ln_exported = Lex::is_exported_name(ln); - } - if (ln != ".") - { - ln = this->pack_hidden_name(ln, is_ln_exported); - this->package_->bindings()->add_package(ln, package); - } - else - { - Bindings* bindings = package->bindings(); - for (Bindings::const_declarations_iterator p = - bindings->begin_declarations(); - p != bindings->end_declarations(); - ++p) - this->add_named_object(p->second); - } - return; - } - - Import::Stream* stream = Import::open_package(filename, location); - if (stream == NULL) - { - error_at(location, "import file %qs not found", filename.c_str()); - return; - } - - Import imp(stream, location); - imp.register_builtin_types(this); - Package* package = imp.import(this, local_name, is_local_name_exported); - this->imports_.insert(std::make_pair(filename, package)); - package->set_is_imported(); - - delete stream; -} - -// Add an import control function for an imported package to the list. - -void -Gogo::add_import_init_fn(const std::string& package_name, - const std::string& init_name, int prio) -{ - for (std::set::const_iterator p = - this->imported_init_fns_.begin(); - p != this->imported_init_fns_.end(); - ++p) - { - if (p->init_name() == init_name - && (p->package_name() != package_name || p->priority() != prio)) - { - error("duplicate package initialization name %qs", - Gogo::message_name(init_name).c_str()); - inform(UNKNOWN_LOCATION, "used by package %qs at priority %d", - Gogo::message_name(p->package_name()).c_str(), - p->priority()); - inform(UNKNOWN_LOCATION, " and by package %qs at priority %d", - Gogo::message_name(package_name).c_str(), prio); - return; - } - } - - this->imported_init_fns_.insert(Import_init(package_name, init_name, - prio)); -} - -// Return whether we are at the global binding level. - -bool -Gogo::in_global_scope() const -{ - return this->functions_.empty(); -} - -// Return the current binding contour. - -Bindings* -Gogo::current_bindings() -{ - if (!this->functions_.empty()) - return this->functions_.back().blocks.back()->bindings(); - else if (this->package_ != NULL) - return this->package_->bindings(); - else - return this->globals_; -} - -const Bindings* -Gogo::current_bindings() const -{ - if (!this->functions_.empty()) - return this->functions_.back().blocks.back()->bindings(); - else if (this->package_ != NULL) - return this->package_->bindings(); - else - return this->globals_; -} - -// Return the current block. - -Block* -Gogo::current_block() -{ - if (this->functions_.empty()) - return NULL; - else - return this->functions_.back().blocks.back(); -} - -// Look up a name in the current binding contour. If PFUNCTION is not -// NULL, set it to the function in which the name is defined, or NULL -// if the name is defined in global scope. - -Named_object* -Gogo::lookup(const std::string& name, Named_object** pfunction) const -{ - if (Gogo::is_sink_name(name)) - return Named_object::make_sink(); - - for (Open_functions::const_reverse_iterator p = this->functions_.rbegin(); - p != this->functions_.rend(); - ++p) - { - Named_object* ret = p->blocks.back()->bindings()->lookup(name); - if (ret != NULL) - { - if (pfunction != NULL) - *pfunction = p->function; - return ret; - } - } - - if (pfunction != NULL) - *pfunction = NULL; - - if (this->package_ != NULL) - { - Named_object* ret = this->package_->bindings()->lookup(name); - if (ret != NULL) - { - if (ret->package() != NULL) - ret->package()->set_used(); - return ret; - } - } - - // We do not look in the global namespace. If we did, the global - // namespace would effectively hide names which were defined in - // package scope which we have not yet seen. Instead, - // define_global_names is called after parsing is over to connect - // undefined names at package scope with names defined at global - // scope. - - return NULL; -} - -// Look up a name in the current block, without searching enclosing -// blocks. - -Named_object* -Gogo::lookup_in_block(const std::string& name) const -{ - gcc_assert(!this->functions_.empty()); - gcc_assert(!this->functions_.back().blocks.empty()); - return this->functions_.back().blocks.back()->bindings()->lookup_local(name); -} - -// Look up a name in the global namespace. - -Named_object* -Gogo::lookup_global(const char* name) const -{ - return this->globals_->lookup(name); -} - -// Add an imported package. - -Package* -Gogo::add_imported_package(const std::string& real_name, - const std::string& alias_arg, - bool is_alias_exported, - const std::string& unique_prefix, - source_location location, - bool* padd_to_globals) -{ - // FIXME: Now that we compile packages as a whole, should we permit - // importing the current package? - if (this->package_name() == real_name - && this->unique_prefix() == unique_prefix) - { - *padd_to_globals = false; - if (!alias_arg.empty() && alias_arg != ".") - { - std::string alias = this->pack_hidden_name(alias_arg, - is_alias_exported); - this->package_->bindings()->add_package(alias, this->package_); - } - return this->package_; - } - else if (alias_arg == ".") - { - *padd_to_globals = true; - return this->register_package(real_name, unique_prefix, location); - } - else if (alias_arg == "_") - { - Package* ret = this->register_package(real_name, unique_prefix, location); - ret->set_uses_sink_alias(); - return ret; - } - else - { - *padd_to_globals = false; - std::string alias = alias_arg; - if (alias.empty()) - { - alias = real_name; - is_alias_exported = Lex::is_exported_name(alias); - } - alias = this->pack_hidden_name(alias, is_alias_exported); - Named_object* no = this->add_package(real_name, alias, unique_prefix, - location); - if (!no->is_package()) - return NULL; - return no->package_value(); - } -} - -// Add a package. - -Named_object* -Gogo::add_package(const std::string& real_name, const std::string& alias, - const std::string& unique_prefix, source_location location) -{ - gcc_assert(this->in_global_scope()); - - // Register the package. Note that we might have already seen it in - // an earlier import. - Package* package = this->register_package(real_name, unique_prefix, location); - - return this->package_->bindings()->add_package(alias, package); -} - -// Register a package. This package may or may not be imported. This -// returns the Package structure for the package, creating if it -// necessary. - -Package* -Gogo::register_package(const std::string& package_name, - const std::string& unique_prefix, - source_location location) -{ - gcc_assert(!unique_prefix.empty() && !package_name.empty()); - std::string name = unique_prefix + '.' + package_name; - Package* package = NULL; - std::pair ins = - this->packages_.insert(std::make_pair(name, package)); - if (!ins.second) - { - // We have seen this package name before. - package = ins.first->second; - gcc_assert(package != NULL); - gcc_assert(package->name() == package_name - && package->unique_prefix() == unique_prefix); - if (package->location() == UNKNOWN_LOCATION) - package->set_location(location); - } - else - { - // First time we have seen this package name. - package = new Package(package_name, unique_prefix, location); - gcc_assert(ins.first->second == NULL); - ins.first->second = package; - } - - return package; -} - -// Start compiling a function. - -Named_object* -Gogo::start_function(const std::string& name, Function_type* type, - bool add_method_to_type, source_location location) -{ - bool at_top_level = this->functions_.empty(); - - Block* block = new Block(NULL, location); - - Function* enclosing = (at_top_level - ? NULL - : this->functions_.back().function->func_value()); - - Function* function = new Function(type, enclosing, block, location); - - if (type->is_method()) - { - const Typed_identifier* receiver = type->receiver(); - Variable* this_param = new Variable(receiver->type(), NULL, false, - true, true, location); - std::string name = receiver->name(); - if (name.empty()) - { - // We need to give receivers a name since they wind up in - // DECL_ARGUMENTS. FIXME. - static unsigned int count; - char buf[50]; - snprintf(buf, sizeof buf, "r.%u", count); - ++count; - name = buf; - } - block->bindings()->add_variable(name, NULL, this_param); - } - - const Typed_identifier_list* parameters = type->parameters(); - bool is_varargs = type->is_varargs(); - if (parameters != NULL) - { - for (Typed_identifier_list::const_iterator p = parameters->begin(); - p != parameters->end(); - ++p) - { - Variable* param = new Variable(p->type(), NULL, false, true, false, - location); - if (is_varargs && p + 1 == parameters->end()) - param->set_is_varargs_parameter(); - - std::string name = p->name(); - if (name.empty() || Gogo::is_sink_name(name)) - { - // We need to give parameters a name since they wind up - // in DECL_ARGUMENTS. FIXME. - static unsigned int count; - char buf[50]; - snprintf(buf, sizeof buf, "p.%u", count); - ++count; - name = buf; - } - block->bindings()->add_variable(name, NULL, param); - } - } - - function->create_named_result_variables(); - - const std::string* pname; - std::string nested_name; - if (!name.empty()) - pname = &name; - else - { - // Invent a name for a nested function. - static int nested_count; - char buf[30]; - snprintf(buf, sizeof buf, ".$nested%d", nested_count); - ++nested_count; - nested_name = buf; - pname = &nested_name; - } - - Named_object* ret; - if (Gogo::is_sink_name(*pname)) - ret = Named_object::make_sink(); - else if (!type->is_method()) - { - ret = this->package_->bindings()->add_function(*pname, NULL, function); - if (!ret->is_function()) - { - // Redefinition error. - ret = Named_object::make_function(name, NULL, function); - } - } - else - { - if (!add_method_to_type) - ret = Named_object::make_function(name, NULL, function); - else - { - gcc_assert(at_top_level); - Type* rtype = type->receiver()->type(); - - // We want to look through the pointer created by the - // parser, without getting an error if the type is not yet - // defined. - if (rtype->classification() == Type::TYPE_POINTER) - rtype = rtype->points_to(); - - if (rtype->is_error_type()) - ret = Named_object::make_function(name, NULL, function); - else if (rtype->named_type() != NULL) - { - ret = rtype->named_type()->add_method(name, function); - if (!ret->is_function()) - { - // Redefinition error. - ret = Named_object::make_function(name, NULL, function); - } - } - else if (rtype->forward_declaration_type() != NULL) - { - Named_object* type_no = - rtype->forward_declaration_type()->named_object(); - if (type_no->is_unknown()) - { - // If we are seeing methods it really must be a - // type. Declare it as such. An alternative would - // be to support lists of methods for unknown - // expressions. Either way the error messages if - // this is not a type are going to get confusing. - Named_object* declared = - this->declare_package_type(type_no->name(), - type_no->location()); - gcc_assert(declared - == type_no->unknown_value()->real_named_object()); - } - ret = rtype->forward_declaration_type()->add_method(name, - function); - } - else - gcc_unreachable(); - } - this->package_->bindings()->add_method(ret); - } - - this->functions_.resize(this->functions_.size() + 1); - Open_function& of(this->functions_.back()); - of.function = ret; - of.blocks.push_back(block); - - if (!type->is_method() && Gogo::unpack_hidden_name(name) == "init") - { - this->init_functions_.push_back(ret); - this->need_init_fn_ = true; - } - - return ret; -} - -// Finish compiling a function. - -void -Gogo::finish_function(source_location location) -{ - this->finish_block(location); - gcc_assert(this->functions_.back().blocks.empty()); - this->functions_.pop_back(); -} - -// Return the current function. - -Named_object* -Gogo::current_function() const -{ - gcc_assert(!this->functions_.empty()); - return this->functions_.back().function; -} - -// Start a new block. - -void -Gogo::start_block(source_location location) -{ - gcc_assert(!this->functions_.empty()); - Block* block = new Block(this->current_block(), location); - this->functions_.back().blocks.push_back(block); -} - -// Finish a block. - -Block* -Gogo::finish_block(source_location location) -{ - gcc_assert(!this->functions_.empty()); - gcc_assert(!this->functions_.back().blocks.empty()); - Block* block = this->functions_.back().blocks.back(); - this->functions_.back().blocks.pop_back(); - block->set_end_location(location); - return block; -} - -// Add an unknown name. - -Named_object* -Gogo::add_unknown_name(const std::string& name, source_location location) -{ - return this->package_->bindings()->add_unknown_name(name, location); -} - -// Declare a function. - -Named_object* -Gogo::declare_function(const std::string& name, Function_type* type, - source_location location) -{ - if (!type->is_method()) - return this->current_bindings()->add_function_declaration(name, NULL, type, - location); - else - { - // We don't bother to add this to the list of global - // declarations. - Type* rtype = type->receiver()->type(); - - // We want to look through the pointer created by the - // parser, without getting an error if the type is not yet - // defined. - if (rtype->classification() == Type::TYPE_POINTER) - rtype = rtype->points_to(); - - if (rtype->is_error_type()) - return NULL; - else if (rtype->named_type() != NULL) - return rtype->named_type()->add_method_declaration(name, NULL, type, - location); - else if (rtype->forward_declaration_type() != NULL) - { - Forward_declaration_type* ftype = rtype->forward_declaration_type(); - return ftype->add_method_declaration(name, type, location); - } - else - gcc_unreachable(); - } -} - -// Add a label definition. - -Label* -Gogo::add_label_definition(const std::string& label_name, - source_location location) -{ - gcc_assert(!this->functions_.empty()); - Function* func = this->functions_.back().function->func_value(); - Label* label = func->add_label_definition(label_name, location); - this->add_statement(Statement::make_label_statement(label, location)); - return label; -} - -// Add a label reference. - -Label* -Gogo::add_label_reference(const std::string& label_name) -{ - gcc_assert(!this->functions_.empty()); - Function* func = this->functions_.back().function->func_value(); - return func->add_label_reference(label_name); -} - -// Add a statement. - -void -Gogo::add_statement(Statement* statement) -{ - gcc_assert(!this->functions_.empty() - && !this->functions_.back().blocks.empty()); - this->functions_.back().blocks.back()->add_statement(statement); -} - -// Add a block. - -void -Gogo::add_block(Block* block, source_location location) -{ - gcc_assert(!this->functions_.empty() - && !this->functions_.back().blocks.empty()); - Statement* statement = Statement::make_block_statement(block, location); - this->functions_.back().blocks.back()->add_statement(statement); -} - -// Add a constant. - -Named_object* -Gogo::add_constant(const Typed_identifier& tid, Expression* expr, - int iota_value) -{ - return this->current_bindings()->add_constant(tid, NULL, expr, iota_value); -} - -// Add a type. - -void -Gogo::add_type(const std::string& name, Type* type, source_location location) -{ - Named_object* no = this->current_bindings()->add_type(name, NULL, type, - location); - if (!this->in_global_scope()) - no->type_value()->set_in_function(this->functions_.back().function); -} - -// Add a named type. - -void -Gogo::add_named_type(Named_type* type) -{ - gcc_assert(this->in_global_scope()); - this->current_bindings()->add_named_type(type); -} - -// Declare a type. - -Named_object* -Gogo::declare_type(const std::string& name, source_location location) -{ - Bindings* bindings = this->current_bindings(); - Named_object* no = bindings->add_type_declaration(name, NULL, location); - if (!this->in_global_scope()) - { - Named_object* f = this->functions_.back().function; - no->type_declaration_value()->set_in_function(f); - } - return no; -} - -// Declare a type at the package level. - -Named_object* -Gogo::declare_package_type(const std::string& name, source_location location) -{ - return this->package_->bindings()->add_type_declaration(name, NULL, location); -} - -// Define a type which was already declared. - -void -Gogo::define_type(Named_object* no, Named_type* type) -{ - this->current_bindings()->define_type(no, type); -} - -// Add a variable. - -Named_object* -Gogo::add_variable(const std::string& name, Variable* variable) -{ - Named_object* no = this->current_bindings()->add_variable(name, NULL, - variable); - - // In a function the middle-end wants to see a DECL_EXPR node. - if (no != NULL - && no->is_variable() - && !no->var_value()->is_parameter() - && !this->functions_.empty()) - this->add_statement(Statement::make_variable_declaration(no)); - - return no; -} - -// Add a sink--a reference to the blank identifier _. - -Named_object* -Gogo::add_sink() -{ - return Named_object::make_sink(); -} - -// Add a named object. - -void -Gogo::add_named_object(Named_object* no) -{ - this->current_bindings()->add_named_object(no); -} - -// Record that we've seen an interface type. - -void -Gogo::record_interface_type(Interface_type* itype) -{ - this->interface_types_.push_back(itype); -} - -// Return a name for a thunk object. - -std::string -Gogo::thunk_name() -{ - static int thunk_count; - char thunk_name[50]; - snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count); - ++thunk_count; - return thunk_name; -} - -// Return whether a function is a thunk. - -bool -Gogo::is_thunk(const Named_object* no) -{ - return no->name().compare(0, 6, "$thunk") == 0; -} - -// Define the global names. We do this only after parsing all the -// input files, because the program might define the global names -// itself. - -void -Gogo::define_global_names() -{ - for (Bindings::const_declarations_iterator p = - this->globals_->begin_declarations(); - p != this->globals_->end_declarations(); - ++p) - { - Named_object* global_no = p->second; - std::string name(Gogo::pack_hidden_name(global_no->name(), false)); - Named_object* no = this->package_->bindings()->lookup(name); - if (no == NULL) - continue; - no = no->resolve(); - if (no->is_type_declaration()) - { - if (global_no->is_type()) - { - if (no->type_declaration_value()->has_methods()) - error_at(no->location(), - "may not define methods for global type"); - no->set_type_value(global_no->type_value()); - } - else - { - error_at(no->location(), "expected type"); - Type* errtype = Type::make_error_type(); - Named_object* err = Named_object::make_type("error", NULL, - errtype, - BUILTINS_LOCATION); - no->set_type_value(err->type_value()); - } - } - else if (no->is_unknown()) - no->unknown_value()->set_real_named_object(global_no); - } -} - -// Clear out names in file scope. - -void -Gogo::clear_file_scope() -{ - this->package_->bindings()->clear_file_scope(); - - // Warn about packages which were imported but not used. - for (Packages::iterator p = this->packages_.begin(); - p != this->packages_.end(); - ++p) - { - Package* package = p->second; - if (package != this->package_ - && package->is_imported() - && !package->used() - && !package->uses_sink_alias() - && !saw_errors()) - error_at(package->location(), "imported and not used: %s", - Gogo::message_name(package->name()).c_str()); - package->clear_is_imported(); - package->clear_uses_sink_alias(); - package->clear_used(); - } -} - -// Traverse the tree. - -void -Gogo::traverse(Traverse* traverse) -{ - // Traverse the current package first for consistency. The other - // packages will only contain imported types, constants, and - // declarations. - if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT) - return; - for (Packages::const_iterator p = this->packages_.begin(); - p != this->packages_.end(); - ++p) - { - if (p->second != this->package_) - { - if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT) - break; - } - } -} - -// Traversal class used to verify types. - -class Verify_types : public Traverse -{ - public: - Verify_types() - : Traverse(traverse_types) - { } - - int - type(Type*); -}; - -// Verify that a type is correct. - -int -Verify_types::type(Type* t) -{ - // Don't verify types defined in other packages. - Named_type* nt = t->named_type(); - if (nt != NULL && nt->named_object()->package() != NULL) - return TRAVERSE_SKIP_COMPONENTS; - - if (!t->verify()) - return TRAVERSE_SKIP_COMPONENTS; - return TRAVERSE_CONTINUE; -} - -// Verify that all types are correct. - -void -Gogo::verify_types() -{ - Verify_types traverse; - this->traverse(&traverse); -} - -// Traversal class used to lower parse tree. - -class Lower_parse_tree : public Traverse -{ - public: - Lower_parse_tree(Gogo* gogo, Named_object* function) - : Traverse(traverse_constants - | traverse_functions - | traverse_statements - | traverse_expressions), - gogo_(gogo), function_(function), iota_value_(-1) - { } - - int - constant(Named_object*, bool); - - int - function(Named_object*); - - int - statement(Block*, size_t* pindex, Statement*); - - int - expression(Expression**); - - private: - // General IR. - Gogo* gogo_; - // The function we are traversing. - Named_object* function_; - // Value to use for the predeclared constant iota. - int iota_value_; -}; - -// Lower constants. We handle constants specially so that we can set -// the right value for the predeclared constant iota. This works in -// conjunction with the way we lower Const_expression objects. - -int -Lower_parse_tree::constant(Named_object* no, bool) -{ - Named_constant* nc = no->const_value(); - - // We can recursively a constant if the initializer expression - // manages to refer to itself. - if (nc->lowering()) - return TRAVERSE_CONTINUE; - nc->set_lowering(); - - gcc_assert(this->iota_value_ == -1); - this->iota_value_ = nc->iota_value(); - nc->traverse_expression(this); - this->iota_value_ = -1; - - nc->clear_lowering(); - - // We will traverse the expression a second time, but that will be - // fast. - - return TRAVERSE_CONTINUE; -} - -// Lower function closure types. Record the function while lowering -// it, so that we can pass it down when lowering an expression. - -int -Lower_parse_tree::function(Named_object* no) -{ - no->func_value()->set_closure_type(); - - gcc_assert(this->function_ == NULL); - this->function_ = no; - int t = no->func_value()->traverse(this); - this->function_ = NULL; - - if (t == TRAVERSE_EXIT) - return t; - return TRAVERSE_SKIP_COMPONENTS; -} - -// Lower statement parse trees. - -int -Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig) -{ - // Lower the expressions first. - int t = sorig->traverse_contents(this); - if (t == TRAVERSE_EXIT) - return t; - - // Keep lowering until nothing changes. - Statement* s = sorig; - while (true) - { - Statement* snew = s->lower(this->gogo_, block); - if (snew == s) - break; - s = snew; - t = s->traverse_contents(this); - if (t == TRAVERSE_EXIT) - return t; - } - - if (s != sorig) - block->replace_statement(*pindex, s); - - return TRAVERSE_SKIP_COMPONENTS; -} - -// Lower expression parse trees. - -int -Lower_parse_tree::expression(Expression** pexpr) -{ - // We have to lower all subexpressions first, so that we can get - // their type if necessary. This is awkward, because we don't have - // a postorder traversal pass. - if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - // Keep lowering until nothing changes. - while (true) - { - Expression* e = *pexpr; - Expression* enew = e->lower(this->gogo_, this->function_, - this->iota_value_); - if (enew == e) - break; - *pexpr = enew; - } - return TRAVERSE_SKIP_COMPONENTS; -} - -// Lower the parse tree. This is called after the parse is complete, -// when all names should be resolved. - -void -Gogo::lower_parse_tree() -{ - Lower_parse_tree lower_parse_tree(this, NULL); - this->traverse(&lower_parse_tree); -} - -// Lower an expression. - -void -Gogo::lower_expression(Named_object* function, Expression** pexpr) -{ - Lower_parse_tree lower_parse_tree(this, function); - lower_parse_tree.expression(pexpr); -} - -// Lower a constant. This is called when lowering a reference to a -// constant. We have to make sure that the constant has already been -// lowered. - -void -Gogo::lower_constant(Named_object* no) -{ - gcc_assert(no->is_const()); - Lower_parse_tree lower(this, NULL); - lower.constant(no, false); -} - -// Look for interface types to finalize methods of inherited -// interfaces. - -class Finalize_methods : public Traverse -{ - public: - Finalize_methods(Gogo* gogo) - : Traverse(traverse_types), - gogo_(gogo) - { } - - int - type(Type*); - - private: - Gogo* gogo_; -}; - -// Finalize the methods of an interface type. - -int -Finalize_methods::type(Type* t) -{ - // Check the classification so that we don't finalize the methods - // twice for a named interface type. - switch (t->classification()) - { - case Type::TYPE_INTERFACE: - t->interface_type()->finalize_methods(); - break; - - case Type::TYPE_NAMED: - { - // We have to finalize the methods of the real type first. - // But if the real type is a struct type, then we only want to - // finalize the methods of the field types, not of the struct - // type itself. We don't want to add methods to the struct, - // since it has a name. - Type* rt = t->named_type()->real_type(); - if (rt->classification() != Type::TYPE_STRUCT) - { - if (Type::traverse(rt, this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - else - { - if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - - t->named_type()->finalize_methods(this->gogo_); - - return TRAVERSE_SKIP_COMPONENTS; - } - - case Type::TYPE_STRUCT: - t->struct_type()->finalize_methods(this->gogo_); - break; - - default: - break; - } - - return TRAVERSE_CONTINUE; -} - -// Finalize method lists and build stub methods for types. - -void -Gogo::finalize_methods() -{ - Finalize_methods finalize(this); - this->traverse(&finalize); -} - -// Set types for unspecified variables and constants. - -void -Gogo::determine_types() -{ - Bindings* bindings = this->current_bindings(); - for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); - p != bindings->end_definitions(); - ++p) - { - if ((*p)->is_function()) - (*p)->func_value()->determine_types(); - else if ((*p)->is_variable()) - (*p)->var_value()->determine_type(); - else if ((*p)->is_const()) - (*p)->const_value()->determine_type(); - - // See if a variable requires us to build an initialization - // function. We know that we will see all global variables - // here. - if (!this->need_init_fn_ && (*p)->is_variable()) - { - Variable* variable = (*p)->var_value(); - - // If this is a global variable which requires runtime - // initialization, we need an initialization function. - if (!variable->is_global() || variable->init() == NULL) - ; - else if (variable->type()->interface_type() != NULL) - this->need_init_fn_ = true; - else if (variable->init()->is_constant()) - ; - else if (!variable->init()->is_composite_literal()) - this->need_init_fn_ = true; - else if (variable->init()->is_nonconstant_composite_literal()) - this->need_init_fn_ = true; - - // If this is a global variable which holds a pointer value, - // then we need an initialization function to register it as a - // GC root. - if (variable->is_global() && variable->type()->has_pointer()) - this->need_init_fn_ = true; - } - } - - // Determine the types of constants in packages. - for (Packages::const_iterator p = this->packages_.begin(); - p != this->packages_.end(); - ++p) - p->second->determine_types(); -} - -// Traversal class used for type checking. - -class Check_types_traverse : public Traverse -{ - public: - Check_types_traverse(Gogo* gogo) - : Traverse(traverse_variables - | traverse_constants - | traverse_statements - | traverse_expressions), - gogo_(gogo) - { } - - int - variable(Named_object*); - - int - constant(Named_object*, bool); - - int - statement(Block*, size_t* pindex, Statement*); - - int - expression(Expression**); - - private: - // General IR. - Gogo* gogo_; -}; - -// Check that a variable initializer has the right type. - -int -Check_types_traverse::variable(Named_object* named_object) -{ - if (named_object->is_variable()) - { - Variable* var = named_object->var_value(); - Expression* init = var->init(); - std::string reason; - if (init != NULL - && !Type::are_assignable(var->type(), init->type(), &reason)) - { - if (reason.empty()) - error_at(var->location(), "incompatible type in initialization"); - else - error_at(var->location(), - "incompatible type in initialization (%s)", - reason.c_str()); - var->clear_init(); - } - } - return TRAVERSE_CONTINUE; -} - -// Check that a constant initializer has the right type. - -int -Check_types_traverse::constant(Named_object* named_object, bool) -{ - Named_constant* constant = named_object->const_value(); - Type* ctype = constant->type(); - if (ctype->integer_type() == NULL - && ctype->float_type() == NULL - && ctype->complex_type() == NULL - && !ctype->is_boolean_type() - && !ctype->is_string_type()) - { - error_at(constant->location(), "invalid constant type"); - constant->set_error(); - } - else if (!constant->expr()->is_constant()) - { - error_at(constant->expr()->location(), "expression is not constant"); - constant->set_error(); - } - else if (!Type::are_assignable(constant->type(), constant->expr()->type(), - NULL)) - { - error_at(constant->location(), - "initialization expression has wrong type"); - constant->set_error(); - } - return TRAVERSE_CONTINUE; -} - -// Check that types are valid in a statement. - -int -Check_types_traverse::statement(Block*, size_t*, Statement* s) -{ - s->check_types(this->gogo_); - return TRAVERSE_CONTINUE; -} - -// Check that types are valid in an expression. - -int -Check_types_traverse::expression(Expression** expr) -{ - (*expr)->check_types(this->gogo_); - return TRAVERSE_CONTINUE; -} - -// Check that types are valid. - -void -Gogo::check_types() -{ - Check_types_traverse traverse(this); - this->traverse(&traverse); -} - -// Check the types in a single block. - -void -Gogo::check_types_in_block(Block* block) -{ - Check_types_traverse traverse(this); - block->traverse(&traverse); -} - -// A traversal class used to find a single shortcut operator within an -// expression. - -class Find_shortcut : public Traverse -{ - public: - Find_shortcut() - : Traverse(traverse_blocks - | traverse_statements - | traverse_expressions), - found_(NULL) - { } - - // A pointer to the expression which was found, or NULL if none was - // found. - Expression** - found() const - { return this->found_; } - - protected: - int - block(Block*) - { return TRAVERSE_SKIP_COMPONENTS; } - - int - statement(Block*, size_t*, Statement*) - { return TRAVERSE_SKIP_COMPONENTS; } - - int - expression(Expression**); - - private: - Expression** found_; -}; - -// Find a shortcut expression. - -int -Find_shortcut::expression(Expression** pexpr) -{ - Expression* expr = *pexpr; - Binary_expression* be = expr->binary_expression(); - if (be == NULL) - return TRAVERSE_CONTINUE; - Operator op = be->op(); - if (op != OPERATOR_OROR && op != OPERATOR_ANDAND) - return TRAVERSE_CONTINUE; - gcc_assert(this->found_ == NULL); - this->found_ = pexpr; - return TRAVERSE_EXIT; -} - -// A traversal class used to turn shortcut operators into explicit if -// statements. - -class Shortcuts : public Traverse -{ - public: - Shortcuts() - : Traverse(traverse_variables - | traverse_statements) - { } - - protected: - int - variable(Named_object*); - - int - statement(Block*, size_t*, Statement*); - - private: - // Convert a shortcut operator. - Statement* - convert_shortcut(Block* enclosing, Expression** pshortcut); -}; - -// Remove shortcut operators in a single statement. - -int -Shortcuts::statement(Block* block, size_t* pindex, Statement* s) -{ - // FIXME: This approach doesn't work for switch statements, because - // we add the new statements before the whole switch when we need to - // instead add them just before the switch expression. The right - // fix is probably to lower switch statements with nonconstant cases - // to a series of conditionals. - if (s->switch_statement() != NULL) - return TRAVERSE_CONTINUE; - - while (true) - { - Find_shortcut find_shortcut; - - // If S is a variable declaration, then ordinary traversal won't - // do anything. We want to explicitly traverse the - // initialization expression if there is one. - Variable_declaration_statement* vds = s->variable_declaration_statement(); - Expression* init = NULL; - if (vds == NULL) - s->traverse_contents(&find_shortcut); - else - { - init = vds->var()->var_value()->init(); - if (init == NULL) - return TRAVERSE_CONTINUE; - init->traverse(&init, &find_shortcut); - } - Expression** pshortcut = find_shortcut.found(); - if (pshortcut == NULL) - return TRAVERSE_CONTINUE; - - Statement* snew = this->convert_shortcut(block, pshortcut); - block->insert_statement_before(*pindex, snew); - ++*pindex; - - if (pshortcut == &init) - vds->var()->var_value()->set_init(init); - } -} - -// Remove shortcut operators in the initializer of a global variable. - -int -Shortcuts::variable(Named_object* no) -{ - if (no->is_result_variable()) - return TRAVERSE_CONTINUE; - Variable* var = no->var_value(); - Expression* init = var->init(); - if (!var->is_global() || init == NULL) - return TRAVERSE_CONTINUE; - - while (true) - { - Find_shortcut find_shortcut; - init->traverse(&init, &find_shortcut); - Expression** pshortcut = find_shortcut.found(); - if (pshortcut == NULL) - return TRAVERSE_CONTINUE; - - Statement* snew = this->convert_shortcut(NULL, pshortcut); - var->add_preinit_statement(snew); - if (pshortcut == &init) - var->set_init(init); - } -} - -// Given an expression which uses a shortcut operator, return a -// statement which implements it, and update *PSHORTCUT accordingly. - -Statement* -Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut) -{ - Binary_expression* shortcut = (*pshortcut)->binary_expression(); - Expression* left = shortcut->left(); - Expression* right = shortcut->right(); - source_location loc = shortcut->location(); - - Block* retblock = new Block(enclosing, loc); - retblock->set_end_location(loc); - - Temporary_statement* ts = Statement::make_temporary(Type::make_boolean_type(), - left, loc); - retblock->add_statement(ts); - - Block* block = new Block(retblock, loc); - block->set_end_location(loc); - Expression* tmpref = Expression::make_temporary_reference(ts, loc); - Statement* assign = Statement::make_assignment(tmpref, right, loc); - block->add_statement(assign); - - Expression* cond = Expression::make_temporary_reference(ts, loc); - if (shortcut->binary_expression()->op() == OPERATOR_OROR) - cond = Expression::make_unary(OPERATOR_NOT, cond, loc); - - Statement* if_statement = Statement::make_if_statement(cond, block, NULL, - loc); - retblock->add_statement(if_statement); - - *pshortcut = Expression::make_temporary_reference(ts, loc); - - delete shortcut; - - // Now convert any shortcut operators in LEFT and RIGHT. - Shortcuts shortcuts; - retblock->traverse(&shortcuts); - - return Statement::make_block_statement(retblock, loc); -} - -// Turn shortcut operators into explicit if statements. Doing this -// considerably simplifies the order of evaluation rules. - -void -Gogo::remove_shortcuts() -{ - Shortcuts shortcuts; - this->traverse(&shortcuts); -} - -// A traversal class which finds all the expressions which must be -// evaluated in order within a statement or larger expression. This -// is used to implement the rules about order of evaluation. - -class Find_eval_ordering : public Traverse -{ - private: - typedef std::vector Expression_pointers; - - public: - Find_eval_ordering() - : Traverse(traverse_blocks - | traverse_statements - | traverse_expressions), - exprs_() - { } - - size_t - size() const - { return this->exprs_.size(); } - - typedef Expression_pointers::const_iterator const_iterator; - - const_iterator - begin() const - { return this->exprs_.begin(); } - - const_iterator - end() const - { return this->exprs_.end(); } - - protected: - int - block(Block*) - { return TRAVERSE_SKIP_COMPONENTS; } - - int - statement(Block*, size_t*, Statement*) - { return TRAVERSE_SKIP_COMPONENTS; } - - int - expression(Expression**); - - private: - // A list of pointers to expressions with side-effects. - Expression_pointers exprs_; -}; - -// If an expression must be evaluated in order, put it on the list. - -int -Find_eval_ordering::expression(Expression** expression_pointer) -{ - // We have to look at subexpressions before this one. - if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if ((*expression_pointer)->must_eval_in_order()) - this->exprs_.push_back(expression_pointer); - return TRAVERSE_SKIP_COMPONENTS; -} - -// A traversal class for ordering evaluations. - -class Order_eval : public Traverse -{ - public: - Order_eval() - : Traverse(traverse_variables - | traverse_statements) - { } - - int - variable(Named_object*); - - int - statement(Block*, size_t*, Statement*); -}; - -// Implement the order of evaluation rules for a statement. - -int -Order_eval::statement(Block* block, size_t* pindex, Statement* s) -{ - // FIXME: This approach doesn't work for switch statements, because - // we add the new statements before the whole switch when we need to - // instead add them just before the switch expression. The right - // fix is probably to lower switch statements with nonconstant cases - // to a series of conditionals. - if (s->switch_statement() != NULL) - return TRAVERSE_CONTINUE; - - Find_eval_ordering find_eval_ordering; - - // If S is a variable declaration, then ordinary traversal won't do - // anything. We want to explicitly traverse the initialization - // expression if there is one. - Variable_declaration_statement* vds = s->variable_declaration_statement(); - Expression* init = NULL; - Expression* orig_init = NULL; - if (vds == NULL) - s->traverse_contents(&find_eval_ordering); - else - { - init = vds->var()->var_value()->init(); - if (init == NULL) - return TRAVERSE_CONTINUE; - orig_init = init; - - // It might seem that this could be - // init->traverse_subexpressions. Unfortunately that can fail - // in a case like - // var err os.Error - // newvar, err := call(arg()) - // Here newvar will have an init of call result 0 of - // call(arg()). If we only traverse subexpressions, we will - // only find arg(), and we won't bother to move anything out. - // Then we get to the assignment to err, we will traverse the - // whole statement, and this time we will find both call() and - // arg(), and so we will move them out. This will cause them to - // be put into temporary variables before the assignment to err - // but after the declaration of newvar. To avoid that problem, - // we traverse the entire expression here. - Expression::traverse(&init, &find_eval_ordering); - } - - if (find_eval_ordering.size() <= 1) - { - // If there is only one expression with a side-effect, we can - // leave it in place. - return TRAVERSE_CONTINUE; - } - - bool is_thunk = s->thunk_statement() != NULL; - for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin(); - p != find_eval_ordering.end(); - ++p) - { - Expression** pexpr = *p; - - // If the last expression is a send or receive expression, we - // may be ignoring the value; we don't want to evaluate it - // early. - if (p + 1 == find_eval_ordering.end() - && ((*pexpr)->classification() == Expression::EXPRESSION_SEND - || (*pexpr)->classification() == Expression::EXPRESSION_RECEIVE)) - break; - - // The last expression in a thunk will be the call passed to go - // or defer, which we must not evaluate early. - if (is_thunk && p + 1 == find_eval_ordering.end()) - break; - - source_location loc = (*pexpr)->location(); - Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc); - block->insert_statement_before(*pindex, ts); - ++*pindex; - - *pexpr = Expression::make_temporary_reference(ts, loc); - } - - if (init != orig_init) - vds->var()->var_value()->set_init(init); - - return TRAVERSE_CONTINUE; -} - -// Implement the order of evaluation rules for the initializer of a -// global variable. - -int -Order_eval::variable(Named_object* no) -{ - if (no->is_result_variable()) - return TRAVERSE_CONTINUE; - Variable* var = no->var_value(); - Expression* init = var->init(); - if (!var->is_global() || init == NULL) - return TRAVERSE_CONTINUE; - - Find_eval_ordering find_eval_ordering; - init->traverse_subexpressions(&find_eval_ordering); - - if (find_eval_ordering.size() <= 1) - { - // If there is only one expression with a side-effect, we can - // leave it in place. - return TRAVERSE_SKIP_COMPONENTS; - } - - for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin(); - p != find_eval_ordering.end(); - ++p) - { - Expression** pexpr = *p; - source_location loc = (*pexpr)->location(); - Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc); - var->add_preinit_statement(ts); - *pexpr = Expression::make_temporary_reference(ts, loc); - } - - return TRAVERSE_SKIP_COMPONENTS; -} - -// Use temporary variables to implement the order of evaluation rules. - -void -Gogo::order_evaluations() -{ - Order_eval order_eval; - this->traverse(&order_eval); -} - -// Traversal to convert calls to the predeclared recover function to -// pass in an argument indicating whether it can recover from a panic -// or not. - -class Convert_recover : public Traverse -{ - public: - Convert_recover(Named_object* arg) - : Traverse(traverse_expressions), - arg_(arg) - { } - - protected: - int - expression(Expression**); - - private: - // The argument to pass to the function. - Named_object* arg_; -}; - -// Convert calls to recover. - -int -Convert_recover::expression(Expression** pp) -{ - Call_expression* ce = (*pp)->call_expression(); - if (ce != NULL && ce->is_recover_call()) - ce->set_recover_arg(Expression::make_var_reference(this->arg_, - ce->location())); - return TRAVERSE_CONTINUE; -} - -// Traversal for build_recover_thunks. - -class Build_recover_thunks : public Traverse -{ - public: - Build_recover_thunks(Gogo* gogo) - : Traverse(traverse_functions), - gogo_(gogo) - { } - - int - function(Named_object*); - - private: - Expression* - can_recover_arg(source_location); - - // General IR. - Gogo* gogo_; -}; - -// If this function calls recover, turn it into a thunk. - -int -Build_recover_thunks::function(Named_object* orig_no) -{ - Function* orig_func = orig_no->func_value(); - if (!orig_func->calls_recover() - || orig_func->is_recover_thunk() - || orig_func->has_recover_thunk()) - return TRAVERSE_CONTINUE; - - Gogo* gogo = this->gogo_; - source_location location = orig_func->location(); - - static int count; - char buf[50]; - - Function_type* orig_fntype = orig_func->type(); - Typed_identifier_list* new_params = new Typed_identifier_list(); - std::string receiver_name; - if (orig_fntype->is_method()) - { - const Typed_identifier* receiver = orig_fntype->receiver(); - snprintf(buf, sizeof buf, "rt.%u", count); - ++count; - receiver_name = buf; - new_params->push_back(Typed_identifier(receiver_name, receiver->type(), - receiver->location())); - } - const Typed_identifier_list* orig_params = orig_fntype->parameters(); - if (orig_params != NULL && !orig_params->empty()) - { - for (Typed_identifier_list::const_iterator p = orig_params->begin(); - p != orig_params->end(); - ++p) - { - snprintf(buf, sizeof buf, "pt.%u", count); - ++count; - new_params->push_back(Typed_identifier(buf, p->type(), - p->location())); - } - } - snprintf(buf, sizeof buf, "pr.%u", count); - ++count; - std::string can_recover_name = buf; - new_params->push_back(Typed_identifier(can_recover_name, - Type::make_boolean_type(), - orig_fntype->location())); - - const Typed_identifier_list* orig_results = orig_fntype->results(); - Typed_identifier_list* new_results; - if (orig_results == NULL || orig_results->empty()) - new_results = NULL; - else - { - new_results = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator p = orig_results->begin(); - p != orig_results->end(); - ++p) - new_results->push_back(*p); - } - - Function_type *new_fntype = Type::make_function_type(NULL, new_params, - new_results, - orig_fntype->location()); - if (orig_fntype->is_varargs()) - new_fntype->set_is_varargs(); - - std::string name = orig_no->name() + "$recover"; - Named_object *new_no = gogo->start_function(name, new_fntype, false, - location); - Function *new_func = new_no->func_value(); - if (orig_func->enclosing() != NULL) - new_func->set_enclosing(orig_func->enclosing()); - - // We build the code for the original function attached to the new - // function, and then swap the original and new function bodies. - // This means that existing references to the original function will - // then refer to the new function. That makes this code a little - // confusing, in that the reference to NEW_NO really refers to the - // other function, not the one we are building. - - Expression* closure = NULL; - if (orig_func->needs_closure()) - { - Named_object* orig_closure_no = orig_func->closure_var(); - Variable* orig_closure_var = orig_closure_no->var_value(); - Variable* new_var = new Variable(orig_closure_var->type(), NULL, false, - true, false, location); - snprintf(buf, sizeof buf, "closure.%u", count); - ++count; - Named_object* new_closure_no = Named_object::make_variable(buf, NULL, - new_var); - new_func->set_closure_var(new_closure_no); - closure = Expression::make_var_reference(new_closure_no, location); - } - - Expression* fn = Expression::make_func_reference(new_no, closure, location); - - Expression_list* args = new Expression_list(); - if (orig_fntype->is_method()) - { - Named_object* rec_no = gogo->lookup(receiver_name, NULL); - gcc_assert(rec_no != NULL - && rec_no->is_variable() - && rec_no->var_value()->is_parameter()); - args->push_back(Expression::make_var_reference(rec_no, location)); - } - if (new_params != NULL) - { - // Note that we skip the last parameter, which is the boolean - // indicating whether recover can succed. - for (Typed_identifier_list::const_iterator p = new_params->begin(); - p + 1 != new_params->end(); - ++p) - { - Named_object* p_no = gogo->lookup(p->name(), NULL); - gcc_assert(p_no != NULL - && p_no->is_variable() - && p_no->var_value()->is_parameter()); - args->push_back(Expression::make_var_reference(p_no, location)); - } - } - args->push_back(this->can_recover_arg(location)); - - Expression* call = Expression::make_call(fn, args, false, location); - - Statement* s; - if (orig_fntype->results() == NULL || orig_fntype->results()->empty()) - s = Statement::make_statement(call); - else - { - Expression_list* vals = new Expression_list(); - vals->push_back(call); - s = Statement::make_return_statement(new_func->type()->results(), - vals, location); - } - s->determine_types(); - gogo->add_statement(s); - - gogo->finish_function(location); - - // Swap the function bodies and types. - new_func->swap_for_recover(orig_func); - orig_func->set_is_recover_thunk(); - new_func->set_calls_recover(); - new_func->set_has_recover_thunk(); - - Bindings* orig_bindings = orig_func->block()->bindings(); - Bindings* new_bindings = new_func->block()->bindings(); - if (orig_fntype->is_method()) - { - // We changed the receiver to be a regular parameter. We have - // to update the binding accordingly in both functions. - Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name); - gcc_assert(orig_rec_no != NULL - && orig_rec_no->is_variable() - && !orig_rec_no->var_value()->is_receiver()); - orig_rec_no->var_value()->set_is_receiver(); - - Named_object* new_rec_no = new_bindings->lookup_local(receiver_name); - gcc_assert(new_rec_no != NULL - && new_rec_no->is_variable() - && !new_rec_no->var_value()->is_receiver()); - new_rec_no->var_value()->set_is_not_receiver(); - } - - // Because we flipped blocks but not types, the can_recover - // parameter appears in the (now) old bindings as a parameter. - // Change it to a local variable, whereupon it will be discarded. - Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name); - gcc_assert(can_recover_no != NULL - && can_recover_no->is_variable() - && can_recover_no->var_value()->is_parameter()); - orig_bindings->remove_binding(can_recover_no); - - // Add the can_recover argument to the (now) new bindings, and - // attach it to any recover statements. - Variable* can_recover_var = new Variable(Type::make_boolean_type(), NULL, - false, true, false, location); - can_recover_no = new_bindings->add_variable(can_recover_name, NULL, - can_recover_var); - Convert_recover convert_recover(can_recover_no); - new_func->traverse(&convert_recover); - - return TRAVERSE_CONTINUE; -} - -// Return the expression to pass for the .can_recover parameter to the -// new function. This indicates whether a call to recover may return -// non-nil. The expression is -// __go_can_recover(__builtin_return_address()). - -Expression* -Build_recover_thunks::can_recover_arg(source_location location) -{ - static Named_object* builtin_return_address; - if (builtin_return_address == NULL) - { - const source_location bloc = BUILTINS_LOCATION; - - Typed_identifier_list* param_types = new Typed_identifier_list(); - Type* uint_type = Type::lookup_integer_type("uint"); - param_types->push_back(Typed_identifier("l", uint_type, bloc)); - - Typed_identifier_list* return_types = new Typed_identifier_list(); - Type* voidptr_type = Type::make_pointer_type(Type::make_void_type()); - return_types->push_back(Typed_identifier("", voidptr_type, bloc)); - - Function_type* fntype = Type::make_function_type(NULL, param_types, - return_types, bloc); - builtin_return_address = - Named_object::make_function_declaration("__builtin_return_address", - NULL, fntype, bloc); - const char* n = "__builtin_return_address"; - builtin_return_address->func_declaration_value()->set_asm_name(n); - } - - static Named_object* can_recover; - if (can_recover == NULL) - { - const source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - Type* voidptr_type = Type::make_pointer_type(Type::make_void_type()); - param_types->push_back(Typed_identifier("a", voidptr_type, bloc)); - Type* boolean_type = Type::make_boolean_type(); - Typed_identifier_list* results = new Typed_identifier_list(); - results->push_back(Typed_identifier("", boolean_type, bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, - results, bloc); - can_recover = Named_object::make_function_declaration("__go_can_recover", - NULL, fntype, - bloc); - can_recover->func_declaration_value()->set_asm_name("__go_can_recover"); - } - - Expression* fn = Expression::make_func_reference(builtin_return_address, - NULL, location); - - mpz_t zval; - mpz_init_set_ui(zval, 0UL); - Expression* zexpr = Expression::make_integer(&zval, NULL, location); - mpz_clear(zval); - Expression_list *args = new Expression_list(); - args->push_back(zexpr); - - Expression* call = Expression::make_call(fn, args, false, location); - - args = new Expression_list(); - args->push_back(call); - - fn = Expression::make_func_reference(can_recover, NULL, location); - return Expression::make_call(fn, args, false, location); -} - -// Build thunks for functions which call recover. We build a new -// function with an extra parameter, which is whether a call to -// recover can succeed. We then move the body of this function to -// that one. We then turn this function into a thunk which calls the -// new one, passing the value of -// __go_can_recover(__builtin_return_address()). The function will be -// marked as not splitting the stack. This will cooperate with the -// implementation of defer to make recover do the right thing. - -void -Gogo::build_recover_thunks() -{ - Build_recover_thunks build_recover_thunks(this); - this->traverse(&build_recover_thunks); -} - -// Look for named types to see whether we need to create an interface -// method table. - -class Build_method_tables : public Traverse -{ - public: - Build_method_tables(Gogo* gogo, - const std::vector& interfaces) - : Traverse(traverse_types), - gogo_(gogo), interfaces_(interfaces) - { } - - int - type(Type*); - - private: - // The IR. - Gogo* gogo_; - // A list of locally defined interfaces which have hidden methods. - const std::vector& interfaces_; -}; - -// Build all required interface method tables for types. We need to -// ensure that we have an interface method table for every interface -// which has a hidden method, for every named type which implements -// that interface. Normally we can just build interface method tables -// as we need them. However, in some cases we can require an -// interface method table for an interface defined in a different -// package for a type defined in that package. If that interface and -// type both use a hidden method, that is OK. However, we will not be -// able to build that interface method table when we need it, because -// the type's hidden method will be static. So we have to build it -// here, and just refer it from other packages as needed. - -void -Gogo::build_interface_method_tables() -{ - std::vector hidden_interfaces; - hidden_interfaces.reserve(this->interface_types_.size()); - for (std::vector::const_iterator pi = - this->interface_types_.begin(); - pi != this->interface_types_.end(); - ++pi) - { - const Typed_identifier_list* methods = (*pi)->methods(); - if (methods == NULL) - continue; - for (Typed_identifier_list::const_iterator pm = methods->begin(); - pm != methods->end(); - ++pm) - { - if (Gogo::is_hidden_name(pm->name())) - { - hidden_interfaces.push_back(*pi); - break; - } - } - } - - if (!hidden_interfaces.empty()) - { - // Now traverse the tree looking for all named types. - Build_method_tables bmt(this, hidden_interfaces); - this->traverse(&bmt); - } - - // We no longer need the list of interfaces. - - this->interface_types_.clear(); -} - -// This is called for each type. For a named type, for each of the -// interfaces with hidden methods that it implements, create the -// method table. - -int -Build_method_tables::type(Type* type) -{ - Named_type* nt = type->named_type(); - if (nt != NULL) - { - for (std::vector::const_iterator p = - this->interfaces_.begin(); - p != this->interfaces_.end(); - ++p) - { - // We ask whether a pointer to the named type implements the - // interface, because a pointer can implement more methods - // than a value. - if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL)) - { - nt->interface_method_table(this->gogo_, *p, false); - nt->interface_method_table(this->gogo_, *p, true); - } - } - } - return TRAVERSE_CONTINUE; -} - -// Traversal class used to check for return statements. - -class Check_return_statements_traverse : public Traverse -{ - public: - Check_return_statements_traverse() - : Traverse(traverse_functions) - { } - - int - function(Named_object*); -}; - -// Check that a function has a return statement if it needs one. - -int -Check_return_statements_traverse::function(Named_object* no) -{ - Function* func = no->func_value(); - const Function_type* fntype = func->type(); - const Typed_identifier_list* results = fntype->results(); - - // We only need a return statement if there is a return value. - if (results == NULL || results->empty()) - return TRAVERSE_CONTINUE; - - if (func->block()->may_fall_through()) - error_at(func->location(), "control reaches end of non-void function"); - - return TRAVERSE_CONTINUE; -} - -// Check return statements. - -void -Gogo::check_return_statements() -{ - Check_return_statements_traverse traverse; - this->traverse(&traverse); -} - -// Get the unique prefix to use before all exported symbols. This -// must be unique across the entire link. - -const std::string& -Gogo::unique_prefix() const -{ - gcc_assert(!this->unique_prefix_.empty()); - return this->unique_prefix_; -} - -// Set the unique prefix to use before all exported symbols. This -// comes from the command line option -fgo-prefix=XXX. - -void -Gogo::set_unique_prefix(const std::string& arg) -{ - gcc_assert(this->unique_prefix_.empty()); - this->unique_prefix_ = arg; -} - -// Work out the package priority. It is one more than the maximum -// priority of an imported package. - -int -Gogo::package_priority() const -{ - int priority = 0; - for (Packages::const_iterator p = this->packages_.begin(); - p != this->packages_.end(); - ++p) - if (p->second->priority() > priority) - priority = p->second->priority(); - return priority + 1; -} - -// Export identifiers as requested. - -void -Gogo::do_exports() -{ - // For now we always stream to a section. Later we may want to - // support streaming to a separate file. - Stream_to_section stream; - - Export exp(&stream); - exp.register_builtin_types(this); - exp.export_globals(this->package_name(), - this->unique_prefix(), - this->package_priority(), - (this->need_init_fn_ && this->package_name() != "main" - ? this->get_init_fn_name() - : ""), - this->imported_init_fns_, - this->package_->bindings()); -} - -// Class Function. - -Function::Function(Function_type* type, Function* enclosing, Block* block, - source_location location) - : type_(type), enclosing_(enclosing), named_results_(NULL), - closure_var_(NULL), block_(block), location_(location), fndecl_(NULL), - defer_stack_(NULL), calls_recover_(false), is_recover_thunk_(false), - has_recover_thunk_(false) -{ -} - -// Create the named result variables. - -void -Function::create_named_result_variables() -{ - const Typed_identifier_list* results = this->type_->results(); - if (results == NULL - || results->empty() - || results->front().name().empty()) - return; - - this->named_results_ = new Named_results(); - this->named_results_->reserve(results->size()); - - Block* block = this->block_; - int index = 0; - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p, ++index) - { - Result_variable* result = new Result_variable(p->type(), this, - index); - Named_object* no = block->bindings()->add_result_variable(p->name(), - result); - this->named_results_->push_back(no); - } -} - -// Return the closure variable, creating it if necessary. - -Named_object* -Function::closure_var() -{ - if (this->closure_var_ == NULL) - { - // We don't know the type of the variable yet. We add fields as - // we find them. - source_location loc = this->type_->location(); - Struct_field_list* sfl = new Struct_field_list; - Type* struct_type = Type::make_struct_type(sfl, loc); - Variable* var = new Variable(Type::make_pointer_type(struct_type), - NULL, false, true, false, loc); - this->closure_var_ = Named_object::make_variable("closure", NULL, var); - // Note that the new variable is not in any binding contour. - } - return this->closure_var_; -} - -// Set the type of the closure variable. - -void -Function::set_closure_type() -{ - if (this->closure_var_ == NULL) - return; - Named_object* closure = this->closure_var_; - Struct_type* st = closure->var_value()->type()->deref()->struct_type(); - unsigned int index = 0; - for (Closure_fields::const_iterator p = this->closure_fields_.begin(); - p != this->closure_fields_.end(); - ++p, ++index) - { - Named_object* no = p->first; - char buf[20]; - snprintf(buf, sizeof buf, "%u", index); - std::string n = no->name() + buf; - Type* var_type; - if (no->is_variable()) - var_type = no->var_value()->type(); - else - var_type = no->result_var_value()->type(); - Type* field_type = Type::make_pointer_type(var_type); - st->push_field(Struct_field(Typed_identifier(n, field_type, p->second))); - } -} - -// Return whether this function is a method. - -bool -Function::is_method() const -{ - return this->type_->is_method(); -} - -// Add a label definition. - -Label* -Function::add_label_definition(const std::string& label_name, - source_location location) -{ - Label* lnull = NULL; - std::pair ins = - this->labels_.insert(std::make_pair(label_name, lnull)); - if (ins.second) - { - // This is a new label. - Label* label = new Label(label_name); - label->define(location); - ins.first->second = label; - return label; - } - else - { - // The label was already in the hash table. - Label* label = ins.first->second; - if (!label->is_defined()) - { - label->define(location); - return label; - } - else - { - error_at(location, "redefinition of label %qs", - Gogo::message_name(label_name).c_str()); - inform(label->location(), "previous definition of %qs was here", - Gogo::message_name(label_name).c_str()); - return new Label(label_name); - } - } -} - -// Add a reference to a label. - -Label* -Function::add_label_reference(const std::string& label_name) -{ - Label* lnull = NULL; - std::pair ins = - this->labels_.insert(std::make_pair(label_name, lnull)); - if (!ins.second) - { - // The label was already in the hash table. - return ins.first->second; - } - else - { - gcc_assert(ins.first->second == NULL); - Label* label = new Label(label_name); - ins.first->second = label; - return label; - } -} - -// Swap one function with another. This is used when building the -// thunk we use to call a function which calls recover. It may not -// work for any other case. - -void -Function::swap_for_recover(Function *x) -{ - gcc_assert(this->enclosing_ == x->enclosing_); - gcc_assert(this->named_results_ == x->named_results_); - std::swap(this->closure_var_, x->closure_var_); - std::swap(this->block_, x->block_); - gcc_assert(this->location_ == x->location_); - gcc_assert(this->fndecl_ == NULL && x->fndecl_ == NULL); - gcc_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL); -} - -// Traverse the tree. - -int -Function::traverse(Traverse* traverse) -{ - unsigned int traverse_mask = traverse->traverse_mask(); - - // FIXME: We should check traverse_functions here if nested - // functions are stored in block bindings. - if (this->block_ != NULL - && (traverse_mask - & (Traverse::traverse_variables - | Traverse::traverse_constants - | Traverse::traverse_blocks - | Traverse::traverse_statements - | Traverse::traverse_expressions - | Traverse::traverse_types)) != 0) - { - if (this->block_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - - return TRAVERSE_CONTINUE; -} - -// Work out types for unspecified variables and constants. - -void -Function::determine_types() -{ - if (this->block_ != NULL) - this->block_->determine_types(); -} - -// Export the function. - -void -Function::export_func(Export* exp, const std::string& name) const -{ - Function::export_func_with_type(exp, name, this->type_); -} - -// Export a function with a type. - -void -Function::export_func_with_type(Export* exp, const std::string& name, - const Function_type* fntype) -{ - exp->write_c_string("func "); - - if (fntype->is_method()) - { - exp->write_c_string("("); - exp->write_type(fntype->receiver()->type()); - exp->write_c_string(") "); - } - - exp->write_string(name); - - exp->write_c_string(" ("); - const Typed_identifier_list* parameters = fntype->parameters(); - if (parameters != NULL) - { - bool is_varargs = fntype->is_varargs(); - bool first = true; - for (Typed_identifier_list::const_iterator p = parameters->begin(); - p != parameters->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - if (!is_varargs || p + 1 != parameters->end()) - exp->write_type(p->type()); - else - { - exp->write_c_string("..."); - exp->write_type(p->type()->array_type()->element_type()); - } - } - } - exp->write_c_string(")"); - - const Typed_identifier_list* results = fntype->results(); - if (results != NULL) - { - if (results->size() == 1) - { - exp->write_c_string(" "); - exp->write_type(results->begin()->type()); - } - else - { - exp->write_c_string(" ("); - bool first = true; - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - exp->write_type(p->type()); - } - exp->write_c_string(")"); - } - } - exp->write_c_string(";\n"); -} - -// Import a function. - -void -Function::import_func(Import* imp, std::string* pname, - Typed_identifier** preceiver, - Typed_identifier_list** pparameters, - Typed_identifier_list** presults, - bool* is_varargs) -{ - imp->require_c_string("func "); - - *preceiver = NULL; - if (imp->peek_char() == '(') - { - imp->require_c_string("("); - Type* rtype = imp->read_type(); - *preceiver = new Typed_identifier(Import::import_marker, rtype, - imp->location()); - imp->require_c_string(") "); - } - - *pname = imp->read_identifier(); - - Typed_identifier_list* parameters; - *is_varargs = false; - imp->require_c_string(" ("); - if (imp->peek_char() == ')') - parameters = NULL; - else - { - parameters = new Typed_identifier_list(); - while (true) - { - if (imp->match_c_string("...")) - { - imp->advance(3); - *is_varargs = true; - } - - Type* ptype = imp->read_type(); - if (*is_varargs) - ptype = Type::make_array_type(ptype, NULL); - parameters->push_back(Typed_identifier(Import::import_marker, - ptype, imp->location())); - if (imp->peek_char() != ',') - break; - gcc_assert(!*is_varargs); - imp->require_c_string(", "); - } - } - imp->require_c_string(")"); - *pparameters = parameters; - - Typed_identifier_list* results; - if (imp->peek_char() != ' ') - results = NULL; - else - { - results = new Typed_identifier_list(); - imp->require_c_string(" "); - if (imp->peek_char() != '(') - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, rtype, - imp->location())); - } - else - { - imp->require_c_string("("); - while (true) - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, - rtype, imp->location())); - if (imp->peek_char() != ',') - break; - imp->require_c_string(", "); - } - imp->require_c_string(")"); - } - } - imp->require_c_string(";\n"); - *presults = results; -} - -// Class Block. - -Block::Block(Block* enclosing, source_location location) - : enclosing_(enclosing), statements_(), - bindings_(new Bindings(enclosing == NULL - ? NULL - : enclosing->bindings())), - start_location_(location), - end_location_(UNKNOWN_LOCATION) -{ -} - -// Add a statement to a block. - -void -Block::add_statement(Statement* statement) -{ - this->statements_.push_back(statement); -} - -// Add a statement to the front of a block. This is slow but is only -// used for reference counts of parameters. - -void -Block::add_statement_at_front(Statement* statement) -{ - this->statements_.insert(this->statements_.begin(), statement); -} - -// Replace a statement in a block. - -void -Block::replace_statement(size_t index, Statement* s) -{ - gcc_assert(index < this->statements_.size()); - this->statements_[index] = s; -} - -// Add a statement before another statement. - -void -Block::insert_statement_before(size_t index, Statement* s) -{ - gcc_assert(index < this->statements_.size()); - this->statements_.insert(this->statements_.begin() + index, s); -} - -// Add a statement after another statement. - -void -Block::insert_statement_after(size_t index, Statement* s) -{ - gcc_assert(index < this->statements_.size()); - this->statements_.insert(this->statements_.begin() + index + 1, s); -} - -// Traverse the tree. - -int -Block::traverse(Traverse* traverse) -{ - unsigned int traverse_mask = traverse->traverse_mask(); - - if ((traverse_mask & Traverse::traverse_blocks) != 0) - { - int t = traverse->block(this); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - return TRAVERSE_CONTINUE; - } - - if ((traverse_mask - & (Traverse::traverse_variables - | Traverse::traverse_constants - | Traverse::traverse_expressions - | Traverse::traverse_types)) != 0) - { - for (Bindings::const_definitions_iterator pb = - this->bindings_->begin_definitions(); - pb != this->bindings_->end_definitions(); - ++pb) - { - switch ((*pb)->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - if ((traverse_mask & Traverse::traverse_constants) != 0) - { - if (traverse->constant(*pb, false) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if ((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - { - Type* t = (*pb)->const_value()->type(); - if (t != NULL - && Type::traverse(t, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if ((traverse_mask & Traverse::traverse_expressions) != 0 - || (traverse_mask & Traverse::traverse_types) != 0) - { - if ((*pb)->const_value()->traverse_expression(traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - if ((traverse_mask & Traverse::traverse_variables) != 0) - { - if (traverse->variable(*pb) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - && ((*pb)->is_result_variable() - || (*pb)->var_value()->has_type())) - { - Type* t = ((*pb)->is_variable() - ? (*pb)->var_value()->type() - : (*pb)->result_var_value()->type()); - if (t != NULL - && Type::traverse(t, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if ((*pb)->is_variable() - && ((traverse_mask & Traverse::traverse_expressions) != 0 - || (traverse_mask & Traverse::traverse_types) != 0)) - { - if ((*pb)->var_value()->traverse_expression(traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_FUNC: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - // FIXME: Where will nested functions be found? - gcc_unreachable(); - - case Named_object::NAMED_OBJECT_TYPE: - if ((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - { - if (Type::traverse((*pb)->type_value(), traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - case Named_object::NAMED_OBJECT_UNKNOWN: - break; - - case Named_object::NAMED_OBJECT_PACKAGE: - case Named_object::NAMED_OBJECT_SINK: - gcc_unreachable(); - - default: - gcc_unreachable(); - } - } - } - - // No point in checking traverse_mask here--if we got here we always - // want to walk the statements. The traversal can insert new - // statements before or after the current statement. Inserting - // statements before the current statement requires updating I via - // the pointer; those statements will not be traversed. Any new - // statements inserted after the current statement will be traversed - // in their turn. - for (size_t i = 0; i < this->statements_.size(); ++i) - { - if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - - return TRAVERSE_CONTINUE; -} - -// Work out types for unspecified variables and constants. - -void -Block::determine_types() -{ - for (Bindings::const_definitions_iterator pb = - this->bindings_->begin_definitions(); - pb != this->bindings_->end_definitions(); - ++pb) - { - if ((*pb)->is_variable()) - (*pb)->var_value()->determine_type(); - else if ((*pb)->is_const()) - (*pb)->const_value()->determine_type(); - } - - for (std::vector::const_iterator ps = this->statements_.begin(); - ps != this->statements_.end(); - ++ps) - (*ps)->determine_types(); -} - -// Return true if the statements in this block may fall through. - -bool -Block::may_fall_through() const -{ - if (this->statements_.empty()) - return true; - return this->statements_.back()->may_fall_through(); -} - -// Class Variable. - -Variable::Variable(Type* type, Expression* init, bool is_global, - bool is_parameter, bool is_receiver, - source_location location) - : type_(type), init_(init), preinit_(NULL), location_(location), - is_global_(is_global), is_parameter_(is_parameter), - is_receiver_(is_receiver), is_varargs_parameter_(false), - is_address_taken_(false), init_is_lowered_(false), - type_from_init_tuple_(false), type_from_range_index_(false), - type_from_range_value_(false), type_from_chan_element_(false), - is_type_switch_var_(false) -{ - gcc_assert(type != NULL || init != NULL); - gcc_assert(!is_parameter || init == NULL); -} - -// Traverse the initializer expression. - -int -Variable::traverse_expression(Traverse* traverse) -{ - if (this->preinit_ != NULL) - { - if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->init_ != NULL) - { - if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lower the initialization expression after parsing is complete. - -void -Variable::lower_init_expression(Gogo* gogo, Named_object* function) -{ - if (this->init_ != NULL && !this->init_is_lowered_) - { - gogo->lower_expression(function, &this->init_); - this->init_is_lowered_ = true; - } -} - -// Get the preinit block. - -Block* -Variable::preinit_block() -{ - gcc_assert(this->is_global_); - if (this->preinit_ == NULL) - this->preinit_ = new Block(NULL, this->location()); - return this->preinit_; -} - -// Add a statement to be run before the initialization expression. - -void -Variable::add_preinit_statement(Statement* s) -{ - Block* b = this->preinit_block(); - b->add_statement(s); - b->set_end_location(s->location()); -} - -// In an assignment which sets a variable to a tuple of EXPR, return -// the type of the first element of the tuple. - -Type* -Variable::type_from_tuple(Expression* expr, bool report_error) const -{ - if (expr->map_index_expression() != NULL) - return expr->map_index_expression()->get_map_type()->val_type(); - else if (expr->receive_expression() != NULL) - { - Expression* channel = expr->receive_expression()->channel(); - return channel->type()->channel_type()->element_type(); - } - else - { - if (report_error) - error_at(this->location(), "invalid tuple definition"); - return Type::make_error_type(); - } -} - -// Given EXPR used in a range clause, return either the index type or -// the value type of the range, depending upon GET_INDEX_TYPE. - -Type* -Variable::type_from_range(Expression* expr, bool get_index_type, - bool report_error) const -{ - Type* t = expr->type(); - if (t->array_type() != NULL - || (t->points_to() != NULL - && t->points_to()->array_type() != NULL - && !t->points_to()->is_open_array_type())) - { - if (get_index_type) - return Type::lookup_integer_type("int"); - else - return t->deref()->array_type()->element_type(); - } - else if (t->is_string_type()) - return Type::lookup_integer_type("int"); - else if (t->map_type() != NULL) - { - if (get_index_type) - return t->map_type()->key_type(); - else - return t->map_type()->val_type(); - } - else if (t->channel_type() != NULL) - { - if (get_index_type) - return t->channel_type()->element_type(); - else - { - if (report_error) - error_at(this->location(), - "invalid definition of value variable for channel range"); - return Type::make_error_type(); - } - } - else - { - if (report_error) - error_at(this->location(), "invalid type for range clause"); - return Type::make_error_type(); - } -} - -// EXPR should be a channel. Return the channel's element type. - -Type* -Variable::type_from_chan_element(Expression* expr, bool report_error) const -{ - Type* t = expr->type(); - if (t->channel_type() != NULL) - return t->channel_type()->element_type(); - else - { - if (report_error) - error_at(this->location(), "expected channel"); - return Type::make_error_type(); - } -} - -// Return the type of the Variable. This may be called before -// Variable::determine_type is called, which means that we may need to -// get the type from the initializer. FIXME: If we combine lowering -// with type determination, then this should be unnecessary. - -Type* -Variable::type() const -{ - // A variable in a type switch with a nil case will have the wrong - // type here. This gets fixed up in determine_type, below. - Type* type = this->type_; - Expression* init = this->init_; - if (this->is_type_switch_var_ - && this->type_->is_nil_constant_as_type()) - { - Type_guard_expression* tge = this->init_->type_guard_expression(); - gcc_assert(tge != NULL); - init = tge->expr(); - type = NULL; - } - - if (type != NULL) - return type; - else if (this->type_from_init_tuple_) - return this->type_from_tuple(init, false); - else if (this->type_from_range_index_ || this->type_from_range_value_) - return this->type_from_range(init, this->type_from_range_index_, false); - else if (this->type_from_chan_element_) - return this->type_from_chan_element(init, false); - else - { - gcc_assert(init != NULL); - type = init->type(); - gcc_assert(type != NULL); - - // Variables should not have abstract types. - if (type->is_abstract()) - type = type->make_non_abstract_type(); - - if (type->is_void_type()) - type = Type::make_error_type(); - - return type; - } -} - -// Set the type if necessary. - -void -Variable::determine_type() -{ - // A variable in a type switch with a nil case will have the wrong - // type here. It will have an initializer which is a type guard. - // We want to initialize it to the value without the type guard, and - // use the type of that value as well. - if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type()) - { - Type_guard_expression* tge = this->init_->type_guard_expression(); - gcc_assert(tge != NULL); - this->type_ = NULL; - this->init_ = tge->expr(); - } - - if (this->init_ == NULL) - gcc_assert(this->type_ != NULL && !this->type_->is_abstract()); - else if (this->type_from_init_tuple_) - { - Expression *init = this->init_; - init->determine_type_no_context(); - this->type_ = this->type_from_tuple(init, true); - this->init_ = NULL; - } - else if (this->type_from_range_index_ || this->type_from_range_value_) - { - Expression* init = this->init_; - init->determine_type_no_context(); - this->type_ = this->type_from_range(init, this->type_from_range_index_, - true); - this->init_ = NULL; - } - else - { - // type_from_chan_element_ should have been cleared during - // lowering. - gcc_assert(!this->type_from_chan_element_); - - Type_context context(this->type_, false); - this->init_->determine_type(&context); - if (this->type_ == NULL) - { - Type* type = this->init_->type(); - gcc_assert(type != NULL); - if (type->is_abstract()) - type = type->make_non_abstract_type(); - - if (type->is_void_type()) - { - error_at(this->location_, "variable has no type"); - type = Type::make_error_type(); - } - else if (type->is_nil_type()) - { - error_at(this->location_, "variable defined to nil type"); - type = Type::make_error_type(); - } - else if (type->is_call_multiple_result_type()) - { - error_at(this->location_, - "single variable set to multiple value function call"); - type = Type::make_error_type(); - } - - this->type_ = type; - } - } -} - -// Export the variable - -void -Variable::export_var(Export* exp, const std::string& name) const -{ - gcc_assert(this->is_global_); - exp->write_c_string("var "); - exp->write_string(name); - exp->write_c_string(" "); - exp->write_type(this->type()); - exp->write_c_string(";\n"); -} - -// Import a variable. - -void -Variable::import_var(Import* imp, std::string* pname, Type** ptype) -{ - imp->require_c_string("var "); - *pname = imp->read_identifier(); - imp->require_c_string(" "); - *ptype = imp->read_type(); - imp->require_c_string(";\n"); -} - -// Class Named_constant. - -// Traverse the initializer expression. - -int -Named_constant::traverse_expression(Traverse* traverse) -{ - return Expression::traverse(&this->expr_, traverse); -} - -// Determine the type of the constant. - -void -Named_constant::determine_type() -{ - if (this->type_ != NULL) - { - Type_context context(this->type_, false); - this->expr_->determine_type(&context); - } - else - { - // A constant may have an abstract type. - Type_context context(NULL, true); - this->expr_->determine_type(&context); - this->type_ = this->expr_->type(); - gcc_assert(this->type_ != NULL); - } -} - -// Indicate that we found and reported an error for this constant. - -void -Named_constant::set_error() -{ - this->type_ = Type::make_error_type(); - this->expr_ = Expression::make_error(this->location_); -} - -// Export a constant. - -void -Named_constant::export_const(Export* exp, const std::string& name) const -{ - exp->write_c_string("const "); - exp->write_string(name); - exp->write_c_string(" "); - if (!this->type_->is_abstract()) - { - exp->write_type(this->type_); - exp->write_c_string(" "); - } - exp->write_c_string("= "); - this->expr()->export_expression(exp); - exp->write_c_string(";\n"); -} - -// Import a constant. - -void -Named_constant::import_const(Import* imp, std::string* pname, Type** ptype, - Expression** pexpr) -{ - imp->require_c_string("const "); - *pname = imp->read_identifier(); - imp->require_c_string(" "); - if (imp->peek_char() == '=') - *ptype = NULL; - else - { - *ptype = imp->read_type(); - imp->require_c_string(" "); - } - imp->require_c_string("= "); - *pexpr = Expression::import_expression(imp); - imp->require_c_string(";\n"); -} - -// Add a method. - -Named_object* -Type_declaration::add_method(const std::string& name, Function* function) -{ - Named_object* ret = Named_object::make_function(name, NULL, function); - this->methods_.push_back(ret); - return ret; -} - -// Add a method declaration. - -Named_object* -Type_declaration::add_method_declaration(const std::string& name, - Function_type* type, - source_location location) -{ - Named_object* ret = Named_object::make_function_declaration(name, NULL, type, - location); - this->methods_.push_back(ret); - return ret; -} - -// Return whether any methods ere defined. - -bool -Type_declaration::has_methods() const -{ - return !this->methods_.empty(); -} - -// Define methods for the real type. - -void -Type_declaration::define_methods(Named_type* nt) -{ - for (Methods::const_iterator p = this->methods_.begin(); - p != this->methods_.end(); - ++p) - nt->add_existing_method(*p); -} - -// We are using the type. Return true if we should issue a warning. - -bool -Type_declaration::using_type() -{ - bool ret = !this->issued_warning_; - this->issued_warning_ = true; - return ret; -} - -// Class Unknown_name. - -// Set the real named object. - -void -Unknown_name::set_real_named_object(Named_object* no) -{ - gcc_assert(this->real_named_object_ == NULL); - gcc_assert(!no->is_unknown()); - this->real_named_object_ = no; -} - -// Class Named_object. - -Named_object::Named_object(const std::string& name, - const Package* package, - Classification classification) - : name_(name), package_(package), classification_(classification), - tree_(NULL) -{ - if (Gogo::is_sink_name(name)) - gcc_assert(classification == NAMED_OBJECT_SINK); -} - -// Make an unknown name. This is used by the parser. The name must -// be resolved later. Unknown names are only added in the current -// package. - -Named_object* -Named_object::make_unknown_name(const std::string& name, - source_location location) -{ - Named_object* named_object = new Named_object(name, NULL, - NAMED_OBJECT_UNKNOWN); - Unknown_name* value = new Unknown_name(location); - named_object->u_.unknown_value = value; - return named_object; -} - -// Make a constant. - -Named_object* -Named_object::make_constant(const Typed_identifier& tid, - const Package* package, Expression* expr, - int iota_value) -{ - Named_object* named_object = new Named_object(tid.name(), package, - NAMED_OBJECT_CONST); - Named_constant* named_constant = new Named_constant(tid.type(), expr, - iota_value, - tid.location()); - named_object->u_.const_value = named_constant; - return named_object; -} - -// Make a named type. - -Named_object* -Named_object::make_type(const std::string& name, const Package* package, - Type* type, source_location location) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_TYPE); - Named_type* named_type = Type::make_named_type(named_object, type, location); - named_object->u_.type_value = named_type; - return named_object; -} - -// Make a type declaration. - -Named_object* -Named_object::make_type_declaration(const std::string& name, - const Package* package, - source_location location) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_TYPE_DECLARATION); - Type_declaration* type_declaration = new Type_declaration(location); - named_object->u_.type_declaration = type_declaration; - return named_object; -} - -// Make a variable. - -Named_object* -Named_object::make_variable(const std::string& name, const Package* package, - Variable* variable) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_VAR); - named_object->u_.var_value = variable; - return named_object; -} - -// Make a result variable. - -Named_object* -Named_object::make_result_variable(const std::string& name, - Result_variable* result) -{ - Named_object* named_object = new Named_object(name, NULL, - NAMED_OBJECT_RESULT_VAR); - named_object->u_.result_var_value = result; - return named_object; -} - -// Make a sink. This is used for the special blank identifier _. - -Named_object* -Named_object::make_sink() -{ - return new Named_object("_", NULL, NAMED_OBJECT_SINK); -} - -// Make a named function. - -Named_object* -Named_object::make_function(const std::string& name, const Package* package, - Function* function) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_FUNC); - named_object->u_.func_value = function; - return named_object; -} - -// Make a function declaration. - -Named_object* -Named_object::make_function_declaration(const std::string& name, - const Package* package, - Function_type* fntype, - source_location location) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_FUNC_DECLARATION); - Function_declaration *func_decl = new Function_declaration(fntype, location); - named_object->u_.func_declaration_value = func_decl; - return named_object; -} - -// Make a package. - -Named_object* -Named_object::make_package(const std::string& alias, Package* package) -{ - Named_object* named_object = new Named_object(alias, NULL, - NAMED_OBJECT_PACKAGE); - named_object->u_.package_value = package; - return named_object; -} - -// Return the name to use in an error message. - -std::string -Named_object::message_name() const -{ - if (this->package_ == NULL) - return Gogo::message_name(this->name_); - std::string ret = Gogo::message_name(this->package_->name()); - ret += '.'; - ret += Gogo::message_name(this->name_); - return ret; -} - -// Set the type when a declaration is defined. - -void -Named_object::set_type_value(Named_type* named_type) -{ - gcc_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION); - Type_declaration* td = this->u_.type_declaration; - td->define_methods(named_type); - Named_object* in_function = td->in_function(); - if (in_function != NULL) - named_type->set_in_function(in_function); - delete td; - this->classification_ = NAMED_OBJECT_TYPE; - this->u_.type_value = named_type; -} - -// Define a function which was previously declared. - -void -Named_object::set_function_value(Function* function) -{ - gcc_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION); - this->classification_ = NAMED_OBJECT_FUNC; - // FIXME: We should free the old value. - this->u_.func_value = function; -} - -// Return the location of a named object. - -source_location -Named_object::location() const -{ - switch (this->classification_) - { - default: - case NAMED_OBJECT_UNINITIALIZED: - gcc_unreachable(); - - case NAMED_OBJECT_UNKNOWN: - return this->unknown_value()->location(); - - case NAMED_OBJECT_CONST: - return this->const_value()->location(); - - case NAMED_OBJECT_TYPE: - return this->type_value()->location(); - - case NAMED_OBJECT_TYPE_DECLARATION: - return this->type_declaration_value()->location(); - - case NAMED_OBJECT_VAR: - return this->var_value()->location(); - - case NAMED_OBJECT_RESULT_VAR: - return this->result_var_value()->function()->location(); - - case NAMED_OBJECT_SINK: - gcc_unreachable(); - - case NAMED_OBJECT_FUNC: - return this->func_value()->location(); - - case NAMED_OBJECT_FUNC_DECLARATION: - return this->func_declaration_value()->location(); - - case NAMED_OBJECT_PACKAGE: - return this->package_value()->location(); - } -} - -// Export a named object. - -void -Named_object::export_named_object(Export* exp) const -{ - switch (this->classification_) - { - default: - case NAMED_OBJECT_UNINITIALIZED: - case NAMED_OBJECT_UNKNOWN: - gcc_unreachable(); - - case NAMED_OBJECT_CONST: - this->const_value()->export_const(exp, this->name_); - break; - - case NAMED_OBJECT_TYPE: - this->type_value()->export_named_type(exp, this->name_); - break; - - case NAMED_OBJECT_TYPE_DECLARATION: - error_at(this->type_declaration_value()->location(), - "attempt to export %<%s%> which was declared but not defined", - this->message_name().c_str()); - break; - - case NAMED_OBJECT_FUNC_DECLARATION: - this->func_declaration_value()->export_func(exp, this->name_); - break; - - case NAMED_OBJECT_VAR: - this->var_value()->export_var(exp, this->name_); - break; - - case NAMED_OBJECT_RESULT_VAR: - case NAMED_OBJECT_SINK: - gcc_unreachable(); - - case NAMED_OBJECT_FUNC: - this->func_value()->export_func(exp, this->name_); - break; - } -} - -// Class Bindings. - -Bindings::Bindings(Bindings* enclosing) - : enclosing_(enclosing), named_objects_(), bindings_() -{ -} - -// Clear imports. - -void -Bindings::clear_file_scope() -{ - Contour::iterator p = this->bindings_.begin(); - while (p != this->bindings_.end()) - { - bool keep; - if (p->second->package() != NULL) - keep = false; - else if (p->second->is_package()) - keep = false; - else if (p->second->is_function() - && !p->second->func_value()->type()->is_method() - && Gogo::unpack_hidden_name(p->second->name()) == "init") - keep = false; - else - keep = true; - - if (keep) - ++p; - else - p = this->bindings_.erase(p); - } -} - -// Look up a symbol. - -Named_object* -Bindings::lookup(const std::string& name) const -{ - Contour::const_iterator p = this->bindings_.find(name); - if (p != this->bindings_.end()) - return p->second->resolve(); - else if (this->enclosing_ != NULL) - return this->enclosing_->lookup(name); - else - return NULL; -} - -// Look up a symbol locally. - -Named_object* -Bindings::lookup_local(const std::string& name) const -{ - Contour::const_iterator p = this->bindings_.find(name); - if (p == this->bindings_.end()) - return NULL; - return p->second; -} - -// Remove an object from a set of bindings. This is used for a -// special case in thunks for functions which call recover. - -void -Bindings::remove_binding(Named_object* no) -{ - Contour::iterator pb = this->bindings_.find(no->name()); - gcc_assert(pb != this->bindings_.end()); - this->bindings_.erase(pb); - for (std::vector::iterator pn = this->named_objects_.begin(); - pn != this->named_objects_.end(); - ++pn) - { - if (*pn == no) - { - this->named_objects_.erase(pn); - return; - } - } - gcc_unreachable(); -} - -// Add a method to the list of objects. This is not added to the -// lookup table. This is so that we have a single list of objects -// declared at the top level, which we walk through when it's time to -// convert to trees. - -void -Bindings::add_method(Named_object* method) -{ - this->named_objects_.push_back(method); -} - -// Add a generic Named_object to a Contour. - -Named_object* -Bindings::add_named_object_to_contour(Contour* contour, - Named_object* named_object) -{ - gcc_assert(named_object == named_object->resolve()); - const std::string& name(named_object->name()); - gcc_assert(!Gogo::is_sink_name(name)); - - std::pair ins = - contour->insert(std::make_pair(name, named_object)); - if (!ins.second) - { - // The name was already there. - if (named_object->package() != NULL - && ins.first->second->package() == named_object->package() - && (ins.first->second->classification() - == named_object->classification())) - { - // This is a second import of the same object. - return ins.first->second; - } - ins.first->second = this->new_definition(ins.first->second, - named_object); - return ins.first->second; - } - else - { - // Don't push declarations on the list. We push them on when - // and if we find the definitions. That way we genericize the - // functions in order. - if (!named_object->is_type_declaration() - && !named_object->is_function_declaration() - && !named_object->is_unknown()) - this->named_objects_.push_back(named_object); - return named_object; - } -} - -// We had an existing named object OLD_OBJECT, and we've seen a new -// one NEW_OBJECT with the same name. FIXME: This does not free the -// new object when we don't need it. - -Named_object* -Bindings::new_definition(Named_object* old_object, Named_object* new_object) -{ - std::string reason; - switch (old_object->classification()) - { - default: - case Named_object::NAMED_OBJECT_UNINITIALIZED: - gcc_unreachable(); - - case Named_object::NAMED_OBJECT_UNKNOWN: - { - Named_object* real = old_object->unknown_value()->real_named_object(); - if (real != NULL) - return this->new_definition(real, new_object); - gcc_assert(!new_object->is_unknown()); - old_object->unknown_value()->set_real_named_object(new_object); - if (!new_object->is_type_declaration() - && !new_object->is_function_declaration()) - this->named_objects_.push_back(new_object); - return new_object; - } - - case Named_object::NAMED_OBJECT_CONST: - break; - - case Named_object::NAMED_OBJECT_TYPE: - if (new_object->is_type_declaration()) - return old_object; - break; - - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - if (new_object->is_type_declaration()) - return old_object; - if (new_object->is_type()) - { - old_object->set_type_value(new_object->type_value()); - new_object->type_value()->set_named_object(old_object); - this->named_objects_.push_back(old_object); - return old_object; - } - break; - - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - break; - - case Named_object::NAMED_OBJECT_SINK: - gcc_unreachable(); - - case Named_object::NAMED_OBJECT_FUNC: - if (new_object->is_function_declaration()) - { - if (!new_object->func_declaration_value()->asm_name().empty()) - sorry("__asm__ for function definitions"); - Function_type* old_type = old_object->func_value()->type(); - Function_type* new_type = - new_object->func_declaration_value()->type(); - if (old_type->is_valid_redeclaration(new_type, &reason)) - return old_object; - } - break; - - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - { - Function_type* old_type = old_object->func_declaration_value()->type(); - if (new_object->is_function_declaration()) - { - Function_type* new_type = - new_object->func_declaration_value()->type(); - if (old_type->is_valid_redeclaration(new_type, &reason)) - return old_object; - } - if (new_object->is_function()) - { - Function_type* new_type = new_object->func_value()->type(); - if (old_type->is_valid_redeclaration(new_type, &reason)) - { - if (!old_object->func_declaration_value()->asm_name().empty()) - sorry("__asm__ for function definitions"); - old_object->set_function_value(new_object->func_value()); - this->named_objects_.push_back(old_object); - return old_object; - } - } - } - break; - - case Named_object::NAMED_OBJECT_PACKAGE: - if (new_object->is_package() - && (old_object->package_value()->name() - == new_object->package_value()->name())) - return old_object; - - break; - } - - std::string n = old_object->message_name(); - if (reason.empty()) - error_at(new_object->location(), "redefinition of %qs", n.c_str()); - else - error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(), - reason.c_str()); - - inform(old_object->location(), "previous definition of %qs was here", - n.c_str()); - - return old_object; -} - -// Add a named type. - -Named_object* -Bindings::add_named_type(Named_type* named_type) -{ - return this->add_named_object(named_type->named_object()); -} - -// Add a function. - -Named_object* -Bindings::add_function(const std::string& name, const Package* package, - Function* function) -{ - return this->add_named_object(Named_object::make_function(name, package, - function)); -} - -// Add a function declaration. - -Named_object* -Bindings::add_function_declaration(const std::string& name, - const Package* package, - Function_type* type, - source_location location) -{ - Named_object* no = Named_object::make_function_declaration(name, package, - type, location); - return this->add_named_object(no); -} - -// Define a type which was previously declared. - -void -Bindings::define_type(Named_object* no, Named_type* type) -{ - no->set_type_value(type); - this->named_objects_.push_back(no); -} - -// Traverse bindings. - -int -Bindings::traverse(Traverse* traverse, bool is_global) -{ - unsigned int traverse_mask = traverse->traverse_mask(); - - // We don't use an iterator because we permit the traversal to add - // new global objects. - for (size_t i = 0; i < this->named_objects_.size(); ++i) - { - Named_object* p = this->named_objects_[i]; - switch (p->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - if ((traverse_mask & Traverse::traverse_constants) != 0) - { - if (traverse->constant(p, is_global) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if ((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - { - Type* t = p->const_value()->type(); - if (t != NULL - && Type::traverse(t, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if ((traverse_mask & Traverse::traverse_expressions) != 0) - { - if (p->const_value()->traverse_expression(traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - if ((traverse_mask & Traverse::traverse_variables) != 0) - { - if (traverse->variable(p) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - && (p->is_result_variable() - || p->var_value()->has_type())) - { - Type* t = (p->is_variable() - ? p->var_value()->type() - : p->result_var_value()->type()); - if (t != NULL - && Type::traverse(t, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (p->is_variable() - && (traverse_mask & Traverse::traverse_expressions) != 0) - { - if (p->var_value()->traverse_expression(traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_FUNC: - if ((traverse_mask & Traverse::traverse_functions) != 0) - { - int t = traverse->function(p); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - break; - } - - if ((traverse_mask - & (Traverse::traverse_variables - | Traverse::traverse_constants - | Traverse::traverse_functions - | Traverse::traverse_blocks - | Traverse::traverse_statements - | Traverse::traverse_expressions - | Traverse::traverse_types)) != 0) - { - if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_PACKAGE: - // These are traversed in Gogo::traverse. - gcc_assert(is_global); - break; - - case Named_object::NAMED_OBJECT_TYPE: - if ((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - { - if (Type::traverse(p->type_value(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - case Named_object::NAMED_OBJECT_UNKNOWN: - break; - - case Named_object::NAMED_OBJECT_SINK: - default: - gcc_unreachable(); - } - } - - return TRAVERSE_CONTINUE; -} - -// Class Package. - -Package::Package(const std::string& name, const std::string& unique_prefix, - source_location location) - : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)), - priority_(0), location_(location), used_(false), is_imported_(false), - uses_sink_alias_(false) -{ - gcc_assert(!name.empty() && !unique_prefix.empty()); -} - -// Set the priority. We may see multiple priorities for an imported -// package; we want to use the largest one. - -void -Package::set_priority(int priority) -{ - if (priority > this->priority_) - this->priority_ = priority; -} - -// Determine types of constants. Everything else in a package -// (variables, function declarations) should already have a fixed -// type. Constants may have abstract types. - -void -Package::determine_types() -{ - Bindings* bindings = this->bindings_; - for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); - p != bindings->end_definitions(); - ++p) - { - if ((*p)->is_const()) - (*p)->const_value()->determine_type(); - } -} - -// Class Traverse. - -// Destructor. - -Traverse::~Traverse() -{ - if (this->types_seen_ != NULL) - delete this->types_seen_; - if (this->expressions_seen_ != NULL) - delete this->expressions_seen_; -} - -// Record that we are looking at a type, and return true if we have -// already seen it. - -bool -Traverse::remember_type(const Type* type) -{ - gcc_assert((this->traverse_mask() & traverse_types) != 0 - || (this->traverse_mask() & traverse_expressions) != 0); - // We only have to remember named types, as they are the only ones - // we can see multiple times in a traversal. - if (type->classification() != Type::TYPE_NAMED) - return false; - if (this->types_seen_ == NULL) - this->types_seen_ = new Types_seen(); - std::pair ins = this->types_seen_->insert(type); - return !ins.second; -} - -// Record that we are looking at an expression, and return true if we -// have already seen it. - -bool -Traverse::remember_expression(const Expression* expression) -{ - gcc_assert((this->traverse_mask() & traverse_types) != 0 - || (this->traverse_mask() & traverse_expressions) != 0); - if (this->expressions_seen_ == NULL) - this->expressions_seen_ = new Expressions_seen(); - std::pair ins = - this->expressions_seen_->insert(expression); - return !ins.second; -} - -// The default versions of these functions should never be called: the -// traversal mask indicates which functions may be called. - -int -Traverse::variable(Named_object*) -{ - gcc_unreachable(); -} - -int -Traverse::constant(Named_object*, bool) -{ - gcc_unreachable(); -} - -int -Traverse::function(Named_object*) -{ - gcc_unreachable(); -} - -int -Traverse::block(Block*) -{ - gcc_unreachable(); -} - -int -Traverse::statement(Block*, size_t*, Statement*) -{ - gcc_unreachable(); -} - -int -Traverse::expression(Expression**) -{ - gcc_unreachable(); -} - -int -Traverse::type(Type*) -{ - gcc_unreachable(); -} diff --git a/gcc/go/gofrontend/gogo.cc.merge-right.r172891 b/gcc/go/gofrontend/gogo.cc.merge-right.r172891 deleted file mode 100644 index d9f604a5f22..00000000000 --- a/gcc/go/gofrontend/gogo.cc.merge-right.r172891 +++ /dev/null @@ -1,4796 +0,0 @@ -// gogo.cc -- Go frontend parsed representation. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include "go-c.h" -#include "go-dump.h" -#include "lex.h" -#include "types.h" -#include "statements.h" -#include "expressions.h" -#include "dataflow.h" -#include "runtime.h" -#include "import.h" -#include "export.h" -#include "backend.h" -#include "gogo.h" - -// Class Gogo. - -Gogo::Gogo(Backend* backend, int int_type_size, int pointer_size) - : backend_(backend), - package_(NULL), - functions_(), - globals_(new Bindings(NULL)), - imports_(), - imported_unsafe_(false), - packages_(), - map_descriptors_(NULL), - type_descriptor_decls_(NULL), - init_functions_(), - need_init_fn_(false), - init_fn_name_(), - imported_init_fns_(), - unique_prefix_(), - unique_prefix_specified_(false), - interface_types_(), - named_types_are_converted_(false) -{ - const source_location loc = BUILTINS_LOCATION; - - Named_type* uint8_type = Type::make_integer_type("uint8", true, 8, - RUNTIME_TYPE_KIND_UINT8); - this->add_named_type(uint8_type); - this->add_named_type(Type::make_integer_type("uint16", true, 16, - RUNTIME_TYPE_KIND_UINT16)); - this->add_named_type(Type::make_integer_type("uint32", true, 32, - RUNTIME_TYPE_KIND_UINT32)); - this->add_named_type(Type::make_integer_type("uint64", true, 64, - RUNTIME_TYPE_KIND_UINT64)); - - this->add_named_type(Type::make_integer_type("int8", false, 8, - RUNTIME_TYPE_KIND_INT8)); - this->add_named_type(Type::make_integer_type("int16", false, 16, - RUNTIME_TYPE_KIND_INT16)); - this->add_named_type(Type::make_integer_type("int32", false, 32, - RUNTIME_TYPE_KIND_INT32)); - this->add_named_type(Type::make_integer_type("int64", false, 64, - RUNTIME_TYPE_KIND_INT64)); - - this->add_named_type(Type::make_float_type("float32", 32, - RUNTIME_TYPE_KIND_FLOAT32)); - this->add_named_type(Type::make_float_type("float64", 64, - RUNTIME_TYPE_KIND_FLOAT64)); - - this->add_named_type(Type::make_complex_type("complex64", 64, - RUNTIME_TYPE_KIND_COMPLEX64)); - this->add_named_type(Type::make_complex_type("complex128", 128, - RUNTIME_TYPE_KIND_COMPLEX128)); - - if (int_type_size < 32) - int_type_size = 32; - this->add_named_type(Type::make_integer_type("uint", true, - int_type_size, - RUNTIME_TYPE_KIND_UINT)); - Named_type* int_type = Type::make_integer_type("int", false, int_type_size, - RUNTIME_TYPE_KIND_INT); - this->add_named_type(int_type); - - // "byte" is an alias for "uint8". Construct a Named_object which - // points to UINT8_TYPE. Note that this breaks the normal pairing - // in which a Named_object points to a Named_type which points back - // to the same Named_object. - Named_object* byte_type = this->declare_type("byte", loc); - byte_type->set_type_value(uint8_type); - - this->add_named_type(Type::make_integer_type("uintptr", true, - pointer_size, - RUNTIME_TYPE_KIND_UINTPTR)); - - this->add_named_type(Type::make_named_bool_type()); - - this->add_named_type(Type::make_named_string_type()); - - this->globals_->add_constant(Typed_identifier("true", - Type::make_boolean_type(), - loc), - NULL, - Expression::make_boolean(true, loc), - 0); - this->globals_->add_constant(Typed_identifier("false", - Type::make_boolean_type(), - loc), - NULL, - Expression::make_boolean(false, loc), - 0); - - this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(), - loc), - NULL, - Expression::make_nil(loc), - 0); - - Type* abstract_int_type = Type::make_abstract_integer_type(); - this->globals_->add_constant(Typed_identifier("iota", abstract_int_type, - loc), - NULL, - Expression::make_iota(), - 0); - - Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc); - new_type->set_is_varargs(); - new_type->set_is_builtin(); - this->globals_->add_function_declaration("new", NULL, new_type, loc); - - Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc); - make_type->set_is_varargs(); - make_type->set_is_builtin(); - this->globals_->add_function_declaration("make", NULL, make_type, loc); - - Typed_identifier_list* len_result = new Typed_identifier_list(); - len_result->push_back(Typed_identifier("", int_type, loc)); - Function_type* len_type = Type::make_function_type(NULL, NULL, len_result, - loc); - len_type->set_is_builtin(); - this->globals_->add_function_declaration("len", NULL, len_type, loc); - - Typed_identifier_list* cap_result = new Typed_identifier_list(); - cap_result->push_back(Typed_identifier("", int_type, loc)); - Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result, - loc); - cap_type->set_is_builtin(); - this->globals_->add_function_declaration("cap", NULL, cap_type, loc); - - Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc); - print_type->set_is_varargs(); - print_type->set_is_builtin(); - this->globals_->add_function_declaration("print", NULL, print_type, loc); - - print_type = Type::make_function_type(NULL, NULL, NULL, loc); - print_type->set_is_varargs(); - print_type->set_is_builtin(); - this->globals_->add_function_declaration("println", NULL, print_type, loc); - - Type *empty = Type::make_interface_type(NULL, loc); - Typed_identifier_list* panic_parms = new Typed_identifier_list(); - panic_parms->push_back(Typed_identifier("e", empty, loc)); - Function_type *panic_type = Type::make_function_type(NULL, panic_parms, - NULL, loc); - panic_type->set_is_builtin(); - this->globals_->add_function_declaration("panic", NULL, panic_type, loc); - - Typed_identifier_list* recover_result = new Typed_identifier_list(); - recover_result->push_back(Typed_identifier("", empty, loc)); - Function_type* recover_type = Type::make_function_type(NULL, NULL, - recover_result, - loc); - recover_type->set_is_builtin(); - this->globals_->add_function_declaration("recover", NULL, recover_type, loc); - - Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc); - close_type->set_is_varargs(); - close_type->set_is_builtin(); - this->globals_->add_function_declaration("close", NULL, close_type, loc); - - Typed_identifier_list* copy_result = new Typed_identifier_list(); - copy_result->push_back(Typed_identifier("", int_type, loc)); - Function_type* copy_type = Type::make_function_type(NULL, NULL, - copy_result, loc); - copy_type->set_is_varargs(); - copy_type->set_is_builtin(); - this->globals_->add_function_declaration("copy", NULL, copy_type, loc); - - Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc); - append_type->set_is_varargs(); - append_type->set_is_builtin(); - this->globals_->add_function_declaration("append", NULL, append_type, loc); - - Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc); - complex_type->set_is_varargs(); - complex_type->set_is_builtin(); - this->globals_->add_function_declaration("complex", NULL, complex_type, loc); - - Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc); - real_type->set_is_varargs(); - real_type->set_is_builtin(); - this->globals_->add_function_declaration("real", NULL, real_type, loc); - - Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc); - imag_type->set_is_varargs(); - imag_type->set_is_builtin(); - this->globals_->add_function_declaration("imag", NULL, imag_type, loc); - - this->define_builtin_function_trees(); -} - -// Munge name for use in an error message. - -std::string -Gogo::message_name(const std::string& name) -{ - return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str()); -} - -// Get the package name. - -const std::string& -Gogo::package_name() const -{ - go_assert(this->package_ != NULL); - return this->package_->name(); -} - -// Set the package name. - -void -Gogo::set_package_name(const std::string& package_name, - source_location location) -{ - if (this->package_ != NULL && this->package_->name() != package_name) - { - error_at(location, "expected package %<%s%>", - Gogo::message_name(this->package_->name()).c_str()); - return; - } - - // If the user did not specify a unique prefix, we always use "go". - // This in effect requires that the package name be unique. - if (this->unique_prefix_.empty()) - this->unique_prefix_ = "go"; - - this->package_ = this->register_package(package_name, this->unique_prefix_, - location); - - // We used to permit people to qualify symbols with the current - // package name (e.g., P.x), but we no longer do. - // this->globals_->add_package(package_name, this->package_); - - if (this->is_main_package()) - { - // Declare "main" as a function which takes no parameters and - // returns no value. - this->declare_function("main", - Type::make_function_type(NULL, NULL, NULL, - BUILTINS_LOCATION), - BUILTINS_LOCATION); - } -} - -// Return whether this is the "main" package. This is not true if -// -fgo-prefix was used. - -bool -Gogo::is_main_package() const -{ - return this->package_name() == "main" && !this->unique_prefix_specified_; -} - -// Import a package. - -void -Gogo::import_package(const std::string& filename, - const std::string& local_name, - bool is_local_name_exported, - source_location location) -{ - if (filename == "unsafe") - { - this->import_unsafe(local_name, is_local_name_exported, location); - return; - } - - Imports::const_iterator p = this->imports_.find(filename); - if (p != this->imports_.end()) - { - Package* package = p->second; - package->set_location(location); - package->set_is_imported(); - std::string ln = local_name; - bool is_ln_exported = is_local_name_exported; - if (ln.empty()) - { - ln = package->name(); - is_ln_exported = Lex::is_exported_name(ln); - } - if (ln == ".") - { - Bindings* bindings = package->bindings(); - for (Bindings::const_declarations_iterator p = - bindings->begin_declarations(); - p != bindings->end_declarations(); - ++p) - this->add_named_object(p->second); - } - else if (ln == "_") - package->set_uses_sink_alias(); - else - { - ln = this->pack_hidden_name(ln, is_ln_exported); - this->package_->bindings()->add_package(ln, package); - } - return; - } - - Import::Stream* stream = Import::open_package(filename, location); - if (stream == NULL) - { - error_at(location, "import file %qs not found", filename.c_str()); - return; - } - - Import imp(stream, location); - imp.register_builtin_types(this); - Package* package = imp.import(this, local_name, is_local_name_exported); - if (package != NULL) - { - if (package->name() == this->package_name() - && package->unique_prefix() == this->unique_prefix()) - error_at(location, - ("imported package uses same package name and prefix " - "as package being compiled (see -fgo-prefix option)")); - - this->imports_.insert(std::make_pair(filename, package)); - package->set_is_imported(); - } - - delete stream; -} - -// Add an import control function for an imported package to the list. - -void -Gogo::add_import_init_fn(const std::string& package_name, - const std::string& init_name, int prio) -{ - for (std::set::const_iterator p = - this->imported_init_fns_.begin(); - p != this->imported_init_fns_.end(); - ++p) - { - if (p->init_name() == init_name - && (p->package_name() != package_name || p->priority() != prio)) - { - error("duplicate package initialization name %qs", - Gogo::message_name(init_name).c_str()); - inform(UNKNOWN_LOCATION, "used by package %qs at priority %d", - Gogo::message_name(p->package_name()).c_str(), - p->priority()); - inform(UNKNOWN_LOCATION, " and by package %qs at priority %d", - Gogo::message_name(package_name).c_str(), prio); - return; - } - } - - this->imported_init_fns_.insert(Import_init(package_name, init_name, - prio)); -} - -// Return whether we are at the global binding level. - -bool -Gogo::in_global_scope() const -{ - return this->functions_.empty(); -} - -// Return the current binding contour. - -Bindings* -Gogo::current_bindings() -{ - if (!this->functions_.empty()) - return this->functions_.back().blocks.back()->bindings(); - else if (this->package_ != NULL) - return this->package_->bindings(); - else - return this->globals_; -} - -const Bindings* -Gogo::current_bindings() const -{ - if (!this->functions_.empty()) - return this->functions_.back().blocks.back()->bindings(); - else if (this->package_ != NULL) - return this->package_->bindings(); - else - return this->globals_; -} - -// Return the current block. - -Block* -Gogo::current_block() -{ - if (this->functions_.empty()) - return NULL; - else - return this->functions_.back().blocks.back(); -} - -// Look up a name in the current binding contour. If PFUNCTION is not -// NULL, set it to the function in which the name is defined, or NULL -// if the name is defined in global scope. - -Named_object* -Gogo::lookup(const std::string& name, Named_object** pfunction) const -{ - if (pfunction != NULL) - *pfunction = NULL; - - if (Gogo::is_sink_name(name)) - return Named_object::make_sink(); - - for (Open_functions::const_reverse_iterator p = this->functions_.rbegin(); - p != this->functions_.rend(); - ++p) - { - Named_object* ret = p->blocks.back()->bindings()->lookup(name); - if (ret != NULL) - { - if (pfunction != NULL) - *pfunction = p->function; - return ret; - } - } - - if (this->package_ != NULL) - { - Named_object* ret = this->package_->bindings()->lookup(name); - if (ret != NULL) - { - if (ret->package() != NULL) - ret->package()->set_used(); - return ret; - } - } - - // We do not look in the global namespace. If we did, the global - // namespace would effectively hide names which were defined in - // package scope which we have not yet seen. Instead, - // define_global_names is called after parsing is over to connect - // undefined names at package scope with names defined at global - // scope. - - return NULL; -} - -// Look up a name in the current block, without searching enclosing -// blocks. - -Named_object* -Gogo::lookup_in_block(const std::string& name) const -{ - go_assert(!this->functions_.empty()); - go_assert(!this->functions_.back().blocks.empty()); - return this->functions_.back().blocks.back()->bindings()->lookup_local(name); -} - -// Look up a name in the global namespace. - -Named_object* -Gogo::lookup_global(const char* name) const -{ - return this->globals_->lookup(name); -} - -// Add an imported package. - -Package* -Gogo::add_imported_package(const std::string& real_name, - const std::string& alias_arg, - bool is_alias_exported, - const std::string& unique_prefix, - source_location location, - bool* padd_to_globals) -{ - // FIXME: Now that we compile packages as a whole, should we permit - // importing the current package? - if (this->package_name() == real_name - && this->unique_prefix() == unique_prefix) - { - *padd_to_globals = false; - if (!alias_arg.empty() && alias_arg != ".") - { - std::string alias = this->pack_hidden_name(alias_arg, - is_alias_exported); - this->package_->bindings()->add_package(alias, this->package_); - } - return this->package_; - } - else if (alias_arg == ".") - { - *padd_to_globals = true; - return this->register_package(real_name, unique_prefix, location); - } - else if (alias_arg == "_") - { - Package* ret = this->register_package(real_name, unique_prefix, location); - ret->set_uses_sink_alias(); - return ret; - } - else - { - *padd_to_globals = false; - std::string alias = alias_arg; - if (alias.empty()) - { - alias = real_name; - is_alias_exported = Lex::is_exported_name(alias); - } - alias = this->pack_hidden_name(alias, is_alias_exported); - Named_object* no = this->add_package(real_name, alias, unique_prefix, - location); - if (!no->is_package()) - return NULL; - return no->package_value(); - } -} - -// Add a package. - -Named_object* -Gogo::add_package(const std::string& real_name, const std::string& alias, - const std::string& unique_prefix, source_location location) -{ - go_assert(this->in_global_scope()); - - // Register the package. Note that we might have already seen it in - // an earlier import. - Package* package = this->register_package(real_name, unique_prefix, location); - - return this->package_->bindings()->add_package(alias, package); -} - -// Register a package. This package may or may not be imported. This -// returns the Package structure for the package, creating if it -// necessary. - -Package* -Gogo::register_package(const std::string& package_name, - const std::string& unique_prefix, - source_location location) -{ - go_assert(!unique_prefix.empty() && !package_name.empty()); - std::string name = unique_prefix + '.' + package_name; - Package* package = NULL; - std::pair ins = - this->packages_.insert(std::make_pair(name, package)); - if (!ins.second) - { - // We have seen this package name before. - package = ins.first->second; - go_assert(package != NULL); - go_assert(package->name() == package_name - && package->unique_prefix() == unique_prefix); - if (package->location() == UNKNOWN_LOCATION) - package->set_location(location); - } - else - { - // First time we have seen this package name. - package = new Package(package_name, unique_prefix, location); - go_assert(ins.first->second == NULL); - ins.first->second = package; - } - - return package; -} - -// Start compiling a function. - -Named_object* -Gogo::start_function(const std::string& name, Function_type* type, - bool add_method_to_type, source_location location) -{ - bool at_top_level = this->functions_.empty(); - - Block* block = new Block(NULL, location); - - Function* enclosing = (at_top_level - ? NULL - : this->functions_.back().function->func_value()); - - Function* function = new Function(type, enclosing, block, location); - - if (type->is_method()) - { - const Typed_identifier* receiver = type->receiver(); - Variable* this_param = new Variable(receiver->type(), NULL, false, - true, true, location); - std::string name = receiver->name(); - if (name.empty()) - { - // We need to give receivers a name since they wind up in - // DECL_ARGUMENTS. FIXME. - static unsigned int count; - char buf[50]; - snprintf(buf, sizeof buf, "r.%u", count); - ++count; - name = buf; - } - block->bindings()->add_variable(name, NULL, this_param); - } - - const Typed_identifier_list* parameters = type->parameters(); - bool is_varargs = type->is_varargs(); - if (parameters != NULL) - { - for (Typed_identifier_list::const_iterator p = parameters->begin(); - p != parameters->end(); - ++p) - { - Variable* param = new Variable(p->type(), NULL, false, true, false, - location); - if (is_varargs && p + 1 == parameters->end()) - param->set_is_varargs_parameter(); - - std::string name = p->name(); - if (name.empty() || Gogo::is_sink_name(name)) - { - // We need to give parameters a name since they wind up - // in DECL_ARGUMENTS. FIXME. - static unsigned int count; - char buf[50]; - snprintf(buf, sizeof buf, "p.%u", count); - ++count; - name = buf; - } - block->bindings()->add_variable(name, NULL, param); - } - } - - function->create_result_variables(this); - - const std::string* pname; - std::string nested_name; - bool is_init = false; - if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method()) - { - if ((type->parameters() != NULL && !type->parameters()->empty()) - || (type->results() != NULL && !type->results()->empty())) - error_at(location, - "func init must have no arguments and no return values"); - // There can be multiple "init" functions, so give them each a - // different name. - static int init_count; - char buf[30]; - snprintf(buf, sizeof buf, ".$init%d", init_count); - ++init_count; - nested_name = buf; - pname = &nested_name; - is_init = true; - } - else if (!name.empty()) - pname = &name; - else - { - // Invent a name for a nested function. - static int nested_count; - char buf[30]; - snprintf(buf, sizeof buf, ".$nested%d", nested_count); - ++nested_count; - nested_name = buf; - pname = &nested_name; - } - - Named_object* ret; - if (Gogo::is_sink_name(*pname)) - { - static int sink_count; - char buf[30]; - snprintf(buf, sizeof buf, ".$sink%d", sink_count); - ++sink_count; - ret = Named_object::make_function(buf, NULL, function); - } - else if (!type->is_method()) - { - ret = this->package_->bindings()->add_function(*pname, NULL, function); - if (!ret->is_function() || ret->func_value() != function) - { - // Redefinition error. Invent a name to avoid knockon - // errors. - static int redefinition_count; - char buf[30]; - snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count); - ++redefinition_count; - ret = this->package_->bindings()->add_function(buf, NULL, function); - } - } - else - { - if (!add_method_to_type) - ret = Named_object::make_function(name, NULL, function); - else - { - go_assert(at_top_level); - Type* rtype = type->receiver()->type(); - - // We want to look through the pointer created by the - // parser, without getting an error if the type is not yet - // defined. - if (rtype->classification() == Type::TYPE_POINTER) - rtype = rtype->points_to(); - - if (rtype->is_error_type()) - ret = Named_object::make_function(name, NULL, function); - else if (rtype->named_type() != NULL) - { - ret = rtype->named_type()->add_method(name, function); - if (!ret->is_function()) - { - // Redefinition error. - ret = Named_object::make_function(name, NULL, function); - } - } - else if (rtype->forward_declaration_type() != NULL) - { - Named_object* type_no = - rtype->forward_declaration_type()->named_object(); - if (type_no->is_unknown()) - { - // If we are seeing methods it really must be a - // type. Declare it as such. An alternative would - // be to support lists of methods for unknown - // expressions. Either way the error messages if - // this is not a type are going to get confusing. - Named_object* declared = - this->declare_package_type(type_no->name(), - type_no->location()); - go_assert(declared - == type_no->unknown_value()->real_named_object()); - } - ret = rtype->forward_declaration_type()->add_method(name, - function); - } - else - go_unreachable(); - } - this->package_->bindings()->add_method(ret); - } - - this->functions_.resize(this->functions_.size() + 1); - Open_function& of(this->functions_.back()); - of.function = ret; - of.blocks.push_back(block); - - if (is_init) - { - this->init_functions_.push_back(ret); - this->need_init_fn_ = true; - } - - return ret; -} - -// Finish compiling a function. - -void -Gogo::finish_function(source_location location) -{ - this->finish_block(location); - go_assert(this->functions_.back().blocks.empty()); - this->functions_.pop_back(); -} - -// Return the current function. - -Named_object* -Gogo::current_function() const -{ - go_assert(!this->functions_.empty()); - return this->functions_.back().function; -} - -// Start a new block. - -void -Gogo::start_block(source_location location) -{ - go_assert(!this->functions_.empty()); - Block* block = new Block(this->current_block(), location); - this->functions_.back().blocks.push_back(block); -} - -// Finish a block. - -Block* -Gogo::finish_block(source_location location) -{ - go_assert(!this->functions_.empty()); - go_assert(!this->functions_.back().blocks.empty()); - Block* block = this->functions_.back().blocks.back(); - this->functions_.back().blocks.pop_back(); - block->set_end_location(location); - return block; -} - -// Add an unknown name. - -Named_object* -Gogo::add_unknown_name(const std::string& name, source_location location) -{ - return this->package_->bindings()->add_unknown_name(name, location); -} - -// Declare a function. - -Named_object* -Gogo::declare_function(const std::string& name, Function_type* type, - source_location location) -{ - if (!type->is_method()) - return this->current_bindings()->add_function_declaration(name, NULL, type, - location); - else - { - // We don't bother to add this to the list of global - // declarations. - Type* rtype = type->receiver()->type(); - - // We want to look through the pointer created by the - // parser, without getting an error if the type is not yet - // defined. - if (rtype->classification() == Type::TYPE_POINTER) - rtype = rtype->points_to(); - - if (rtype->is_error_type()) - return NULL; - else if (rtype->named_type() != NULL) - return rtype->named_type()->add_method_declaration(name, NULL, type, - location); - else if (rtype->forward_declaration_type() != NULL) - { - Forward_declaration_type* ftype = rtype->forward_declaration_type(); - return ftype->add_method_declaration(name, type, location); - } - else - go_unreachable(); - } -} - -// Add a label definition. - -Label* -Gogo::add_label_definition(const std::string& label_name, - source_location location) -{ - go_assert(!this->functions_.empty()); - Function* func = this->functions_.back().function->func_value(); - Label* label = func->add_label_definition(label_name, location); - this->add_statement(Statement::make_label_statement(label, location)); - return label; -} - -// Add a label reference. - -Label* -Gogo::add_label_reference(const std::string& label_name) -{ - go_assert(!this->functions_.empty()); - Function* func = this->functions_.back().function->func_value(); - return func->add_label_reference(label_name); -} - -// Add a statement. - -void -Gogo::add_statement(Statement* statement) -{ - go_assert(!this->functions_.empty() - && !this->functions_.back().blocks.empty()); - this->functions_.back().blocks.back()->add_statement(statement); -} - -// Add a block. - -void -Gogo::add_block(Block* block, source_location location) -{ - go_assert(!this->functions_.empty() - && !this->functions_.back().blocks.empty()); - Statement* statement = Statement::make_block_statement(block, location); - this->functions_.back().blocks.back()->add_statement(statement); -} - -// Add a constant. - -Named_object* -Gogo::add_constant(const Typed_identifier& tid, Expression* expr, - int iota_value) -{ - return this->current_bindings()->add_constant(tid, NULL, expr, iota_value); -} - -// Add a type. - -void -Gogo::add_type(const std::string& name, Type* type, source_location location) -{ - Named_object* no = this->current_bindings()->add_type(name, NULL, type, - location); - if (!this->in_global_scope() && no->is_type()) - no->type_value()->set_in_function(this->functions_.back().function); -} - -// Add a named type. - -void -Gogo::add_named_type(Named_type* type) -{ - go_assert(this->in_global_scope()); - this->current_bindings()->add_named_type(type); -} - -// Declare a type. - -Named_object* -Gogo::declare_type(const std::string& name, source_location location) -{ - Bindings* bindings = this->current_bindings(); - Named_object* no = bindings->add_type_declaration(name, NULL, location); - if (!this->in_global_scope() && no->is_type_declaration()) - { - Named_object* f = this->functions_.back().function; - no->type_declaration_value()->set_in_function(f); - } - return no; -} - -// Declare a type at the package level. - -Named_object* -Gogo::declare_package_type(const std::string& name, source_location location) -{ - return this->package_->bindings()->add_type_declaration(name, NULL, location); -} - -// Define a type which was already declared. - -void -Gogo::define_type(Named_object* no, Named_type* type) -{ - this->current_bindings()->define_type(no, type); -} - -// Add a variable. - -Named_object* -Gogo::add_variable(const std::string& name, Variable* variable) -{ - Named_object* no = this->current_bindings()->add_variable(name, NULL, - variable); - - // In a function the middle-end wants to see a DECL_EXPR node. - if (no != NULL - && no->is_variable() - && !no->var_value()->is_parameter() - && !this->functions_.empty()) - this->add_statement(Statement::make_variable_declaration(no)); - - return no; -} - -// Add a sink--a reference to the blank identifier _. - -Named_object* -Gogo::add_sink() -{ - return Named_object::make_sink(); -} - -// Add a named object. - -void -Gogo::add_named_object(Named_object* no) -{ - this->current_bindings()->add_named_object(no); -} - -// Record that we've seen an interface type. - -void -Gogo::record_interface_type(Interface_type* itype) -{ - this->interface_types_.push_back(itype); -} - -// Return a name for a thunk object. - -std::string -Gogo::thunk_name() -{ - static int thunk_count; - char thunk_name[50]; - snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count); - ++thunk_count; - return thunk_name; -} - -// Return whether a function is a thunk. - -bool -Gogo::is_thunk(const Named_object* no) -{ - return no->name().compare(0, 6, "$thunk") == 0; -} - -// Define the global names. We do this only after parsing all the -// input files, because the program might define the global names -// itself. - -void -Gogo::define_global_names() -{ - for (Bindings::const_declarations_iterator p = - this->globals_->begin_declarations(); - p != this->globals_->end_declarations(); - ++p) - { - Named_object* global_no = p->second; - std::string name(Gogo::pack_hidden_name(global_no->name(), false)); - Named_object* no = this->package_->bindings()->lookup(name); - if (no == NULL) - continue; - no = no->resolve(); - if (no->is_type_declaration()) - { - if (global_no->is_type()) - { - if (no->type_declaration_value()->has_methods()) - error_at(no->location(), - "may not define methods for global type"); - no->set_type_value(global_no->type_value()); - } - else - { - error_at(no->location(), "expected type"); - Type* errtype = Type::make_error_type(); - Named_object* err = Named_object::make_type("error", NULL, - errtype, - BUILTINS_LOCATION); - no->set_type_value(err->type_value()); - } - } - else if (no->is_unknown()) - no->unknown_value()->set_real_named_object(global_no); - } -} - -// Clear out names in file scope. - -void -Gogo::clear_file_scope() -{ - this->package_->bindings()->clear_file_scope(); - - // Warn about packages which were imported but not used. - for (Packages::iterator p = this->packages_.begin(); - p != this->packages_.end(); - ++p) - { - Package* package = p->second; - if (package != this->package_ - && package->is_imported() - && !package->used() - && !package->uses_sink_alias() - && !saw_errors()) - error_at(package->location(), "imported and not used: %s", - Gogo::message_name(package->name()).c_str()); - package->clear_is_imported(); - package->clear_uses_sink_alias(); - package->clear_used(); - } -} - -// Traverse the tree. - -void -Gogo::traverse(Traverse* traverse) -{ - // Traverse the current package first for consistency. The other - // packages will only contain imported types, constants, and - // declarations. - if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT) - return; - for (Packages::const_iterator p = this->packages_.begin(); - p != this->packages_.end(); - ++p) - { - if (p->second != this->package_) - { - if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT) - break; - } - } -} - -// Traversal class used to verify types. - -class Verify_types : public Traverse -{ - public: - Verify_types() - : Traverse(traverse_types) - { } - - int - type(Type*); -}; - -// Verify that a type is correct. - -int -Verify_types::type(Type* t) -{ - if (!t->verify()) - return TRAVERSE_SKIP_COMPONENTS; - return TRAVERSE_CONTINUE; -} - -// Verify that all types are correct. - -void -Gogo::verify_types() -{ - Verify_types traverse; - this->traverse(&traverse); -} - -// Traversal class used to lower parse tree. - -class Lower_parse_tree : public Traverse -{ - public: - Lower_parse_tree(Gogo* gogo, Named_object* function) - : Traverse(traverse_variables - | traverse_constants - | traverse_functions - | traverse_statements - | traverse_expressions), - gogo_(gogo), function_(function), iota_value_(-1) - { } - - int - variable(Named_object*); - - int - constant(Named_object*, bool); - - int - function(Named_object*); - - int - statement(Block*, size_t* pindex, Statement*); - - int - expression(Expression**); - - private: - // General IR. - Gogo* gogo_; - // The function we are traversing. - Named_object* function_; - // Value to use for the predeclared constant iota. - int iota_value_; -}; - -// Lower variables. We handle variables specially to break loops in -// which a variable initialization expression refers to itself. The -// loop breaking is in lower_init_expression. - -int -Lower_parse_tree::variable(Named_object* no) -{ - if (no->is_variable()) - no->var_value()->lower_init_expression(this->gogo_, this->function_); - return TRAVERSE_CONTINUE; -} - -// Lower constants. We handle constants specially so that we can set -// the right value for the predeclared constant iota. This works in -// conjunction with the way we lower Const_expression objects. - -int -Lower_parse_tree::constant(Named_object* no, bool) -{ - Named_constant* nc = no->const_value(); - - // Don't get into trouble if the constant's initializer expression - // refers to the constant itself. - if (nc->lowering()) - return TRAVERSE_CONTINUE; - nc->set_lowering(); - - go_assert(this->iota_value_ == -1); - this->iota_value_ = nc->iota_value(); - nc->traverse_expression(this); - this->iota_value_ = -1; - - nc->clear_lowering(); - - // We will traverse the expression a second time, but that will be - // fast. - - return TRAVERSE_CONTINUE; -} - -// Lower function closure types. Record the function while lowering -// it, so that we can pass it down when lowering an expression. - -int -Lower_parse_tree::function(Named_object* no) -{ - no->func_value()->set_closure_type(); - - go_assert(this->function_ == NULL); - this->function_ = no; - int t = no->func_value()->traverse(this); - this->function_ = NULL; - - if (t == TRAVERSE_EXIT) - return t; - return TRAVERSE_SKIP_COMPONENTS; -} - -// Lower statement parse trees. - -int -Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig) -{ - // Lower the expressions first. - int t = sorig->traverse_contents(this); - if (t == TRAVERSE_EXIT) - return t; - - // Keep lowering until nothing changes. - Statement* s = sorig; - while (true) - { - Statement* snew = s->lower(this->gogo_, this->function_, block); - if (snew == s) - break; - s = snew; - t = s->traverse_contents(this); - if (t == TRAVERSE_EXIT) - return t; - } - - if (s != sorig) - block->replace_statement(*pindex, s); - - return TRAVERSE_SKIP_COMPONENTS; -} - -// Lower expression parse trees. - -int -Lower_parse_tree::expression(Expression** pexpr) -{ - // We have to lower all subexpressions first, so that we can get - // their type if necessary. This is awkward, because we don't have - // a postorder traversal pass. - if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - // Keep lowering until nothing changes. - while (true) - { - Expression* e = *pexpr; - Expression* enew = e->lower(this->gogo_, this->function_, - this->iota_value_); - if (enew == e) - break; - *pexpr = enew; - } - return TRAVERSE_SKIP_COMPONENTS; -} - -// Lower the parse tree. This is called after the parse is complete, -// when all names should be resolved. - -void -Gogo::lower_parse_tree() -{ - Lower_parse_tree lower_parse_tree(this, NULL); - this->traverse(&lower_parse_tree); -} - -// Lower a block. - -void -Gogo::lower_block(Named_object* function, Block* block) -{ - Lower_parse_tree lower_parse_tree(this, function); - block->traverse(&lower_parse_tree); -} - -// Lower an expression. - -void -Gogo::lower_expression(Named_object* function, Expression** pexpr) -{ - Lower_parse_tree lower_parse_tree(this, function); - lower_parse_tree.expression(pexpr); -} - -// Lower a constant. This is called when lowering a reference to a -// constant. We have to make sure that the constant has already been -// lowered. - -void -Gogo::lower_constant(Named_object* no) -{ - go_assert(no->is_const()); - Lower_parse_tree lower(this, NULL); - lower.constant(no, false); -} - -// Look for interface types to finalize methods of inherited -// interfaces. - -class Finalize_methods : public Traverse -{ - public: - Finalize_methods(Gogo* gogo) - : Traverse(traverse_types), - gogo_(gogo) - { } - - int - type(Type*); - - private: - Gogo* gogo_; -}; - -// Finalize the methods of an interface type. - -int -Finalize_methods::type(Type* t) -{ - // Check the classification so that we don't finalize the methods - // twice for a named interface type. - switch (t->classification()) - { - case Type::TYPE_INTERFACE: - t->interface_type()->finalize_methods(); - break; - - case Type::TYPE_NAMED: - { - // We have to finalize the methods of the real type first. - // But if the real type is a struct type, then we only want to - // finalize the methods of the field types, not of the struct - // type itself. We don't want to add methods to the struct, - // since it has a name. - Type* rt = t->named_type()->real_type(); - if (rt->classification() != Type::TYPE_STRUCT) - { - if (Type::traverse(rt, this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - else - { - if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - - t->named_type()->finalize_methods(this->gogo_); - - return TRAVERSE_SKIP_COMPONENTS; - } - - case Type::TYPE_STRUCT: - t->struct_type()->finalize_methods(this->gogo_); - break; - - default: - break; - } - - return TRAVERSE_CONTINUE; -} - -// Finalize method lists and build stub methods for types. - -void -Gogo::finalize_methods() -{ - Finalize_methods finalize(this); - this->traverse(&finalize); -} - -// Set types for unspecified variables and constants. - -void -Gogo::determine_types() -{ - Bindings* bindings = this->current_bindings(); - for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); - p != bindings->end_definitions(); - ++p) - { - if ((*p)->is_function()) - (*p)->func_value()->determine_types(); - else if ((*p)->is_variable()) - (*p)->var_value()->determine_type(); - else if ((*p)->is_const()) - (*p)->const_value()->determine_type(); - - // See if a variable requires us to build an initialization - // function. We know that we will see all global variables - // here. - if (!this->need_init_fn_ && (*p)->is_variable()) - { - Variable* variable = (*p)->var_value(); - - // If this is a global variable which requires runtime - // initialization, we need an initialization function. - if (!variable->is_global()) - ; - else if (variable->init() == NULL) - ; - else if (variable->type()->interface_type() != NULL) - this->need_init_fn_ = true; - else if (variable->init()->is_constant()) - ; - else if (!variable->init()->is_composite_literal()) - this->need_init_fn_ = true; - else if (variable->init()->is_nonconstant_composite_literal()) - this->need_init_fn_ = true; - - // If this is a global variable which holds a pointer value, - // then we need an initialization function to register it as a - // GC root. - if (variable->is_global() && variable->type()->has_pointer()) - this->need_init_fn_ = true; - } - } - - // Determine the types of constants in packages. - for (Packages::const_iterator p = this->packages_.begin(); - p != this->packages_.end(); - ++p) - p->second->determine_types(); -} - -// Traversal class used for type checking. - -class Check_types_traverse : public Traverse -{ - public: - Check_types_traverse(Gogo* gogo) - : Traverse(traverse_variables - | traverse_constants - | traverse_functions - | traverse_statements - | traverse_expressions), - gogo_(gogo) - { } - - int - variable(Named_object*); - - int - constant(Named_object*, bool); - - int - function(Named_object*); - - int - statement(Block*, size_t* pindex, Statement*); - - int - expression(Expression**); - - private: - // General IR. - Gogo* gogo_; -}; - -// Check that a variable initializer has the right type. - -int -Check_types_traverse::variable(Named_object* named_object) -{ - if (named_object->is_variable()) - { - Variable* var = named_object->var_value(); - Expression* init = var->init(); - std::string reason; - if (init != NULL - && !Type::are_assignable(var->type(), init->type(), &reason)) - { - if (reason.empty()) - error_at(var->location(), "incompatible type in initialization"); - else - error_at(var->location(), - "incompatible type in initialization (%s)", - reason.c_str()); - var->clear_init(); - } - } - return TRAVERSE_CONTINUE; -} - -// Check that a constant initializer has the right type. - -int -Check_types_traverse::constant(Named_object* named_object, bool) -{ - Named_constant* constant = named_object->const_value(); - Type* ctype = constant->type(); - if (ctype->integer_type() == NULL - && ctype->float_type() == NULL - && ctype->complex_type() == NULL - && !ctype->is_boolean_type() - && !ctype->is_string_type()) - { - if (ctype->is_nil_type()) - error_at(constant->location(), "const initializer cannot be nil"); - else if (!ctype->is_error()) - error_at(constant->location(), "invalid constant type"); - constant->set_error(); - } - else if (!constant->expr()->is_constant()) - { - error_at(constant->expr()->location(), "expression is not constant"); - constant->set_error(); - } - else if (!Type::are_assignable(constant->type(), constant->expr()->type(), - NULL)) - { - error_at(constant->location(), - "initialization expression has wrong type"); - constant->set_error(); - } - return TRAVERSE_CONTINUE; -} - -// There are no types to check in a function, but this is where we -// issue warnings about labels which are defined but not referenced. - -int -Check_types_traverse::function(Named_object* no) -{ - no->func_value()->check_labels(); - return TRAVERSE_CONTINUE; -} - -// Check that types are valid in a statement. - -int -Check_types_traverse::statement(Block*, size_t*, Statement* s) -{ - s->check_types(this->gogo_); - return TRAVERSE_CONTINUE; -} - -// Check that types are valid in an expression. - -int -Check_types_traverse::expression(Expression** expr) -{ - (*expr)->check_types(this->gogo_); - return TRAVERSE_CONTINUE; -} - -// Check that types are valid. - -void -Gogo::check_types() -{ - Check_types_traverse traverse(this); - this->traverse(&traverse); -} - -// Check the types in a single block. - -void -Gogo::check_types_in_block(Block* block) -{ - Check_types_traverse traverse(this); - block->traverse(&traverse); -} - -// A traversal class used to find a single shortcut operator within an -// expression. - -class Find_shortcut : public Traverse -{ - public: - Find_shortcut() - : Traverse(traverse_blocks - | traverse_statements - | traverse_expressions), - found_(NULL) - { } - - // A pointer to the expression which was found, or NULL if none was - // found. - Expression** - found() const - { return this->found_; } - - protected: - int - block(Block*) - { return TRAVERSE_SKIP_COMPONENTS; } - - int - statement(Block*, size_t*, Statement*) - { return TRAVERSE_SKIP_COMPONENTS; } - - int - expression(Expression**); - - private: - Expression** found_; -}; - -// Find a shortcut expression. - -int -Find_shortcut::expression(Expression** pexpr) -{ - Expression* expr = *pexpr; - Binary_expression* be = expr->binary_expression(); - if (be == NULL) - return TRAVERSE_CONTINUE; - Operator op = be->op(); - if (op != OPERATOR_OROR && op != OPERATOR_ANDAND) - return TRAVERSE_CONTINUE; - go_assert(this->found_ == NULL); - this->found_ = pexpr; - return TRAVERSE_EXIT; -} - -// A traversal class used to turn shortcut operators into explicit if -// statements. - -class Shortcuts : public Traverse -{ - public: - Shortcuts(Gogo* gogo) - : Traverse(traverse_variables - | traverse_statements), - gogo_(gogo) - { } - - protected: - int - variable(Named_object*); - - int - statement(Block*, size_t*, Statement*); - - private: - // Convert a shortcut operator. - Statement* - convert_shortcut(Block* enclosing, Expression** pshortcut); - - // The IR. - Gogo* gogo_; -}; - -// Remove shortcut operators in a single statement. - -int -Shortcuts::statement(Block* block, size_t* pindex, Statement* s) -{ - // FIXME: This approach doesn't work for switch statements, because - // we add the new statements before the whole switch when we need to - // instead add them just before the switch expression. The right - // fix is probably to lower switch statements with nonconstant cases - // to a series of conditionals. - if (s->switch_statement() != NULL) - return TRAVERSE_CONTINUE; - - while (true) - { - Find_shortcut find_shortcut; - - // If S is a variable declaration, then ordinary traversal won't - // do anything. We want to explicitly traverse the - // initialization expression if there is one. - Variable_declaration_statement* vds = s->variable_declaration_statement(); - Expression* init = NULL; - if (vds == NULL) - s->traverse_contents(&find_shortcut); - else - { - init = vds->var()->var_value()->init(); - if (init == NULL) - return TRAVERSE_CONTINUE; - init->traverse(&init, &find_shortcut); - } - Expression** pshortcut = find_shortcut.found(); - if (pshortcut == NULL) - return TRAVERSE_CONTINUE; - - Statement* snew = this->convert_shortcut(block, pshortcut); - block->insert_statement_before(*pindex, snew); - ++*pindex; - - if (pshortcut == &init) - vds->var()->var_value()->set_init(init); - } -} - -// Remove shortcut operators in the initializer of a global variable. - -int -Shortcuts::variable(Named_object* no) -{ - if (no->is_result_variable()) - return TRAVERSE_CONTINUE; - Variable* var = no->var_value(); - Expression* init = var->init(); - if (!var->is_global() || init == NULL) - return TRAVERSE_CONTINUE; - - while (true) - { - Find_shortcut find_shortcut; - init->traverse(&init, &find_shortcut); - Expression** pshortcut = find_shortcut.found(); - if (pshortcut == NULL) - return TRAVERSE_CONTINUE; - - Statement* snew = this->convert_shortcut(NULL, pshortcut); - var->add_preinit_statement(this->gogo_, snew); - if (pshortcut == &init) - var->set_init(init); - } -} - -// Given an expression which uses a shortcut operator, return a -// statement which implements it, and update *PSHORTCUT accordingly. - -Statement* -Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut) -{ - Binary_expression* shortcut = (*pshortcut)->binary_expression(); - Expression* left = shortcut->left(); - Expression* right = shortcut->right(); - source_location loc = shortcut->location(); - - Block* retblock = new Block(enclosing, loc); - retblock->set_end_location(loc); - - Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(), - left, loc); - retblock->add_statement(ts); - - Block* block = new Block(retblock, loc); - block->set_end_location(loc); - Expression* tmpref = Expression::make_temporary_reference(ts, loc); - Statement* assign = Statement::make_assignment(tmpref, right, loc); - block->add_statement(assign); - - Expression* cond = Expression::make_temporary_reference(ts, loc); - if (shortcut->binary_expression()->op() == OPERATOR_OROR) - cond = Expression::make_unary(OPERATOR_NOT, cond, loc); - - Statement* if_statement = Statement::make_if_statement(cond, block, NULL, - loc); - retblock->add_statement(if_statement); - - *pshortcut = Expression::make_temporary_reference(ts, loc); - - delete shortcut; - - // Now convert any shortcut operators in LEFT and RIGHT. - Shortcuts shortcuts(this->gogo_); - retblock->traverse(&shortcuts); - - return Statement::make_block_statement(retblock, loc); -} - -// Turn shortcut operators into explicit if statements. Doing this -// considerably simplifies the order of evaluation rules. - -void -Gogo::remove_shortcuts() -{ - Shortcuts shortcuts(this); - this->traverse(&shortcuts); -} - -// A traversal class which finds all the expressions which must be -// evaluated in order within a statement or larger expression. This -// is used to implement the rules about order of evaluation. - -class Find_eval_ordering : public Traverse -{ - private: - typedef std::vector Expression_pointers; - - public: - Find_eval_ordering() - : Traverse(traverse_blocks - | traverse_statements - | traverse_expressions), - exprs_() - { } - - size_t - size() const - { return this->exprs_.size(); } - - typedef Expression_pointers::const_iterator const_iterator; - - const_iterator - begin() const - { return this->exprs_.begin(); } - - const_iterator - end() const - { return this->exprs_.end(); } - - protected: - int - block(Block*) - { return TRAVERSE_SKIP_COMPONENTS; } - - int - statement(Block*, size_t*, Statement*) - { return TRAVERSE_SKIP_COMPONENTS; } - - int - expression(Expression**); - - private: - // A list of pointers to expressions with side-effects. - Expression_pointers exprs_; -}; - -// If an expression must be evaluated in order, put it on the list. - -int -Find_eval_ordering::expression(Expression** expression_pointer) -{ - // We have to look at subexpressions before this one. - if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if ((*expression_pointer)->must_eval_in_order()) - this->exprs_.push_back(expression_pointer); - return TRAVERSE_SKIP_COMPONENTS; -} - -// A traversal class for ordering evaluations. - -class Order_eval : public Traverse -{ - public: - Order_eval(Gogo* gogo) - : Traverse(traverse_variables - | traverse_statements), - gogo_(gogo) - { } - - int - variable(Named_object*); - - int - statement(Block*, size_t*, Statement*); - - private: - // The IR. - Gogo* gogo_; -}; - -// Implement the order of evaluation rules for a statement. - -int -Order_eval::statement(Block* block, size_t* pindex, Statement* s) -{ - // FIXME: This approach doesn't work for switch statements, because - // we add the new statements before the whole switch when we need to - // instead add them just before the switch expression. The right - // fix is probably to lower switch statements with nonconstant cases - // to a series of conditionals. - if (s->switch_statement() != NULL) - return TRAVERSE_CONTINUE; - - Find_eval_ordering find_eval_ordering; - - // If S is a variable declaration, then ordinary traversal won't do - // anything. We want to explicitly traverse the initialization - // expression if there is one. - Variable_declaration_statement* vds = s->variable_declaration_statement(); - Expression* init = NULL; - Expression* orig_init = NULL; - if (vds == NULL) - s->traverse_contents(&find_eval_ordering); - else - { - init = vds->var()->var_value()->init(); - if (init == NULL) - return TRAVERSE_CONTINUE; - orig_init = init; - - // It might seem that this could be - // init->traverse_subexpressions. Unfortunately that can fail - // in a case like - // var err os.Error - // newvar, err := call(arg()) - // Here newvar will have an init of call result 0 of - // call(arg()). If we only traverse subexpressions, we will - // only find arg(), and we won't bother to move anything out. - // Then we get to the assignment to err, we will traverse the - // whole statement, and this time we will find both call() and - // arg(), and so we will move them out. This will cause them to - // be put into temporary variables before the assignment to err - // but after the declaration of newvar. To avoid that problem, - // we traverse the entire expression here. - Expression::traverse(&init, &find_eval_ordering); - } - - if (find_eval_ordering.size() <= 1) - { - // If there is only one expression with a side-effect, we can - // leave it in place. - return TRAVERSE_CONTINUE; - } - - bool is_thunk = s->thunk_statement() != NULL; - for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin(); - p != find_eval_ordering.end(); - ++p) - { - Expression** pexpr = *p; - - // The last expression in a thunk will be the call passed to go - // or defer, which we must not evaluate early. - if (is_thunk && p + 1 == find_eval_ordering.end()) - break; - - source_location loc = (*pexpr)->location(); - Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc); - block->insert_statement_before(*pindex, ts); - ++*pindex; - - *pexpr = Expression::make_temporary_reference(ts, loc); - } - - if (init != orig_init) - vds->var()->var_value()->set_init(init); - - return TRAVERSE_CONTINUE; -} - -// Implement the order of evaluation rules for the initializer of a -// global variable. - -int -Order_eval::variable(Named_object* no) -{ - if (no->is_result_variable()) - return TRAVERSE_CONTINUE; - Variable* var = no->var_value(); - Expression* init = var->init(); - if (!var->is_global() || init == NULL) - return TRAVERSE_CONTINUE; - - Find_eval_ordering find_eval_ordering; - init->traverse_subexpressions(&find_eval_ordering); - - if (find_eval_ordering.size() <= 1) - { - // If there is only one expression with a side-effect, we can - // leave it in place. - return TRAVERSE_SKIP_COMPONENTS; - } - - for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin(); - p != find_eval_ordering.end(); - ++p) - { - Expression** pexpr = *p; - source_location loc = (*pexpr)->location(); - Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc); - var->add_preinit_statement(this->gogo_, ts); - *pexpr = Expression::make_temporary_reference(ts, loc); - } - - return TRAVERSE_SKIP_COMPONENTS; -} - -// Use temporary variables to implement the order of evaluation rules. - -void -Gogo::order_evaluations() -{ - Order_eval order_eval(this); - this->traverse(&order_eval); -} - -// Traversal to convert calls to the predeclared recover function to -// pass in an argument indicating whether it can recover from a panic -// or not. - -class Convert_recover : public Traverse -{ - public: - Convert_recover(Named_object* arg) - : Traverse(traverse_expressions), - arg_(arg) - { } - - protected: - int - expression(Expression**); - - private: - // The argument to pass to the function. - Named_object* arg_; -}; - -// Convert calls to recover. - -int -Convert_recover::expression(Expression** pp) -{ - Call_expression* ce = (*pp)->call_expression(); - if (ce != NULL && ce->is_recover_call()) - ce->set_recover_arg(Expression::make_var_reference(this->arg_, - ce->location())); - return TRAVERSE_CONTINUE; -} - -// Traversal for build_recover_thunks. - -class Build_recover_thunks : public Traverse -{ - public: - Build_recover_thunks(Gogo* gogo) - : Traverse(traverse_functions), - gogo_(gogo) - { } - - int - function(Named_object*); - - private: - Expression* - can_recover_arg(source_location); - - // General IR. - Gogo* gogo_; -}; - -// If this function calls recover, turn it into a thunk. - -int -Build_recover_thunks::function(Named_object* orig_no) -{ - Function* orig_func = orig_no->func_value(); - if (!orig_func->calls_recover() - || orig_func->is_recover_thunk() - || orig_func->has_recover_thunk()) - return TRAVERSE_CONTINUE; - - Gogo* gogo = this->gogo_; - source_location location = orig_func->location(); - - static int count; - char buf[50]; - - Function_type* orig_fntype = orig_func->type(); - Typed_identifier_list* new_params = new Typed_identifier_list(); - std::string receiver_name; - if (orig_fntype->is_method()) - { - const Typed_identifier* receiver = orig_fntype->receiver(); - snprintf(buf, sizeof buf, "rt.%u", count); - ++count; - receiver_name = buf; - new_params->push_back(Typed_identifier(receiver_name, receiver->type(), - receiver->location())); - } - const Typed_identifier_list* orig_params = orig_fntype->parameters(); - if (orig_params != NULL && !orig_params->empty()) - { - for (Typed_identifier_list::const_iterator p = orig_params->begin(); - p != orig_params->end(); - ++p) - { - snprintf(buf, sizeof buf, "pt.%u", count); - ++count; - new_params->push_back(Typed_identifier(buf, p->type(), - p->location())); - } - } - snprintf(buf, sizeof buf, "pr.%u", count); - ++count; - std::string can_recover_name = buf; - new_params->push_back(Typed_identifier(can_recover_name, - Type::lookup_bool_type(), - orig_fntype->location())); - - const Typed_identifier_list* orig_results = orig_fntype->results(); - Typed_identifier_list* new_results; - if (orig_results == NULL || orig_results->empty()) - new_results = NULL; - else - { - new_results = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator p = orig_results->begin(); - p != orig_results->end(); - ++p) - new_results->push_back(Typed_identifier("", p->type(), p->location())); - } - - Function_type *new_fntype = Type::make_function_type(NULL, new_params, - new_results, - orig_fntype->location()); - if (orig_fntype->is_varargs()) - new_fntype->set_is_varargs(); - - std::string name = orig_no->name() + "$recover"; - Named_object *new_no = gogo->start_function(name, new_fntype, false, - location); - Function *new_func = new_no->func_value(); - if (orig_func->enclosing() != NULL) - new_func->set_enclosing(orig_func->enclosing()); - - // We build the code for the original function attached to the new - // function, and then swap the original and new function bodies. - // This means that existing references to the original function will - // then refer to the new function. That makes this code a little - // confusing, in that the reference to NEW_NO really refers to the - // other function, not the one we are building. - - Expression* closure = NULL; - if (orig_func->needs_closure()) - { - Named_object* orig_closure_no = orig_func->closure_var(); - Variable* orig_closure_var = orig_closure_no->var_value(); - Variable* new_var = new Variable(orig_closure_var->type(), NULL, false, - true, false, location); - snprintf(buf, sizeof buf, "closure.%u", count); - ++count; - Named_object* new_closure_no = Named_object::make_variable(buf, NULL, - new_var); - new_func->set_closure_var(new_closure_no); - closure = Expression::make_var_reference(new_closure_no, location); - } - - Expression* fn = Expression::make_func_reference(new_no, closure, location); - - Expression_list* args = new Expression_list(); - if (new_params != NULL) - { - // Note that we skip the last parameter, which is the boolean - // indicating whether recover can succed. - for (Typed_identifier_list::const_iterator p = new_params->begin(); - p + 1 != new_params->end(); - ++p) - { - Named_object* p_no = gogo->lookup(p->name(), NULL); - go_assert(p_no != NULL - && p_no->is_variable() - && p_no->var_value()->is_parameter()); - args->push_back(Expression::make_var_reference(p_no, location)); - } - } - args->push_back(this->can_recover_arg(location)); - - Call_expression* call = Expression::make_call(fn, args, false, location); - - Statement* s; - if (orig_fntype->results() == NULL || orig_fntype->results()->empty()) - s = Statement::make_statement(call); - else - { - Expression_list* vals = new Expression_list(); - size_t rc = orig_fntype->results()->size(); - if (rc == 1) - vals->push_back(call); - else - { - for (size_t i = 0; i < rc; ++i) - vals->push_back(Expression::make_call_result(call, i)); - } - s = Statement::make_return_statement(vals, location); - } - s->determine_types(); - gogo->add_statement(s); - - gogo->finish_function(location); - - // Swap the function bodies and types. - new_func->swap_for_recover(orig_func); - orig_func->set_is_recover_thunk(); - new_func->set_calls_recover(); - new_func->set_has_recover_thunk(); - - Bindings* orig_bindings = orig_func->block()->bindings(); - Bindings* new_bindings = new_func->block()->bindings(); - if (orig_fntype->is_method()) - { - // We changed the receiver to be a regular parameter. We have - // to update the binding accordingly in both functions. - Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name); - go_assert(orig_rec_no != NULL - && orig_rec_no->is_variable() - && !orig_rec_no->var_value()->is_receiver()); - orig_rec_no->var_value()->set_is_receiver(); - - const std::string& new_receiver_name(orig_fntype->receiver()->name()); - Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name); - if (new_rec_no == NULL) - go_assert(saw_errors()); - else - { - go_assert(new_rec_no->is_variable() - && new_rec_no->var_value()->is_receiver()); - new_rec_no->var_value()->set_is_not_receiver(); - } - } - - // Because we flipped blocks but not types, the can_recover - // parameter appears in the (now) old bindings as a parameter. - // Change it to a local variable, whereupon it will be discarded. - Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name); - go_assert(can_recover_no != NULL - && can_recover_no->is_variable() - && can_recover_no->var_value()->is_parameter()); - orig_bindings->remove_binding(can_recover_no); - - // Add the can_recover argument to the (now) new bindings, and - // attach it to any recover statements. - Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL, - false, true, false, location); - can_recover_no = new_bindings->add_variable(can_recover_name, NULL, - can_recover_var); - Convert_recover convert_recover(can_recover_no); - new_func->traverse(&convert_recover); - - // Update the function pointers in any named results. - new_func->update_result_variables(); - orig_func->update_result_variables(); - - return TRAVERSE_CONTINUE; -} - -// Return the expression to pass for the .can_recover parameter to the -// new function. This indicates whether a call to recover may return -// non-nil. The expression is -// __go_can_recover(__builtin_return_address()). - -Expression* -Build_recover_thunks::can_recover_arg(source_location location) -{ - static Named_object* builtin_return_address; - if (builtin_return_address == NULL) - { - const source_location bloc = BUILTINS_LOCATION; - - Typed_identifier_list* param_types = new Typed_identifier_list(); - Type* uint_type = Type::lookup_integer_type("uint"); - param_types->push_back(Typed_identifier("l", uint_type, bloc)); - - Typed_identifier_list* return_types = new Typed_identifier_list(); - Type* voidptr_type = Type::make_pointer_type(Type::make_void_type()); - return_types->push_back(Typed_identifier("", voidptr_type, bloc)); - - Function_type* fntype = Type::make_function_type(NULL, param_types, - return_types, bloc); - builtin_return_address = - Named_object::make_function_declaration("__builtin_return_address", - NULL, fntype, bloc); - const char* n = "__builtin_return_address"; - builtin_return_address->func_declaration_value()->set_asm_name(n); - } - - static Named_object* can_recover; - if (can_recover == NULL) - { - const source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - Type* voidptr_type = Type::make_pointer_type(Type::make_void_type()); - param_types->push_back(Typed_identifier("a", voidptr_type, bloc)); - Type* boolean_type = Type::lookup_bool_type(); - Typed_identifier_list* results = new Typed_identifier_list(); - results->push_back(Typed_identifier("", boolean_type, bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, - results, bloc); - can_recover = Named_object::make_function_declaration("__go_can_recover", - NULL, fntype, - bloc); - can_recover->func_declaration_value()->set_asm_name("__go_can_recover"); - } - - Expression* fn = Expression::make_func_reference(builtin_return_address, - NULL, location); - - mpz_t zval; - mpz_init_set_ui(zval, 0UL); - Expression* zexpr = Expression::make_integer(&zval, NULL, location); - mpz_clear(zval); - Expression_list *args = new Expression_list(); - args->push_back(zexpr); - - Expression* call = Expression::make_call(fn, args, false, location); - - args = new Expression_list(); - args->push_back(call); - - fn = Expression::make_func_reference(can_recover, NULL, location); - return Expression::make_call(fn, args, false, location); -} - -// Build thunks for functions which call recover. We build a new -// function with an extra parameter, which is whether a call to -// recover can succeed. We then move the body of this function to -// that one. We then turn this function into a thunk which calls the -// new one, passing the value of -// __go_can_recover(__builtin_return_address()). The function will be -// marked as not splitting the stack. This will cooperate with the -// implementation of defer to make recover do the right thing. - -void -Gogo::build_recover_thunks() -{ - Build_recover_thunks build_recover_thunks(this); - this->traverse(&build_recover_thunks); -} - -// Look for named types to see whether we need to create an interface -// method table. - -class Build_method_tables : public Traverse -{ - public: - Build_method_tables(Gogo* gogo, - const std::vector& interfaces) - : Traverse(traverse_types), - gogo_(gogo), interfaces_(interfaces) - { } - - int - type(Type*); - - private: - // The IR. - Gogo* gogo_; - // A list of locally defined interfaces which have hidden methods. - const std::vector& interfaces_; -}; - -// Build all required interface method tables for types. We need to -// ensure that we have an interface method table for every interface -// which has a hidden method, for every named type which implements -// that interface. Normally we can just build interface method tables -// as we need them. However, in some cases we can require an -// interface method table for an interface defined in a different -// package for a type defined in that package. If that interface and -// type both use a hidden method, that is OK. However, we will not be -// able to build that interface method table when we need it, because -// the type's hidden method will be static. So we have to build it -// here, and just refer it from other packages as needed. - -void -Gogo::build_interface_method_tables() -{ - std::vector hidden_interfaces; - hidden_interfaces.reserve(this->interface_types_.size()); - for (std::vector::const_iterator pi = - this->interface_types_.begin(); - pi != this->interface_types_.end(); - ++pi) - { - const Typed_identifier_list* methods = (*pi)->methods(); - if (methods == NULL) - continue; - for (Typed_identifier_list::const_iterator pm = methods->begin(); - pm != methods->end(); - ++pm) - { - if (Gogo::is_hidden_name(pm->name())) - { - hidden_interfaces.push_back(*pi); - break; - } - } - } - - if (!hidden_interfaces.empty()) - { - // Now traverse the tree looking for all named types. - Build_method_tables bmt(this, hidden_interfaces); - this->traverse(&bmt); - } - - // We no longer need the list of interfaces. - - this->interface_types_.clear(); -} - -// This is called for each type. For a named type, for each of the -// interfaces with hidden methods that it implements, create the -// method table. - -int -Build_method_tables::type(Type* type) -{ - Named_type* nt = type->named_type(); - if (nt != NULL) - { - for (std::vector::const_iterator p = - this->interfaces_.begin(); - p != this->interfaces_.end(); - ++p) - { - // We ask whether a pointer to the named type implements the - // interface, because a pointer can implement more methods - // than a value. - if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL)) - { - nt->interface_method_table(this->gogo_, *p, false); - nt->interface_method_table(this->gogo_, *p, true); - } - } - } - return TRAVERSE_CONTINUE; -} - -// Traversal class used to check for return statements. - -class Check_return_statements_traverse : public Traverse -{ - public: - Check_return_statements_traverse() - : Traverse(traverse_functions) - { } - - int - function(Named_object*); -}; - -// Check that a function has a return statement if it needs one. - -int -Check_return_statements_traverse::function(Named_object* no) -{ - Function* func = no->func_value(); - const Function_type* fntype = func->type(); - const Typed_identifier_list* results = fntype->results(); - - // We only need a return statement if there is a return value. - if (results == NULL || results->empty()) - return TRAVERSE_CONTINUE; - - if (func->block()->may_fall_through()) - error_at(func->location(), "control reaches end of non-void function"); - - return TRAVERSE_CONTINUE; -} - -// Check return statements. - -void -Gogo::check_return_statements() -{ - Check_return_statements_traverse traverse; - this->traverse(&traverse); -} - -// Get the unique prefix to use before all exported symbols. This -// must be unique across the entire link. - -const std::string& -Gogo::unique_prefix() const -{ - go_assert(!this->unique_prefix_.empty()); - return this->unique_prefix_; -} - -// Set the unique prefix to use before all exported symbols. This -// comes from the command line option -fgo-prefix=XXX. - -void -Gogo::set_unique_prefix(const std::string& arg) -{ - go_assert(this->unique_prefix_.empty()); - this->unique_prefix_ = arg; - this->unique_prefix_specified_ = true; -} - -// Work out the package priority. It is one more than the maximum -// priority of an imported package. - -int -Gogo::package_priority() const -{ - int priority = 0; - for (Packages::const_iterator p = this->packages_.begin(); - p != this->packages_.end(); - ++p) - if (p->second->priority() > priority) - priority = p->second->priority(); - return priority + 1; -} - -// Export identifiers as requested. - -void -Gogo::do_exports() -{ - // For now we always stream to a section. Later we may want to - // support streaming to a separate file. - Stream_to_section stream; - - Export exp(&stream); - exp.register_builtin_types(this); - exp.export_globals(this->package_name(), - this->unique_prefix(), - this->package_priority(), - (this->need_init_fn_ && !this->is_main_package() - ? this->get_init_fn_name() - : ""), - this->imported_init_fns_, - this->package_->bindings()); -} - -// Find the blocks in order to convert named types defined in blocks. - -class Convert_named_types : public Traverse -{ - public: - Convert_named_types(Gogo* gogo) - : Traverse(traverse_blocks), - gogo_(gogo) - { } - - protected: - int - block(Block* block); - - private: - Gogo* gogo_; -}; - -int -Convert_named_types::block(Block* block) -{ - this->gogo_->convert_named_types_in_bindings(block->bindings()); - return TRAVERSE_CONTINUE; -} - -// Convert all named types to the backend representation. Since named -// types can refer to other types, this needs to be done in the right -// sequence, which is handled by Named_type::convert. Here we arrange -// to call that for each named type. - -void -Gogo::convert_named_types() -{ - this->convert_named_types_in_bindings(this->globals_); - for (Packages::iterator p = this->packages_.begin(); - p != this->packages_.end(); - ++p) - { - Package* package = p->second; - this->convert_named_types_in_bindings(package->bindings()); - } - - Convert_named_types cnt(this); - this->traverse(&cnt); - - // Make all the builtin named types used for type descriptors, and - // then convert them. They will only be written out if they are - // needed. - Type::make_type_descriptor_type(); - Type::make_type_descriptor_ptr_type(); - Function_type::make_function_type_descriptor_type(); - Pointer_type::make_pointer_type_descriptor_type(); - Struct_type::make_struct_type_descriptor_type(); - Array_type::make_array_type_descriptor_type(); - Array_type::make_slice_type_descriptor_type(); - Map_type::make_map_type_descriptor_type(); - Channel_type::make_chan_type_descriptor_type(); - Interface_type::make_interface_type_descriptor_type(); - Type::convert_builtin_named_types(this); - - Runtime::convert_types(this); - - this->named_types_are_converted_ = true; -} - -// Convert all names types in a set of bindings. - -void -Gogo::convert_named_types_in_bindings(Bindings* bindings) -{ - for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); - p != bindings->end_definitions(); - ++p) - { - if ((*p)->is_type()) - (*p)->type_value()->convert(this); - } -} - -// Class Function. - -Function::Function(Function_type* type, Function* enclosing, Block* block, - source_location location) - : type_(type), enclosing_(enclosing), results_(NULL), - closure_var_(NULL), block_(block), location_(location), fndecl_(NULL), - defer_stack_(NULL), results_are_named_(false), calls_recover_(false), - is_recover_thunk_(false), has_recover_thunk_(false) -{ -} - -// Create the named result variables. - -void -Function::create_result_variables(Gogo* gogo) -{ - const Typed_identifier_list* results = this->type_->results(); - if (results == NULL || results->empty()) - return; - - if (!results->front().name().empty()) - this->results_are_named_ = true; - - this->results_ = new Results(); - this->results_->reserve(results->size()); - - Block* block = this->block_; - int index = 0; - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p, ++index) - { - std::string name = p->name(); - if (name.empty() || Gogo::is_sink_name(name)) - { - static int result_counter; - char buf[100]; - snprintf(buf, sizeof buf, "$ret%d", result_counter); - ++result_counter; - name = gogo->pack_hidden_name(buf, false); - } - Result_variable* result = new Result_variable(p->type(), this, index, - p->location()); - Named_object* no = block->bindings()->add_result_variable(name, result); - if (no->is_result_variable()) - this->results_->push_back(no); - else - { - static int dummy_result_count; - char buf[100]; - snprintf(buf, sizeof buf, "$dret%d", dummy_result_count); - ++dummy_result_count; - name = gogo->pack_hidden_name(buf, false); - no = block->bindings()->add_result_variable(name, result); - go_assert(no->is_result_variable()); - this->results_->push_back(no); - } - } -} - -// Update the named result variables when cloning a function which -// calls recover. - -void -Function::update_result_variables() -{ - if (this->results_ == NULL) - return; - - for (Results::iterator p = this->results_->begin(); - p != this->results_->end(); - ++p) - (*p)->result_var_value()->set_function(this); -} - -// Return the closure variable, creating it if necessary. - -Named_object* -Function::closure_var() -{ - if (this->closure_var_ == NULL) - { - // We don't know the type of the variable yet. We add fields as - // we find them. - source_location loc = this->type_->location(); - Struct_field_list* sfl = new Struct_field_list; - Type* struct_type = Type::make_struct_type(sfl, loc); - Variable* var = new Variable(Type::make_pointer_type(struct_type), - NULL, false, true, false, loc); - this->closure_var_ = Named_object::make_variable("closure", NULL, var); - // Note that the new variable is not in any binding contour. - } - return this->closure_var_; -} - -// Set the type of the closure variable. - -void -Function::set_closure_type() -{ - if (this->closure_var_ == NULL) - return; - Named_object* closure = this->closure_var_; - Struct_type* st = closure->var_value()->type()->deref()->struct_type(); - unsigned int index = 0; - for (Closure_fields::const_iterator p = this->closure_fields_.begin(); - p != this->closure_fields_.end(); - ++p, ++index) - { - Named_object* no = p->first; - char buf[20]; - snprintf(buf, sizeof buf, "%u", index); - std::string n = no->name() + buf; - Type* var_type; - if (no->is_variable()) - var_type = no->var_value()->type(); - else - var_type = no->result_var_value()->type(); - Type* field_type = Type::make_pointer_type(var_type); - st->push_field(Struct_field(Typed_identifier(n, field_type, p->second))); - } -} - -// Return whether this function is a method. - -bool -Function::is_method() const -{ - return this->type_->is_method(); -} - -// Add a label definition. - -Label* -Function::add_label_definition(const std::string& label_name, - source_location location) -{ - Label* lnull = NULL; - std::pair ins = - this->labels_.insert(std::make_pair(label_name, lnull)); - if (ins.second) - { - // This is a new label. - Label* label = new Label(label_name); - label->define(location); - ins.first->second = label; - return label; - } - else - { - // The label was already in the hash table. - Label* label = ins.first->second; - if (!label->is_defined()) - { - label->define(location); - return label; - } - else - { - error_at(location, "label %qs already defined", - Gogo::message_name(label_name).c_str()); - inform(label->location(), "previous definition of %qs was here", - Gogo::message_name(label_name).c_str()); - return new Label(label_name); - } - } -} - -// Add a reference to a label. - -Label* -Function::add_label_reference(const std::string& label_name) -{ - Label* lnull = NULL; - std::pair ins = - this->labels_.insert(std::make_pair(label_name, lnull)); - if (!ins.second) - { - // The label was already in the hash table. - Label* label = ins.first->second; - label->set_is_used(); - return label; - } - else - { - go_assert(ins.first->second == NULL); - Label* label = new Label(label_name); - ins.first->second = label; - label->set_is_used(); - return label; - } -} - -// Warn about labels that are defined but not used. - -void -Function::check_labels() const -{ - for (Labels::const_iterator p = this->labels_.begin(); - p != this->labels_.end(); - p++) - { - Label* label = p->second; - if (!label->is_used()) - error_at(label->location(), "label %qs defined and not used", - Gogo::message_name(label->name()).c_str()); - } -} - -// Swap one function with another. This is used when building the -// thunk we use to call a function which calls recover. It may not -// work for any other case. - -void -Function::swap_for_recover(Function *x) -{ - go_assert(this->enclosing_ == x->enclosing_); - std::swap(this->results_, x->results_); - std::swap(this->closure_var_, x->closure_var_); - std::swap(this->block_, x->block_); - go_assert(this->location_ == x->location_); - go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL); - go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL); -} - -// Traverse the tree. - -int -Function::traverse(Traverse* traverse) -{ - unsigned int traverse_mask = traverse->traverse_mask(); - - if ((traverse_mask - & (Traverse::traverse_types | Traverse::traverse_expressions)) - != 0) - { - if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - - // FIXME: We should check traverse_functions here if nested - // functions are stored in block bindings. - if (this->block_ != NULL - && (traverse_mask - & (Traverse::traverse_variables - | Traverse::traverse_constants - | Traverse::traverse_blocks - | Traverse::traverse_statements - | Traverse::traverse_expressions - | Traverse::traverse_types)) != 0) - { - if (this->block_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - - return TRAVERSE_CONTINUE; -} - -// Work out types for unspecified variables and constants. - -void -Function::determine_types() -{ - if (this->block_ != NULL) - this->block_->determine_types(); -} - -// Get a pointer to the variable holding the defer stack for this -// function, making it if necessary. At least at present, the value -// of this variable is not used. However, a pointer to this variable -// is used as a marker for the functions on the defer stack associated -// with this function. Doing things this way permits inlining a -// function which uses defer. - -Expression* -Function::defer_stack(source_location location) -{ - Type* t = Type::make_pointer_type(Type::make_void_type()); - if (this->defer_stack_ == NULL) - { - Expression* n = Expression::make_nil(location); - this->defer_stack_ = Statement::make_temporary(t, n, location); - this->defer_stack_->set_is_address_taken(); - } - Expression* ref = Expression::make_temporary_reference(this->defer_stack_, - location); - Expression* addr = Expression::make_unary(OPERATOR_AND, ref, location); - return Expression::make_unsafe_cast(t, addr, location); -} - -// Export the function. - -void -Function::export_func(Export* exp, const std::string& name) const -{ - Function::export_func_with_type(exp, name, this->type_); -} - -// Export a function with a type. - -void -Function::export_func_with_type(Export* exp, const std::string& name, - const Function_type* fntype) -{ - exp->write_c_string("func "); - - if (fntype->is_method()) - { - exp->write_c_string("("); - exp->write_type(fntype->receiver()->type()); - exp->write_c_string(") "); - } - - exp->write_string(name); - - exp->write_c_string(" ("); - const Typed_identifier_list* parameters = fntype->parameters(); - if (parameters != NULL) - { - bool is_varargs = fntype->is_varargs(); - bool first = true; - for (Typed_identifier_list::const_iterator p = parameters->begin(); - p != parameters->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - if (!is_varargs || p + 1 != parameters->end()) - exp->write_type(p->type()); - else - { - exp->write_c_string("..."); - exp->write_type(p->type()->array_type()->element_type()); - } - } - } - exp->write_c_string(")"); - - const Typed_identifier_list* results = fntype->results(); - if (results != NULL) - { - if (results->size() == 1) - { - exp->write_c_string(" "); - exp->write_type(results->begin()->type()); - } - else - { - exp->write_c_string(" ("); - bool first = true; - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - exp->write_type(p->type()); - } - exp->write_c_string(")"); - } - } - exp->write_c_string(";\n"); -} - -// Import a function. - -void -Function::import_func(Import* imp, std::string* pname, - Typed_identifier** preceiver, - Typed_identifier_list** pparameters, - Typed_identifier_list** presults, - bool* is_varargs) -{ - imp->require_c_string("func "); - - *preceiver = NULL; - if (imp->peek_char() == '(') - { - imp->require_c_string("("); - Type* rtype = imp->read_type(); - *preceiver = new Typed_identifier(Import::import_marker, rtype, - imp->location()); - imp->require_c_string(") "); - } - - *pname = imp->read_identifier(); - - Typed_identifier_list* parameters; - *is_varargs = false; - imp->require_c_string(" ("); - if (imp->peek_char() == ')') - parameters = NULL; - else - { - parameters = new Typed_identifier_list(); - while (true) - { - if (imp->match_c_string("...")) - { - imp->advance(3); - *is_varargs = true; - } - - Type* ptype = imp->read_type(); - if (*is_varargs) - ptype = Type::make_array_type(ptype, NULL); - parameters->push_back(Typed_identifier(Import::import_marker, - ptype, imp->location())); - if (imp->peek_char() != ',') - break; - go_assert(!*is_varargs); - imp->require_c_string(", "); - } - } - imp->require_c_string(")"); - *pparameters = parameters; - - Typed_identifier_list* results; - if (imp->peek_char() != ' ') - results = NULL; - else - { - results = new Typed_identifier_list(); - imp->require_c_string(" "); - if (imp->peek_char() != '(') - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, rtype, - imp->location())); - } - else - { - imp->require_c_string("("); - while (true) - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, - rtype, imp->location())); - if (imp->peek_char() != ',') - break; - imp->require_c_string(", "); - } - imp->require_c_string(")"); - } - } - imp->require_c_string(";\n"); - *presults = results; -} - -// Class Block. - -Block::Block(Block* enclosing, source_location location) - : enclosing_(enclosing), statements_(), - bindings_(new Bindings(enclosing == NULL - ? NULL - : enclosing->bindings())), - start_location_(location), - end_location_(UNKNOWN_LOCATION) -{ -} - -// Add a statement to a block. - -void -Block::add_statement(Statement* statement) -{ - this->statements_.push_back(statement); -} - -// Add a statement to the front of a block. This is slow but is only -// used for reference counts of parameters. - -void -Block::add_statement_at_front(Statement* statement) -{ - this->statements_.insert(this->statements_.begin(), statement); -} - -// Replace a statement in a block. - -void -Block::replace_statement(size_t index, Statement* s) -{ - go_assert(index < this->statements_.size()); - this->statements_[index] = s; -} - -// Add a statement before another statement. - -void -Block::insert_statement_before(size_t index, Statement* s) -{ - go_assert(index < this->statements_.size()); - this->statements_.insert(this->statements_.begin() + index, s); -} - -// Add a statement after another statement. - -void -Block::insert_statement_after(size_t index, Statement* s) -{ - go_assert(index < this->statements_.size()); - this->statements_.insert(this->statements_.begin() + index + 1, s); -} - -// Traverse the tree. - -int -Block::traverse(Traverse* traverse) -{ - unsigned int traverse_mask = traverse->traverse_mask(); - - if ((traverse_mask & Traverse::traverse_blocks) != 0) - { - int t = traverse->block(this); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - return TRAVERSE_CONTINUE; - } - - if ((traverse_mask - & (Traverse::traverse_variables - | Traverse::traverse_constants - | Traverse::traverse_expressions - | Traverse::traverse_types)) != 0) - { - for (Bindings::const_definitions_iterator pb = - this->bindings_->begin_definitions(); - pb != this->bindings_->end_definitions(); - ++pb) - { - switch ((*pb)->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - if ((traverse_mask & Traverse::traverse_constants) != 0) - { - if (traverse->constant(*pb, false) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if ((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - { - Type* t = (*pb)->const_value()->type(); - if (t != NULL - && Type::traverse(t, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if ((traverse_mask & Traverse::traverse_expressions) != 0 - || (traverse_mask & Traverse::traverse_types) != 0) - { - if ((*pb)->const_value()->traverse_expression(traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - if ((traverse_mask & Traverse::traverse_variables) != 0) - { - if (traverse->variable(*pb) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - && ((*pb)->is_result_variable() - || (*pb)->var_value()->has_type())) - { - Type* t = ((*pb)->is_variable() - ? (*pb)->var_value()->type() - : (*pb)->result_var_value()->type()); - if (t != NULL - && Type::traverse(t, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if ((*pb)->is_variable() - && ((traverse_mask & Traverse::traverse_expressions) != 0 - || (traverse_mask & Traverse::traverse_types) != 0)) - { - if ((*pb)->var_value()->traverse_expression(traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_FUNC: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - // FIXME: Where will nested functions be found? - go_unreachable(); - - case Named_object::NAMED_OBJECT_TYPE: - if ((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - { - if (Type::traverse((*pb)->type_value(), traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - case Named_object::NAMED_OBJECT_UNKNOWN: - break; - - case Named_object::NAMED_OBJECT_PACKAGE: - case Named_object::NAMED_OBJECT_SINK: - go_unreachable(); - - default: - go_unreachable(); - } - } - } - - // No point in checking traverse_mask here--if we got here we always - // want to walk the statements. The traversal can insert new - // statements before or after the current statement. Inserting - // statements before the current statement requires updating I via - // the pointer; those statements will not be traversed. Any new - // statements inserted after the current statement will be traversed - // in their turn. - for (size_t i = 0; i < this->statements_.size(); ++i) - { - if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - - return TRAVERSE_CONTINUE; -} - -// Work out types for unspecified variables and constants. - -void -Block::determine_types() -{ - for (Bindings::const_definitions_iterator pb = - this->bindings_->begin_definitions(); - pb != this->bindings_->end_definitions(); - ++pb) - { - if ((*pb)->is_variable()) - (*pb)->var_value()->determine_type(); - else if ((*pb)->is_const()) - (*pb)->const_value()->determine_type(); - } - - for (std::vector::const_iterator ps = this->statements_.begin(); - ps != this->statements_.end(); - ++ps) - (*ps)->determine_types(); -} - -// Return true if the statements in this block may fall through. - -bool -Block::may_fall_through() const -{ - if (this->statements_.empty()) - return true; - return this->statements_.back()->may_fall_through(); -} - -// Convert a block to the backend representation. - -Bblock* -Block::get_backend(Translate_context* context) -{ - Gogo* gogo = context->gogo(); - Named_object* function = context->function(); - std::vector vars; - vars.reserve(this->bindings_->size_definitions()); - for (Bindings::const_definitions_iterator pv = - this->bindings_->begin_definitions(); - pv != this->bindings_->end_definitions(); - ++pv) - { - if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter()) - vars.push_back((*pv)->get_backend_variable(gogo, function)); - } - - // FIXME: Permitting FUNCTION to be NULL here is a temporary measure - // until we have a proper representation of the init function. - Bfunction* bfunction; - if (function == NULL) - bfunction = NULL; - else - bfunction = tree_to_function(function->func_value()->get_decl()); - Bblock* ret = context->backend()->block(bfunction, context->bblock(), - vars, this->start_location_, - this->end_location_); - - Translate_context subcontext(gogo, function, this, ret); - std::vector bstatements; - bstatements.reserve(this->statements_.size()); - for (std::vector::const_iterator p = this->statements_.begin(); - p != this->statements_.end(); - ++p) - bstatements.push_back((*p)->get_backend(&subcontext)); - - context->backend()->block_add_statements(ret, bstatements); - - return ret; -} - -// Class Variable. - -Variable::Variable(Type* type, Expression* init, bool is_global, - bool is_parameter, bool is_receiver, - source_location location) - : type_(type), init_(init), preinit_(NULL), location_(location), - backend_(NULL), is_global_(is_global), is_parameter_(is_parameter), - is_receiver_(is_receiver), is_varargs_parameter_(false), - is_address_taken_(false), seen_(false), init_is_lowered_(false), - type_from_init_tuple_(false), type_from_range_index_(false), - type_from_range_value_(false), type_from_chan_element_(false), - is_type_switch_var_(false), determined_type_(false) -{ - go_assert(type != NULL || init != NULL); - go_assert(!is_parameter || init == NULL); -} - -// Traverse the initializer expression. - -int -Variable::traverse_expression(Traverse* traverse) -{ - if (this->preinit_ != NULL) - { - if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->init_ != NULL) - { - if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lower the initialization expression after parsing is complete. - -void -Variable::lower_init_expression(Gogo* gogo, Named_object* function) -{ - if (this->init_ != NULL && !this->init_is_lowered_) - { - if (this->seen_) - { - // We will give an error elsewhere, this is just to prevent - // an infinite loop. - return; - } - this->seen_ = true; - - gogo->lower_expression(function, &this->init_); - - this->seen_ = false; - - this->init_is_lowered_ = true; - } -} - -// Get the preinit block. - -Block* -Variable::preinit_block(Gogo* gogo) -{ - go_assert(this->is_global_); - if (this->preinit_ == NULL) - this->preinit_ = new Block(NULL, this->location()); - - // If a global variable has a preinitialization statement, then we - // need to have an initialization function. - gogo->set_need_init_fn(); - - return this->preinit_; -} - -// Add a statement to be run before the initialization expression. - -void -Variable::add_preinit_statement(Gogo* gogo, Statement* s) -{ - Block* b = this->preinit_block(gogo); - b->add_statement(s); - b->set_end_location(s->location()); -} - -// In an assignment which sets a variable to a tuple of EXPR, return -// the type of the first element of the tuple. - -Type* -Variable::type_from_tuple(Expression* expr, bool report_error) const -{ - if (expr->map_index_expression() != NULL) - { - Map_type* mt = expr->map_index_expression()->get_map_type(); - if (mt == NULL) - return Type::make_error_type(); - return mt->val_type(); - } - else if (expr->receive_expression() != NULL) - { - Expression* channel = expr->receive_expression()->channel(); - Type* channel_type = channel->type(); - if (channel_type->channel_type() == NULL) - return Type::make_error_type(); - return channel_type->channel_type()->element_type(); - } - else - { - if (report_error) - error_at(this->location(), "invalid tuple definition"); - return Type::make_error_type(); - } -} - -// Given EXPR used in a range clause, return either the index type or -// the value type of the range, depending upon GET_INDEX_TYPE. - -Type* -Variable::type_from_range(Expression* expr, bool get_index_type, - bool report_error) const -{ - Type* t = expr->type(); - if (t->array_type() != NULL - || (t->points_to() != NULL - && t->points_to()->array_type() != NULL - && !t->points_to()->is_open_array_type())) - { - if (get_index_type) - return Type::lookup_integer_type("int"); - else - return t->deref()->array_type()->element_type(); - } - else if (t->is_string_type()) - return Type::lookup_integer_type("int"); - else if (t->map_type() != NULL) - { - if (get_index_type) - return t->map_type()->key_type(); - else - return t->map_type()->val_type(); - } - else if (t->channel_type() != NULL) - { - if (get_index_type) - return t->channel_type()->element_type(); - else - { - if (report_error) - error_at(this->location(), - "invalid definition of value variable for channel range"); - return Type::make_error_type(); - } - } - else - { - if (report_error) - error_at(this->location(), "invalid type for range clause"); - return Type::make_error_type(); - } -} - -// EXPR should be a channel. Return the channel's element type. - -Type* -Variable::type_from_chan_element(Expression* expr, bool report_error) const -{ - Type* t = expr->type(); - if (t->channel_type() != NULL) - return t->channel_type()->element_type(); - else - { - if (report_error) - error_at(this->location(), "expected channel"); - return Type::make_error_type(); - } -} - -// Return the type of the Variable. This may be called before -// Variable::determine_type is called, which means that we may need to -// get the type from the initializer. FIXME: If we combine lowering -// with type determination, then this should be unnecessary. - -Type* -Variable::type() -{ - // A variable in a type switch with a nil case will have the wrong - // type here. This gets fixed up in determine_type, below. - Type* type = this->type_; - Expression* init = this->init_; - if (this->is_type_switch_var_ - && this->type_->is_nil_constant_as_type()) - { - Type_guard_expression* tge = this->init_->type_guard_expression(); - go_assert(tge != NULL); - init = tge->expr(); - type = NULL; - } - - if (this->seen_) - { - if (this->type_ == NULL || !this->type_->is_error_type()) - { - error_at(this->location_, "variable initializer refers to itself"); - this->type_ = Type::make_error_type(); - } - return this->type_; - } - - this->seen_ = true; - - if (type != NULL) - ; - else if (this->type_from_init_tuple_) - type = this->type_from_tuple(init, false); - else if (this->type_from_range_index_ || this->type_from_range_value_) - type = this->type_from_range(init, this->type_from_range_index_, false); - else if (this->type_from_chan_element_) - type = this->type_from_chan_element(init, false); - else - { - go_assert(init != NULL); - type = init->type(); - go_assert(type != NULL); - - // Variables should not have abstract types. - if (type->is_abstract()) - type = type->make_non_abstract_type(); - - if (type->is_void_type()) - type = Type::make_error_type(); - } - - this->seen_ = false; - - return type; -} - -// Fetch the type from a const pointer, in which case it should have -// been set already. - -Type* -Variable::type() const -{ - go_assert(this->type_ != NULL); - return this->type_; -} - -// Set the type if necessary. - -void -Variable::determine_type() -{ - if (this->determined_type_) - return; - this->determined_type_ = true; - - if (this->preinit_ != NULL) - this->preinit_->determine_types(); - - // A variable in a type switch with a nil case will have the wrong - // type here. It will have an initializer which is a type guard. - // We want to initialize it to the value without the type guard, and - // use the type of that value as well. - if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type()) - { - Type_guard_expression* tge = this->init_->type_guard_expression(); - go_assert(tge != NULL); - this->type_ = NULL; - this->init_ = tge->expr(); - } - - if (this->init_ == NULL) - go_assert(this->type_ != NULL && !this->type_->is_abstract()); - else if (this->type_from_init_tuple_) - { - Expression *init = this->init_; - init->determine_type_no_context(); - this->type_ = this->type_from_tuple(init, true); - this->init_ = NULL; - } - else if (this->type_from_range_index_ || this->type_from_range_value_) - { - Expression* init = this->init_; - init->determine_type_no_context(); - this->type_ = this->type_from_range(init, this->type_from_range_index_, - true); - this->init_ = NULL; - } - else if (this->type_from_chan_element_) - { - Expression* init = this->init_; - init->determine_type_no_context(); - this->type_ = this->type_from_chan_element(init, true); - this->init_ = NULL; - } - else - { - Type_context context(this->type_, false); - this->init_->determine_type(&context); - if (this->type_ == NULL) - { - Type* type = this->init_->type(); - go_assert(type != NULL); - if (type->is_abstract()) - type = type->make_non_abstract_type(); - - if (type->is_void_type()) - { - error_at(this->location_, "variable has no type"); - type = Type::make_error_type(); - } - else if (type->is_nil_type()) - { - error_at(this->location_, "variable defined to nil type"); - type = Type::make_error_type(); - } - else if (type->is_call_multiple_result_type()) - { - error_at(this->location_, - "single variable set to multiple value function call"); - type = Type::make_error_type(); - } - - this->type_ = type; - } - } -} - -// Export the variable - -void -Variable::export_var(Export* exp, const std::string& name) const -{ - go_assert(this->is_global_); - exp->write_c_string("var "); - exp->write_string(name); - exp->write_c_string(" "); - exp->write_type(this->type()); - exp->write_c_string(";\n"); -} - -// Import a variable. - -void -Variable::import_var(Import* imp, std::string* pname, Type** ptype) -{ - imp->require_c_string("var "); - *pname = imp->read_identifier(); - imp->require_c_string(" "); - *ptype = imp->read_type(); - imp->require_c_string(";\n"); -} - -// Convert a variable to the backend representation. - -Bvariable* -Variable::get_backend_variable(Gogo* gogo, Named_object* function, - const Package* package, const std::string& name) -{ - if (this->backend_ == NULL) - { - Backend* backend = gogo->backend(); - Type* type = this->type_; - if (type->is_error_type() - || (type->is_undefined() - && (!this->is_global_ || package == NULL))) - this->backend_ = backend->error_variable(); - else - { - bool is_parameter = this->is_parameter_; - if (this->is_receiver_ && type->points_to() == NULL) - is_parameter = false; - if (this->is_in_heap()) - { - is_parameter = false; - type = Type::make_pointer_type(type); - } - - std::string n = Gogo::unpack_hidden_name(name); - Btype* btype = tree_to_type(type->get_tree(gogo)); - - Bvariable* bvar; - if (this->is_global_) - bvar = backend->global_variable((package == NULL - ? gogo->package_name() - : package->name()), - (package == NULL - ? gogo->unique_prefix() - : package->unique_prefix()), - n, - btype, - package != NULL, - Gogo::is_hidden_name(name), - this->location_); - else - { - tree fndecl = function->func_value()->get_decl(); - Bfunction* bfunction = tree_to_function(fndecl); - if (is_parameter) - bvar = backend->parameter_variable(bfunction, n, btype, - this->location_); - else - bvar = backend->local_variable(bfunction, n, btype, - this->location_); - } - this->backend_ = bvar; - } - } - return this->backend_; -} - -// Class Result_variable. - -// Convert a result variable to the backend representation. - -Bvariable* -Result_variable::get_backend_variable(Gogo* gogo, Named_object* function, - const std::string& name) -{ - if (this->backend_ == NULL) - { - Backend* backend = gogo->backend(); - Type* type = this->type_; - if (type->is_error()) - this->backend_ = backend->error_variable(); - else - { - if (this->is_in_heap()) - type = Type::make_pointer_type(type); - Btype* btype = tree_to_type(type->get_tree(gogo)); - tree fndecl = function->func_value()->get_decl(); - Bfunction* bfunction = tree_to_function(fndecl); - std::string n = Gogo::unpack_hidden_name(name); - this->backend_ = backend->local_variable(bfunction, n, btype, - this->location_); - } - } - return this->backend_; -} - -// Class Named_constant. - -// Traverse the initializer expression. - -int -Named_constant::traverse_expression(Traverse* traverse) -{ - return Expression::traverse(&this->expr_, traverse); -} - -// Determine the type of the constant. - -void -Named_constant::determine_type() -{ - if (this->type_ != NULL) - { - Type_context context(this->type_, false); - this->expr_->determine_type(&context); - } - else - { - // A constant may have an abstract type. - Type_context context(NULL, true); - this->expr_->determine_type(&context); - this->type_ = this->expr_->type(); - go_assert(this->type_ != NULL); - } -} - -// Indicate that we found and reported an error for this constant. - -void -Named_constant::set_error() -{ - this->type_ = Type::make_error_type(); - this->expr_ = Expression::make_error(this->location_); -} - -// Export a constant. - -void -Named_constant::export_const(Export* exp, const std::string& name) const -{ - exp->write_c_string("const "); - exp->write_string(name); - exp->write_c_string(" "); - if (!this->type_->is_abstract()) - { - exp->write_type(this->type_); - exp->write_c_string(" "); - } - exp->write_c_string("= "); - this->expr()->export_expression(exp); - exp->write_c_string(";\n"); -} - -// Import a constant. - -void -Named_constant::import_const(Import* imp, std::string* pname, Type** ptype, - Expression** pexpr) -{ - imp->require_c_string("const "); - *pname = imp->read_identifier(); - imp->require_c_string(" "); - if (imp->peek_char() == '=') - *ptype = NULL; - else - { - *ptype = imp->read_type(); - imp->require_c_string(" "); - } - imp->require_c_string("= "); - *pexpr = Expression::import_expression(imp); - imp->require_c_string(";\n"); -} - -// Add a method. - -Named_object* -Type_declaration::add_method(const std::string& name, Function* function) -{ - Named_object* ret = Named_object::make_function(name, NULL, function); - this->methods_.push_back(ret); - return ret; -} - -// Add a method declaration. - -Named_object* -Type_declaration::add_method_declaration(const std::string& name, - Function_type* type, - source_location location) -{ - Named_object* ret = Named_object::make_function_declaration(name, NULL, type, - location); - this->methods_.push_back(ret); - return ret; -} - -// Return whether any methods ere defined. - -bool -Type_declaration::has_methods() const -{ - return !this->methods_.empty(); -} - -// Define methods for the real type. - -void -Type_declaration::define_methods(Named_type* nt) -{ - for (Methods::const_iterator p = this->methods_.begin(); - p != this->methods_.end(); - ++p) - nt->add_existing_method(*p); -} - -// We are using the type. Return true if we should issue a warning. - -bool -Type_declaration::using_type() -{ - bool ret = !this->issued_warning_; - this->issued_warning_ = true; - return ret; -} - -// Class Unknown_name. - -// Set the real named object. - -void -Unknown_name::set_real_named_object(Named_object* no) -{ - go_assert(this->real_named_object_ == NULL); - go_assert(!no->is_unknown()); - this->real_named_object_ = no; -} - -// Class Named_object. - -Named_object::Named_object(const std::string& name, - const Package* package, - Classification classification) - : name_(name), package_(package), classification_(classification), - tree_(NULL) -{ - if (Gogo::is_sink_name(name)) - go_assert(classification == NAMED_OBJECT_SINK); -} - -// Make an unknown name. This is used by the parser. The name must -// be resolved later. Unknown names are only added in the current -// package. - -Named_object* -Named_object::make_unknown_name(const std::string& name, - source_location location) -{ - Named_object* named_object = new Named_object(name, NULL, - NAMED_OBJECT_UNKNOWN); - Unknown_name* value = new Unknown_name(location); - named_object->u_.unknown_value = value; - return named_object; -} - -// Make a constant. - -Named_object* -Named_object::make_constant(const Typed_identifier& tid, - const Package* package, Expression* expr, - int iota_value) -{ - Named_object* named_object = new Named_object(tid.name(), package, - NAMED_OBJECT_CONST); - Named_constant* named_constant = new Named_constant(tid.type(), expr, - iota_value, - tid.location()); - named_object->u_.const_value = named_constant; - return named_object; -} - -// Make a named type. - -Named_object* -Named_object::make_type(const std::string& name, const Package* package, - Type* type, source_location location) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_TYPE); - Named_type* named_type = Type::make_named_type(named_object, type, location); - named_object->u_.type_value = named_type; - return named_object; -} - -// Make a type declaration. - -Named_object* -Named_object::make_type_declaration(const std::string& name, - const Package* package, - source_location location) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_TYPE_DECLARATION); - Type_declaration* type_declaration = new Type_declaration(location); - named_object->u_.type_declaration = type_declaration; - return named_object; -} - -// Make a variable. - -Named_object* -Named_object::make_variable(const std::string& name, const Package* package, - Variable* variable) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_VAR); - named_object->u_.var_value = variable; - return named_object; -} - -// Make a result variable. - -Named_object* -Named_object::make_result_variable(const std::string& name, - Result_variable* result) -{ - Named_object* named_object = new Named_object(name, NULL, - NAMED_OBJECT_RESULT_VAR); - named_object->u_.result_var_value = result; - return named_object; -} - -// Make a sink. This is used for the special blank identifier _. - -Named_object* -Named_object::make_sink() -{ - return new Named_object("_", NULL, NAMED_OBJECT_SINK); -} - -// Make a named function. - -Named_object* -Named_object::make_function(const std::string& name, const Package* package, - Function* function) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_FUNC); - named_object->u_.func_value = function; - return named_object; -} - -// Make a function declaration. - -Named_object* -Named_object::make_function_declaration(const std::string& name, - const Package* package, - Function_type* fntype, - source_location location) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_FUNC_DECLARATION); - Function_declaration *func_decl = new Function_declaration(fntype, location); - named_object->u_.func_declaration_value = func_decl; - return named_object; -} - -// Make a package. - -Named_object* -Named_object::make_package(const std::string& alias, Package* package) -{ - Named_object* named_object = new Named_object(alias, NULL, - NAMED_OBJECT_PACKAGE); - named_object->u_.package_value = package; - return named_object; -} - -// Return the name to use in an error message. - -std::string -Named_object::message_name() const -{ - if (this->package_ == NULL) - return Gogo::message_name(this->name_); - std::string ret = Gogo::message_name(this->package_->name()); - ret += '.'; - ret += Gogo::message_name(this->name_); - return ret; -} - -// Set the type when a declaration is defined. - -void -Named_object::set_type_value(Named_type* named_type) -{ - go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION); - Type_declaration* td = this->u_.type_declaration; - td->define_methods(named_type); - Named_object* in_function = td->in_function(); - if (in_function != NULL) - named_type->set_in_function(in_function); - delete td; - this->classification_ = NAMED_OBJECT_TYPE; - this->u_.type_value = named_type; -} - -// Define a function which was previously declared. - -void -Named_object::set_function_value(Function* function) -{ - go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION); - this->classification_ = NAMED_OBJECT_FUNC; - // FIXME: We should free the old value. - this->u_.func_value = function; -} - -// Declare an unknown object as a type declaration. - -void -Named_object::declare_as_type() -{ - go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN); - Unknown_name* unk = this->u_.unknown_value; - this->classification_ = NAMED_OBJECT_TYPE_DECLARATION; - this->u_.type_declaration = new Type_declaration(unk->location()); - delete unk; -} - -// Return the location of a named object. - -source_location -Named_object::location() const -{ - switch (this->classification_) - { - default: - case NAMED_OBJECT_UNINITIALIZED: - go_unreachable(); - - case NAMED_OBJECT_UNKNOWN: - return this->unknown_value()->location(); - - case NAMED_OBJECT_CONST: - return this->const_value()->location(); - - case NAMED_OBJECT_TYPE: - return this->type_value()->location(); - - case NAMED_OBJECT_TYPE_DECLARATION: - return this->type_declaration_value()->location(); - - case NAMED_OBJECT_VAR: - return this->var_value()->location(); - - case NAMED_OBJECT_RESULT_VAR: - return this->result_var_value()->location(); - - case NAMED_OBJECT_SINK: - go_unreachable(); - - case NAMED_OBJECT_FUNC: - return this->func_value()->location(); - - case NAMED_OBJECT_FUNC_DECLARATION: - return this->func_declaration_value()->location(); - - case NAMED_OBJECT_PACKAGE: - return this->package_value()->location(); - } -} - -// Export a named object. - -void -Named_object::export_named_object(Export* exp) const -{ - switch (this->classification_) - { - default: - case NAMED_OBJECT_UNINITIALIZED: - case NAMED_OBJECT_UNKNOWN: - go_unreachable(); - - case NAMED_OBJECT_CONST: - this->const_value()->export_const(exp, this->name_); - break; - - case NAMED_OBJECT_TYPE: - this->type_value()->export_named_type(exp, this->name_); - break; - - case NAMED_OBJECT_TYPE_DECLARATION: - error_at(this->type_declaration_value()->location(), - "attempt to export %<%s%> which was declared but not defined", - this->message_name().c_str()); - break; - - case NAMED_OBJECT_FUNC_DECLARATION: - this->func_declaration_value()->export_func(exp, this->name_); - break; - - case NAMED_OBJECT_VAR: - this->var_value()->export_var(exp, this->name_); - break; - - case NAMED_OBJECT_RESULT_VAR: - case NAMED_OBJECT_SINK: - go_unreachable(); - - case NAMED_OBJECT_FUNC: - this->func_value()->export_func(exp, this->name_); - break; - } -} - -// Convert a variable to the backend representation. - -Bvariable* -Named_object::get_backend_variable(Gogo* gogo, Named_object* function) -{ - if (this->classification_ == NAMED_OBJECT_VAR) - return this->var_value()->get_backend_variable(gogo, function, - this->package_, this->name_); - else if (this->classification_ == NAMED_OBJECT_RESULT_VAR) - return this->result_var_value()->get_backend_variable(gogo, function, - this->name_); - else - go_unreachable(); -} - -// Class Bindings. - -Bindings::Bindings(Bindings* enclosing) - : enclosing_(enclosing), named_objects_(), bindings_() -{ -} - -// Clear imports. - -void -Bindings::clear_file_scope() -{ - Contour::iterator p = this->bindings_.begin(); - while (p != this->bindings_.end()) - { - bool keep; - if (p->second->package() != NULL) - keep = false; - else if (p->second->is_package()) - keep = false; - else if (p->second->is_function() - && !p->second->func_value()->type()->is_method() - && Gogo::unpack_hidden_name(p->second->name()) == "init") - keep = false; - else - keep = true; - - if (keep) - ++p; - else - p = this->bindings_.erase(p); - } -} - -// Look up a symbol. - -Named_object* -Bindings::lookup(const std::string& name) const -{ - Contour::const_iterator p = this->bindings_.find(name); - if (p != this->bindings_.end()) - return p->second->resolve(); - else if (this->enclosing_ != NULL) - return this->enclosing_->lookup(name); - else - return NULL; -} - -// Look up a symbol locally. - -Named_object* -Bindings::lookup_local(const std::string& name) const -{ - Contour::const_iterator p = this->bindings_.find(name); - if (p == this->bindings_.end()) - return NULL; - return p->second; -} - -// Remove an object from a set of bindings. This is used for a -// special case in thunks for functions which call recover. - -void -Bindings::remove_binding(Named_object* no) -{ - Contour::iterator pb = this->bindings_.find(no->name()); - go_assert(pb != this->bindings_.end()); - this->bindings_.erase(pb); - for (std::vector::iterator pn = this->named_objects_.begin(); - pn != this->named_objects_.end(); - ++pn) - { - if (*pn == no) - { - this->named_objects_.erase(pn); - return; - } - } - go_unreachable(); -} - -// Add a method to the list of objects. This is not added to the -// lookup table. This is so that we have a single list of objects -// declared at the top level, which we walk through when it's time to -// convert to trees. - -void -Bindings::add_method(Named_object* method) -{ - this->named_objects_.push_back(method); -} - -// Add a generic Named_object to a Contour. - -Named_object* -Bindings::add_named_object_to_contour(Contour* contour, - Named_object* named_object) -{ - go_assert(named_object == named_object->resolve()); - const std::string& name(named_object->name()); - go_assert(!Gogo::is_sink_name(name)); - - std::pair ins = - contour->insert(std::make_pair(name, named_object)); - if (!ins.second) - { - // The name was already there. - if (named_object->package() != NULL - && ins.first->second->package() == named_object->package() - && (ins.first->second->classification() - == named_object->classification())) - { - // This is a second import of the same object. - return ins.first->second; - } - ins.first->second = this->new_definition(ins.first->second, - named_object); - return ins.first->second; - } - else - { - // Don't push declarations on the list. We push them on when - // and if we find the definitions. That way we genericize the - // functions in order. - if (!named_object->is_type_declaration() - && !named_object->is_function_declaration() - && !named_object->is_unknown()) - this->named_objects_.push_back(named_object); - return named_object; - } -} - -// We had an existing named object OLD_OBJECT, and we've seen a new -// one NEW_OBJECT with the same name. FIXME: This does not free the -// new object when we don't need it. - -Named_object* -Bindings::new_definition(Named_object* old_object, Named_object* new_object) -{ - std::string reason; - switch (old_object->classification()) - { - default: - case Named_object::NAMED_OBJECT_UNINITIALIZED: - go_unreachable(); - - case Named_object::NAMED_OBJECT_UNKNOWN: - { - Named_object* real = old_object->unknown_value()->real_named_object(); - if (real != NULL) - return this->new_definition(real, new_object); - go_assert(!new_object->is_unknown()); - old_object->unknown_value()->set_real_named_object(new_object); - if (!new_object->is_type_declaration() - && !new_object->is_function_declaration()) - this->named_objects_.push_back(new_object); - return new_object; - } - - case Named_object::NAMED_OBJECT_CONST: - break; - - case Named_object::NAMED_OBJECT_TYPE: - if (new_object->is_type_declaration()) - return old_object; - break; - - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - if (new_object->is_type_declaration()) - return old_object; - if (new_object->is_type()) - { - old_object->set_type_value(new_object->type_value()); - new_object->type_value()->set_named_object(old_object); - this->named_objects_.push_back(old_object); - return old_object; - } - break; - - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - break; - - case Named_object::NAMED_OBJECT_SINK: - go_unreachable(); - - case Named_object::NAMED_OBJECT_FUNC: - if (new_object->is_function_declaration()) - { - if (!new_object->func_declaration_value()->asm_name().empty()) - sorry("__asm__ for function definitions"); - Function_type* old_type = old_object->func_value()->type(); - Function_type* new_type = - new_object->func_declaration_value()->type(); - if (old_type->is_valid_redeclaration(new_type, &reason)) - return old_object; - } - break; - - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - { - Function_type* old_type = old_object->func_declaration_value()->type(); - if (new_object->is_function_declaration()) - { - Function_type* new_type = - new_object->func_declaration_value()->type(); - if (old_type->is_valid_redeclaration(new_type, &reason)) - return old_object; - } - if (new_object->is_function()) - { - Function_type* new_type = new_object->func_value()->type(); - if (old_type->is_valid_redeclaration(new_type, &reason)) - { - if (!old_object->func_declaration_value()->asm_name().empty()) - sorry("__asm__ for function definitions"); - old_object->set_function_value(new_object->func_value()); - this->named_objects_.push_back(old_object); - return old_object; - } - } - } - break; - - case Named_object::NAMED_OBJECT_PACKAGE: - if (new_object->is_package() - && (old_object->package_value()->name() - == new_object->package_value()->name())) - return old_object; - - break; - } - - std::string n = old_object->message_name(); - if (reason.empty()) - error_at(new_object->location(), "redefinition of %qs", n.c_str()); - else - error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(), - reason.c_str()); - - inform(old_object->location(), "previous definition of %qs was here", - n.c_str()); - - return old_object; -} - -// Add a named type. - -Named_object* -Bindings::add_named_type(Named_type* named_type) -{ - return this->add_named_object(named_type->named_object()); -} - -// Add a function. - -Named_object* -Bindings::add_function(const std::string& name, const Package* package, - Function* function) -{ - return this->add_named_object(Named_object::make_function(name, package, - function)); -} - -// Add a function declaration. - -Named_object* -Bindings::add_function_declaration(const std::string& name, - const Package* package, - Function_type* type, - source_location location) -{ - Named_object* no = Named_object::make_function_declaration(name, package, - type, location); - return this->add_named_object(no); -} - -// Define a type which was previously declared. - -void -Bindings::define_type(Named_object* no, Named_type* type) -{ - no->set_type_value(type); - this->named_objects_.push_back(no); -} - -// Traverse bindings. - -int -Bindings::traverse(Traverse* traverse, bool is_global) -{ - unsigned int traverse_mask = traverse->traverse_mask(); - - // We don't use an iterator because we permit the traversal to add - // new global objects. - for (size_t i = 0; i < this->named_objects_.size(); ++i) - { - Named_object* p = this->named_objects_[i]; - switch (p->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - if ((traverse_mask & Traverse::traverse_constants) != 0) - { - if (traverse->constant(p, is_global) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if ((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - { - Type* t = p->const_value()->type(); - if (t != NULL - && Type::traverse(t, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (p->const_value()->traverse_expression(traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - if ((traverse_mask & Traverse::traverse_variables) != 0) - { - if (traverse->variable(p) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - && (p->is_result_variable() - || p->var_value()->has_type())) - { - Type* t = (p->is_variable() - ? p->var_value()->type() - : p->result_var_value()->type()); - if (t != NULL - && Type::traverse(t, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (p->is_variable() - && ((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0)) - { - if (p->var_value()->traverse_expression(traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_FUNC: - if ((traverse_mask & Traverse::traverse_functions) != 0) - { - int t = traverse->function(p); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - break; - } - - if ((traverse_mask - & (Traverse::traverse_variables - | Traverse::traverse_constants - | Traverse::traverse_functions - | Traverse::traverse_blocks - | Traverse::traverse_statements - | Traverse::traverse_expressions - | Traverse::traverse_types)) != 0) - { - if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_PACKAGE: - // These are traversed in Gogo::traverse. - go_assert(is_global); - break; - - case Named_object::NAMED_OBJECT_TYPE: - if ((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - { - if (Type::traverse(p->type_value(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - case Named_object::NAMED_OBJECT_UNKNOWN: - break; - - case Named_object::NAMED_OBJECT_SINK: - default: - go_unreachable(); - } - } - - return TRAVERSE_CONTINUE; -} - -// Class Label. - -// Get the backend representation for a label. - -Blabel* -Label::get_backend_label(Translate_context* context) -{ - if (this->blabel_ == NULL) - { - Function* function = context->function()->func_value(); - tree fndecl = function->get_decl(); - Bfunction* bfunction = tree_to_function(fndecl); - this->blabel_ = context->backend()->label(bfunction, this->name_, - this->location_); - } - return this->blabel_; -} - -// Return an expression for the address of this label. - -Bexpression* -Label::get_addr(Translate_context* context, source_location location) -{ - Blabel* label = this->get_backend_label(context); - return context->backend()->label_address(label, location); -} - -// Class Unnamed_label. - -// Get the backend representation for an unnamed label. - -Blabel* -Unnamed_label::get_blabel(Translate_context* context) -{ - if (this->blabel_ == NULL) - { - Function* function = context->function()->func_value(); - tree fndecl = function->get_decl(); - Bfunction* bfunction = tree_to_function(fndecl); - this->blabel_ = context->backend()->label(bfunction, "", - this->location_); - } - return this->blabel_; -} - -// Return a statement which defines this unnamed label. - -Bstatement* -Unnamed_label::get_definition(Translate_context* context) -{ - Blabel* blabel = this->get_blabel(context); - return context->backend()->label_definition_statement(blabel); -} - -// Return a goto statement to this unnamed label. - -Bstatement* -Unnamed_label::get_goto(Translate_context* context, source_location location) -{ - Blabel* blabel = this->get_blabel(context); - return context->backend()->goto_statement(blabel, location); -} - -// Class Package. - -Package::Package(const std::string& name, const std::string& unique_prefix, - source_location location) - : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)), - priority_(0), location_(location), used_(false), is_imported_(false), - uses_sink_alias_(false) -{ - go_assert(!name.empty() && !unique_prefix.empty()); -} - -// Set the priority. We may see multiple priorities for an imported -// package; we want to use the largest one. - -void -Package::set_priority(int priority) -{ - if (priority > this->priority_) - this->priority_ = priority; -} - -// Determine types of constants. Everything else in a package -// (variables, function declarations) should already have a fixed -// type. Constants may have abstract types. - -void -Package::determine_types() -{ - Bindings* bindings = this->bindings_; - for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); - p != bindings->end_definitions(); - ++p) - { - if ((*p)->is_const()) - (*p)->const_value()->determine_type(); - } -} - -// Class Traverse. - -// Destructor. - -Traverse::~Traverse() -{ - if (this->types_seen_ != NULL) - delete this->types_seen_; - if (this->expressions_seen_ != NULL) - delete this->expressions_seen_; -} - -// Record that we are looking at a type, and return true if we have -// already seen it. - -bool -Traverse::remember_type(const Type* type) -{ - if (type->is_error_type()) - return true; - go_assert((this->traverse_mask() & traverse_types) != 0 - || (this->traverse_mask() & traverse_expressions) != 0); - // We only have to remember named types, as they are the only ones - // we can see multiple times in a traversal. - if (type->classification() != Type::TYPE_NAMED) - return false; - if (this->types_seen_ == NULL) - this->types_seen_ = new Types_seen(); - std::pair ins = this->types_seen_->insert(type); - return !ins.second; -} - -// Record that we are looking at an expression, and return true if we -// have already seen it. - -bool -Traverse::remember_expression(const Expression* expression) -{ - go_assert((this->traverse_mask() & traverse_types) != 0 - || (this->traverse_mask() & traverse_expressions) != 0); - if (this->expressions_seen_ == NULL) - this->expressions_seen_ = new Expressions_seen(); - std::pair ins = - this->expressions_seen_->insert(expression); - return !ins.second; -} - -// The default versions of these functions should never be called: the -// traversal mask indicates which functions may be called. - -int -Traverse::variable(Named_object*) -{ - go_unreachable(); -} - -int -Traverse::constant(Named_object*, bool) -{ - go_unreachable(); -} - -int -Traverse::function(Named_object*) -{ - go_unreachable(); -} - -int -Traverse::block(Block*) -{ - go_unreachable(); -} - -int -Traverse::statement(Block*, size_t*, Statement*) -{ - go_unreachable(); -} - -int -Traverse::expression(Expression**) -{ - go_unreachable(); -} - -int -Traverse::type(Type*) -{ - go_unreachable(); -} diff --git a/gcc/go/gofrontend/gogo.cc.working b/gcc/go/gofrontend/gogo.cc.working deleted file mode 100644 index a6411d362c4..00000000000 --- a/gcc/go/gofrontend/gogo.cc.working +++ /dev/null @@ -1,4514 +0,0 @@ -// gogo.cc -- Go frontend parsed representation. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include "go-c.h" -#include "go-dump.h" -#include "lex.h" -#include "types.h" -#include "statements.h" -#include "expressions.h" -#include "dataflow.h" -#include "import.h" -#include "export.h" -#include "gogo.h" - -// Class Gogo. - -Gogo::Gogo(int int_type_size, int pointer_size) - : package_(NULL), - functions_(), - globals_(new Bindings(NULL)), - imports_(), - imported_unsafe_(false), - packages_(), - map_descriptors_(NULL), - type_descriptor_decls_(NULL), - init_functions_(), - need_init_fn_(false), - init_fn_name_(), - imported_init_fns_(), - unique_prefix_(), - unique_prefix_specified_(false), - interface_types_(), - named_types_are_converted_(false) -{ - const source_location loc = BUILTINS_LOCATION; - - Named_type* uint8_type = Type::make_integer_type("uint8", true, 8, - RUNTIME_TYPE_KIND_UINT8); - this->add_named_type(uint8_type); - this->add_named_type(Type::make_integer_type("uint16", true, 16, - RUNTIME_TYPE_KIND_UINT16)); - this->add_named_type(Type::make_integer_type("uint32", true, 32, - RUNTIME_TYPE_KIND_UINT32)); - this->add_named_type(Type::make_integer_type("uint64", true, 64, - RUNTIME_TYPE_KIND_UINT64)); - - this->add_named_type(Type::make_integer_type("int8", false, 8, - RUNTIME_TYPE_KIND_INT8)); - this->add_named_type(Type::make_integer_type("int16", false, 16, - RUNTIME_TYPE_KIND_INT16)); - this->add_named_type(Type::make_integer_type("int32", false, 32, - RUNTIME_TYPE_KIND_INT32)); - this->add_named_type(Type::make_integer_type("int64", false, 64, - RUNTIME_TYPE_KIND_INT64)); - - this->add_named_type(Type::make_float_type("float32", 32, - RUNTIME_TYPE_KIND_FLOAT32)); - this->add_named_type(Type::make_float_type("float64", 64, - RUNTIME_TYPE_KIND_FLOAT64)); - - this->add_named_type(Type::make_complex_type("complex64", 64, - RUNTIME_TYPE_KIND_COMPLEX64)); - this->add_named_type(Type::make_complex_type("complex128", 128, - RUNTIME_TYPE_KIND_COMPLEX128)); - - if (int_type_size < 32) - int_type_size = 32; - this->add_named_type(Type::make_integer_type("uint", true, - int_type_size, - RUNTIME_TYPE_KIND_UINT)); - Named_type* int_type = Type::make_integer_type("int", false, int_type_size, - RUNTIME_TYPE_KIND_INT); - this->add_named_type(int_type); - - // "byte" is an alias for "uint8". Construct a Named_object which - // points to UINT8_TYPE. Note that this breaks the normal pairing - // in which a Named_object points to a Named_type which points back - // to the same Named_object. - Named_object* byte_type = this->declare_type("byte", loc); - byte_type->set_type_value(uint8_type); - - this->add_named_type(Type::make_integer_type("uintptr", true, - pointer_size, - RUNTIME_TYPE_KIND_UINTPTR)); - - this->add_named_type(Type::make_named_bool_type()); - - this->add_named_type(Type::make_named_string_type()); - - this->globals_->add_constant(Typed_identifier("true", - Type::make_boolean_type(), - loc), - NULL, - Expression::make_boolean(true, loc), - 0); - this->globals_->add_constant(Typed_identifier("false", - Type::make_boolean_type(), - loc), - NULL, - Expression::make_boolean(false, loc), - 0); - - this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(), - loc), - NULL, - Expression::make_nil(loc), - 0); - - Type* abstract_int_type = Type::make_abstract_integer_type(); - this->globals_->add_constant(Typed_identifier("iota", abstract_int_type, - loc), - NULL, - Expression::make_iota(), - 0); - - Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc); - new_type->set_is_varargs(); - new_type->set_is_builtin(); - this->globals_->add_function_declaration("new", NULL, new_type, loc); - - Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc); - make_type->set_is_varargs(); - make_type->set_is_builtin(); - this->globals_->add_function_declaration("make", NULL, make_type, loc); - - Typed_identifier_list* len_result = new Typed_identifier_list(); - len_result->push_back(Typed_identifier("", int_type, loc)); - Function_type* len_type = Type::make_function_type(NULL, NULL, len_result, - loc); - len_type->set_is_builtin(); - this->globals_->add_function_declaration("len", NULL, len_type, loc); - - Typed_identifier_list* cap_result = new Typed_identifier_list(); - cap_result->push_back(Typed_identifier("", int_type, loc)); - Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result, - loc); - cap_type->set_is_builtin(); - this->globals_->add_function_declaration("cap", NULL, cap_type, loc); - - Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc); - print_type->set_is_varargs(); - print_type->set_is_builtin(); - this->globals_->add_function_declaration("print", NULL, print_type, loc); - - print_type = Type::make_function_type(NULL, NULL, NULL, loc); - print_type->set_is_varargs(); - print_type->set_is_builtin(); - this->globals_->add_function_declaration("println", NULL, print_type, loc); - - Type *empty = Type::make_interface_type(NULL, loc); - Typed_identifier_list* panic_parms = new Typed_identifier_list(); - panic_parms->push_back(Typed_identifier("e", empty, loc)); - Function_type *panic_type = Type::make_function_type(NULL, panic_parms, - NULL, loc); - panic_type->set_is_builtin(); - this->globals_->add_function_declaration("panic", NULL, panic_type, loc); - - Typed_identifier_list* recover_result = new Typed_identifier_list(); - recover_result->push_back(Typed_identifier("", empty, loc)); - Function_type* recover_type = Type::make_function_type(NULL, NULL, - recover_result, - loc); - recover_type->set_is_builtin(); - this->globals_->add_function_declaration("recover", NULL, recover_type, loc); - - Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc); - close_type->set_is_varargs(); - close_type->set_is_builtin(); - this->globals_->add_function_declaration("close", NULL, close_type, loc); - - Typed_identifier_list* copy_result = new Typed_identifier_list(); - copy_result->push_back(Typed_identifier("", int_type, loc)); - Function_type* copy_type = Type::make_function_type(NULL, NULL, - copy_result, loc); - copy_type->set_is_varargs(); - copy_type->set_is_builtin(); - this->globals_->add_function_declaration("copy", NULL, copy_type, loc); - - Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc); - append_type->set_is_varargs(); - append_type->set_is_builtin(); - this->globals_->add_function_declaration("append", NULL, append_type, loc); - - Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc); - complex_type->set_is_varargs(); - complex_type->set_is_builtin(); - this->globals_->add_function_declaration("complex", NULL, complex_type, loc); - - Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc); - real_type->set_is_varargs(); - real_type->set_is_builtin(); - this->globals_->add_function_declaration("real", NULL, real_type, loc); - - Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc); - imag_type->set_is_varargs(); - imag_type->set_is_builtin(); - this->globals_->add_function_declaration("imag", NULL, imag_type, loc); - - this->define_builtin_function_trees(); -} - -// Munge name for use in an error message. - -std::string -Gogo::message_name(const std::string& name) -{ - return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str()); -} - -// Get the package name. - -const std::string& -Gogo::package_name() const -{ - gcc_assert(this->package_ != NULL); - return this->package_->name(); -} - -// Set the package name. - -void -Gogo::set_package_name(const std::string& package_name, - source_location location) -{ - if (this->package_ != NULL && this->package_->name() != package_name) - { - error_at(location, "expected package %<%s%>", - Gogo::message_name(this->package_->name()).c_str()); - return; - } - - // If the user did not specify a unique prefix, we always use "go". - // This in effect requires that the package name be unique. - if (this->unique_prefix_.empty()) - this->unique_prefix_ = "go"; - - this->package_ = this->register_package(package_name, this->unique_prefix_, - location); - - // We used to permit people to qualify symbols with the current - // package name (e.g., P.x), but we no longer do. - // this->globals_->add_package(package_name, this->package_); - - if (this->is_main_package()) - { - // Declare "main" as a function which takes no parameters and - // returns no value. - this->declare_function("main", - Type::make_function_type(NULL, NULL, NULL, - BUILTINS_LOCATION), - BUILTINS_LOCATION); - } -} - -// Return whether this is the "main" package. This is not true if -// -fgo-prefix was used. - -bool -Gogo::is_main_package() const -{ - return this->package_name() == "main" && !this->unique_prefix_specified_; -} - -// Import a package. - -void -Gogo::import_package(const std::string& filename, - const std::string& local_name, - bool is_local_name_exported, - source_location location) -{ - if (filename == "unsafe") - { - this->import_unsafe(local_name, is_local_name_exported, location); - return; - } - - Imports::const_iterator p = this->imports_.find(filename); - if (p != this->imports_.end()) - { - Package* package = p->second; - package->set_location(location); - package->set_is_imported(); - std::string ln = local_name; - bool is_ln_exported = is_local_name_exported; - if (ln.empty()) - { - ln = package->name(); - is_ln_exported = Lex::is_exported_name(ln); - } - if (ln == ".") - { - Bindings* bindings = package->bindings(); - for (Bindings::const_declarations_iterator p = - bindings->begin_declarations(); - p != bindings->end_declarations(); - ++p) - this->add_named_object(p->second); - } - else if (ln == "_") - package->set_uses_sink_alias(); - else - { - ln = this->pack_hidden_name(ln, is_ln_exported); - this->package_->bindings()->add_package(ln, package); - } - return; - } - - Import::Stream* stream = Import::open_package(filename, location); - if (stream == NULL) - { - error_at(location, "import file %qs not found", filename.c_str()); - return; - } - - Import imp(stream, location); - imp.register_builtin_types(this); - Package* package = imp.import(this, local_name, is_local_name_exported); - if (package != NULL) - { - if (package->name() == this->package_name() - && package->unique_prefix() == this->unique_prefix()) - error_at(location, - ("imported package uses same package name and prefix " - "as package being compiled (see -fgo-prefix option)")); - - this->imports_.insert(std::make_pair(filename, package)); - package->set_is_imported(); - } - - delete stream; -} - -// Add an import control function for an imported package to the list. - -void -Gogo::add_import_init_fn(const std::string& package_name, - const std::string& init_name, int prio) -{ - for (std::set::const_iterator p = - this->imported_init_fns_.begin(); - p != this->imported_init_fns_.end(); - ++p) - { - if (p->init_name() == init_name - && (p->package_name() != package_name || p->priority() != prio)) - { - error("duplicate package initialization name %qs", - Gogo::message_name(init_name).c_str()); - inform(UNKNOWN_LOCATION, "used by package %qs at priority %d", - Gogo::message_name(p->package_name()).c_str(), - p->priority()); - inform(UNKNOWN_LOCATION, " and by package %qs at priority %d", - Gogo::message_name(package_name).c_str(), prio); - return; - } - } - - this->imported_init_fns_.insert(Import_init(package_name, init_name, - prio)); -} - -// Return whether we are at the global binding level. - -bool -Gogo::in_global_scope() const -{ - return this->functions_.empty(); -} - -// Return the current binding contour. - -Bindings* -Gogo::current_bindings() -{ - if (!this->functions_.empty()) - return this->functions_.back().blocks.back()->bindings(); - else if (this->package_ != NULL) - return this->package_->bindings(); - else - return this->globals_; -} - -const Bindings* -Gogo::current_bindings() const -{ - if (!this->functions_.empty()) - return this->functions_.back().blocks.back()->bindings(); - else if (this->package_ != NULL) - return this->package_->bindings(); - else - return this->globals_; -} - -// Return the current block. - -Block* -Gogo::current_block() -{ - if (this->functions_.empty()) - return NULL; - else - return this->functions_.back().blocks.back(); -} - -// Look up a name in the current binding contour. If PFUNCTION is not -// NULL, set it to the function in which the name is defined, or NULL -// if the name is defined in global scope. - -Named_object* -Gogo::lookup(const std::string& name, Named_object** pfunction) const -{ - if (pfunction != NULL) - *pfunction = NULL; - - if (Gogo::is_sink_name(name)) - return Named_object::make_sink(); - - for (Open_functions::const_reverse_iterator p = this->functions_.rbegin(); - p != this->functions_.rend(); - ++p) - { - Named_object* ret = p->blocks.back()->bindings()->lookup(name); - if (ret != NULL) - { - if (pfunction != NULL) - *pfunction = p->function; - return ret; - } - } - - if (this->package_ != NULL) - { - Named_object* ret = this->package_->bindings()->lookup(name); - if (ret != NULL) - { - if (ret->package() != NULL) - ret->package()->set_used(); - return ret; - } - } - - // We do not look in the global namespace. If we did, the global - // namespace would effectively hide names which were defined in - // package scope which we have not yet seen. Instead, - // define_global_names is called after parsing is over to connect - // undefined names at package scope with names defined at global - // scope. - - return NULL; -} - -// Look up a name in the current block, without searching enclosing -// blocks. - -Named_object* -Gogo::lookup_in_block(const std::string& name) const -{ - gcc_assert(!this->functions_.empty()); - gcc_assert(!this->functions_.back().blocks.empty()); - return this->functions_.back().blocks.back()->bindings()->lookup_local(name); -} - -// Look up a name in the global namespace. - -Named_object* -Gogo::lookup_global(const char* name) const -{ - return this->globals_->lookup(name); -} - -// Add an imported package. - -Package* -Gogo::add_imported_package(const std::string& real_name, - const std::string& alias_arg, - bool is_alias_exported, - const std::string& unique_prefix, - source_location location, - bool* padd_to_globals) -{ - // FIXME: Now that we compile packages as a whole, should we permit - // importing the current package? - if (this->package_name() == real_name - && this->unique_prefix() == unique_prefix) - { - *padd_to_globals = false; - if (!alias_arg.empty() && alias_arg != ".") - { - std::string alias = this->pack_hidden_name(alias_arg, - is_alias_exported); - this->package_->bindings()->add_package(alias, this->package_); - } - return this->package_; - } - else if (alias_arg == ".") - { - *padd_to_globals = true; - return this->register_package(real_name, unique_prefix, location); - } - else if (alias_arg == "_") - { - Package* ret = this->register_package(real_name, unique_prefix, location); - ret->set_uses_sink_alias(); - return ret; - } - else - { - *padd_to_globals = false; - std::string alias = alias_arg; - if (alias.empty()) - { - alias = real_name; - is_alias_exported = Lex::is_exported_name(alias); - } - alias = this->pack_hidden_name(alias, is_alias_exported); - Named_object* no = this->add_package(real_name, alias, unique_prefix, - location); - if (!no->is_package()) - return NULL; - return no->package_value(); - } -} - -// Add a package. - -Named_object* -Gogo::add_package(const std::string& real_name, const std::string& alias, - const std::string& unique_prefix, source_location location) -{ - gcc_assert(this->in_global_scope()); - - // Register the package. Note that we might have already seen it in - // an earlier import. - Package* package = this->register_package(real_name, unique_prefix, location); - - return this->package_->bindings()->add_package(alias, package); -} - -// Register a package. This package may or may not be imported. This -// returns the Package structure for the package, creating if it -// necessary. - -Package* -Gogo::register_package(const std::string& package_name, - const std::string& unique_prefix, - source_location location) -{ - gcc_assert(!unique_prefix.empty() && !package_name.empty()); - std::string name = unique_prefix + '.' + package_name; - Package* package = NULL; - std::pair ins = - this->packages_.insert(std::make_pair(name, package)); - if (!ins.second) - { - // We have seen this package name before. - package = ins.first->second; - gcc_assert(package != NULL); - gcc_assert(package->name() == package_name - && package->unique_prefix() == unique_prefix); - if (package->location() == UNKNOWN_LOCATION) - package->set_location(location); - } - else - { - // First time we have seen this package name. - package = new Package(package_name, unique_prefix, location); - gcc_assert(ins.first->second == NULL); - ins.first->second = package; - } - - return package; -} - -// Start compiling a function. - -Named_object* -Gogo::start_function(const std::string& name, Function_type* type, - bool add_method_to_type, source_location location) -{ - bool at_top_level = this->functions_.empty(); - - Block* block = new Block(NULL, location); - - Function* enclosing = (at_top_level - ? NULL - : this->functions_.back().function->func_value()); - - Function* function = new Function(type, enclosing, block, location); - - if (type->is_method()) - { - const Typed_identifier* receiver = type->receiver(); - Variable* this_param = new Variable(receiver->type(), NULL, false, - true, true, location); - std::string name = receiver->name(); - if (name.empty()) - { - // We need to give receivers a name since they wind up in - // DECL_ARGUMENTS. FIXME. - static unsigned int count; - char buf[50]; - snprintf(buf, sizeof buf, "r.%u", count); - ++count; - name = buf; - } - block->bindings()->add_variable(name, NULL, this_param); - } - - const Typed_identifier_list* parameters = type->parameters(); - bool is_varargs = type->is_varargs(); - if (parameters != NULL) - { - for (Typed_identifier_list::const_iterator p = parameters->begin(); - p != parameters->end(); - ++p) - { - Variable* param = new Variable(p->type(), NULL, false, true, false, - location); - if (is_varargs && p + 1 == parameters->end()) - param->set_is_varargs_parameter(); - - std::string name = p->name(); - if (name.empty() || Gogo::is_sink_name(name)) - { - // We need to give parameters a name since they wind up - // in DECL_ARGUMENTS. FIXME. - static unsigned int count; - char buf[50]; - snprintf(buf, sizeof buf, "p.%u", count); - ++count; - name = buf; - } - block->bindings()->add_variable(name, NULL, param); - } - } - - function->create_named_result_variables(this); - - const std::string* pname; - std::string nested_name; - bool is_init = false; - if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method()) - { - if ((type->parameters() != NULL && !type->parameters()->empty()) - || (type->results() != NULL && !type->results()->empty())) - error_at(location, - "func init must have no arguments and no return values"); - // There can be multiple "init" functions, so give them each a - // different name. - static int init_count; - char buf[30]; - snprintf(buf, sizeof buf, ".$init%d", init_count); - ++init_count; - nested_name = buf; - pname = &nested_name; - is_init = true; - } - else if (!name.empty()) - pname = &name; - else - { - // Invent a name for a nested function. - static int nested_count; - char buf[30]; - snprintf(buf, sizeof buf, ".$nested%d", nested_count); - ++nested_count; - nested_name = buf; - pname = &nested_name; - } - - Named_object* ret; - if (Gogo::is_sink_name(*pname)) - { - static int sink_count; - char buf[30]; - snprintf(buf, sizeof buf, ".$sink%d", sink_count); - ++sink_count; - ret = Named_object::make_function(buf, NULL, function); - } - else if (!type->is_method()) - { - ret = this->package_->bindings()->add_function(*pname, NULL, function); - if (!ret->is_function() || ret->func_value() != function) - { - // Redefinition error. Invent a name to avoid knockon - // errors. - static int redefinition_count; - char buf[30]; - snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count); - ++redefinition_count; - ret = this->package_->bindings()->add_function(buf, NULL, function); - } - } - else - { - if (!add_method_to_type) - ret = Named_object::make_function(name, NULL, function); - else - { - gcc_assert(at_top_level); - Type* rtype = type->receiver()->type(); - - // We want to look through the pointer created by the - // parser, without getting an error if the type is not yet - // defined. - if (rtype->classification() == Type::TYPE_POINTER) - rtype = rtype->points_to(); - - if (rtype->is_error_type()) - ret = Named_object::make_function(name, NULL, function); - else if (rtype->named_type() != NULL) - { - ret = rtype->named_type()->add_method(name, function); - if (!ret->is_function()) - { - // Redefinition error. - ret = Named_object::make_function(name, NULL, function); - } - } - else if (rtype->forward_declaration_type() != NULL) - { - Named_object* type_no = - rtype->forward_declaration_type()->named_object(); - if (type_no->is_unknown()) - { - // If we are seeing methods it really must be a - // type. Declare it as such. An alternative would - // be to support lists of methods for unknown - // expressions. Either way the error messages if - // this is not a type are going to get confusing. - Named_object* declared = - this->declare_package_type(type_no->name(), - type_no->location()); - gcc_assert(declared - == type_no->unknown_value()->real_named_object()); - } - ret = rtype->forward_declaration_type()->add_method(name, - function); - } - else - gcc_unreachable(); - } - this->package_->bindings()->add_method(ret); - } - - this->functions_.resize(this->functions_.size() + 1); - Open_function& of(this->functions_.back()); - of.function = ret; - of.blocks.push_back(block); - - if (is_init) - { - this->init_functions_.push_back(ret); - this->need_init_fn_ = true; - } - - return ret; -} - -// Finish compiling a function. - -void -Gogo::finish_function(source_location location) -{ - this->finish_block(location); - gcc_assert(this->functions_.back().blocks.empty()); - this->functions_.pop_back(); -} - -// Return the current function. - -Named_object* -Gogo::current_function() const -{ - gcc_assert(!this->functions_.empty()); - return this->functions_.back().function; -} - -// Start a new block. - -void -Gogo::start_block(source_location location) -{ - gcc_assert(!this->functions_.empty()); - Block* block = new Block(this->current_block(), location); - this->functions_.back().blocks.push_back(block); -} - -// Finish a block. - -Block* -Gogo::finish_block(source_location location) -{ - gcc_assert(!this->functions_.empty()); - gcc_assert(!this->functions_.back().blocks.empty()); - Block* block = this->functions_.back().blocks.back(); - this->functions_.back().blocks.pop_back(); - block->set_end_location(location); - return block; -} - -// Add an unknown name. - -Named_object* -Gogo::add_unknown_name(const std::string& name, source_location location) -{ - return this->package_->bindings()->add_unknown_name(name, location); -} - -// Declare a function. - -Named_object* -Gogo::declare_function(const std::string& name, Function_type* type, - source_location location) -{ - if (!type->is_method()) - return this->current_bindings()->add_function_declaration(name, NULL, type, - location); - else - { - // We don't bother to add this to the list of global - // declarations. - Type* rtype = type->receiver()->type(); - - // We want to look through the pointer created by the - // parser, without getting an error if the type is not yet - // defined. - if (rtype->classification() == Type::TYPE_POINTER) - rtype = rtype->points_to(); - - if (rtype->is_error_type()) - return NULL; - else if (rtype->named_type() != NULL) - return rtype->named_type()->add_method_declaration(name, NULL, type, - location); - else if (rtype->forward_declaration_type() != NULL) - { - Forward_declaration_type* ftype = rtype->forward_declaration_type(); - return ftype->add_method_declaration(name, type, location); - } - else - gcc_unreachable(); - } -} - -// Add a label definition. - -Label* -Gogo::add_label_definition(const std::string& label_name, - source_location location) -{ - gcc_assert(!this->functions_.empty()); - Function* func = this->functions_.back().function->func_value(); - Label* label = func->add_label_definition(label_name, location); - this->add_statement(Statement::make_label_statement(label, location)); - return label; -} - -// Add a label reference. - -Label* -Gogo::add_label_reference(const std::string& label_name) -{ - gcc_assert(!this->functions_.empty()); - Function* func = this->functions_.back().function->func_value(); - return func->add_label_reference(label_name); -} - -// Add a statement. - -void -Gogo::add_statement(Statement* statement) -{ - gcc_assert(!this->functions_.empty() - && !this->functions_.back().blocks.empty()); - this->functions_.back().blocks.back()->add_statement(statement); -} - -// Add a block. - -void -Gogo::add_block(Block* block, source_location location) -{ - gcc_assert(!this->functions_.empty() - && !this->functions_.back().blocks.empty()); - Statement* statement = Statement::make_block_statement(block, location); - this->functions_.back().blocks.back()->add_statement(statement); -} - -// Add a constant. - -Named_object* -Gogo::add_constant(const Typed_identifier& tid, Expression* expr, - int iota_value) -{ - return this->current_bindings()->add_constant(tid, NULL, expr, iota_value); -} - -// Add a type. - -void -Gogo::add_type(const std::string& name, Type* type, source_location location) -{ - Named_object* no = this->current_bindings()->add_type(name, NULL, type, - location); - if (!this->in_global_scope() && no->is_type()) - no->type_value()->set_in_function(this->functions_.back().function); -} - -// Add a named type. - -void -Gogo::add_named_type(Named_type* type) -{ - gcc_assert(this->in_global_scope()); - this->current_bindings()->add_named_type(type); -} - -// Declare a type. - -Named_object* -Gogo::declare_type(const std::string& name, source_location location) -{ - Bindings* bindings = this->current_bindings(); - Named_object* no = bindings->add_type_declaration(name, NULL, location); - if (!this->in_global_scope() && no->is_type_declaration()) - { - Named_object* f = this->functions_.back().function; - no->type_declaration_value()->set_in_function(f); - } - return no; -} - -// Declare a type at the package level. - -Named_object* -Gogo::declare_package_type(const std::string& name, source_location location) -{ - return this->package_->bindings()->add_type_declaration(name, NULL, location); -} - -// Define a type which was already declared. - -void -Gogo::define_type(Named_object* no, Named_type* type) -{ - this->current_bindings()->define_type(no, type); -} - -// Add a variable. - -Named_object* -Gogo::add_variable(const std::string& name, Variable* variable) -{ - Named_object* no = this->current_bindings()->add_variable(name, NULL, - variable); - - // In a function the middle-end wants to see a DECL_EXPR node. - if (no != NULL - && no->is_variable() - && !no->var_value()->is_parameter() - && !this->functions_.empty()) - this->add_statement(Statement::make_variable_declaration(no)); - - return no; -} - -// Add a sink--a reference to the blank identifier _. - -Named_object* -Gogo::add_sink() -{ - return Named_object::make_sink(); -} - -// Add a named object. - -void -Gogo::add_named_object(Named_object* no) -{ - this->current_bindings()->add_named_object(no); -} - -// Record that we've seen an interface type. - -void -Gogo::record_interface_type(Interface_type* itype) -{ - this->interface_types_.push_back(itype); -} - -// Return a name for a thunk object. - -std::string -Gogo::thunk_name() -{ - static int thunk_count; - char thunk_name[50]; - snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count); - ++thunk_count; - return thunk_name; -} - -// Return whether a function is a thunk. - -bool -Gogo::is_thunk(const Named_object* no) -{ - return no->name().compare(0, 6, "$thunk") == 0; -} - -// Define the global names. We do this only after parsing all the -// input files, because the program might define the global names -// itself. - -void -Gogo::define_global_names() -{ - for (Bindings::const_declarations_iterator p = - this->globals_->begin_declarations(); - p != this->globals_->end_declarations(); - ++p) - { - Named_object* global_no = p->second; - std::string name(Gogo::pack_hidden_name(global_no->name(), false)); - Named_object* no = this->package_->bindings()->lookup(name); - if (no == NULL) - continue; - no = no->resolve(); - if (no->is_type_declaration()) - { - if (global_no->is_type()) - { - if (no->type_declaration_value()->has_methods()) - error_at(no->location(), - "may not define methods for global type"); - no->set_type_value(global_no->type_value()); - } - else - { - error_at(no->location(), "expected type"); - Type* errtype = Type::make_error_type(); - Named_object* err = Named_object::make_type("error", NULL, - errtype, - BUILTINS_LOCATION); - no->set_type_value(err->type_value()); - } - } - else if (no->is_unknown()) - no->unknown_value()->set_real_named_object(global_no); - } -} - -// Clear out names in file scope. - -void -Gogo::clear_file_scope() -{ - this->package_->bindings()->clear_file_scope(); - - // Warn about packages which were imported but not used. - for (Packages::iterator p = this->packages_.begin(); - p != this->packages_.end(); - ++p) - { - Package* package = p->second; - if (package != this->package_ - && package->is_imported() - && !package->used() - && !package->uses_sink_alias() - && !saw_errors()) - error_at(package->location(), "imported and not used: %s", - Gogo::message_name(package->name()).c_str()); - package->clear_is_imported(); - package->clear_uses_sink_alias(); - package->clear_used(); - } -} - -// Traverse the tree. - -void -Gogo::traverse(Traverse* traverse) -{ - // Traverse the current package first for consistency. The other - // packages will only contain imported types, constants, and - // declarations. - if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT) - return; - for (Packages::const_iterator p = this->packages_.begin(); - p != this->packages_.end(); - ++p) - { - if (p->second != this->package_) - { - if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT) - break; - } - } -} - -// Traversal class used to verify types. - -class Verify_types : public Traverse -{ - public: - Verify_types() - : Traverse(traverse_types) - { } - - int - type(Type*); -}; - -// Verify that a type is correct. - -int -Verify_types::type(Type* t) -{ - if (!t->verify()) - return TRAVERSE_SKIP_COMPONENTS; - return TRAVERSE_CONTINUE; -} - -// Verify that all types are correct. - -void -Gogo::verify_types() -{ - Verify_types traverse; - this->traverse(&traverse); -} - -// Traversal class used to lower parse tree. - -class Lower_parse_tree : public Traverse -{ - public: - Lower_parse_tree(Gogo* gogo, Named_object* function) - : Traverse(traverse_variables - | traverse_constants - | traverse_functions - | traverse_statements - | traverse_expressions), - gogo_(gogo), function_(function), iota_value_(-1) - { } - - int - variable(Named_object*); - - int - constant(Named_object*, bool); - - int - function(Named_object*); - - int - statement(Block*, size_t* pindex, Statement*); - - int - expression(Expression**); - - private: - // General IR. - Gogo* gogo_; - // The function we are traversing. - Named_object* function_; - // Value to use for the predeclared constant iota. - int iota_value_; -}; - -// Lower variables. We handle variables specially to break loops in -// which a variable initialization expression refers to itself. The -// loop breaking is in lower_init_expression. - -int -Lower_parse_tree::variable(Named_object* no) -{ - if (no->is_variable()) - no->var_value()->lower_init_expression(this->gogo_, this->function_); - return TRAVERSE_CONTINUE; -} - -// Lower constants. We handle constants specially so that we can set -// the right value for the predeclared constant iota. This works in -// conjunction with the way we lower Const_expression objects. - -int -Lower_parse_tree::constant(Named_object* no, bool) -{ - Named_constant* nc = no->const_value(); - - // Don't get into trouble if the constant's initializer expression - // refers to the constant itself. - if (nc->lowering()) - return TRAVERSE_CONTINUE; - nc->set_lowering(); - - gcc_assert(this->iota_value_ == -1); - this->iota_value_ = nc->iota_value(); - nc->traverse_expression(this); - this->iota_value_ = -1; - - nc->clear_lowering(); - - // We will traverse the expression a second time, but that will be - // fast. - - return TRAVERSE_CONTINUE; -} - -// Lower function closure types. Record the function while lowering -// it, so that we can pass it down when lowering an expression. - -int -Lower_parse_tree::function(Named_object* no) -{ - no->func_value()->set_closure_type(); - - gcc_assert(this->function_ == NULL); - this->function_ = no; - int t = no->func_value()->traverse(this); - this->function_ = NULL; - - if (t == TRAVERSE_EXIT) - return t; - return TRAVERSE_SKIP_COMPONENTS; -} - -// Lower statement parse trees. - -int -Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig) -{ - // Lower the expressions first. - int t = sorig->traverse_contents(this); - if (t == TRAVERSE_EXIT) - return t; - - // Keep lowering until nothing changes. - Statement* s = sorig; - while (true) - { - Statement* snew = s->lower(this->gogo_, this->function_, block); - if (snew == s) - break; - s = snew; - t = s->traverse_contents(this); - if (t == TRAVERSE_EXIT) - return t; - } - - if (s != sorig) - block->replace_statement(*pindex, s); - - return TRAVERSE_SKIP_COMPONENTS; -} - -// Lower expression parse trees. - -int -Lower_parse_tree::expression(Expression** pexpr) -{ - // We have to lower all subexpressions first, so that we can get - // their type if necessary. This is awkward, because we don't have - // a postorder traversal pass. - if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - // Keep lowering until nothing changes. - while (true) - { - Expression* e = *pexpr; - Expression* enew = e->lower(this->gogo_, this->function_, - this->iota_value_); - if (enew == e) - break; - *pexpr = enew; - } - return TRAVERSE_SKIP_COMPONENTS; -} - -// Lower the parse tree. This is called after the parse is complete, -// when all names should be resolved. - -void -Gogo::lower_parse_tree() -{ - Lower_parse_tree lower_parse_tree(this, NULL); - this->traverse(&lower_parse_tree); -} - -// Lower a block. - -void -Gogo::lower_block(Named_object* function, Block* block) -{ - Lower_parse_tree lower_parse_tree(this, function); - block->traverse(&lower_parse_tree); -} - -// Lower an expression. - -void -Gogo::lower_expression(Named_object* function, Expression** pexpr) -{ - Lower_parse_tree lower_parse_tree(this, function); - lower_parse_tree.expression(pexpr); -} - -// Lower a constant. This is called when lowering a reference to a -// constant. We have to make sure that the constant has already been -// lowered. - -void -Gogo::lower_constant(Named_object* no) -{ - gcc_assert(no->is_const()); - Lower_parse_tree lower(this, NULL); - lower.constant(no, false); -} - -// Look for interface types to finalize methods of inherited -// interfaces. - -class Finalize_methods : public Traverse -{ - public: - Finalize_methods(Gogo* gogo) - : Traverse(traverse_types), - gogo_(gogo) - { } - - int - type(Type*); - - private: - Gogo* gogo_; -}; - -// Finalize the methods of an interface type. - -int -Finalize_methods::type(Type* t) -{ - // Check the classification so that we don't finalize the methods - // twice for a named interface type. - switch (t->classification()) - { - case Type::TYPE_INTERFACE: - t->interface_type()->finalize_methods(); - break; - - case Type::TYPE_NAMED: - { - // We have to finalize the methods of the real type first. - // But if the real type is a struct type, then we only want to - // finalize the methods of the field types, not of the struct - // type itself. We don't want to add methods to the struct, - // since it has a name. - Type* rt = t->named_type()->real_type(); - if (rt->classification() != Type::TYPE_STRUCT) - { - if (Type::traverse(rt, this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - else - { - if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - - t->named_type()->finalize_methods(this->gogo_); - - return TRAVERSE_SKIP_COMPONENTS; - } - - case Type::TYPE_STRUCT: - t->struct_type()->finalize_methods(this->gogo_); - break; - - default: - break; - } - - return TRAVERSE_CONTINUE; -} - -// Finalize method lists and build stub methods for types. - -void -Gogo::finalize_methods() -{ - Finalize_methods finalize(this); - this->traverse(&finalize); -} - -// Set types for unspecified variables and constants. - -void -Gogo::determine_types() -{ - Bindings* bindings = this->current_bindings(); - for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); - p != bindings->end_definitions(); - ++p) - { - if ((*p)->is_function()) - (*p)->func_value()->determine_types(); - else if ((*p)->is_variable()) - (*p)->var_value()->determine_type(); - else if ((*p)->is_const()) - (*p)->const_value()->determine_type(); - - // See if a variable requires us to build an initialization - // function. We know that we will see all global variables - // here. - if (!this->need_init_fn_ && (*p)->is_variable()) - { - Variable* variable = (*p)->var_value(); - - // If this is a global variable which requires runtime - // initialization, we need an initialization function. - if (!variable->is_global()) - ; - else if (variable->init() == NULL) - ; - else if (variable->type()->interface_type() != NULL) - this->need_init_fn_ = true; - else if (variable->init()->is_constant()) - ; - else if (!variable->init()->is_composite_literal()) - this->need_init_fn_ = true; - else if (variable->init()->is_nonconstant_composite_literal()) - this->need_init_fn_ = true; - - // If this is a global variable which holds a pointer value, - // then we need an initialization function to register it as a - // GC root. - if (variable->is_global() && variable->type()->has_pointer()) - this->need_init_fn_ = true; - } - } - - // Determine the types of constants in packages. - for (Packages::const_iterator p = this->packages_.begin(); - p != this->packages_.end(); - ++p) - p->second->determine_types(); -} - -// Traversal class used for type checking. - -class Check_types_traverse : public Traverse -{ - public: - Check_types_traverse(Gogo* gogo) - : Traverse(traverse_variables - | traverse_constants - | traverse_statements - | traverse_expressions), - gogo_(gogo) - { } - - int - variable(Named_object*); - - int - constant(Named_object*, bool); - - int - statement(Block*, size_t* pindex, Statement*); - - int - expression(Expression**); - - private: - // General IR. - Gogo* gogo_; -}; - -// Check that a variable initializer has the right type. - -int -Check_types_traverse::variable(Named_object* named_object) -{ - if (named_object->is_variable()) - { - Variable* var = named_object->var_value(); - Expression* init = var->init(); - std::string reason; - if (init != NULL - && !Type::are_assignable(var->type(), init->type(), &reason)) - { - if (reason.empty()) - error_at(var->location(), "incompatible type in initialization"); - else - error_at(var->location(), - "incompatible type in initialization (%s)", - reason.c_str()); - var->clear_init(); - } - } - return TRAVERSE_CONTINUE; -} - -// Check that a constant initializer has the right type. - -int -Check_types_traverse::constant(Named_object* named_object, bool) -{ - Named_constant* constant = named_object->const_value(); - Type* ctype = constant->type(); - if (ctype->integer_type() == NULL - && ctype->float_type() == NULL - && ctype->complex_type() == NULL - && !ctype->is_boolean_type() - && !ctype->is_string_type()) - { - if (!ctype->is_error_type()) - error_at(constant->location(), "invalid constant type"); - constant->set_error(); - } - else if (!constant->expr()->is_constant()) - { - error_at(constant->expr()->location(), "expression is not constant"); - constant->set_error(); - } - else if (!Type::are_assignable(constant->type(), constant->expr()->type(), - NULL)) - { - error_at(constant->location(), - "initialization expression has wrong type"); - constant->set_error(); - } - return TRAVERSE_CONTINUE; -} - -// Check that types are valid in a statement. - -int -Check_types_traverse::statement(Block*, size_t*, Statement* s) -{ - s->check_types(this->gogo_); - return TRAVERSE_CONTINUE; -} - -// Check that types are valid in an expression. - -int -Check_types_traverse::expression(Expression** expr) -{ - (*expr)->check_types(this->gogo_); - return TRAVERSE_CONTINUE; -} - -// Check that types are valid. - -void -Gogo::check_types() -{ - Check_types_traverse traverse(this); - this->traverse(&traverse); -} - -// Check the types in a single block. - -void -Gogo::check_types_in_block(Block* block) -{ - Check_types_traverse traverse(this); - block->traverse(&traverse); -} - -// A traversal class used to find a single shortcut operator within an -// expression. - -class Find_shortcut : public Traverse -{ - public: - Find_shortcut() - : Traverse(traverse_blocks - | traverse_statements - | traverse_expressions), - found_(NULL) - { } - - // A pointer to the expression which was found, or NULL if none was - // found. - Expression** - found() const - { return this->found_; } - - protected: - int - block(Block*) - { return TRAVERSE_SKIP_COMPONENTS; } - - int - statement(Block*, size_t*, Statement*) - { return TRAVERSE_SKIP_COMPONENTS; } - - int - expression(Expression**); - - private: - Expression** found_; -}; - -// Find a shortcut expression. - -int -Find_shortcut::expression(Expression** pexpr) -{ - Expression* expr = *pexpr; - Binary_expression* be = expr->binary_expression(); - if (be == NULL) - return TRAVERSE_CONTINUE; - Operator op = be->op(); - if (op != OPERATOR_OROR && op != OPERATOR_ANDAND) - return TRAVERSE_CONTINUE; - gcc_assert(this->found_ == NULL); - this->found_ = pexpr; - return TRAVERSE_EXIT; -} - -// A traversal class used to turn shortcut operators into explicit if -// statements. - -class Shortcuts : public Traverse -{ - public: - Shortcuts(Gogo* gogo) - : Traverse(traverse_variables - | traverse_statements), - gogo_(gogo) - { } - - protected: - int - variable(Named_object*); - - int - statement(Block*, size_t*, Statement*); - - private: - // Convert a shortcut operator. - Statement* - convert_shortcut(Block* enclosing, Expression** pshortcut); - - // The IR. - Gogo* gogo_; -}; - -// Remove shortcut operators in a single statement. - -int -Shortcuts::statement(Block* block, size_t* pindex, Statement* s) -{ - // FIXME: This approach doesn't work for switch statements, because - // we add the new statements before the whole switch when we need to - // instead add them just before the switch expression. The right - // fix is probably to lower switch statements with nonconstant cases - // to a series of conditionals. - if (s->switch_statement() != NULL) - return TRAVERSE_CONTINUE; - - while (true) - { - Find_shortcut find_shortcut; - - // If S is a variable declaration, then ordinary traversal won't - // do anything. We want to explicitly traverse the - // initialization expression if there is one. - Variable_declaration_statement* vds = s->variable_declaration_statement(); - Expression* init = NULL; - if (vds == NULL) - s->traverse_contents(&find_shortcut); - else - { - init = vds->var()->var_value()->init(); - if (init == NULL) - return TRAVERSE_CONTINUE; - init->traverse(&init, &find_shortcut); - } - Expression** pshortcut = find_shortcut.found(); - if (pshortcut == NULL) - return TRAVERSE_CONTINUE; - - Statement* snew = this->convert_shortcut(block, pshortcut); - block->insert_statement_before(*pindex, snew); - ++*pindex; - - if (pshortcut == &init) - vds->var()->var_value()->set_init(init); - } -} - -// Remove shortcut operators in the initializer of a global variable. - -int -Shortcuts::variable(Named_object* no) -{ - if (no->is_result_variable()) - return TRAVERSE_CONTINUE; - Variable* var = no->var_value(); - Expression* init = var->init(); - if (!var->is_global() || init == NULL) - return TRAVERSE_CONTINUE; - - while (true) - { - Find_shortcut find_shortcut; - init->traverse(&init, &find_shortcut); - Expression** pshortcut = find_shortcut.found(); - if (pshortcut == NULL) - return TRAVERSE_CONTINUE; - - Statement* snew = this->convert_shortcut(NULL, pshortcut); - var->add_preinit_statement(this->gogo_, snew); - if (pshortcut == &init) - var->set_init(init); - } -} - -// Given an expression which uses a shortcut operator, return a -// statement which implements it, and update *PSHORTCUT accordingly. - -Statement* -Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut) -{ - Binary_expression* shortcut = (*pshortcut)->binary_expression(); - Expression* left = shortcut->left(); - Expression* right = shortcut->right(); - source_location loc = shortcut->location(); - - Block* retblock = new Block(enclosing, loc); - retblock->set_end_location(loc); - - Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(), - left, loc); - retblock->add_statement(ts); - - Block* block = new Block(retblock, loc); - block->set_end_location(loc); - Expression* tmpref = Expression::make_temporary_reference(ts, loc); - Statement* assign = Statement::make_assignment(tmpref, right, loc); - block->add_statement(assign); - - Expression* cond = Expression::make_temporary_reference(ts, loc); - if (shortcut->binary_expression()->op() == OPERATOR_OROR) - cond = Expression::make_unary(OPERATOR_NOT, cond, loc); - - Statement* if_statement = Statement::make_if_statement(cond, block, NULL, - loc); - retblock->add_statement(if_statement); - - *pshortcut = Expression::make_temporary_reference(ts, loc); - - delete shortcut; - - // Now convert any shortcut operators in LEFT and RIGHT. - Shortcuts shortcuts(this->gogo_); - retblock->traverse(&shortcuts); - - return Statement::make_block_statement(retblock, loc); -} - -// Turn shortcut operators into explicit if statements. Doing this -// considerably simplifies the order of evaluation rules. - -void -Gogo::remove_shortcuts() -{ - Shortcuts shortcuts(this); - this->traverse(&shortcuts); -} - -// A traversal class which finds all the expressions which must be -// evaluated in order within a statement or larger expression. This -// is used to implement the rules about order of evaluation. - -class Find_eval_ordering : public Traverse -{ - private: - typedef std::vector Expression_pointers; - - public: - Find_eval_ordering() - : Traverse(traverse_blocks - | traverse_statements - | traverse_expressions), - exprs_() - { } - - size_t - size() const - { return this->exprs_.size(); } - - typedef Expression_pointers::const_iterator const_iterator; - - const_iterator - begin() const - { return this->exprs_.begin(); } - - const_iterator - end() const - { return this->exprs_.end(); } - - protected: - int - block(Block*) - { return TRAVERSE_SKIP_COMPONENTS; } - - int - statement(Block*, size_t*, Statement*) - { return TRAVERSE_SKIP_COMPONENTS; } - - int - expression(Expression**); - - private: - // A list of pointers to expressions with side-effects. - Expression_pointers exprs_; -}; - -// If an expression must be evaluated in order, put it on the list. - -int -Find_eval_ordering::expression(Expression** expression_pointer) -{ - // We have to look at subexpressions before this one. - if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if ((*expression_pointer)->must_eval_in_order()) - this->exprs_.push_back(expression_pointer); - return TRAVERSE_SKIP_COMPONENTS; -} - -// A traversal class for ordering evaluations. - -class Order_eval : public Traverse -{ - public: - Order_eval(Gogo* gogo) - : Traverse(traverse_variables - | traverse_statements), - gogo_(gogo) - { } - - int - variable(Named_object*); - - int - statement(Block*, size_t*, Statement*); - - private: - // The IR. - Gogo* gogo_; -}; - -// Implement the order of evaluation rules for a statement. - -int -Order_eval::statement(Block* block, size_t* pindex, Statement* s) -{ - // FIXME: This approach doesn't work for switch statements, because - // we add the new statements before the whole switch when we need to - // instead add them just before the switch expression. The right - // fix is probably to lower switch statements with nonconstant cases - // to a series of conditionals. - if (s->switch_statement() != NULL) - return TRAVERSE_CONTINUE; - - Find_eval_ordering find_eval_ordering; - - // If S is a variable declaration, then ordinary traversal won't do - // anything. We want to explicitly traverse the initialization - // expression if there is one. - Variable_declaration_statement* vds = s->variable_declaration_statement(); - Expression* init = NULL; - Expression* orig_init = NULL; - if (vds == NULL) - s->traverse_contents(&find_eval_ordering); - else - { - init = vds->var()->var_value()->init(); - if (init == NULL) - return TRAVERSE_CONTINUE; - orig_init = init; - - // It might seem that this could be - // init->traverse_subexpressions. Unfortunately that can fail - // in a case like - // var err os.Error - // newvar, err := call(arg()) - // Here newvar will have an init of call result 0 of - // call(arg()). If we only traverse subexpressions, we will - // only find arg(), and we won't bother to move anything out. - // Then we get to the assignment to err, we will traverse the - // whole statement, and this time we will find both call() and - // arg(), and so we will move them out. This will cause them to - // be put into temporary variables before the assignment to err - // but after the declaration of newvar. To avoid that problem, - // we traverse the entire expression here. - Expression::traverse(&init, &find_eval_ordering); - } - - if (find_eval_ordering.size() <= 1) - { - // If there is only one expression with a side-effect, we can - // leave it in place. - return TRAVERSE_CONTINUE; - } - - bool is_thunk = s->thunk_statement() != NULL; - for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin(); - p != find_eval_ordering.end(); - ++p) - { - Expression** pexpr = *p; - - // The last expression in a thunk will be the call passed to go - // or defer, which we must not evaluate early. - if (is_thunk && p + 1 == find_eval_ordering.end()) - break; - - source_location loc = (*pexpr)->location(); - Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc); - block->insert_statement_before(*pindex, ts); - ++*pindex; - - *pexpr = Expression::make_temporary_reference(ts, loc); - } - - if (init != orig_init) - vds->var()->var_value()->set_init(init); - - return TRAVERSE_CONTINUE; -} - -// Implement the order of evaluation rules for the initializer of a -// global variable. - -int -Order_eval::variable(Named_object* no) -{ - if (no->is_result_variable()) - return TRAVERSE_CONTINUE; - Variable* var = no->var_value(); - Expression* init = var->init(); - if (!var->is_global() || init == NULL) - return TRAVERSE_CONTINUE; - - Find_eval_ordering find_eval_ordering; - init->traverse_subexpressions(&find_eval_ordering); - - if (find_eval_ordering.size() <= 1) - { - // If there is only one expression with a side-effect, we can - // leave it in place. - return TRAVERSE_SKIP_COMPONENTS; - } - - for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin(); - p != find_eval_ordering.end(); - ++p) - { - Expression** pexpr = *p; - source_location loc = (*pexpr)->location(); - Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc); - var->add_preinit_statement(this->gogo_, ts); - *pexpr = Expression::make_temporary_reference(ts, loc); - } - - return TRAVERSE_SKIP_COMPONENTS; -} - -// Use temporary variables to implement the order of evaluation rules. - -void -Gogo::order_evaluations() -{ - Order_eval order_eval(this); - this->traverse(&order_eval); -} - -// Traversal to convert calls to the predeclared recover function to -// pass in an argument indicating whether it can recover from a panic -// or not. - -class Convert_recover : public Traverse -{ - public: - Convert_recover(Named_object* arg) - : Traverse(traverse_expressions), - arg_(arg) - { } - - protected: - int - expression(Expression**); - - private: - // The argument to pass to the function. - Named_object* arg_; -}; - -// Convert calls to recover. - -int -Convert_recover::expression(Expression** pp) -{ - Call_expression* ce = (*pp)->call_expression(); - if (ce != NULL && ce->is_recover_call()) - ce->set_recover_arg(Expression::make_var_reference(this->arg_, - ce->location())); - return TRAVERSE_CONTINUE; -} - -// Traversal for build_recover_thunks. - -class Build_recover_thunks : public Traverse -{ - public: - Build_recover_thunks(Gogo* gogo) - : Traverse(traverse_functions), - gogo_(gogo) - { } - - int - function(Named_object*); - - private: - Expression* - can_recover_arg(source_location); - - // General IR. - Gogo* gogo_; -}; - -// If this function calls recover, turn it into a thunk. - -int -Build_recover_thunks::function(Named_object* orig_no) -{ - Function* orig_func = orig_no->func_value(); - if (!orig_func->calls_recover() - || orig_func->is_recover_thunk() - || orig_func->has_recover_thunk()) - return TRAVERSE_CONTINUE; - - Gogo* gogo = this->gogo_; - source_location location = orig_func->location(); - - static int count; - char buf[50]; - - Function_type* orig_fntype = orig_func->type(); - Typed_identifier_list* new_params = new Typed_identifier_list(); - std::string receiver_name; - if (orig_fntype->is_method()) - { - const Typed_identifier* receiver = orig_fntype->receiver(); - snprintf(buf, sizeof buf, "rt.%u", count); - ++count; - receiver_name = buf; - new_params->push_back(Typed_identifier(receiver_name, receiver->type(), - receiver->location())); - } - const Typed_identifier_list* orig_params = orig_fntype->parameters(); - if (orig_params != NULL && !orig_params->empty()) - { - for (Typed_identifier_list::const_iterator p = orig_params->begin(); - p != orig_params->end(); - ++p) - { - snprintf(buf, sizeof buf, "pt.%u", count); - ++count; - new_params->push_back(Typed_identifier(buf, p->type(), - p->location())); - } - } - snprintf(buf, sizeof buf, "pr.%u", count); - ++count; - std::string can_recover_name = buf; - new_params->push_back(Typed_identifier(can_recover_name, - Type::lookup_bool_type(), - orig_fntype->location())); - - const Typed_identifier_list* orig_results = orig_fntype->results(); - Typed_identifier_list* new_results; - if (orig_results == NULL || orig_results->empty()) - new_results = NULL; - else - { - new_results = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator p = orig_results->begin(); - p != orig_results->end(); - ++p) - new_results->push_back(Typed_identifier("", p->type(), p->location())); - } - - Function_type *new_fntype = Type::make_function_type(NULL, new_params, - new_results, - orig_fntype->location()); - if (orig_fntype->is_varargs()) - new_fntype->set_is_varargs(); - - std::string name = orig_no->name() + "$recover"; - Named_object *new_no = gogo->start_function(name, new_fntype, false, - location); - Function *new_func = new_no->func_value(); - if (orig_func->enclosing() != NULL) - new_func->set_enclosing(orig_func->enclosing()); - - // We build the code for the original function attached to the new - // function, and then swap the original and new function bodies. - // This means that existing references to the original function will - // then refer to the new function. That makes this code a little - // confusing, in that the reference to NEW_NO really refers to the - // other function, not the one we are building. - - Expression* closure = NULL; - if (orig_func->needs_closure()) - { - Named_object* orig_closure_no = orig_func->closure_var(); - Variable* orig_closure_var = orig_closure_no->var_value(); - Variable* new_var = new Variable(orig_closure_var->type(), NULL, false, - true, false, location); - snprintf(buf, sizeof buf, "closure.%u", count); - ++count; - Named_object* new_closure_no = Named_object::make_variable(buf, NULL, - new_var); - new_func->set_closure_var(new_closure_no); - closure = Expression::make_var_reference(new_closure_no, location); - } - - Expression* fn = Expression::make_func_reference(new_no, closure, location); - - Expression_list* args = new Expression_list(); - if (new_params != NULL) - { - // Note that we skip the last parameter, which is the boolean - // indicating whether recover can succed. - for (Typed_identifier_list::const_iterator p = new_params->begin(); - p + 1 != new_params->end(); - ++p) - { - Named_object* p_no = gogo->lookup(p->name(), NULL); - gcc_assert(p_no != NULL - && p_no->is_variable() - && p_no->var_value()->is_parameter()); - args->push_back(Expression::make_var_reference(p_no, location)); - } - } - args->push_back(this->can_recover_arg(location)); - - Call_expression* call = Expression::make_call(fn, args, false, location); - - Statement* s; - if (orig_fntype->results() == NULL || orig_fntype->results()->empty()) - s = Statement::make_statement(call); - else - { - Expression_list* vals = new Expression_list(); - size_t rc = orig_fntype->results()->size(); - if (rc == 1) - vals->push_back(call); - else - { - for (size_t i = 0; i < rc; ++i) - vals->push_back(Expression::make_call_result(call, i)); - } - s = Statement::make_return_statement(new_func->type()->results(), - vals, location); - } - s->determine_types(); - gogo->add_statement(s); - - gogo->finish_function(location); - - // Swap the function bodies and types. - new_func->swap_for_recover(orig_func); - orig_func->set_is_recover_thunk(); - new_func->set_calls_recover(); - new_func->set_has_recover_thunk(); - - Bindings* orig_bindings = orig_func->block()->bindings(); - Bindings* new_bindings = new_func->block()->bindings(); - if (orig_fntype->is_method()) - { - // We changed the receiver to be a regular parameter. We have - // to update the binding accordingly in both functions. - Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name); - gcc_assert(orig_rec_no != NULL - && orig_rec_no->is_variable() - && !orig_rec_no->var_value()->is_receiver()); - orig_rec_no->var_value()->set_is_receiver(); - - const std::string& new_receiver_name(orig_fntype->receiver()->name()); - Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name); - if (new_rec_no == NULL) - gcc_assert(saw_errors()); - else - { - gcc_assert(new_rec_no->is_variable() - && new_rec_no->var_value()->is_receiver()); - new_rec_no->var_value()->set_is_not_receiver(); - } - } - - // Because we flipped blocks but not types, the can_recover - // parameter appears in the (now) old bindings as a parameter. - // Change it to a local variable, whereupon it will be discarded. - Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name); - gcc_assert(can_recover_no != NULL - && can_recover_no->is_variable() - && can_recover_no->var_value()->is_parameter()); - orig_bindings->remove_binding(can_recover_no); - - // Add the can_recover argument to the (now) new bindings, and - // attach it to any recover statements. - Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL, - false, true, false, location); - can_recover_no = new_bindings->add_variable(can_recover_name, NULL, - can_recover_var); - Convert_recover convert_recover(can_recover_no); - new_func->traverse(&convert_recover); - - // Update the function pointers in any named results. - new_func->update_named_result_variables(); - orig_func->update_named_result_variables(); - - return TRAVERSE_CONTINUE; -} - -// Return the expression to pass for the .can_recover parameter to the -// new function. This indicates whether a call to recover may return -// non-nil. The expression is -// __go_can_recover(__builtin_return_address()). - -Expression* -Build_recover_thunks::can_recover_arg(source_location location) -{ - static Named_object* builtin_return_address; - if (builtin_return_address == NULL) - { - const source_location bloc = BUILTINS_LOCATION; - - Typed_identifier_list* param_types = new Typed_identifier_list(); - Type* uint_type = Type::lookup_integer_type("uint"); - param_types->push_back(Typed_identifier("l", uint_type, bloc)); - - Typed_identifier_list* return_types = new Typed_identifier_list(); - Type* voidptr_type = Type::make_pointer_type(Type::make_void_type()); - return_types->push_back(Typed_identifier("", voidptr_type, bloc)); - - Function_type* fntype = Type::make_function_type(NULL, param_types, - return_types, bloc); - builtin_return_address = - Named_object::make_function_declaration("__builtin_return_address", - NULL, fntype, bloc); - const char* n = "__builtin_return_address"; - builtin_return_address->func_declaration_value()->set_asm_name(n); - } - - static Named_object* can_recover; - if (can_recover == NULL) - { - const source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - Type* voidptr_type = Type::make_pointer_type(Type::make_void_type()); - param_types->push_back(Typed_identifier("a", voidptr_type, bloc)); - Type* boolean_type = Type::lookup_bool_type(); - Typed_identifier_list* results = new Typed_identifier_list(); - results->push_back(Typed_identifier("", boolean_type, bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, - results, bloc); - can_recover = Named_object::make_function_declaration("__go_can_recover", - NULL, fntype, - bloc); - can_recover->func_declaration_value()->set_asm_name("__go_can_recover"); - } - - Expression* fn = Expression::make_func_reference(builtin_return_address, - NULL, location); - - mpz_t zval; - mpz_init_set_ui(zval, 0UL); - Expression* zexpr = Expression::make_integer(&zval, NULL, location); - mpz_clear(zval); - Expression_list *args = new Expression_list(); - args->push_back(zexpr); - - Expression* call = Expression::make_call(fn, args, false, location); - - args = new Expression_list(); - args->push_back(call); - - fn = Expression::make_func_reference(can_recover, NULL, location); - return Expression::make_call(fn, args, false, location); -} - -// Build thunks for functions which call recover. We build a new -// function with an extra parameter, which is whether a call to -// recover can succeed. We then move the body of this function to -// that one. We then turn this function into a thunk which calls the -// new one, passing the value of -// __go_can_recover(__builtin_return_address()). The function will be -// marked as not splitting the stack. This will cooperate with the -// implementation of defer to make recover do the right thing. - -void -Gogo::build_recover_thunks() -{ - Build_recover_thunks build_recover_thunks(this); - this->traverse(&build_recover_thunks); -} - -// Look for named types to see whether we need to create an interface -// method table. - -class Build_method_tables : public Traverse -{ - public: - Build_method_tables(Gogo* gogo, - const std::vector& interfaces) - : Traverse(traverse_types), - gogo_(gogo), interfaces_(interfaces) - { } - - int - type(Type*); - - private: - // The IR. - Gogo* gogo_; - // A list of locally defined interfaces which have hidden methods. - const std::vector& interfaces_; -}; - -// Build all required interface method tables for types. We need to -// ensure that we have an interface method table for every interface -// which has a hidden method, for every named type which implements -// that interface. Normally we can just build interface method tables -// as we need them. However, in some cases we can require an -// interface method table for an interface defined in a different -// package for a type defined in that package. If that interface and -// type both use a hidden method, that is OK. However, we will not be -// able to build that interface method table when we need it, because -// the type's hidden method will be static. So we have to build it -// here, and just refer it from other packages as needed. - -void -Gogo::build_interface_method_tables() -{ - std::vector hidden_interfaces; - hidden_interfaces.reserve(this->interface_types_.size()); - for (std::vector::const_iterator pi = - this->interface_types_.begin(); - pi != this->interface_types_.end(); - ++pi) - { - const Typed_identifier_list* methods = (*pi)->methods(); - if (methods == NULL) - continue; - for (Typed_identifier_list::const_iterator pm = methods->begin(); - pm != methods->end(); - ++pm) - { - if (Gogo::is_hidden_name(pm->name())) - { - hidden_interfaces.push_back(*pi); - break; - } - } - } - - if (!hidden_interfaces.empty()) - { - // Now traverse the tree looking for all named types. - Build_method_tables bmt(this, hidden_interfaces); - this->traverse(&bmt); - } - - // We no longer need the list of interfaces. - - this->interface_types_.clear(); -} - -// This is called for each type. For a named type, for each of the -// interfaces with hidden methods that it implements, create the -// method table. - -int -Build_method_tables::type(Type* type) -{ - Named_type* nt = type->named_type(); - if (nt != NULL) - { - for (std::vector::const_iterator p = - this->interfaces_.begin(); - p != this->interfaces_.end(); - ++p) - { - // We ask whether a pointer to the named type implements the - // interface, because a pointer can implement more methods - // than a value. - if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL)) - { - nt->interface_method_table(this->gogo_, *p, false); - nt->interface_method_table(this->gogo_, *p, true); - } - } - } - return TRAVERSE_CONTINUE; -} - -// Traversal class used to check for return statements. - -class Check_return_statements_traverse : public Traverse -{ - public: - Check_return_statements_traverse() - : Traverse(traverse_functions) - { } - - int - function(Named_object*); -}; - -// Check that a function has a return statement if it needs one. - -int -Check_return_statements_traverse::function(Named_object* no) -{ - Function* func = no->func_value(); - const Function_type* fntype = func->type(); - const Typed_identifier_list* results = fntype->results(); - - // We only need a return statement if there is a return value. - if (results == NULL || results->empty()) - return TRAVERSE_CONTINUE; - - if (func->block()->may_fall_through()) - error_at(func->location(), "control reaches end of non-void function"); - - return TRAVERSE_CONTINUE; -} - -// Check return statements. - -void -Gogo::check_return_statements() -{ - Check_return_statements_traverse traverse; - this->traverse(&traverse); -} - -// Get the unique prefix to use before all exported symbols. This -// must be unique across the entire link. - -const std::string& -Gogo::unique_prefix() const -{ - gcc_assert(!this->unique_prefix_.empty()); - return this->unique_prefix_; -} - -// Set the unique prefix to use before all exported symbols. This -// comes from the command line option -fgo-prefix=XXX. - -void -Gogo::set_unique_prefix(const std::string& arg) -{ - gcc_assert(this->unique_prefix_.empty()); - this->unique_prefix_ = arg; - this->unique_prefix_specified_ = true; -} - -// Work out the package priority. It is one more than the maximum -// priority of an imported package. - -int -Gogo::package_priority() const -{ - int priority = 0; - for (Packages::const_iterator p = this->packages_.begin(); - p != this->packages_.end(); - ++p) - if (p->second->priority() > priority) - priority = p->second->priority(); - return priority + 1; -} - -// Export identifiers as requested. - -void -Gogo::do_exports() -{ - // For now we always stream to a section. Later we may want to - // support streaming to a separate file. - Stream_to_section stream; - - Export exp(&stream); - exp.register_builtin_types(this); - exp.export_globals(this->package_name(), - this->unique_prefix(), - this->package_priority(), - (this->need_init_fn_ && !this->is_main_package() - ? this->get_init_fn_name() - : ""), - this->imported_init_fns_, - this->package_->bindings()); -} - -// Find the blocks in order to convert named types defined in blocks. - -class Convert_named_types : public Traverse -{ - public: - Convert_named_types(Gogo* gogo) - : Traverse(traverse_blocks), - gogo_(gogo) - { } - - protected: - int - block(Block* block); - - private: - Gogo* gogo_; -}; - -int -Convert_named_types::block(Block* block) -{ - this->gogo_->convert_named_types_in_bindings(block->bindings()); - return TRAVERSE_CONTINUE; -} - -// Convert all named types to the backend representation. Since named -// types can refer to other types, this needs to be done in the right -// sequence, which is handled by Named_type::convert. Here we arrange -// to call that for each named type. - -void -Gogo::convert_named_types() -{ - this->convert_named_types_in_bindings(this->globals_); - for (Packages::iterator p = this->packages_.begin(); - p != this->packages_.end(); - ++p) - { - Package* package = p->second; - this->convert_named_types_in_bindings(package->bindings()); - } - - Convert_named_types cnt(this); - this->traverse(&cnt); - - // Make all the builtin named types used for type descriptors, and - // then convert them. They will only be written out if they are - // needed. - Type::make_type_descriptor_type(); - Type::make_type_descriptor_ptr_type(); - Function_type::make_function_type_descriptor_type(); - Pointer_type::make_pointer_type_descriptor_type(); - Struct_type::make_struct_type_descriptor_type(); - Array_type::make_array_type_descriptor_type(); - Array_type::make_slice_type_descriptor_type(); - Map_type::make_map_type_descriptor_type(); - Channel_type::make_chan_type_descriptor_type(); - Interface_type::make_interface_type_descriptor_type(); - Type::convert_builtin_named_types(this); - - this->named_types_are_converted_ = true; -} - -// Convert all names types in a set of bindings. - -void -Gogo::convert_named_types_in_bindings(Bindings* bindings) -{ - for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); - p != bindings->end_definitions(); - ++p) - { - if ((*p)->is_type()) - (*p)->type_value()->convert(this); - } -} - -// Class Function. - -Function::Function(Function_type* type, Function* enclosing, Block* block, - source_location location) - : type_(type), enclosing_(enclosing), named_results_(NULL), - closure_var_(NULL), block_(block), location_(location), fndecl_(NULL), - defer_stack_(NULL), calls_recover_(false), is_recover_thunk_(false), - has_recover_thunk_(false) -{ -} - -// Create the named result variables. - -void -Function::create_named_result_variables(Gogo* gogo) -{ - const Typed_identifier_list* results = this->type_->results(); - if (results == NULL - || results->empty() - || results->front().name().empty()) - return; - - this->named_results_ = new Named_results(); - this->named_results_->reserve(results->size()); - - Block* block = this->block_; - int index = 0; - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p, ++index) - { - std::string name = p->name(); - if (Gogo::is_sink_name(name)) - { - static int unnamed_result_counter; - char buf[100]; - snprintf(buf, sizeof buf, "_$%d", unnamed_result_counter); - ++unnamed_result_counter; - name = gogo->pack_hidden_name(buf, false); - } - Result_variable* result = new Result_variable(p->type(), this, index); - Named_object* no = block->bindings()->add_result_variable(name, result); - if (no->is_result_variable()) - this->named_results_->push_back(no); - } -} - -// Update the named result variables when cloning a function which -// calls recover. - -void -Function::update_named_result_variables() -{ - if (this->named_results_ == NULL) - return; - - for (Named_results::iterator p = this->named_results_->begin(); - p != this->named_results_->end(); - ++p) - (*p)->result_var_value()->set_function(this); -} - -// Return the closure variable, creating it if necessary. - -Named_object* -Function::closure_var() -{ - if (this->closure_var_ == NULL) - { - // We don't know the type of the variable yet. We add fields as - // we find them. - source_location loc = this->type_->location(); - Struct_field_list* sfl = new Struct_field_list; - Type* struct_type = Type::make_struct_type(sfl, loc); - Variable* var = new Variable(Type::make_pointer_type(struct_type), - NULL, false, true, false, loc); - this->closure_var_ = Named_object::make_variable("closure", NULL, var); - // Note that the new variable is not in any binding contour. - } - return this->closure_var_; -} - -// Set the type of the closure variable. - -void -Function::set_closure_type() -{ - if (this->closure_var_ == NULL) - return; - Named_object* closure = this->closure_var_; - Struct_type* st = closure->var_value()->type()->deref()->struct_type(); - unsigned int index = 0; - for (Closure_fields::const_iterator p = this->closure_fields_.begin(); - p != this->closure_fields_.end(); - ++p, ++index) - { - Named_object* no = p->first; - char buf[20]; - snprintf(buf, sizeof buf, "%u", index); - std::string n = no->name() + buf; - Type* var_type; - if (no->is_variable()) - var_type = no->var_value()->type(); - else - var_type = no->result_var_value()->type(); - Type* field_type = Type::make_pointer_type(var_type); - st->push_field(Struct_field(Typed_identifier(n, field_type, p->second))); - } -} - -// Return whether this function is a method. - -bool -Function::is_method() const -{ - return this->type_->is_method(); -} - -// Add a label definition. - -Label* -Function::add_label_definition(const std::string& label_name, - source_location location) -{ - Label* lnull = NULL; - std::pair ins = - this->labels_.insert(std::make_pair(label_name, lnull)); - if (ins.second) - { - // This is a new label. - Label* label = new Label(label_name); - label->define(location); - ins.first->second = label; - return label; - } - else - { - // The label was already in the hash table. - Label* label = ins.first->second; - if (!label->is_defined()) - { - label->define(location); - return label; - } - else - { - error_at(location, "redefinition of label %qs", - Gogo::message_name(label_name).c_str()); - inform(label->location(), "previous definition of %qs was here", - Gogo::message_name(label_name).c_str()); - return new Label(label_name); - } - } -} - -// Add a reference to a label. - -Label* -Function::add_label_reference(const std::string& label_name) -{ - Label* lnull = NULL; - std::pair ins = - this->labels_.insert(std::make_pair(label_name, lnull)); - if (!ins.second) - { - // The label was already in the hash table. - return ins.first->second; - } - else - { - gcc_assert(ins.first->second == NULL); - Label* label = new Label(label_name); - ins.first->second = label; - return label; - } -} - -// Swap one function with another. This is used when building the -// thunk we use to call a function which calls recover. It may not -// work for any other case. - -void -Function::swap_for_recover(Function *x) -{ - gcc_assert(this->enclosing_ == x->enclosing_); - std::swap(this->named_results_, x->named_results_); - std::swap(this->closure_var_, x->closure_var_); - std::swap(this->block_, x->block_); - gcc_assert(this->location_ == x->location_); - gcc_assert(this->fndecl_ == NULL && x->fndecl_ == NULL); - gcc_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL); -} - -// Traverse the tree. - -int -Function::traverse(Traverse* traverse) -{ - unsigned int traverse_mask = traverse->traverse_mask(); - - if ((traverse_mask - & (Traverse::traverse_types | Traverse::traverse_expressions)) - != 0) - { - if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - - // FIXME: We should check traverse_functions here if nested - // functions are stored in block bindings. - if (this->block_ != NULL - && (traverse_mask - & (Traverse::traverse_variables - | Traverse::traverse_constants - | Traverse::traverse_blocks - | Traverse::traverse_statements - | Traverse::traverse_expressions - | Traverse::traverse_types)) != 0) - { - if (this->block_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - - return TRAVERSE_CONTINUE; -} - -// Work out types for unspecified variables and constants. - -void -Function::determine_types() -{ - if (this->block_ != NULL) - this->block_->determine_types(); -} - -// Export the function. - -void -Function::export_func(Export* exp, const std::string& name) const -{ - Function::export_func_with_type(exp, name, this->type_); -} - -// Export a function with a type. - -void -Function::export_func_with_type(Export* exp, const std::string& name, - const Function_type* fntype) -{ - exp->write_c_string("func "); - - if (fntype->is_method()) - { - exp->write_c_string("("); - exp->write_type(fntype->receiver()->type()); - exp->write_c_string(") "); - } - - exp->write_string(name); - - exp->write_c_string(" ("); - const Typed_identifier_list* parameters = fntype->parameters(); - if (parameters != NULL) - { - bool is_varargs = fntype->is_varargs(); - bool first = true; - for (Typed_identifier_list::const_iterator p = parameters->begin(); - p != parameters->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - if (!is_varargs || p + 1 != parameters->end()) - exp->write_type(p->type()); - else - { - exp->write_c_string("..."); - exp->write_type(p->type()->array_type()->element_type()); - } - } - } - exp->write_c_string(")"); - - const Typed_identifier_list* results = fntype->results(); - if (results != NULL) - { - if (results->size() == 1) - { - exp->write_c_string(" "); - exp->write_type(results->begin()->type()); - } - else - { - exp->write_c_string(" ("); - bool first = true; - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - exp->write_type(p->type()); - } - exp->write_c_string(")"); - } - } - exp->write_c_string(";\n"); -} - -// Import a function. - -void -Function::import_func(Import* imp, std::string* pname, - Typed_identifier** preceiver, - Typed_identifier_list** pparameters, - Typed_identifier_list** presults, - bool* is_varargs) -{ - imp->require_c_string("func "); - - *preceiver = NULL; - if (imp->peek_char() == '(') - { - imp->require_c_string("("); - Type* rtype = imp->read_type(); - *preceiver = new Typed_identifier(Import::import_marker, rtype, - imp->location()); - imp->require_c_string(") "); - } - - *pname = imp->read_identifier(); - - Typed_identifier_list* parameters; - *is_varargs = false; - imp->require_c_string(" ("); - if (imp->peek_char() == ')') - parameters = NULL; - else - { - parameters = new Typed_identifier_list(); - while (true) - { - if (imp->match_c_string("...")) - { - imp->advance(3); - *is_varargs = true; - } - - Type* ptype = imp->read_type(); - if (*is_varargs) - ptype = Type::make_array_type(ptype, NULL); - parameters->push_back(Typed_identifier(Import::import_marker, - ptype, imp->location())); - if (imp->peek_char() != ',') - break; - gcc_assert(!*is_varargs); - imp->require_c_string(", "); - } - } - imp->require_c_string(")"); - *pparameters = parameters; - - Typed_identifier_list* results; - if (imp->peek_char() != ' ') - results = NULL; - else - { - results = new Typed_identifier_list(); - imp->require_c_string(" "); - if (imp->peek_char() != '(') - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, rtype, - imp->location())); - } - else - { - imp->require_c_string("("); - while (true) - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, - rtype, imp->location())); - if (imp->peek_char() != ',') - break; - imp->require_c_string(", "); - } - imp->require_c_string(")"); - } - } - imp->require_c_string(";\n"); - *presults = results; -} - -// Class Block. - -Block::Block(Block* enclosing, source_location location) - : enclosing_(enclosing), statements_(), - bindings_(new Bindings(enclosing == NULL - ? NULL - : enclosing->bindings())), - start_location_(location), - end_location_(UNKNOWN_LOCATION) -{ -} - -// Add a statement to a block. - -void -Block::add_statement(Statement* statement) -{ - this->statements_.push_back(statement); -} - -// Add a statement to the front of a block. This is slow but is only -// used for reference counts of parameters. - -void -Block::add_statement_at_front(Statement* statement) -{ - this->statements_.insert(this->statements_.begin(), statement); -} - -// Replace a statement in a block. - -void -Block::replace_statement(size_t index, Statement* s) -{ - gcc_assert(index < this->statements_.size()); - this->statements_[index] = s; -} - -// Add a statement before another statement. - -void -Block::insert_statement_before(size_t index, Statement* s) -{ - gcc_assert(index < this->statements_.size()); - this->statements_.insert(this->statements_.begin() + index, s); -} - -// Add a statement after another statement. - -void -Block::insert_statement_after(size_t index, Statement* s) -{ - gcc_assert(index < this->statements_.size()); - this->statements_.insert(this->statements_.begin() + index + 1, s); -} - -// Traverse the tree. - -int -Block::traverse(Traverse* traverse) -{ - unsigned int traverse_mask = traverse->traverse_mask(); - - if ((traverse_mask & Traverse::traverse_blocks) != 0) - { - int t = traverse->block(this); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - return TRAVERSE_CONTINUE; - } - - if ((traverse_mask - & (Traverse::traverse_variables - | Traverse::traverse_constants - | Traverse::traverse_expressions - | Traverse::traverse_types)) != 0) - { - for (Bindings::const_definitions_iterator pb = - this->bindings_->begin_definitions(); - pb != this->bindings_->end_definitions(); - ++pb) - { - switch ((*pb)->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - if ((traverse_mask & Traverse::traverse_constants) != 0) - { - if (traverse->constant(*pb, false) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if ((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - { - Type* t = (*pb)->const_value()->type(); - if (t != NULL - && Type::traverse(t, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if ((traverse_mask & Traverse::traverse_expressions) != 0 - || (traverse_mask & Traverse::traverse_types) != 0) - { - if ((*pb)->const_value()->traverse_expression(traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - if ((traverse_mask & Traverse::traverse_variables) != 0) - { - if (traverse->variable(*pb) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - && ((*pb)->is_result_variable() - || (*pb)->var_value()->has_type())) - { - Type* t = ((*pb)->is_variable() - ? (*pb)->var_value()->type() - : (*pb)->result_var_value()->type()); - if (t != NULL - && Type::traverse(t, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if ((*pb)->is_variable() - && ((traverse_mask & Traverse::traverse_expressions) != 0 - || (traverse_mask & Traverse::traverse_types) != 0)) - { - if ((*pb)->var_value()->traverse_expression(traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_FUNC: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - // FIXME: Where will nested functions be found? - gcc_unreachable(); - - case Named_object::NAMED_OBJECT_TYPE: - if ((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - { - if (Type::traverse((*pb)->type_value(), traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - case Named_object::NAMED_OBJECT_UNKNOWN: - break; - - case Named_object::NAMED_OBJECT_PACKAGE: - case Named_object::NAMED_OBJECT_SINK: - gcc_unreachable(); - - default: - gcc_unreachable(); - } - } - } - - // No point in checking traverse_mask here--if we got here we always - // want to walk the statements. The traversal can insert new - // statements before or after the current statement. Inserting - // statements before the current statement requires updating I via - // the pointer; those statements will not be traversed. Any new - // statements inserted after the current statement will be traversed - // in their turn. - for (size_t i = 0; i < this->statements_.size(); ++i) - { - if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - - return TRAVERSE_CONTINUE; -} - -// Work out types for unspecified variables and constants. - -void -Block::determine_types() -{ - for (Bindings::const_definitions_iterator pb = - this->bindings_->begin_definitions(); - pb != this->bindings_->end_definitions(); - ++pb) - { - if ((*pb)->is_variable()) - (*pb)->var_value()->determine_type(); - else if ((*pb)->is_const()) - (*pb)->const_value()->determine_type(); - } - - for (std::vector::const_iterator ps = this->statements_.begin(); - ps != this->statements_.end(); - ++ps) - (*ps)->determine_types(); -} - -// Return true if the statements in this block may fall through. - -bool -Block::may_fall_through() const -{ - if (this->statements_.empty()) - return true; - return this->statements_.back()->may_fall_through(); -} - -// Class Variable. - -Variable::Variable(Type* type, Expression* init, bool is_global, - bool is_parameter, bool is_receiver, - source_location location) - : type_(type), init_(init), preinit_(NULL), location_(location), - is_global_(is_global), is_parameter_(is_parameter), - is_receiver_(is_receiver), is_varargs_parameter_(false), - is_address_taken_(false), seen_(false), init_is_lowered_(false), - type_from_init_tuple_(false), type_from_range_index_(false), - type_from_range_value_(false), type_from_chan_element_(false), - is_type_switch_var_(false), determined_type_(false) -{ - gcc_assert(type != NULL || init != NULL); - gcc_assert(!is_parameter || init == NULL); -} - -// Traverse the initializer expression. - -int -Variable::traverse_expression(Traverse* traverse) -{ - if (this->preinit_ != NULL) - { - if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->init_ != NULL) - { - if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lower the initialization expression after parsing is complete. - -void -Variable::lower_init_expression(Gogo* gogo, Named_object* function) -{ - if (this->init_ != NULL && !this->init_is_lowered_) - { - if (this->seen_) - { - // We will give an error elsewhere, this is just to prevent - // an infinite loop. - return; - } - this->seen_ = true; - - gogo->lower_expression(function, &this->init_); - - this->seen_ = false; - - this->init_is_lowered_ = true; - } -} - -// Get the preinit block. - -Block* -Variable::preinit_block(Gogo* gogo) -{ - gcc_assert(this->is_global_); - if (this->preinit_ == NULL) - this->preinit_ = new Block(NULL, this->location()); - - // If a global variable has a preinitialization statement, then we - // need to have an initialization function. - gogo->set_need_init_fn(); - - return this->preinit_; -} - -// Add a statement to be run before the initialization expression. - -void -Variable::add_preinit_statement(Gogo* gogo, Statement* s) -{ - Block* b = this->preinit_block(gogo); - b->add_statement(s); - b->set_end_location(s->location()); -} - -// In an assignment which sets a variable to a tuple of EXPR, return -// the type of the first element of the tuple. - -Type* -Variable::type_from_tuple(Expression* expr, bool report_error) const -{ - if (expr->map_index_expression() != NULL) - { - Map_type* mt = expr->map_index_expression()->get_map_type(); - if (mt == NULL) - return Type::make_error_type(); - return mt->val_type(); - } - else if (expr->receive_expression() != NULL) - { - Expression* channel = expr->receive_expression()->channel(); - Type* channel_type = channel->type(); - if (channel_type->channel_type() == NULL) - return Type::make_error_type(); - return channel_type->channel_type()->element_type(); - } - else - { - if (report_error) - error_at(this->location(), "invalid tuple definition"); - return Type::make_error_type(); - } -} - -// Given EXPR used in a range clause, return either the index type or -// the value type of the range, depending upon GET_INDEX_TYPE. - -Type* -Variable::type_from_range(Expression* expr, bool get_index_type, - bool report_error) const -{ - Type* t = expr->type(); - if (t->array_type() != NULL - || (t->points_to() != NULL - && t->points_to()->array_type() != NULL - && !t->points_to()->is_open_array_type())) - { - if (get_index_type) - return Type::lookup_integer_type("int"); - else - return t->deref()->array_type()->element_type(); - } - else if (t->is_string_type()) - return Type::lookup_integer_type("int"); - else if (t->map_type() != NULL) - { - if (get_index_type) - return t->map_type()->key_type(); - else - return t->map_type()->val_type(); - } - else if (t->channel_type() != NULL) - { - if (get_index_type) - return t->channel_type()->element_type(); - else - { - if (report_error) - error_at(this->location(), - "invalid definition of value variable for channel range"); - return Type::make_error_type(); - } - } - else - { - if (report_error) - error_at(this->location(), "invalid type for range clause"); - return Type::make_error_type(); - } -} - -// EXPR should be a channel. Return the channel's element type. - -Type* -Variable::type_from_chan_element(Expression* expr, bool report_error) const -{ - Type* t = expr->type(); - if (t->channel_type() != NULL) - return t->channel_type()->element_type(); - else - { - if (report_error) - error_at(this->location(), "expected channel"); - return Type::make_error_type(); - } -} - -// Return the type of the Variable. This may be called before -// Variable::determine_type is called, which means that we may need to -// get the type from the initializer. FIXME: If we combine lowering -// with type determination, then this should be unnecessary. - -Type* -Variable::type() -{ - // A variable in a type switch with a nil case will have the wrong - // type here. This gets fixed up in determine_type, below. - Type* type = this->type_; - Expression* init = this->init_; - if (this->is_type_switch_var_ - && this->type_->is_nil_constant_as_type()) - { - Type_guard_expression* tge = this->init_->type_guard_expression(); - gcc_assert(tge != NULL); - init = tge->expr(); - type = NULL; - } - - if (this->seen_) - { - if (this->type_ == NULL || !this->type_->is_error_type()) - { - error_at(this->location_, "variable initializer refers to itself"); - this->type_ = Type::make_error_type(); - } - return this->type_; - } - - this->seen_ = true; - - if (type != NULL) - ; - else if (this->type_from_init_tuple_) - type = this->type_from_tuple(init, false); - else if (this->type_from_range_index_ || this->type_from_range_value_) - type = this->type_from_range(init, this->type_from_range_index_, false); - else if (this->type_from_chan_element_) - type = this->type_from_chan_element(init, false); - else - { - gcc_assert(init != NULL); - type = init->type(); - gcc_assert(type != NULL); - - // Variables should not have abstract types. - if (type->is_abstract()) - type = type->make_non_abstract_type(); - - if (type->is_void_type()) - type = Type::make_error_type(); - } - - this->seen_ = false; - - return type; -} - -// Fetch the type from a const pointer, in which case it should have -// been set already. - -Type* -Variable::type() const -{ - gcc_assert(this->type_ != NULL); - return this->type_; -} - -// Set the type if necessary. - -void -Variable::determine_type() -{ - if (this->determined_type_) - return; - this->determined_type_ = true; - - if (this->preinit_ != NULL) - this->preinit_->determine_types(); - - // A variable in a type switch with a nil case will have the wrong - // type here. It will have an initializer which is a type guard. - // We want to initialize it to the value without the type guard, and - // use the type of that value as well. - if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type()) - { - Type_guard_expression* tge = this->init_->type_guard_expression(); - gcc_assert(tge != NULL); - this->type_ = NULL; - this->init_ = tge->expr(); - } - - if (this->init_ == NULL) - gcc_assert(this->type_ != NULL && !this->type_->is_abstract()); - else if (this->type_from_init_tuple_) - { - Expression *init = this->init_; - init->determine_type_no_context(); - this->type_ = this->type_from_tuple(init, true); - this->init_ = NULL; - } - else if (this->type_from_range_index_ || this->type_from_range_value_) - { - Expression* init = this->init_; - init->determine_type_no_context(); - this->type_ = this->type_from_range(init, this->type_from_range_index_, - true); - this->init_ = NULL; - } - else if (this->type_from_chan_element_) - { - Expression* init = this->init_; - init->determine_type_no_context(); - this->type_ = this->type_from_chan_element(init, true); - this->init_ = NULL; - } - else - { - Type_context context(this->type_, false); - this->init_->determine_type(&context); - if (this->type_ == NULL) - { - Type* type = this->init_->type(); - gcc_assert(type != NULL); - if (type->is_abstract()) - type = type->make_non_abstract_type(); - - if (type->is_void_type()) - { - error_at(this->location_, "variable has no type"); - type = Type::make_error_type(); - } - else if (type->is_nil_type()) - { - error_at(this->location_, "variable defined to nil type"); - type = Type::make_error_type(); - } - else if (type->is_call_multiple_result_type()) - { - error_at(this->location_, - "single variable set to multiple value function call"); - type = Type::make_error_type(); - } - - this->type_ = type; - } - } -} - -// Export the variable - -void -Variable::export_var(Export* exp, const std::string& name) const -{ - gcc_assert(this->is_global_); - exp->write_c_string("var "); - exp->write_string(name); - exp->write_c_string(" "); - exp->write_type(this->type()); - exp->write_c_string(";\n"); -} - -// Import a variable. - -void -Variable::import_var(Import* imp, std::string* pname, Type** ptype) -{ - imp->require_c_string("var "); - *pname = imp->read_identifier(); - imp->require_c_string(" "); - *ptype = imp->read_type(); - imp->require_c_string(";\n"); -} - -// Class Named_constant. - -// Traverse the initializer expression. - -int -Named_constant::traverse_expression(Traverse* traverse) -{ - return Expression::traverse(&this->expr_, traverse); -} - -// Determine the type of the constant. - -void -Named_constant::determine_type() -{ - if (this->type_ != NULL) - { - Type_context context(this->type_, false); - this->expr_->determine_type(&context); - } - else - { - // A constant may have an abstract type. - Type_context context(NULL, true); - this->expr_->determine_type(&context); - this->type_ = this->expr_->type(); - gcc_assert(this->type_ != NULL); - } -} - -// Indicate that we found and reported an error for this constant. - -void -Named_constant::set_error() -{ - this->type_ = Type::make_error_type(); - this->expr_ = Expression::make_error(this->location_); -} - -// Export a constant. - -void -Named_constant::export_const(Export* exp, const std::string& name) const -{ - exp->write_c_string("const "); - exp->write_string(name); - exp->write_c_string(" "); - if (!this->type_->is_abstract()) - { - exp->write_type(this->type_); - exp->write_c_string(" "); - } - exp->write_c_string("= "); - this->expr()->export_expression(exp); - exp->write_c_string(";\n"); -} - -// Import a constant. - -void -Named_constant::import_const(Import* imp, std::string* pname, Type** ptype, - Expression** pexpr) -{ - imp->require_c_string("const "); - *pname = imp->read_identifier(); - imp->require_c_string(" "); - if (imp->peek_char() == '=') - *ptype = NULL; - else - { - *ptype = imp->read_type(); - imp->require_c_string(" "); - } - imp->require_c_string("= "); - *pexpr = Expression::import_expression(imp); - imp->require_c_string(";\n"); -} - -// Add a method. - -Named_object* -Type_declaration::add_method(const std::string& name, Function* function) -{ - Named_object* ret = Named_object::make_function(name, NULL, function); - this->methods_.push_back(ret); - return ret; -} - -// Add a method declaration. - -Named_object* -Type_declaration::add_method_declaration(const std::string& name, - Function_type* type, - source_location location) -{ - Named_object* ret = Named_object::make_function_declaration(name, NULL, type, - location); - this->methods_.push_back(ret); - return ret; -} - -// Return whether any methods ere defined. - -bool -Type_declaration::has_methods() const -{ - return !this->methods_.empty(); -} - -// Define methods for the real type. - -void -Type_declaration::define_methods(Named_type* nt) -{ - for (Methods::const_iterator p = this->methods_.begin(); - p != this->methods_.end(); - ++p) - nt->add_existing_method(*p); -} - -// We are using the type. Return true if we should issue a warning. - -bool -Type_declaration::using_type() -{ - bool ret = !this->issued_warning_; - this->issued_warning_ = true; - return ret; -} - -// Class Unknown_name. - -// Set the real named object. - -void -Unknown_name::set_real_named_object(Named_object* no) -{ - gcc_assert(this->real_named_object_ == NULL); - gcc_assert(!no->is_unknown()); - this->real_named_object_ = no; -} - -// Class Named_object. - -Named_object::Named_object(const std::string& name, - const Package* package, - Classification classification) - : name_(name), package_(package), classification_(classification), - tree_(NULL) -{ - if (Gogo::is_sink_name(name)) - gcc_assert(classification == NAMED_OBJECT_SINK); -} - -// Make an unknown name. This is used by the parser. The name must -// be resolved later. Unknown names are only added in the current -// package. - -Named_object* -Named_object::make_unknown_name(const std::string& name, - source_location location) -{ - Named_object* named_object = new Named_object(name, NULL, - NAMED_OBJECT_UNKNOWN); - Unknown_name* value = new Unknown_name(location); - named_object->u_.unknown_value = value; - return named_object; -} - -// Make a constant. - -Named_object* -Named_object::make_constant(const Typed_identifier& tid, - const Package* package, Expression* expr, - int iota_value) -{ - Named_object* named_object = new Named_object(tid.name(), package, - NAMED_OBJECT_CONST); - Named_constant* named_constant = new Named_constant(tid.type(), expr, - iota_value, - tid.location()); - named_object->u_.const_value = named_constant; - return named_object; -} - -// Make a named type. - -Named_object* -Named_object::make_type(const std::string& name, const Package* package, - Type* type, source_location location) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_TYPE); - Named_type* named_type = Type::make_named_type(named_object, type, location); - named_object->u_.type_value = named_type; - return named_object; -} - -// Make a type declaration. - -Named_object* -Named_object::make_type_declaration(const std::string& name, - const Package* package, - source_location location) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_TYPE_DECLARATION); - Type_declaration* type_declaration = new Type_declaration(location); - named_object->u_.type_declaration = type_declaration; - return named_object; -} - -// Make a variable. - -Named_object* -Named_object::make_variable(const std::string& name, const Package* package, - Variable* variable) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_VAR); - named_object->u_.var_value = variable; - return named_object; -} - -// Make a result variable. - -Named_object* -Named_object::make_result_variable(const std::string& name, - Result_variable* result) -{ - Named_object* named_object = new Named_object(name, NULL, - NAMED_OBJECT_RESULT_VAR); - named_object->u_.result_var_value = result; - return named_object; -} - -// Make a sink. This is used for the special blank identifier _. - -Named_object* -Named_object::make_sink() -{ - return new Named_object("_", NULL, NAMED_OBJECT_SINK); -} - -// Make a named function. - -Named_object* -Named_object::make_function(const std::string& name, const Package* package, - Function* function) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_FUNC); - named_object->u_.func_value = function; - return named_object; -} - -// Make a function declaration. - -Named_object* -Named_object::make_function_declaration(const std::string& name, - const Package* package, - Function_type* fntype, - source_location location) -{ - Named_object* named_object = new Named_object(name, package, - NAMED_OBJECT_FUNC_DECLARATION); - Function_declaration *func_decl = new Function_declaration(fntype, location); - named_object->u_.func_declaration_value = func_decl; - return named_object; -} - -// Make a package. - -Named_object* -Named_object::make_package(const std::string& alias, Package* package) -{ - Named_object* named_object = new Named_object(alias, NULL, - NAMED_OBJECT_PACKAGE); - named_object->u_.package_value = package; - return named_object; -} - -// Return the name to use in an error message. - -std::string -Named_object::message_name() const -{ - if (this->package_ == NULL) - return Gogo::message_name(this->name_); - std::string ret = Gogo::message_name(this->package_->name()); - ret += '.'; - ret += Gogo::message_name(this->name_); - return ret; -} - -// Set the type when a declaration is defined. - -void -Named_object::set_type_value(Named_type* named_type) -{ - gcc_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION); - Type_declaration* td = this->u_.type_declaration; - td->define_methods(named_type); - Named_object* in_function = td->in_function(); - if (in_function != NULL) - named_type->set_in_function(in_function); - delete td; - this->classification_ = NAMED_OBJECT_TYPE; - this->u_.type_value = named_type; -} - -// Define a function which was previously declared. - -void -Named_object::set_function_value(Function* function) -{ - gcc_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION); - this->classification_ = NAMED_OBJECT_FUNC; - // FIXME: We should free the old value. - this->u_.func_value = function; -} - -// Declare an unknown object as a type declaration. - -void -Named_object::declare_as_type() -{ - gcc_assert(this->classification_ == NAMED_OBJECT_UNKNOWN); - Unknown_name* unk = this->u_.unknown_value; - this->classification_ = NAMED_OBJECT_TYPE_DECLARATION; - this->u_.type_declaration = new Type_declaration(unk->location()); - delete unk; -} - -// Return the location of a named object. - -source_location -Named_object::location() const -{ - switch (this->classification_) - { - default: - case NAMED_OBJECT_UNINITIALIZED: - gcc_unreachable(); - - case NAMED_OBJECT_UNKNOWN: - return this->unknown_value()->location(); - - case NAMED_OBJECT_CONST: - return this->const_value()->location(); - - case NAMED_OBJECT_TYPE: - return this->type_value()->location(); - - case NAMED_OBJECT_TYPE_DECLARATION: - return this->type_declaration_value()->location(); - - case NAMED_OBJECT_VAR: - return this->var_value()->location(); - - case NAMED_OBJECT_RESULT_VAR: - return this->result_var_value()->function()->location(); - - case NAMED_OBJECT_SINK: - gcc_unreachable(); - - case NAMED_OBJECT_FUNC: - return this->func_value()->location(); - - case NAMED_OBJECT_FUNC_DECLARATION: - return this->func_declaration_value()->location(); - - case NAMED_OBJECT_PACKAGE: - return this->package_value()->location(); - } -} - -// Export a named object. - -void -Named_object::export_named_object(Export* exp) const -{ - switch (this->classification_) - { - default: - case NAMED_OBJECT_UNINITIALIZED: - case NAMED_OBJECT_UNKNOWN: - gcc_unreachable(); - - case NAMED_OBJECT_CONST: - this->const_value()->export_const(exp, this->name_); - break; - - case NAMED_OBJECT_TYPE: - this->type_value()->export_named_type(exp, this->name_); - break; - - case NAMED_OBJECT_TYPE_DECLARATION: - error_at(this->type_declaration_value()->location(), - "attempt to export %<%s%> which was declared but not defined", - this->message_name().c_str()); - break; - - case NAMED_OBJECT_FUNC_DECLARATION: - this->func_declaration_value()->export_func(exp, this->name_); - break; - - case NAMED_OBJECT_VAR: - this->var_value()->export_var(exp, this->name_); - break; - - case NAMED_OBJECT_RESULT_VAR: - case NAMED_OBJECT_SINK: - gcc_unreachable(); - - case NAMED_OBJECT_FUNC: - this->func_value()->export_func(exp, this->name_); - break; - } -} - -// Class Bindings. - -Bindings::Bindings(Bindings* enclosing) - : enclosing_(enclosing), named_objects_(), bindings_() -{ -} - -// Clear imports. - -void -Bindings::clear_file_scope() -{ - Contour::iterator p = this->bindings_.begin(); - while (p != this->bindings_.end()) - { - bool keep; - if (p->second->package() != NULL) - keep = false; - else if (p->second->is_package()) - keep = false; - else if (p->second->is_function() - && !p->second->func_value()->type()->is_method() - && Gogo::unpack_hidden_name(p->second->name()) == "init") - keep = false; - else - keep = true; - - if (keep) - ++p; - else - p = this->bindings_.erase(p); - } -} - -// Look up a symbol. - -Named_object* -Bindings::lookup(const std::string& name) const -{ - Contour::const_iterator p = this->bindings_.find(name); - if (p != this->bindings_.end()) - return p->second->resolve(); - else if (this->enclosing_ != NULL) - return this->enclosing_->lookup(name); - else - return NULL; -} - -// Look up a symbol locally. - -Named_object* -Bindings::lookup_local(const std::string& name) const -{ - Contour::const_iterator p = this->bindings_.find(name); - if (p == this->bindings_.end()) - return NULL; - return p->second; -} - -// Remove an object from a set of bindings. This is used for a -// special case in thunks for functions which call recover. - -void -Bindings::remove_binding(Named_object* no) -{ - Contour::iterator pb = this->bindings_.find(no->name()); - gcc_assert(pb != this->bindings_.end()); - this->bindings_.erase(pb); - for (std::vector::iterator pn = this->named_objects_.begin(); - pn != this->named_objects_.end(); - ++pn) - { - if (*pn == no) - { - this->named_objects_.erase(pn); - return; - } - } - gcc_unreachable(); -} - -// Add a method to the list of objects. This is not added to the -// lookup table. This is so that we have a single list of objects -// declared at the top level, which we walk through when it's time to -// convert to trees. - -void -Bindings::add_method(Named_object* method) -{ - this->named_objects_.push_back(method); -} - -// Add a generic Named_object to a Contour. - -Named_object* -Bindings::add_named_object_to_contour(Contour* contour, - Named_object* named_object) -{ - gcc_assert(named_object == named_object->resolve()); - const std::string& name(named_object->name()); - gcc_assert(!Gogo::is_sink_name(name)); - - std::pair ins = - contour->insert(std::make_pair(name, named_object)); - if (!ins.second) - { - // The name was already there. - if (named_object->package() != NULL - && ins.first->second->package() == named_object->package() - && (ins.first->second->classification() - == named_object->classification())) - { - // This is a second import of the same object. - return ins.first->second; - } - ins.first->second = this->new_definition(ins.first->second, - named_object); - return ins.first->second; - } - else - { - // Don't push declarations on the list. We push them on when - // and if we find the definitions. That way we genericize the - // functions in order. - if (!named_object->is_type_declaration() - && !named_object->is_function_declaration() - && !named_object->is_unknown()) - this->named_objects_.push_back(named_object); - return named_object; - } -} - -// We had an existing named object OLD_OBJECT, and we've seen a new -// one NEW_OBJECT with the same name. FIXME: This does not free the -// new object when we don't need it. - -Named_object* -Bindings::new_definition(Named_object* old_object, Named_object* new_object) -{ - std::string reason; - switch (old_object->classification()) - { - default: - case Named_object::NAMED_OBJECT_UNINITIALIZED: - gcc_unreachable(); - - case Named_object::NAMED_OBJECT_UNKNOWN: - { - Named_object* real = old_object->unknown_value()->real_named_object(); - if (real != NULL) - return this->new_definition(real, new_object); - gcc_assert(!new_object->is_unknown()); - old_object->unknown_value()->set_real_named_object(new_object); - if (!new_object->is_type_declaration() - && !new_object->is_function_declaration()) - this->named_objects_.push_back(new_object); - return new_object; - } - - case Named_object::NAMED_OBJECT_CONST: - break; - - case Named_object::NAMED_OBJECT_TYPE: - if (new_object->is_type_declaration()) - return old_object; - break; - - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - if (new_object->is_type_declaration()) - return old_object; - if (new_object->is_type()) - { - old_object->set_type_value(new_object->type_value()); - new_object->type_value()->set_named_object(old_object); - this->named_objects_.push_back(old_object); - return old_object; - } - break; - - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - break; - - case Named_object::NAMED_OBJECT_SINK: - gcc_unreachable(); - - case Named_object::NAMED_OBJECT_FUNC: - if (new_object->is_function_declaration()) - { - if (!new_object->func_declaration_value()->asm_name().empty()) - sorry("__asm__ for function definitions"); - Function_type* old_type = old_object->func_value()->type(); - Function_type* new_type = - new_object->func_declaration_value()->type(); - if (old_type->is_valid_redeclaration(new_type, &reason)) - return old_object; - } - break; - - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - { - Function_type* old_type = old_object->func_declaration_value()->type(); - if (new_object->is_function_declaration()) - { - Function_type* new_type = - new_object->func_declaration_value()->type(); - if (old_type->is_valid_redeclaration(new_type, &reason)) - return old_object; - } - if (new_object->is_function()) - { - Function_type* new_type = new_object->func_value()->type(); - if (old_type->is_valid_redeclaration(new_type, &reason)) - { - if (!old_object->func_declaration_value()->asm_name().empty()) - sorry("__asm__ for function definitions"); - old_object->set_function_value(new_object->func_value()); - this->named_objects_.push_back(old_object); - return old_object; - } - } - } - break; - - case Named_object::NAMED_OBJECT_PACKAGE: - if (new_object->is_package() - && (old_object->package_value()->name() - == new_object->package_value()->name())) - return old_object; - - break; - } - - std::string n = old_object->message_name(); - if (reason.empty()) - error_at(new_object->location(), "redefinition of %qs", n.c_str()); - else - error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(), - reason.c_str()); - - inform(old_object->location(), "previous definition of %qs was here", - n.c_str()); - - return old_object; -} - -// Add a named type. - -Named_object* -Bindings::add_named_type(Named_type* named_type) -{ - return this->add_named_object(named_type->named_object()); -} - -// Add a function. - -Named_object* -Bindings::add_function(const std::string& name, const Package* package, - Function* function) -{ - return this->add_named_object(Named_object::make_function(name, package, - function)); -} - -// Add a function declaration. - -Named_object* -Bindings::add_function_declaration(const std::string& name, - const Package* package, - Function_type* type, - source_location location) -{ - Named_object* no = Named_object::make_function_declaration(name, package, - type, location); - return this->add_named_object(no); -} - -// Define a type which was previously declared. - -void -Bindings::define_type(Named_object* no, Named_type* type) -{ - no->set_type_value(type); - this->named_objects_.push_back(no); -} - -// Traverse bindings. - -int -Bindings::traverse(Traverse* traverse, bool is_global) -{ - unsigned int traverse_mask = traverse->traverse_mask(); - - // We don't use an iterator because we permit the traversal to add - // new global objects. - for (size_t i = 0; i < this->named_objects_.size(); ++i) - { - Named_object* p = this->named_objects_[i]; - switch (p->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - if ((traverse_mask & Traverse::traverse_constants) != 0) - { - if (traverse->constant(p, is_global) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if ((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - { - Type* t = p->const_value()->type(); - if (t != NULL - && Type::traverse(t, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (p->const_value()->traverse_expression(traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - if ((traverse_mask & Traverse::traverse_variables) != 0) - { - if (traverse->variable(p) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - && (p->is_result_variable() - || p->var_value()->has_type())) - { - Type* t = (p->is_variable() - ? p->var_value()->type() - : p->result_var_value()->type()); - if (t != NULL - && Type::traverse(t, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (p->is_variable() - && ((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0)) - { - if (p->var_value()->traverse_expression(traverse) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_FUNC: - if ((traverse_mask & Traverse::traverse_functions) != 0) - { - int t = traverse->function(p); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - break; - } - - if ((traverse_mask - & (Traverse::traverse_variables - | Traverse::traverse_constants - | Traverse::traverse_functions - | Traverse::traverse_blocks - | Traverse::traverse_statements - | Traverse::traverse_expressions - | Traverse::traverse_types)) != 0) - { - if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_PACKAGE: - // These are traversed in Gogo::traverse. - gcc_assert(is_global); - break; - - case Named_object::NAMED_OBJECT_TYPE: - if ((traverse_mask & Traverse::traverse_types) != 0 - || (traverse_mask & Traverse::traverse_expressions) != 0) - { - if (Type::traverse(p->type_value(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - break; - - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - case Named_object::NAMED_OBJECT_UNKNOWN: - break; - - case Named_object::NAMED_OBJECT_SINK: - default: - gcc_unreachable(); - } - } - - return TRAVERSE_CONTINUE; -} - -// Class Package. - -Package::Package(const std::string& name, const std::string& unique_prefix, - source_location location) - : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)), - priority_(0), location_(location), used_(false), is_imported_(false), - uses_sink_alias_(false) -{ - gcc_assert(!name.empty() && !unique_prefix.empty()); -} - -// Set the priority. We may see multiple priorities for an imported -// package; we want to use the largest one. - -void -Package::set_priority(int priority) -{ - if (priority > this->priority_) - this->priority_ = priority; -} - -// Determine types of constants. Everything else in a package -// (variables, function declarations) should already have a fixed -// type. Constants may have abstract types. - -void -Package::determine_types() -{ - Bindings* bindings = this->bindings_; - for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); - p != bindings->end_definitions(); - ++p) - { - if ((*p)->is_const()) - (*p)->const_value()->determine_type(); - } -} - -// Class Traverse. - -// Destructor. - -Traverse::~Traverse() -{ - if (this->types_seen_ != NULL) - delete this->types_seen_; - if (this->expressions_seen_ != NULL) - delete this->expressions_seen_; -} - -// Record that we are looking at a type, and return true if we have -// already seen it. - -bool -Traverse::remember_type(const Type* type) -{ - if (type->is_error_type()) - return true; - gcc_assert((this->traverse_mask() & traverse_types) != 0 - || (this->traverse_mask() & traverse_expressions) != 0); - // We only have to remember named types, as they are the only ones - // we can see multiple times in a traversal. - if (type->classification() != Type::TYPE_NAMED) - return false; - if (this->types_seen_ == NULL) - this->types_seen_ = new Types_seen(); - std::pair ins = this->types_seen_->insert(type); - return !ins.second; -} - -// Record that we are looking at an expression, and return true if we -// have already seen it. - -bool -Traverse::remember_expression(const Expression* expression) -{ - gcc_assert((this->traverse_mask() & traverse_types) != 0 - || (this->traverse_mask() & traverse_expressions) != 0); - if (this->expressions_seen_ == NULL) - this->expressions_seen_ = new Expressions_seen(); - std::pair ins = - this->expressions_seen_->insert(expression); - return !ins.second; -} - -// The default versions of these functions should never be called: the -// traversal mask indicates which functions may be called. - -int -Traverse::variable(Named_object*) -{ - gcc_unreachable(); -} - -int -Traverse::constant(Named_object*, bool) -{ - gcc_unreachable(); -} - -int -Traverse::function(Named_object*) -{ - gcc_unreachable(); -} - -int -Traverse::block(Block*) -{ - gcc_unreachable(); -} - -int -Traverse::statement(Block*, size_t*, Statement*) -{ - gcc_unreachable(); -} - -int -Traverse::expression(Expression**) -{ - gcc_unreachable(); -} - -int -Traverse::type(Type*) -{ - gcc_unreachable(); -} diff --git a/gcc/go/gofrontend/gogo.h.merge-left.r167407 b/gcc/go/gofrontend/gogo.h.merge-left.r167407 deleted file mode 100644 index d0cfa1e90e0..00000000000 --- a/gcc/go/gofrontend/gogo.h.merge-left.r167407 +++ /dev/null @@ -1,2484 +0,0 @@ -// gogo.h -- Go frontend parsed representation. -*- C++ -*- - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#ifndef GO_GOGO_H -#define GO_GOGO_H - -class Traverse; -class Type; -class Type_hash_identical; -class Type_equal; -class Type_identical; -class Typed_identifier; -class Typed_identifier_list; -class Function_type; -class Expression; -class Statement; -class Block; -class Function; -class Bindings; -class Package; -class Variable; -class Pointer_type; -class Struct_type; -class Struct_field; -class Struct_field_list; -class Array_type; -class Map_type; -class Channel_type; -class Interface_type; -class Named_type; -class Forward_declaration_type; -class Method; -class Methods; -class Named_object; -class Label; -class Translate_context; -class Export; -class Import; - -// This file declares the basic classes used to hold the internal -// representation of Go which is built by the parser. - -// An initialization function for an imported package. This is a -// magic function which initializes variables and runs the "init" -// function. - -class Import_init -{ - public: - Import_init(const std::string& package_name, const std::string& init_name, - int priority) - : package_name_(package_name), init_name_(init_name), priority_(priority) - { } - - // The name of the package being imported. - const std::string& - package_name() const - { return this->package_name_; } - - // The name of the package's init function. - const std::string& - init_name() const - { return this->init_name_; } - - // The priority of the initialization function. Functions with a - // lower priority number must be run first. - int - priority() const - { return this->priority_; } - - private: - // The name of the package being imported. - std::string package_name_; - // The name of the package's init function. - std::string init_name_; - // The priority. - int priority_; -}; - -// For sorting purposes. - -inline bool -operator<(const Import_init& i1, const Import_init& i2) -{ - if (i1.priority() < i2.priority()) - return true; - if (i1.priority() > i2.priority()) - return false; - if (i1.package_name() != i2.package_name()) - return i1.package_name() < i2.package_name(); - return i1.init_name() < i2.init_name(); -} - -// The holder for the internal representation of the entire -// compilation unit. - -class Gogo -{ - public: - // Create the IR, passing in the sizes of the types "int", "float", - // and "uintptr" in bits. - Gogo(int int_type_size, int float_type_size, int pointer_size); - - // Get the package name. - const std::string& - package_name() const; - - // Set the package name. - void - set_package_name(const std::string&, source_location); - - // If necessary, adjust the name to use for a hidden symbol. We add - // a prefix of the package name, so that hidden symbols in different - // packages do not collide. - std::string - pack_hidden_name(const std::string& name, bool is_exported) const - { - return (is_exported - ? name - : ('.' + this->unique_prefix() - + '.' + this->package_name() - + '.' + name)); - } - - // Unpack a name which may have been hidden. Returns the - // user-visible name of the object. - static std::string - unpack_hidden_name(const std::string& name) - { return name[0] != '.' ? name : name.substr(name.rfind('.') + 1); } - - // Return whether a possibly packed name is hidden. - static bool - is_hidden_name(const std::string& name) - { return name[0] == '.'; } - - // Return the package prefix of a hidden name. - static std::string - hidden_name_prefix(const std::string& name) - { - gcc_assert(Gogo::is_hidden_name(name)); - return name.substr(1, name.rfind('.') - 1); - } - - // Given a name which may or may not have been hidden, return the - // name to use in an error message. - static std::string - message_name(const std::string& name); - - // Return whether a name is the blank identifier _. - static bool - is_sink_name(const std::string& name) - { - return (name[0] == '.' - && name[name.length() - 1] == '_' - && name[name.length() - 2] == '.'); - } - - // Return the unique prefix to use for all exported symbols. - const std::string& - unique_prefix() const; - - // Set the unique prefix. - void - set_unique_prefix(const std::string&); - - // Return the priority to use for the package we are compiling. - // This is two more than the largest priority of any package we - // import. - int - package_priority() const; - - // Import a package. FILENAME is the file name argument, LOCAL_NAME - // is the local name to give to the package. If LOCAL_NAME is empty - // the declarations are added to the global scope. - void - import_package(const std::string& filename, const std::string& local_name, - bool is_local_name_exported, source_location); - - // Whether we are the global binding level. - bool - in_global_scope() const; - - // Look up a name in the current binding contours. - Named_object* - lookup(const std::string&, Named_object** pfunction) const; - - // Look up a name in the current block. - Named_object* - lookup_in_block(const std::string&) const; - - // Look up a name in the global namespace--the universal scope. - Named_object* - lookup_global(const char*) const; - - // Add a new imported package. REAL_NAME is the real name of the - // package. ALIAS is the alias of the package; this may be the same - // as REAL_NAME. This sets *PADD_TO_GLOBALS if symbols added to - // this package should be added to the global namespace; this is - // true if the alias is ".". LOCATION is the location of the import - // statement. This returns the new package, or NULL on error. - Package* - add_imported_package(const std::string& real_name, const std::string& alias, - bool is_alias_exported, - const std::string& unique_prefix, - source_location location, - bool* padd_to_globals); - - // Register a package. This package may or may not be imported. - // This returns the Package structure for the package, creating if - // it necessary. - Package* - register_package(const std::string& name, const std::string& unique_prefix, - source_location); - - // Start compiling a function. ADD_METHOD_TO_TYPE is true if a - // method function should be added to the type of its receiver. - Named_object* - start_function(const std::string& name, Function_type* type, - bool add_method_to_type, source_location); - - // Finish compiling a function. - void - finish_function(source_location); - - // Return the current function. - Named_object* - current_function() const; - - // Start a new block. This is not initially associated with a - // function. - void - start_block(source_location); - - // Finish the current block and return it. - Block* - finish_block(source_location); - - // Declare an unknown name. This is used while parsing. The name - // must be resolved by the end of the parse. Unknown names are - // always added at the package level. - Named_object* - add_unknown_name(const std::string& name, source_location); - - // Declare a function. - Named_object* - declare_function(const std::string&, Function_type*, source_location); - - // Add a label. - Label* - add_label_definition(const std::string&, source_location); - - // Add a label reference. - Label* - add_label_reference(const std::string&); - - // Add a statement to the current block. - void - add_statement(Statement*); - - // Add a block to the current block. - void - add_block(Block*, source_location); - - // Add a constant. - Named_object* - add_constant(const Typed_identifier&, Expression*, int iota_value); - - // Add a type. - void - add_type(const std::string&, Type*, source_location); - - // Add a named type. This is used for builtin types, and to add an - // imported type to the global scope. - void - add_named_type(Named_type*); - - // Declare a type. - Named_object* - declare_type(const std::string&, source_location); - - // Declare a type at the package level. This is used when the - // parser sees an unknown name where a type name is required. - Named_object* - declare_package_type(const std::string&, source_location); - - // Define a type which was already declared. - void - define_type(Named_object*, Named_type*); - - // Add a variable. - Named_object* - add_variable(const std::string&, Variable*); - - // Add a sink--a reference to the blank identifier _. - Named_object* - add_sink(); - - // Add a named object to the current namespace. This is used for - // import . "package". - void - add_named_object(Named_object*); - - // Return a name to use for a thunk function. A thunk function is - // one we create during the compilation, for a go statement or a - // defer statement or a method expression. - static std::string - thunk_name(); - - // Return whether an object is a thunk. - static bool - is_thunk(const Named_object*); - - // Note that we've seen an interface type. This is used to build - // all required interface method tables. - void - record_interface_type(Interface_type*); - - // Clear out all names in file scope. This is called when we start - // parsing a new file. - void - clear_file_scope(); - - // Traverse the tree. See the Traverse class. - void - traverse(Traverse*); - - // Define the predeclared global names. - void - define_global_names(); - - // Verify and complete all types. - void - verify_types(); - - // Lower the parse tree. - void - lower_parse_tree(); - - // Lower an expression. - void - lower_expression(Named_object* function, Expression**); - - // Lower a constant. - void - lower_constant(Named_object*); - - // Finalize the method lists and build stub methods for named types. - void - finalize_methods(); - - // Work out the types to use for unspecified variables and - // constants. - void - determine_types(); - - // Type check the program. - void - check_types(); - - // Check the types in a single block. This is used for complicated - // go statements. - void - check_types_in_block(Block*); - - // Check for return statements. - void - check_return_statements(); - - // Do all exports. - void - do_exports(); - - // Add an import control function for an imported package to the - // list. - void - add_import_init_fn(const std::string& package_name, - const std::string& init_name, int prio); - - // Turn short-cut operators (&&, ||) into explicit if statements. - void - remove_shortcuts(); - - // Use temporary variables to force order of evaluation. - void - order_evaluations(); - - // Build thunks for functions which call recover. - void - build_recover_thunks(); - - // Simplify statements which might use thunks: go and defer - // statements. - void - simplify_thunk_statements(); - - // Write out the global values. - void - write_globals(); - - // Build a call to a builtin function. PDECL should point to a NULL - // initialized static pointer which will hold the fndecl. NAME is - // the name of the function. NARGS is the number of arguments. - // RETTYPE is the return type. It is followed by NARGS pairs of - // type and argument (both trees). - static tree - call_builtin(tree* pdecl, source_location, const char* name, int nargs, - tree rettype, ...); - - // Build a call to the runtime error function. - static tree - runtime_error(int code, source_location); - - // Build a builtin struct with a list of fields. - static tree - builtin_struct(tree* ptype, const char* struct_name, tree struct_type, - int nfields, ...); - - // Mark a function declaration as a builtin library function. - static void - mark_fndecl_as_builtin_library(tree fndecl); - - // Build the type of the struct that holds a slice for the given - // element type. - tree - slice_type_tree(tree element_type_tree); - - // Given a tree for a slice type, return the tree for the element - // type. - static tree - slice_element_type_tree(tree slice_type_tree); - - // Build a constructor for a slice. SLICE_TYPE_TREE is the type of - // the slice. VALUES points to the values. COUNT is the size, - // CAPACITY is the capacity. If CAPACITY is NULL, it is set to - // COUNT. - static tree - slice_constructor(tree slice_type_tree, tree values, tree count, - tree capacity); - - // Build a constructor for an empty slice. SLICE_TYPE_TREE is the - // type of the slice. - static tree - empty_slice_constructor(tree slice_type_tree); - - // Build a map descriptor. - tree - map_descriptor(Map_type*); - - // Return a tree for the type of a map descriptor. This is struct - // __go_map_descriptor in libgo/runtime/map.h. This is the same for - // all map types. - tree - map_descriptor_type(); - - // Build a type descriptor for TYPE using INITIALIZER as the type - // descriptor. This builds a new decl stored in *PDECL. - void - build_type_descriptor_decl(const Type*, Expression* initializer, - tree* pdecl); - - // Build required interface method tables. - void - build_interface_method_tables(); - - // Build an interface method table for a type: a list of function - // pointers, one for each interface method. This returns a decl. - tree - interface_method_table_for_type(const Interface_type*, Named_type*, - bool is_pointer); - - // Return a tree which allocate SIZE bytes to hold values of type - // TYPE. - tree - allocate_memory(Type *type, tree size, source_location); - - // Return a type to use for pointer to const char. - static tree - const_char_pointer_type_tree(); - - // Build a string constant with the right type. - static tree - string_constant_tree(const std::string&); - - // Build a Go string constant. This returns a pointer to the - // constant. - tree - go_string_constant_tree(const std::string&); - - // Send a value on a channel. - static tree - send_on_channel(tree channel, tree val, bool blocking, bool for_select, - source_location); - - // Receive a value from a channel. - static tree - receive_from_channel(tree type_tree, tree channel, bool for_select, - source_location); - - // Return a tree for receiving an integer on a channel. - static tree - receive_as_64bit_integer(tree type, tree channel, bool blocking, - bool for_select); - - - // Make a trampoline which calls FNADDR passing CLOSURE. - tree - make_trampoline(tree fnaddr, tree closure, source_location); - - private: - // During parsing, we keep a stack of functions. Each function on - // the stack is one that we are currently parsing. For each - // function, we keep track of the current stack of blocks. - struct Open_function - { - // The function. - Named_object* function; - // The stack of active blocks in the function. - std::vector blocks; - }; - - // The stack of functions. - typedef std::vector Open_functions; - - // Create trees for implicit builtin functions. - void - define_builtin_function_trees(); - - // Set up the built-in unsafe package. - void - import_unsafe(const std::string&, bool is_exported, source_location); - - // Add a new imported package. - Named_object* - add_package(const std::string& real_name, const std::string& alias, - const std::string& unique_prefix, source_location location); - - // Return the current binding contour. - Bindings* - current_bindings(); - - const Bindings* - current_bindings() const; - - // Return the current block. - Block* - current_block(); - - // Get the name of the magic initialization function. - const std::string& - get_init_fn_name(); - - // Get the decl for the magic initialization function. - tree - initialization_function_decl(); - - // Write the magic initialization function. - void - write_initialization_function(tree fndecl, tree init_stmt_list); - - // Initialize imported packages. - void - init_imports(tree*); - - // Register variables with the garbage collector. - void - register_gc_vars(const std::vector&, tree*); - - // Build a pointer to a Go string constant. This returns a pointer - // to the pointer. - tree - ptr_go_string_constant_tree(const std::string&); - - // Return the name to use for a type descriptor decl for an unnamed - // type. - std::string - unnamed_type_descriptor_decl_name(const Type* type); - - // Return the name to use for a type descriptor decl for a type - // named NO, defined in IN_FUNCTION. - std::string - type_descriptor_decl_name(const Named_object* no, - const Named_object* in_function); - - // Where a type descriptor should be defined. - enum Type_descriptor_location - { - // Defined in this file. - TYPE_DESCRIPTOR_DEFINED, - // Defined in some other file. - TYPE_DESCRIPTOR_UNDEFINED, - // Common definition which may occur in multiple files. - TYPE_DESCRIPTOR_COMMON - }; - - // Return where the decl for TYPE should be defined. - Type_descriptor_location - type_descriptor_location(const Type* type); - - // Return the type of a trampoline. - static tree - trampoline_type_tree(); - - // Type used to map import names to packages. - typedef std::map Imports; - - // Type used to map package names to packages. - typedef std::map Packages; - - // Type used to map special names in the sys package. - typedef std::map Sys_names; - - // Hash table mapping map types to map descriptor decls. - typedef Unordered_map_hash(const Map_type*, tree, Type_hash_identical, - Type_identical) Map_descriptors; - - // Map unnamed types to type descriptor decls. - typedef Unordered_map_hash(const Type*, tree, Type_hash_identical, - Type_identical) Type_descriptor_decls; - - // The package we are compiling. - Package* package_; - // The list of currently open functions during parsing. - Open_functions functions_; - // The global binding contour. This includes the builtin functions - // and the package we are compiling. - Bindings* globals_; - // Mapping from import file names to packages. - Imports imports_; - // Whether the magic unsafe package was imported. - bool imported_unsafe_; - // Mapping from package names we have seen to packages. This does - // not include the package we are compiling. - Packages packages_; - // Mapping from map types to map descriptors. - Map_descriptors* map_descriptors_; - // Mapping from unnamed types to type descriptor decls. - Type_descriptor_decls* type_descriptor_decls_; - // The functions named "init", if there are any. - std::vector init_functions_; - // Whether we need a magic initialization function. - bool need_init_fn_; - // The name of the magic initialization function. - std::string init_fn_name_; - // A list of import control variables for packages that we import. - std::set imported_init_fns_; - // The unique prefix used for all global symbols. - std::string unique_prefix_; - // A list of interface types defined while parsing. - std::vector interface_types_; -}; - -// A block of statements. - -class Block -{ - public: - Block(Block* enclosing, source_location); - - // Return the enclosing block. - const Block* - enclosing() const - { return this->enclosing_; } - - // Return the bindings of the block. - Bindings* - bindings() - { return this->bindings_; } - - const Bindings* - bindings() const - { return this->bindings_; } - - // Look at the block's statements. - const std::vector* - statements() const - { return &this->statements_; } - - // Return the start location. This is normally the location of the - // left curly brace which starts the block. - source_location - start_location() const - { return this->start_location_; } - - // Return the end location. This is normally the location of the - // right curly brace which ends the block. - source_location - end_location() const - { return this->end_location_; } - - // Add a statement to the block. - void - add_statement(Statement*); - - // Add a statement to the front of the block. - void - add_statement_at_front(Statement*); - - // Replace a statement in a block. - void - replace_statement(size_t index, Statement*); - - // Add a Statement before statement number INDEX. - void - insert_statement_before(size_t index, Statement*); - - // Add a Statement after statement number INDEX. - void - insert_statement_after(size_t index, Statement*); - - // Set the end location of the block. - void - set_end_location(source_location location) - { this->end_location_ = location; } - - // Traverse the tree. - int - traverse(Traverse*); - - // Set final types for unspecified variables and constants. - void - determine_types(); - - // Return true if execution of this block may fall through to the - // next block. - bool - may_fall_through() const; - - // Return a tree of the code in this block. - tree - get_tree(Translate_context*); - - // Iterate over statements. - - typedef std::vector::iterator iterator; - - iterator - begin() - { return this->statements_.begin(); } - - iterator - end() - { return this->statements_.end(); } - - private: - // Enclosing block. - Block* enclosing_; - // Statements in the block. - std::vector statements_; - // Binding contour. - Bindings* bindings_; - // Location of start of block. - source_location start_location_; - // Location of end of block. - source_location end_location_; -}; - -// A function. - -class Function -{ - public: - Function(Function_type* type, Function*, Block*, source_location); - - // Return the function's type. - Function_type* - type() const - { return this->type_; } - - // Return the enclosing function if there is one. - Function* - enclosing() - { return this->enclosing_; } - - // Set the enclosing function. This is used when building thunks - // for functions which call recover. - void - set_enclosing(Function* enclosing) - { - gcc_assert(this->enclosing_ == NULL); - this->enclosing_ = enclosing; - } - - // Create the named result variables in the outer block. - void - create_named_result_variables(); - - // Add a new field to the closure variable. - void - add_closure_field(Named_object* var, source_location loc) - { this->closure_fields_.push_back(std::make_pair(var, loc)); } - - // Whether this function needs a closure. - bool - needs_closure() const - { return !this->closure_fields_.empty(); } - - // Return the closure variable, creating it if necessary. This is - // passed to the function as a static chain parameter. - Named_object* - closure_var(); - - // Set the closure variable. This is used when building thunks for - // functions which call recover. - void - set_closure_var(Named_object* v) - { - gcc_assert(this->closure_var_ == NULL); - this->closure_var_ = v; - } - - // Return the variable for a reference to field INDEX in the closure - // variable. - Named_object* - enclosing_var(unsigned int index) - { - gcc_assert(index < this->closure_fields_.size()); - return closure_fields_[index].first; - } - - // Set the type of the closure variable if there is one. - void - set_closure_type(); - - // Get the block of statements associated with the function. - Block* - block() const - { return this->block_; } - - // Get the location of the start of the function. - source_location - location() const - { return this->location_; } - - // Return whether this function is actually a method. - bool - is_method() const; - - // Add a label definition to the function. - Label* - add_label_definition(const std::string& label_name, source_location); - - // Add a label reference to a function. - Label* - add_label_reference(const std::string& label_name); - - // Whether this function calls the predeclared recover function. - bool - calls_recover() const - { return this->calls_recover_; } - - // Record that this function calls the predeclared recover function. - // This is set during the lowering pass. - void - set_calls_recover() - { this->calls_recover_ = true; } - - // Whether this is a recover thunk function. - bool - is_recover_thunk() const - { return this->is_recover_thunk_; } - - // Record that this is a thunk built for a function which calls - // recover. - void - set_is_recover_thunk() - { this->is_recover_thunk_ = true; } - - // Whether this function already has a recover thunk. - bool - has_recover_thunk() const - { return this->has_recover_thunk_; } - - // Record that this function already has a recover thunk. - void - set_has_recover_thunk() - { this->has_recover_thunk_ = true; } - - // Swap with another function. Used only for the thunk which calls - // recover. - void - swap_for_recover(Function *); - - // Traverse the tree. - int - traverse(Traverse*); - - // Determine types in the function. - void - determine_types(); - - // Return the function's decl given an identifier. - tree - get_or_make_decl(Gogo*, Named_object*, tree id); - - // Return the function's decl after it has been built. - tree - get_decl() const - { - gcc_assert(this->fndecl_ != NULL); - return this->fndecl_; - } - - // Set the function decl to hold a tree of the function code. - void - build_tree(Gogo*, Named_object*); - - // Get the value to return when not explicitly specified. May also - // add statements to execute first to STMT_LIST. - tree - return_value(Gogo*, Named_object*, source_location, tree* stmt_list) const; - - // Get a tree for the variable holding the defer stack. - tree - defer_stack(source_location); - - // Export the function. - void - export_func(Export*, const std::string& name) const; - - // Export a function with a type. - static void - export_func_with_type(Export*, const std::string& name, - const Function_type*); - - // Import a function. - static void - import_func(Import*, std::string* pname, Typed_identifier** receiver, - Typed_identifier_list** pparameters, - Typed_identifier_list** presults, bool* is_varargs); - - private: - // Type for mapping from label names to Label objects. - typedef Unordered_map(std::string, Label*) Labels; - - tree - make_receiver_parm_decl(Gogo*, Named_object*, tree); - - tree - copy_parm_to_heap(Gogo*, Named_object*, tree); - - void - build_defer_wrapper(Gogo*, Named_object*, tree*, tree*); - - typedef std::vector Named_results; - - typedef std::vector > Closure_fields; - - // The function's type. - Function_type* type_; - // The enclosing function. This is NULL when there isn't one, which - // is the normal case. - Function* enclosing_; - // The named result variables, if any. - Named_results* named_results_; - // If there is a closure, this is the list of variables which appear - // in the closure. This is created by the parser, and then resolved - // to a real type when we lower parse trees. - Closure_fields closure_fields_; - // The closure variable, passed as a parameter using the static - // chain parameter. Normally NULL. - Named_object* closure_var_; - // The outer block of statements in the function. - Block* block_; - // The source location of the start of the function. - source_location location_; - // Labels defined or referenced in the function. - Labels labels_; - // The function decl. - tree fndecl_; - // A variable holding the defer stack variable. This is NULL unless - // we actually need a defer stack. - tree defer_stack_; - // True if this function calls the predeclared recover function. - bool calls_recover_; - // True if this a thunk built for a function which calls recover. - bool is_recover_thunk_; - // True if this function already has a recover thunk. - bool has_recover_thunk_; -}; - -// A function declaration. - -class Function_declaration -{ - public: - Function_declaration(Function_type* fntype, source_location location) - : fntype_(fntype), location_(location), asm_name_(), fndecl_(NULL) - { } - - Function_type* - type() const - { return this->fntype_; } - - source_location - location() const - { return this->location_; } - - const std::string& - asm_name() const - { return this->asm_name_; } - - // Set the assembler name. - void - set_asm_name(const std::string& asm_name) - { this->asm_name_ = asm_name; } - - // Return a decl for the function given an identifier. - tree - get_or_make_decl(Gogo*, Named_object*, tree id); - - // Export a function declaration. - void - export_func(Export* exp, const std::string& name) const - { Function::export_func_with_type(exp, name, this->fntype_); } - - private: - // The type of the function. - Function_type* fntype_; - // The location of the declaration. - source_location location_; - // The assembler name: this is the name to use in references to the - // function. This is normally empty. - std::string asm_name_; - // The function decl if needed. - tree fndecl_; -}; - -// A variable. - -class Variable -{ - public: - Variable(Type*, Expression*, bool is_global, bool is_parameter, - bool is_receiver, source_location); - - // Get the type of the variable. - Type* - type() const; - - // Return whether the type is defined yet. - bool - has_type() const - { return this->type_ != NULL; } - - // Get the initial value. - Expression* - init() const - { return this->init_; } - - // Return whether there are any preinit statements. - bool - has_pre_init() const - { return this->preinit_ != NULL; } - - // Return the preinit statements if any. - Block* - preinit() const - { return this->preinit_; } - - // Return whether this is a global variable. - bool - is_global() const - { return this->is_global_; } - - // Return whether this is a function parameter. - bool - is_parameter() const - { return this->is_parameter_; } - - // Return whether this is the receiver parameter of a method. - bool - is_receiver() const - { return this->is_receiver_; } - - // Change this parameter to be a receiver. This is used when - // creating the thunks created for functions which call recover. - void - set_is_receiver() - { - gcc_assert(this->is_parameter_); - this->is_receiver_ = true; - } - - // Change this parameter to not be a receiver. This is used when - // creating the thunks created for functions which call recover. - void - set_is_not_receiver() - { - gcc_assert(this->is_parameter_); - this->is_receiver_ = false; - } - - // Return whether this is the varargs parameter of a function. - bool - is_varargs_parameter() const - { return this->is_varargs_parameter_; } - - // Whether this variable's address is taken. - bool - is_address_taken() const - { return this->is_address_taken_; } - - // Whether this variable should live in the heap. - bool - is_in_heap() const - { return this->is_address_taken_ && !this->is_global_; } - - // Get the source location of the variable's declaration. - source_location - location() const - { return this->location_; } - - // Record that this is the varargs parameter of a function. - void - set_is_varargs_parameter() - { - gcc_assert(this->is_parameter_); - this->is_varargs_parameter_ = true; - } - - // Clear the initial value; used for error handling. - void - clear_init() - { this->init_ = NULL; } - - // Set the initial value; used for converting shortcuts. - void - set_init(Expression* init) - { this->init_ = init; } - - // Get the preinit block, a block of statements to be run before the - // initialization expression. - Block* - preinit_block(); - - // Add a statement to be run before the initialization expression. - // This is only used for global variables. - void - add_preinit_statement(Statement*); - - // Lower the initialization expression after parsing is complete. - void - lower_init_expression(Gogo*, Named_object*); - - // A special case: the init value is used only to determine the - // type. This is used if the variable is defined using := with the - // comma-ok form of a map index or a receive expression. The init - // value is actually the map index expression or receive expression. - // We use this because we may not know the right type at parse time. - void - set_type_from_init_tuple() - { this->type_from_init_tuple_ = true; } - - // Another special case: the init value is used only to determine - // the type. This is used if the variable is defined using := with - // a range clause. The init value is the range expression. The - // type of the variable is the index type of the range expression - // (i.e., the first value returned by a range). - void - set_type_from_range_index() - { this->type_from_range_index_ = true; } - - // Another special case: like set_type_from_range_index, but the - // type is the value type of the range expression (i.e., the second - // value returned by a range). - void - set_type_from_range_value() - { this->type_from_range_value_ = true; } - - // Another special case: the init value is used only to determine - // the type. This is used if the variable is defined using := with - // a case in a select statement. The init value is the channel. - // The type of the variable is the channel's element type. - void - set_type_from_chan_element() - { this->type_from_chan_element_ = true; } - - // After we lower the select statement, we once again set the type - // from the initialization expression. - void - clear_type_from_chan_element() - { - gcc_assert(this->type_from_chan_element_); - this->type_from_chan_element_ = false; - } - - // Note that this variable was created for a type switch clause. - void - set_is_type_switch_var() - { this->is_type_switch_var_ = true; } - - // Traverse the initializer expression. - int - traverse_expression(Traverse*); - - // Determine the type of the variable if necessary. - void - determine_type(); - - // Note that something takes the address of this variable. - void - set_address_taken() - { this->is_address_taken_ = true; } - - // Get the initial value of the variable as a tree. This may only - // be called if has_pre_init() returns false. - tree - get_init_tree(Gogo*, Named_object* function); - - // Return a series of statements which sets the value of the - // variable in DECL. This should only be called is has_pre_init() - // returns true. DECL may be NULL for a sink variable. - tree - get_init_block(Gogo*, Named_object* function, tree decl); - - // Export the variable. - void - export_var(Export*, const std::string& name) const; - - // Import a variable. - static void - import_var(Import*, std::string* pname, Type** ptype); - - private: - // The type of a tuple. - Type* - type_from_tuple(Expression*, bool) const; - - // The type of a range. - Type* - type_from_range(Expression*, bool, bool) const; - - // The element type of a channel. - Type* - type_from_chan_element(Expression*, bool) const; - - // The variable's type. This may be NULL if the type is set from - // the expression. - Type* type_; - // The initial value. This may be NULL if the variable should be - // initialized to the default value for the type. - Expression* init_; - // Statements to run before the init statement. - Block* preinit_; - // Location of variable definition. - source_location location_; - // Whether this is a global variable. - bool is_global_ : 1; - // Whether this is a function parameter. - bool is_parameter_ : 1; - // Whether this is the receiver parameter of a method. - bool is_receiver_ : 1; - // Whether this is the varargs parameter of a function. - bool is_varargs_parameter_ : 1; - // Whether something takes the address of this variable. - bool is_address_taken_ : 1; - // True if we have lowered the initialization expression. - bool init_is_lowered_ : 1; - // True if init is a tuple used to set the type. - bool type_from_init_tuple_ : 1; - // True if init is a range clause and the type is the index type. - bool type_from_range_index_ : 1; - // True if init is a range clause and the type is the value type. - bool type_from_range_value_ : 1; - // True if init is a channel and the type is the channel's element type. - bool type_from_chan_element_ : 1; - // True if this is a variable created for a type switch case. - bool is_type_switch_var_ : 1; -}; - -// A variable which is really the name for a function return value, or -// part of one. - -class Result_variable -{ - public: - Result_variable(Type* type, Function* function, int index) - : type_(type), function_(function), index_(index), - is_address_taken_(false) - { } - - // Get the type of the result variable. - Type* - type() const - { return this->type_; } - - // Get the function that this is associated with. - Function* - function() const - { return this->function_; } - - // Index in the list of function results. - int - index() const - { return this->index_; } - - // Whether this variable's address is taken. - bool - is_address_taken() const - { return this->is_address_taken_; } - - // Note that something takes the address of this variable. - void - set_address_taken() - { this->is_address_taken_ = true; } - - // Whether this variable should live in the heap. - bool - is_in_heap() const - { return this->is_address_taken_; } - - private: - // Type of result variable. - Type* type_; - // Function with which this is associated. - Function* function_; - // Index in list of results. - int index_; - // Whether something takes the address of this variable. - bool is_address_taken_; -}; - -// The value we keep for a named constant. This lets us hold a type -// and an expression. - -class Named_constant -{ - public: - Named_constant(Type* type, Expression* expr, int iota_value, - source_location location) - : type_(type), expr_(expr), iota_value_(iota_value), location_(location), - lowering_(false) - { } - - Type* - type() const - { return this->type_; } - - Expression* - expr() const - { return this->expr_; } - - int - iota_value() const - { return this->iota_value_; } - - source_location - location() const - { return this->location_; } - - // Whether we are lowering. - bool - lowering() const - { return this->lowering_; } - - // Set that we are lowering. - void - set_lowering() - { this->lowering_ = true; } - - // We are no longer lowering. - void - clear_lowering() - { this->lowering_ = false; } - - // Traverse the expression. - int - traverse_expression(Traverse*); - - // Determine the type of the constant if necessary. - void - determine_type(); - - // Indicate that we found and reported an error for this constant. - void - set_error(); - - // Export the constant. - void - export_const(Export*, const std::string& name) const; - - // Import a constant. - static void - import_const(Import*, std::string*, Type**, Expression**); - - private: - // The type of the constant. - Type* type_; - // The expression for the constant. - Expression* expr_; - // If the predeclared constant iota is used in EXPR_, this is the - // value it will have. We do this because at parse time we don't - // know whether the name "iota" will refer to the predeclared - // constant or to something else. We put in the right value in when - // we lower. - int iota_value_; - // The location of the definition. - source_location location_; - // Whether we are currently lowering this constant. - bool lowering_; -}; - -// A type declaration. - -class Type_declaration -{ - public: - Type_declaration(source_location location) - : location_(location), in_function_(NULL), methods_(), - issued_warning_(false) - { } - - // Return the location. - source_location - location() const - { return this->location_; } - - // Return the function in which this type is declared. This will - // return NULL for a type declared in global scope. - Named_object* - in_function() - { return this->in_function_; } - - // Set the function in which this type is declared. - void - set_in_function(Named_object* f) - { this->in_function_ = f; } - - // Add a method to this type. This is used when methods are defined - // before the type. - Named_object* - add_method(const std::string& name, Function* function); - - // Add a method declaration to this type. - Named_object* - add_method_declaration(const std::string& name, Function_type* type, - source_location location); - - // Return whether any methods were defined. - bool - has_methods() const; - - // Define methods when the real type is known. - void - define_methods(Named_type*); - - // This is called if we are trying to use this type. It returns - // true if we should issue a warning. - bool - using_type(); - - private: - typedef std::vector Methods; - - // The location of the type declaration. - source_location location_; - // If this type is declared in a function, a pointer back to the - // function in which it is defined. - Named_object* in_function_; - // Methods defined before the type is defined. - Methods methods_; - // True if we have issued a warning about a use of this type - // declaration when it is undefined. - bool issued_warning_; -}; - -// An unknown object. These are created by the parser for forward -// references to names which have not been seen before. In a correct -// program, these will always point to a real definition by the end of -// the parse. Because they point to another Named_object, these may -// only be referenced by Unknown_expression objects. - -class Unknown_name -{ - public: - Unknown_name(source_location location) - : location_(location), real_named_object_(NULL) - { } - - // Return the location where this name was first seen. - source_location - location() const - { return this->location_; } - - // Return the real named object that this points to, or NULL if it - // was never resolved. - Named_object* - real_named_object() const - { return this->real_named_object_; } - - // Set the real named object that this points to. - void - set_real_named_object(Named_object* no); - - private: - // The location where this name was first seen. - source_location location_; - // The real named object when it is known. - Named_object* - real_named_object_; -}; - -// A named object named. This is the result of a declaration. We -// don't use a superclass because they all have to be handled -// differently. - -class Named_object -{ - public: - enum Classification - { - // An uninitialized Named_object. We should never see this. - NAMED_OBJECT_UNINITIALIZED, - // An unknown name. This is used for forward references. In a - // correct program, these will all be resolved by the end of the - // parse. - NAMED_OBJECT_UNKNOWN, - // A const. - NAMED_OBJECT_CONST, - // A type. - NAMED_OBJECT_TYPE, - // A forward type declaration. - NAMED_OBJECT_TYPE_DECLARATION, - // A var. - NAMED_OBJECT_VAR, - // A result variable in a function. - NAMED_OBJECT_RESULT_VAR, - // The blank identifier--the special variable named _. - NAMED_OBJECT_SINK, - // A func. - NAMED_OBJECT_FUNC, - // A forward func declaration. - NAMED_OBJECT_FUNC_DECLARATION, - // A package. - NAMED_OBJECT_PACKAGE - }; - - // Return the classification. - Classification - classification() const - { return this->classification_; } - - // Classifiers. - - bool - is_unknown() const - { return this->classification_ == NAMED_OBJECT_UNKNOWN; } - - bool - is_const() const - { return this->classification_ == NAMED_OBJECT_CONST; } - - bool - is_type() const - { return this->classification_ == NAMED_OBJECT_TYPE; } - - bool - is_type_declaration() const - { return this->classification_ == NAMED_OBJECT_TYPE_DECLARATION; } - - bool - is_variable() const - { return this->classification_ == NAMED_OBJECT_VAR; } - - bool - is_result_variable() const - { return this->classification_ == NAMED_OBJECT_RESULT_VAR; } - - bool - is_sink() const - { return this->classification_ == NAMED_OBJECT_SINK; } - - bool - is_function() const - { return this->classification_ == NAMED_OBJECT_FUNC; } - - bool - is_function_declaration() const - { return this->classification_ == NAMED_OBJECT_FUNC_DECLARATION; } - - bool - is_package() const - { return this->classification_ == NAMED_OBJECT_PACKAGE; } - - // Creators. - - static Named_object* - make_unknown_name(const std::string& name, source_location); - - static Named_object* - make_constant(const Typed_identifier&, const Package*, Expression*, - int iota_value); - - static Named_object* - make_type(const std::string&, const Package*, Type*, source_location); - - static Named_object* - make_type_declaration(const std::string&, const Package*, source_location); - - static Named_object* - make_variable(const std::string&, const Package*, Variable*); - - static Named_object* - make_result_variable(const std::string&, Result_variable*); - - static Named_object* - make_sink(); - - static Named_object* - make_function(const std::string&, const Package*, Function*); - - static Named_object* - make_function_declaration(const std::string&, const Package*, Function_type*, - source_location); - - static Named_object* - make_package(const std::string& alias, Package* package); - - // Getters. - - Unknown_name* - unknown_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_UNKNOWN); - return this->u_.unknown_value; - } - - const Unknown_name* - unknown_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_UNKNOWN); - return this->u_.unknown_value; - } - - Named_constant* - const_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_CONST); - return this->u_.const_value; - } - - const Named_constant* - const_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_CONST); - return this->u_.const_value; - } - - Named_type* - type_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_TYPE); - return this->u_.type_value; - } - - const Named_type* - type_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_TYPE); - return this->u_.type_value; - } - - Type_declaration* - type_declaration_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION); - return this->u_.type_declaration; - } - - const Type_declaration* - type_declaration_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION); - return this->u_.type_declaration; - } - - Variable* - var_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_VAR); - return this->u_.var_value; - } - - const Variable* - var_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_VAR); - return this->u_.var_value; - } - - Result_variable* - result_var_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_RESULT_VAR); - return this->u_.result_var_value; - } - - const Result_variable* - result_var_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_RESULT_VAR); - return this->u_.result_var_value; - } - - Function* - func_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_FUNC); - return this->u_.func_value; - } - - const Function* - func_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_FUNC); - return this->u_.func_value; - } - - Function_declaration* - func_declaration_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION); - return this->u_.func_declaration_value; - } - - const Function_declaration* - func_declaration_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION); - return this->u_.func_declaration_value; - } - - Package* - package_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_PACKAGE); - return this->u_.package_value; - } - - const Package* - package_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_PACKAGE); - return this->u_.package_value; - } - - const std::string& - name() const - { return this->name_; } - - // Return the name to use in an error message. The difference is - // that if this Named_object is defined in a different package, this - // will return PACKAGE.NAME. - std::string - message_name() const; - - const Package* - package() const - { return this->package_; } - - // Resolve an unknown value if possible. This returns the same - // Named_object or a new one. - Named_object* - resolve() - { - Named_object* ret = this; - if (this->is_unknown()) - { - Named_object* r = this->unknown_value()->real_named_object(); - if (r != NULL) - ret = r; - } - return ret; - } - - const Named_object* - resolve() const - { - const Named_object* ret = this; - if (this->is_unknown()) - { - const Named_object* r = this->unknown_value()->real_named_object(); - if (r != NULL) - ret = r; - } - return ret; - } - - // The location where this object was defined or referenced. - source_location - location() const; - - // Return a tree for the external identifier for this object. - tree - get_id(Gogo*); - - // Return a tree representing this object. - tree - get_tree(Gogo*, Named_object* function); - - // Define a type declaration. - void - set_type_value(Named_type*); - - // Define a function declaration. - void - set_function_value(Function*); - - // Export this object. - void - export_named_object(Export*) const; - - private: - Named_object(const std::string&, const Package*, Classification); - - // The name of the object. - std::string name_; - // The package that this object is in. This is NULL if it is in the - // file we are compiling. - const Package* package_; - // The type of object this is. - Classification classification_; - // The real data. - union - { - Unknown_name* unknown_value; - Named_constant* const_value; - Named_type* type_value; - Type_declaration* type_declaration; - Variable* var_value; - Result_variable* result_var_value; - Function* func_value; - Function_declaration* func_declaration_value; - Package* package_value; - } u_; - // The DECL tree for this object if we have already converted it. - tree tree_; -}; - -// A binding contour. This binds names to objects. - -class Bindings -{ - public: - // Type for mapping from names to objects. - typedef Unordered_map(std::string, Named_object*) Contour; - - Bindings(Bindings* enclosing); - - // Add an unknown name. - Named_object* - add_unknown_name(const std::string& name, source_location location) - { - return this->add_named_object(Named_object::make_unknown_name(name, - location)); - } - - // Add a constant. - Named_object* - add_constant(const Typed_identifier& tid, const Package* package, - Expression* expr, int iota_value) - { - return this->add_named_object(Named_object::make_constant(tid, package, - expr, - iota_value)); - } - - // Add a type. - Named_object* - add_type(const std::string& name, const Package* package, Type* type, - source_location location) - { - return this->add_named_object(Named_object::make_type(name, package, type, - location)); - } - - // Add a named type. This is used for builtin types, and to add an - // imported type to the global scope. - Named_object* - add_named_type(Named_type* named_type); - - // Add a type declaration. - Named_object* - add_type_declaration(const std::string& name, const Package* package, - source_location location) - { - Named_object* no = Named_object::make_type_declaration(name, package, - location); - return this->add_named_object(no); - } - - // Add a variable. - Named_object* - add_variable(const std::string& name, const Package* package, - Variable* variable) - { - return this->add_named_object(Named_object::make_variable(name, package, - variable)); - } - - // Add a result variable. - Named_object* - add_result_variable(const std::string& name, Result_variable* result) - { - return this->add_named_object(Named_object::make_result_variable(name, - result)); - } - - // Add a function. - Named_object* - add_function(const std::string& name, const Package*, Function* function); - - // Add a function declaration. - Named_object* - add_function_declaration(const std::string& name, const Package* package, - Function_type* type, source_location location); - - // Add a package. The location is the location of the import - // statement. - Named_object* - add_package(const std::string& alias, Package* package) - { - Named_object* no = Named_object::make_package(alias, package); - return this->add_named_object(no); - } - - // Define a type which was already declared. - void - define_type(Named_object*, Named_type*); - - // Add a method to the list of objects. This is not added to the - // lookup table. - void - add_method(Named_object*); - - // Add a named object to this binding. - Named_object* - add_named_object(Named_object* no) - { return this->add_named_object_to_contour(&this->bindings_, no); } - - // Clear all names in file scope from the bindings. - void - clear_file_scope(); - - // Look up a name in this binding contour and in any enclosing - // binding contours. This returns NULL if the name is not found. - Named_object* - lookup(const std::string&) const; - - // Look up a name in this binding contour without looking in any - // enclosing binding contours. Returns NULL if the name is not found. - Named_object* - lookup_local(const std::string&) const; - - // Remove a name. - void - remove_binding(Named_object*); - - // Traverse the tree. See the Traverse class. - int - traverse(Traverse*, bool is_global); - - // Iterate over definitions. This does not include things which - // were only declared. - - typedef std::vector::const_iterator - const_definitions_iterator; - - const_definitions_iterator - begin_definitions() const - { return this->named_objects_.begin(); } - - const_definitions_iterator - end_definitions() const - { return this->named_objects_.end(); } - - // Return the number of definitions. - size_t - size_definitions() const - { return this->named_objects_.size(); } - - // Return whether there are no definitions. - bool - empty_definitions() const - { return this->named_objects_.empty(); } - - // Iterate over declarations. This is everything that has been - // declared, which includes everything which has been defined. - - typedef Contour::const_iterator const_declarations_iterator; - - const_declarations_iterator - begin_declarations() const - { return this->bindings_.begin(); } - - const_declarations_iterator - end_declarations() const - { return this->bindings_.end(); } - - // Return the number of declarations. - size_t - size_declarations() const - { return this->bindings_.size(); } - - // Return whether there are no declarations. - bool - empty_declarations() const - { return this->bindings_.empty(); } - - // Return the first declaration. - Named_object* - first_declaration() - { return this->bindings_.empty() ? NULL : this->bindings_.begin()->second; } - - private: - Named_object* - add_named_object_to_contour(Contour*, Named_object*); - - Named_object* - new_definition(Named_object*, Named_object*); - - // Enclosing bindings. - Bindings* enclosing_; - // The list of objects. - std::vector named_objects_; - // The mapping from names to objects. - Contour bindings_; -}; - -// A label. - -class Label -{ - public: - Label(const std::string& name) - : name_(name), location_(0), decl_(NULL) - { } - - // Return the label's name. - const std::string& - name() const - { return this->name_; } - - // Return whether the label has been defined. - bool - is_defined() const - { return this->location_ != 0; } - - // Return the location of the definition. - source_location - location() const - { return this->location_; } - - // Define the label at LOCATION. - void - define(source_location location) - { - gcc_assert(this->location_ == 0); - this->location_ = location; - } - - // Return the LABEL_DECL for this decl. - tree - get_decl(); - - // Return an expression for the address of this label. - tree - get_addr(source_location location); - - private: - // The name of the label. - std::string name_; - // The location of the definition. This is 0 if the label has not - // yet been defined. - source_location location_; - // The LABEL_DECL. - tree decl_; -}; - -// An unnamed label. These are used when lowering loops. - -class Unnamed_label -{ - public: - Unnamed_label(source_location location) - : location_(location), decl_(NULL) - { } - - // Get the location where the label is defined. - source_location - location() const - { return this->location_; } - - // Set the location where the label is defined. - void - set_location(source_location location) - { this->location_ = location; } - - // Return a statement which defines this label. - tree - get_definition(); - - // Return a goto to this label from LOCATION. - tree - get_goto(source_location location); - - private: - // Return the LABEL_DECL to use with GOTO_EXPR. - tree - get_decl(); - - // The location where the label is defined. - source_location location_; - // The LABEL_DECL. - tree decl_; -}; - -// An imported package. - -class Package -{ - public: - Package(const std::string& name, const std::string& unique_prefix, - source_location location); - - // The real name of this package. This may be different from the - // name in the associated Named_object if the import statement used - // an alias. - const std::string& - name() const - { return this->name_; } - - // Return the location of the import statement. - source_location - location() const - { return this->location_; } - - // Get the unique prefix used for all symbols exported from this - // package. - const std::string& - unique_prefix() const - { - gcc_assert(!this->unique_prefix_.empty()); - return this->unique_prefix_; - } - - // The priority of this package. The init function of packages with - // lower priority must be run before the init function of packages - // with higher priority. - int - priority() const - { return this->priority_; } - - // Set the priority. - void - set_priority(int priority); - - // Return the bindings. - Bindings* - bindings() - { return this->bindings_; } - - // Whether some symbol from the package was used. - bool - used() const - { return this->used_; } - - // Note that some symbol from this package was used. - void - set_used() const - { this->used_ = true; } - - // Clear the used field for the next file. - void - clear_used() - { this->used_ = false; } - - // Whether this package was imported in the current file. - bool - is_imported() const - { return this->is_imported_; } - - // Note that this package was imported in the current file. - void - set_is_imported() - { this->is_imported_ = true; } - - // Clear the imported field for the next file. - void - clear_is_imported() - { this->is_imported_ = false; } - - // Whether this package was imported with a name of "_". - bool - uses_sink_alias() const - { return this->uses_sink_alias_; } - - // Note that this package was imported with a name of "_". - void - set_uses_sink_alias() - { this->uses_sink_alias_ = true; } - - // Clear the sink alias field for the next file. - void - clear_uses_sink_alias() - { this->uses_sink_alias_ = false; } - - // Look up a name in the package. Returns NULL if the name is not - // found. - Named_object* - lookup(const std::string& name) const - { return this->bindings_->lookup(name); } - - // Set the location of the package. This is used if it is seen in a - // different import before it is really imported. - void - set_location(source_location location) - { this->location_ = location; } - - // Add a constant to the package. - Named_object* - add_constant(const Typed_identifier& tid, Expression* expr) - { return this->bindings_->add_constant(tid, this, expr, 0); } - - // Add a type to the package. - Named_object* - add_type(const std::string& name, Type* type, source_location location) - { return this->bindings_->add_type(name, this, type, location); } - - // Add a type declaration to the package. - Named_object* - add_type_declaration(const std::string& name, source_location location) - { return this->bindings_->add_type_declaration(name, this, location); } - - // Add a variable to the package. - Named_object* - add_variable(const std::string& name, Variable* variable) - { return this->bindings_->add_variable(name, this, variable); } - - // Add a function declaration to the package. - Named_object* - add_function_declaration(const std::string& name, Function_type* type, - source_location loc) - { return this->bindings_->add_function_declaration(name, this, type, loc); } - - // Determine types of constants. - void - determine_types(); - - private: - // The real name of this package. - std::string name_; - // The unique prefix for all exported global symbols. - std::string unique_prefix_; - // The names in this package. - Bindings* bindings_; - // The priority of this package. A package has a priority higher - // than the priority of all of the packages that it imports. This - // is used to run init functions in the right order. - int priority_; - // The location of the import statement. - source_location location_; - // True if some name from this package was used. This is mutable - // because we can use a package even if we have a const pointer to - // it. - mutable bool used_; - // True if this package was imported in the current file. - bool is_imported_; - // True if this package was imported with a name of "_". - bool uses_sink_alias_; -}; - -// Return codes for the traversal functions. This is not an enum -// because we want to be able to declare traversal functions in other -// header files without including this one. - -// Continue traversal as usual. -const int TRAVERSE_CONTINUE = -1; - -// Exit traversal. -const int TRAVERSE_EXIT = 0; - -// Continue traversal, but skip components of the current object. -// E.g., if this is returned by Traverse::statement, we do not -// traverse the expressions in the statement even if -// traverse_expressions is set in the traverse_mask. -const int TRAVERSE_SKIP_COMPONENTS = 1; - -// This class is used when traversing the parse tree. The caller uses -// a subclass which overrides functions as desired. - -class Traverse -{ - public: - // These bitmasks say what to traverse. - static const unsigned int traverse_variables = 0x1; - static const unsigned int traverse_constants = 0x2; - static const unsigned int traverse_functions = 0x4; - static const unsigned int traverse_blocks = 0x8; - static const unsigned int traverse_statements = 0x10; - static const unsigned int traverse_expressions = 0x20; - static const unsigned int traverse_types = 0x40; - - Traverse(unsigned int traverse_mask) - : traverse_mask_(traverse_mask), types_seen_(NULL), expressions_seen_(NULL) - { } - - virtual ~Traverse(); - - // The bitmask of what to traverse. - unsigned int - traverse_mask() const - { return this->traverse_mask_; } - - // Record that we are going to traverse a type. This returns true - // if the type has already been seen in this traversal. This is - // required because types, unlike expressions, can form a circular - // graph. - bool - remember_type(const Type*); - - // Record that we are going to see an expression. This returns true - // if the expression has already been seen in this traversal. This - // is only needed for cases where multiple expressions can point to - // a single one. - bool - remember_expression(const Expression*); - - // These functions return one of the TRAVERSE codes defined above. - - // If traverse_variables is set in the mask, this is called for - // every variable in the tree. - virtual int - variable(Named_object*); - - // If traverse_constants is set in the mask, this is called for - // every named constant in the tree. The bool parameter is true for - // a global constant. - virtual int - constant(Named_object*, bool); - - // If traverse_functions is set in the mask, this is called for - // every function in the tree. - virtual int - function(Named_object*); - - // If traverse_blocks is set in the mask, this is called for every - // block in the tree. - virtual int - block(Block*); - - // If traverse_statements is set in the mask, this is called for - // every statement in the tree. - virtual int - statement(Block*, size_t* index, Statement*); - - // If traverse_expressions is set in the mask, this is called for - // every expression in the tree. - virtual int - expression(Expression**); - - // If traverse_types is set in the mask, this is called for every - // type in the tree. - virtual int - type(Type*); - - private: - typedef Unordered_set_hash(const Type*, Type_hash_identical, - Type_identical) Types_seen; - - typedef Unordered_set(const Expression*) Expressions_seen; - - // Bitmask of what sort of objects to traverse. - unsigned int traverse_mask_; - // Types which have been seen in this traversal. - Types_seen* types_seen_; - // Expressions which have been seen in this traversal. - Expressions_seen* expressions_seen_; -}; - -// When translating the gogo IR into trees, this is the context we -// pass down the blocks and statements. - -class Translate_context -{ - public: - Translate_context(Gogo* gogo, Named_object* function, Block* block, - tree block_tree) - : gogo_(gogo), function_(function), block_(block), block_tree_(block_tree), - is_const_(false) - { } - - // Accessors. - - Gogo* - gogo() - { return this->gogo_; } - - Named_object* - function() - { return this->function_; } - - Block* - block() - { return this->block_; } - - tree - block_tree() - { return this->block_tree_; } - - bool - is_const() - { return this->is_const_; } - - // Make a constant context. - void - set_is_const() - { this->is_const_ = true; } - - private: - // The IR for the entire compilation unit. - Gogo* gogo_; - // The function we are currently translating. - Named_object* function_; - // The block we are currently translating. - Block *block_; - // The BLOCK node for the current block. - tree block_tree_; - // Whether this is being evaluated in a constant context. This is - // used for type descriptor initializers. - bool is_const_; -}; - -// Runtime error codes. These must match the values in -// libgo/runtime/go-runtime-error.c. - -// Slice index out of bounds: negative or larger than the length of -// the slice. -static const int RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS = 0; - -// Array index out of bounds. -static const int RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS = 1; - -// String index out of bounds. -static const int RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS = 2; - -// Slice slice out of bounds: negative or larger than the length of -// the slice or high bound less than low bound. -static const int RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS = 3; - -// Array slice out of bounds. -static const int RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS = 4; - -// String slice out of bounds. -static const int RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS = 5; - -// Dereference of nil pointer. This is used when there is a -// dereference of a pointer to a very large struct or array, to ensure -// that a gigantic array is not used a proxy to access random memory -// locations. -static const int RUNTIME_ERROR_NIL_DEREFERENCE = 6; - -// Slice length or capacity out of bounds in make: negative or -// overflow or length greater than capacity. -static const int RUNTIME_ERROR_MAKE_SLICE_OUT_OF_BOUNDS = 7; - -// Map capacity out of bounds in make: negative or overflow. -static const int RUNTIME_ERROR_MAKE_MAP_OUT_OF_BOUNDS = 8; - -// Channel capacity out of bounds in make: negative or overflow. -static const int RUNTIME_ERROR_MAKE_CHAN_OUT_OF_BOUNDS = 9; - -// This is used by some of the langhooks. -extern Gogo* go_get_gogo(); - -// Whether we have seen any errors. FIXME: Replace with a backend -// interface. -extern bool saw_errors(); - -#endif // !defined(GO_GOGO_H) diff --git a/gcc/go/gofrontend/gogo.h.merge-right.r172891 b/gcc/go/gofrontend/gogo.h.merge-right.r172891 deleted file mode 100644 index 788c80a454d..00000000000 --- a/gcc/go/gofrontend/gogo.h.merge-right.r172891 +++ /dev/null @@ -1,2612 +0,0 @@ -// gogo.h -- Go frontend parsed representation. -*- C++ -*- - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#ifndef GO_GOGO_H -#define GO_GOGO_H - -class Traverse; -class Type; -class Type_hash_identical; -class Type_equal; -class Type_identical; -class Typed_identifier; -class Typed_identifier_list; -class Function_type; -class Expression; -class Statement; -class Temporary_statement; -class Block; -class Function; -class Bindings; -class Package; -class Variable; -class Pointer_type; -class Struct_type; -class Struct_field; -class Struct_field_list; -class Array_type; -class Map_type; -class Channel_type; -class Interface_type; -class Named_type; -class Forward_declaration_type; -class Method; -class Methods; -class Named_object; -class Label; -class Translate_context; -class Backend; -class Export; -class Import; -class Bexpression; -class Bstatement; -class Bblock; -class Bvariable; -class Blabel; - -// This file declares the basic classes used to hold the internal -// representation of Go which is built by the parser. - -// An initialization function for an imported package. This is a -// magic function which initializes variables and runs the "init" -// function. - -class Import_init -{ - public: - Import_init(const std::string& package_name, const std::string& init_name, - int priority) - : package_name_(package_name), init_name_(init_name), priority_(priority) - { } - - // The name of the package being imported. - const std::string& - package_name() const - { return this->package_name_; } - - // The name of the package's init function. - const std::string& - init_name() const - { return this->init_name_; } - - // The priority of the initialization function. Functions with a - // lower priority number must be run first. - int - priority() const - { return this->priority_; } - - private: - // The name of the package being imported. - std::string package_name_; - // The name of the package's init function. - std::string init_name_; - // The priority. - int priority_; -}; - -// For sorting purposes. - -inline bool -operator<(const Import_init& i1, const Import_init& i2) -{ - if (i1.priority() < i2.priority()) - return true; - if (i1.priority() > i2.priority()) - return false; - if (i1.package_name() != i2.package_name()) - return i1.package_name() < i2.package_name(); - return i1.init_name() < i2.init_name(); -} - -// The holder for the internal representation of the entire -// compilation unit. - -class Gogo -{ - public: - // Create the IR, passing in the sizes of the types "int" and - // "uintptr" in bits. - Gogo(Backend* backend, int int_type_size, int pointer_size); - - // Get the backend generator. - Backend* - backend() - { return this->backend_; } - - // Get the package name. - const std::string& - package_name() const; - - // Set the package name. - void - set_package_name(const std::string&, source_location); - - // Return whether this is the "main" package. - bool - is_main_package() const; - - // If necessary, adjust the name to use for a hidden symbol. We add - // a prefix of the package name, so that hidden symbols in different - // packages do not collide. - std::string - pack_hidden_name(const std::string& name, bool is_exported) const - { - return (is_exported - ? name - : ('.' + this->unique_prefix() - + '.' + this->package_name() - + '.' + name)); - } - - // Unpack a name which may have been hidden. Returns the - // user-visible name of the object. - static std::string - unpack_hidden_name(const std::string& name) - { return name[0] != '.' ? name : name.substr(name.rfind('.') + 1); } - - // Return whether a possibly packed name is hidden. - static bool - is_hidden_name(const std::string& name) - { return name[0] == '.'; } - - // Return the package prefix of a hidden name. - static std::string - hidden_name_prefix(const std::string& name) - { - go_assert(Gogo::is_hidden_name(name)); - return name.substr(1, name.rfind('.') - 1); - } - - // Given a name which may or may not have been hidden, return the - // name to use in an error message. - static std::string - message_name(const std::string& name); - - // Return whether a name is the blank identifier _. - static bool - is_sink_name(const std::string& name) - { - return (name[0] == '.' - && name[name.length() - 1] == '_' - && name[name.length() - 2] == '.'); - } - - // Return the unique prefix to use for all exported symbols. - const std::string& - unique_prefix() const; - - // Set the unique prefix. - void - set_unique_prefix(const std::string&); - - // Return the priority to use for the package we are compiling. - // This is two more than the largest priority of any package we - // import. - int - package_priority() const; - - // Import a package. FILENAME is the file name argument, LOCAL_NAME - // is the local name to give to the package. If LOCAL_NAME is empty - // the declarations are added to the global scope. - void - import_package(const std::string& filename, const std::string& local_name, - bool is_local_name_exported, source_location); - - // Whether we are the global binding level. - bool - in_global_scope() const; - - // Look up a name in the current binding contours. - Named_object* - lookup(const std::string&, Named_object** pfunction) const; - - // Look up a name in the current block. - Named_object* - lookup_in_block(const std::string&) const; - - // Look up a name in the global namespace--the universal scope. - Named_object* - lookup_global(const char*) const; - - // Add a new imported package. REAL_NAME is the real name of the - // package. ALIAS is the alias of the package; this may be the same - // as REAL_NAME. This sets *PADD_TO_GLOBALS if symbols added to - // this package should be added to the global namespace; this is - // true if the alias is ".". LOCATION is the location of the import - // statement. This returns the new package, or NULL on error. - Package* - add_imported_package(const std::string& real_name, const std::string& alias, - bool is_alias_exported, - const std::string& unique_prefix, - source_location location, - bool* padd_to_globals); - - // Register a package. This package may or may not be imported. - // This returns the Package structure for the package, creating if - // it necessary. - Package* - register_package(const std::string& name, const std::string& unique_prefix, - source_location); - - // Start compiling a function. ADD_METHOD_TO_TYPE is true if a - // method function should be added to the type of its receiver. - Named_object* - start_function(const std::string& name, Function_type* type, - bool add_method_to_type, source_location); - - // Finish compiling a function. - void - finish_function(source_location); - - // Return the current function. - Named_object* - current_function() const; - - // Start a new block. This is not initially associated with a - // function. - void - start_block(source_location); - - // Finish the current block and return it. - Block* - finish_block(source_location); - - // Declare an unknown name. This is used while parsing. The name - // must be resolved by the end of the parse. Unknown names are - // always added at the package level. - Named_object* - add_unknown_name(const std::string& name, source_location); - - // Declare a function. - Named_object* - declare_function(const std::string&, Function_type*, source_location); - - // Add a label. - Label* - add_label_definition(const std::string&, source_location); - - // Add a label reference. - Label* - add_label_reference(const std::string&); - - // Add a statement to the current block. - void - add_statement(Statement*); - - // Add a block to the current block. - void - add_block(Block*, source_location); - - // Add a constant. - Named_object* - add_constant(const Typed_identifier&, Expression*, int iota_value); - - // Add a type. - void - add_type(const std::string&, Type*, source_location); - - // Add a named type. This is used for builtin types, and to add an - // imported type to the global scope. - void - add_named_type(Named_type*); - - // Declare a type. - Named_object* - declare_type(const std::string&, source_location); - - // Declare a type at the package level. This is used when the - // parser sees an unknown name where a type name is required. - Named_object* - declare_package_type(const std::string&, source_location); - - // Define a type which was already declared. - void - define_type(Named_object*, Named_type*); - - // Add a variable. - Named_object* - add_variable(const std::string&, Variable*); - - // Add a sink--a reference to the blank identifier _. - Named_object* - add_sink(); - - // Add a named object to the current namespace. This is used for - // import . "package". - void - add_named_object(Named_object*); - - // Return a name to use for a thunk function. A thunk function is - // one we create during the compilation, for a go statement or a - // defer statement or a method expression. - static std::string - thunk_name(); - - // Return whether an object is a thunk. - static bool - is_thunk(const Named_object*); - - // Note that we've seen an interface type. This is used to build - // all required interface method tables. - void - record_interface_type(Interface_type*); - - // Note that we need an initialization function. - void - set_need_init_fn() - { this->need_init_fn_ = true; } - - // Clear out all names in file scope. This is called when we start - // parsing a new file. - void - clear_file_scope(); - - // Traverse the tree. See the Traverse class. - void - traverse(Traverse*); - - // Define the predeclared global names. - void - define_global_names(); - - // Verify and complete all types. - void - verify_types(); - - // Lower the parse tree. - void - lower_parse_tree(); - - // Lower all the statements in a block. - void - lower_block(Named_object* function, Block*); - - // Lower an expression. - void - lower_expression(Named_object* function, Expression**); - - // Lower a constant. - void - lower_constant(Named_object*); - - // Finalize the method lists and build stub methods for named types. - void - finalize_methods(); - - // Work out the types to use for unspecified variables and - // constants. - void - determine_types(); - - // Type check the program. - void - check_types(); - - // Check the types in a single block. This is used for complicated - // go statements. - void - check_types_in_block(Block*); - - // Check for return statements. - void - check_return_statements(); - - // Do all exports. - void - do_exports(); - - // Add an import control function for an imported package to the - // list. - void - add_import_init_fn(const std::string& package_name, - const std::string& init_name, int prio); - - // Turn short-cut operators (&&, ||) into explicit if statements. - void - remove_shortcuts(); - - // Use temporary variables to force order of evaluation. - void - order_evaluations(); - - // Build thunks for functions which call recover. - void - build_recover_thunks(); - - // Simplify statements which might use thunks: go and defer - // statements. - void - simplify_thunk_statements(); - - // Convert named types to the backend representation. - void - convert_named_types(); - - // Convert named types in a list of bindings. - void - convert_named_types_in_bindings(Bindings*); - - // True if named types have been converted to the backend - // representation. - bool - named_types_are_converted() const - { return this->named_types_are_converted_; } - - // Write out the global values. - void - write_globals(); - - // Build a call to a builtin function. PDECL should point to a NULL - // initialized static pointer which will hold the fndecl. NAME is - // the name of the function. NARGS is the number of arguments. - // RETTYPE is the return type. It is followed by NARGS pairs of - // type and argument (both trees). - static tree - call_builtin(tree* pdecl, source_location, const char* name, int nargs, - tree rettype, ...); - - // Build a call to the runtime error function. - static tree - runtime_error(int code, source_location); - - // Build a builtin struct with a list of fields. - static tree - builtin_struct(tree* ptype, const char* struct_name, tree struct_type, - int nfields, ...); - - // Mark a function declaration as a builtin library function. - static void - mark_fndecl_as_builtin_library(tree fndecl); - - // Build the type of the struct that holds a slice for the given - // element type. - tree - slice_type_tree(tree element_type_tree); - - // Given a tree for a slice type, return the tree for the element - // type. - static tree - slice_element_type_tree(tree slice_type_tree); - - // Build a constructor for a slice. SLICE_TYPE_TREE is the type of - // the slice. VALUES points to the values. COUNT is the size, - // CAPACITY is the capacity. If CAPACITY is NULL, it is set to - // COUNT. - static tree - slice_constructor(tree slice_type_tree, tree values, tree count, - tree capacity); - - // Build a constructor for an empty slice. SLICE_TYPE_TREE is the - // type of the slice. - static tree - empty_slice_constructor(tree slice_type_tree); - - // Build a map descriptor. - tree - map_descriptor(Map_type*); - - // Return a tree for the type of a map descriptor. This is struct - // __go_map_descriptor in libgo/runtime/map.h. This is the same for - // all map types. - tree - map_descriptor_type(); - - // Build a type descriptor for TYPE using INITIALIZER as the type - // descriptor. This builds a new decl stored in *PDECL. - void - build_type_descriptor_decl(const Type*, Expression* initializer, - tree* pdecl); - - // Build required interface method tables. - void - build_interface_method_tables(); - - // Build an interface method table for a type: a list of function - // pointers, one for each interface method. This returns a decl. - tree - interface_method_table_for_type(const Interface_type*, Named_type*, - bool is_pointer); - - // Return a tree which allocate SIZE bytes to hold values of type - // TYPE. - tree - allocate_memory(Type *type, tree size, source_location); - - // Return a type to use for pointer to const char. - static tree - const_char_pointer_type_tree(); - - // Build a string constant with the right type. - static tree - string_constant_tree(const std::string&); - - // Build a Go string constant. This returns a pointer to the - // constant. - tree - go_string_constant_tree(const std::string&); - - // Receive a value from a channel. - static tree - receive_from_channel(tree type_tree, tree channel, bool for_select, - source_location); - - // Return a tree for receiving an integer on a channel. - static tree - receive_as_64bit_integer(tree type, tree channel, bool blocking, - bool for_select); - - - // Make a trampoline which calls FNADDR passing CLOSURE. - tree - make_trampoline(tree fnaddr, tree closure, source_location); - - private: - // During parsing, we keep a stack of functions. Each function on - // the stack is one that we are currently parsing. For each - // function, we keep track of the current stack of blocks. - struct Open_function - { - // The function. - Named_object* function; - // The stack of active blocks in the function. - std::vector blocks; - }; - - // The stack of functions. - typedef std::vector Open_functions; - - // Create trees for implicit builtin functions. - void - define_builtin_function_trees(); - - // Set up the built-in unsafe package. - void - import_unsafe(const std::string&, bool is_exported, source_location); - - // Add a new imported package. - Named_object* - add_package(const std::string& real_name, const std::string& alias, - const std::string& unique_prefix, source_location location); - - // Return the current binding contour. - Bindings* - current_bindings(); - - const Bindings* - current_bindings() const; - - // Return the current block. - Block* - current_block(); - - // Get the name of the magic initialization function. - const std::string& - get_init_fn_name(); - - // Get the decl for the magic initialization function. - tree - initialization_function_decl(); - - // Write the magic initialization function. - void - write_initialization_function(tree fndecl, tree init_stmt_list); - - // Initialize imported packages. - void - init_imports(tree*); - - // Register variables with the garbage collector. - void - register_gc_vars(const std::vector&, tree*); - - // Build a pointer to a Go string constant. This returns a pointer - // to the pointer. - tree - ptr_go_string_constant_tree(const std::string&); - - // Return the name to use for a type descriptor decl for an unnamed - // type. - std::string - unnamed_type_descriptor_decl_name(const Type* type); - - // Return the name to use for a type descriptor decl for a type - // named NO, defined in IN_FUNCTION. - std::string - type_descriptor_decl_name(const Named_object* no, - const Named_object* in_function); - - // Where a type descriptor should be defined. - enum Type_descriptor_location - { - // Defined in this file. - TYPE_DESCRIPTOR_DEFINED, - // Defined in some other file. - TYPE_DESCRIPTOR_UNDEFINED, - // Common definition which may occur in multiple files. - TYPE_DESCRIPTOR_COMMON - }; - - // Return where the decl for TYPE should be defined. - Type_descriptor_location - type_descriptor_location(const Type* type); - - // Return the type of a trampoline. - static tree - trampoline_type_tree(); - - // Type used to map import names to packages. - typedef std::map Imports; - - // Type used to map package names to packages. - typedef std::map Packages; - - // Type used to map special names in the sys package. - typedef std::map Sys_names; - - // Hash table mapping map types to map descriptor decls. - typedef Unordered_map_hash(const Map_type*, tree, Type_hash_identical, - Type_identical) Map_descriptors; - - // Map unnamed types to type descriptor decls. - typedef Unordered_map_hash(const Type*, tree, Type_hash_identical, - Type_identical) Type_descriptor_decls; - - // The backend generator. - Backend* backend_; - // The package we are compiling. - Package* package_; - // The list of currently open functions during parsing. - Open_functions functions_; - // The global binding contour. This includes the builtin functions - // and the package we are compiling. - Bindings* globals_; - // Mapping from import file names to packages. - Imports imports_; - // Whether the magic unsafe package was imported. - bool imported_unsafe_; - // Mapping from package names we have seen to packages. This does - // not include the package we are compiling. - Packages packages_; - // Mapping from map types to map descriptors. - Map_descriptors* map_descriptors_; - // Mapping from unnamed types to type descriptor decls. - Type_descriptor_decls* type_descriptor_decls_; - // The functions named "init", if there are any. - std::vector init_functions_; - // Whether we need a magic initialization function. - bool need_init_fn_; - // The name of the magic initialization function. - std::string init_fn_name_; - // A list of import control variables for packages that we import. - std::set imported_init_fns_; - // The unique prefix used for all global symbols. - std::string unique_prefix_; - // Whether an explicit unique prefix was set by -fgo-prefix. - bool unique_prefix_specified_; - // A list of interface types defined while parsing. - std::vector interface_types_; - // Whether named types have been converted. - bool named_types_are_converted_; -}; - -// A block of statements. - -class Block -{ - public: - Block(Block* enclosing, source_location); - - // Return the enclosing block. - const Block* - enclosing() const - { return this->enclosing_; } - - // Return the bindings of the block. - Bindings* - bindings() - { return this->bindings_; } - - const Bindings* - bindings() const - { return this->bindings_; } - - // Look at the block's statements. - const std::vector* - statements() const - { return &this->statements_; } - - // Return the start location. This is normally the location of the - // left curly brace which starts the block. - source_location - start_location() const - { return this->start_location_; } - - // Return the end location. This is normally the location of the - // right curly brace which ends the block. - source_location - end_location() const - { return this->end_location_; } - - // Add a statement to the block. - void - add_statement(Statement*); - - // Add a statement to the front of the block. - void - add_statement_at_front(Statement*); - - // Replace a statement in a block. - void - replace_statement(size_t index, Statement*); - - // Add a Statement before statement number INDEX. - void - insert_statement_before(size_t index, Statement*); - - // Add a Statement after statement number INDEX. - void - insert_statement_after(size_t index, Statement*); - - // Set the end location of the block. - void - set_end_location(source_location location) - { this->end_location_ = location; } - - // Traverse the tree. - int - traverse(Traverse*); - - // Set final types for unspecified variables and constants. - void - determine_types(); - - // Return true if execution of this block may fall through to the - // next block. - bool - may_fall_through() const; - - // Convert the block to the backend representation. - Bblock* - get_backend(Translate_context*); - - // Iterate over statements. - - typedef std::vector::iterator iterator; - - iterator - begin() - { return this->statements_.begin(); } - - iterator - end() - { return this->statements_.end(); } - - private: - // Enclosing block. - Block* enclosing_; - // Statements in the block. - std::vector statements_; - // Binding contour. - Bindings* bindings_; - // Location of start of block. - source_location start_location_; - // Location of end of block. - source_location end_location_; -}; - -// A function. - -class Function -{ - public: - Function(Function_type* type, Function*, Block*, source_location); - - // Return the function's type. - Function_type* - type() const - { return this->type_; } - - // Return the enclosing function if there is one. - Function* - enclosing() - { return this->enclosing_; } - - // Set the enclosing function. This is used when building thunks - // for functions which call recover. - void - set_enclosing(Function* enclosing) - { - go_assert(this->enclosing_ == NULL); - this->enclosing_ = enclosing; - } - - // The result variables. - typedef std::vector Results; - - // Create the result variables in the outer block. - void - create_result_variables(Gogo*); - - // Update the named result variables when cloning a function which - // calls recover. - void - update_result_variables(); - - // Return the result variables. - Results* - result_variables() - { return this->results_; } - - // Whether the result variables have names. - bool - results_are_named() const - { return this->results_are_named_; } - - // Add a new field to the closure variable. - void - add_closure_field(Named_object* var, source_location loc) - { this->closure_fields_.push_back(std::make_pair(var, loc)); } - - // Whether this function needs a closure. - bool - needs_closure() const - { return !this->closure_fields_.empty(); } - - // Return the closure variable, creating it if necessary. This is - // passed to the function as a static chain parameter. - Named_object* - closure_var(); - - // Set the closure variable. This is used when building thunks for - // functions which call recover. - void - set_closure_var(Named_object* v) - { - go_assert(this->closure_var_ == NULL); - this->closure_var_ = v; - } - - // Return the variable for a reference to field INDEX in the closure - // variable. - Named_object* - enclosing_var(unsigned int index) - { - go_assert(index < this->closure_fields_.size()); - return closure_fields_[index].first; - } - - // Set the type of the closure variable if there is one. - void - set_closure_type(); - - // Get the block of statements associated with the function. - Block* - block() const - { return this->block_; } - - // Get the location of the start of the function. - source_location - location() const - { return this->location_; } - - // Return whether this function is actually a method. - bool - is_method() const; - - // Add a label definition to the function. - Label* - add_label_definition(const std::string& label_name, source_location); - - // Add a label reference to a function. - Label* - add_label_reference(const std::string& label_name); - - // Warn about labels that are defined but not used. - void - check_labels() const; - - // Whether this function calls the predeclared recover function. - bool - calls_recover() const - { return this->calls_recover_; } - - // Record that this function calls the predeclared recover function. - // This is set during the lowering pass. - void - set_calls_recover() - { this->calls_recover_ = true; } - - // Whether this is a recover thunk function. - bool - is_recover_thunk() const - { return this->is_recover_thunk_; } - - // Record that this is a thunk built for a function which calls - // recover. - void - set_is_recover_thunk() - { this->is_recover_thunk_ = true; } - - // Whether this function already has a recover thunk. - bool - has_recover_thunk() const - { return this->has_recover_thunk_; } - - // Record that this function already has a recover thunk. - void - set_has_recover_thunk() - { this->has_recover_thunk_ = true; } - - // Swap with another function. Used only for the thunk which calls - // recover. - void - swap_for_recover(Function *); - - // Traverse the tree. - int - traverse(Traverse*); - - // Determine types in the function. - void - determine_types(); - - // Return the function's decl given an identifier. - tree - get_or_make_decl(Gogo*, Named_object*, tree id); - - // Return the function's decl after it has been built. - tree - get_decl() const - { - go_assert(this->fndecl_ != NULL); - return this->fndecl_; - } - - // Set the function decl to hold a tree of the function code. - void - build_tree(Gogo*, Named_object*); - - // Get the value to return when not explicitly specified. May also - // add statements to execute first to STMT_LIST. - tree - return_value(Gogo*, Named_object*, source_location, tree* stmt_list) const; - - // Get a tree for the variable holding the defer stack. - Expression* - defer_stack(source_location); - - // Export the function. - void - export_func(Export*, const std::string& name) const; - - // Export a function with a type. - static void - export_func_with_type(Export*, const std::string& name, - const Function_type*); - - // Import a function. - static void - import_func(Import*, std::string* pname, Typed_identifier** receiver, - Typed_identifier_list** pparameters, - Typed_identifier_list** presults, bool* is_varargs); - - private: - // Type for mapping from label names to Label objects. - typedef Unordered_map(std::string, Label*) Labels; - - tree - make_receiver_parm_decl(Gogo*, Named_object*, tree); - - tree - copy_parm_to_heap(Gogo*, Named_object*, tree); - - void - build_defer_wrapper(Gogo*, Named_object*, tree*, tree*); - - typedef std::vector > Closure_fields; - - // The function's type. - Function_type* type_; - // The enclosing function. This is NULL when there isn't one, which - // is the normal case. - Function* enclosing_; - // The result variables, if any. - Results* results_; - // If there is a closure, this is the list of variables which appear - // in the closure. This is created by the parser, and then resolved - // to a real type when we lower parse trees. - Closure_fields closure_fields_; - // The closure variable, passed as a parameter using the static - // chain parameter. Normally NULL. - Named_object* closure_var_; - // The outer block of statements in the function. - Block* block_; - // The source location of the start of the function. - source_location location_; - // Labels defined or referenced in the function. - Labels labels_; - // The function decl. - tree fndecl_; - // The defer stack variable. A pointer to this variable is used to - // distinguish the defer stack for one function from another. This - // is NULL unless we actually need a defer stack. - Temporary_statement* defer_stack_; - // True if the result variables are named. - bool results_are_named_; - // True if this function calls the predeclared recover function. - bool calls_recover_; - // True if this a thunk built for a function which calls recover. - bool is_recover_thunk_; - // True if this function already has a recover thunk. - bool has_recover_thunk_; -}; - -// A function declaration. - -class Function_declaration -{ - public: - Function_declaration(Function_type* fntype, source_location location) - : fntype_(fntype), location_(location), asm_name_(), fndecl_(NULL) - { } - - Function_type* - type() const - { return this->fntype_; } - - source_location - location() const - { return this->location_; } - - const std::string& - asm_name() const - { return this->asm_name_; } - - // Set the assembler name. - void - set_asm_name(const std::string& asm_name) - { this->asm_name_ = asm_name; } - - // Return a decl for the function given an identifier. - tree - get_or_make_decl(Gogo*, Named_object*, tree id); - - // Export a function declaration. - void - export_func(Export* exp, const std::string& name) const - { Function::export_func_with_type(exp, name, this->fntype_); } - - private: - // The type of the function. - Function_type* fntype_; - // The location of the declaration. - source_location location_; - // The assembler name: this is the name to use in references to the - // function. This is normally empty. - std::string asm_name_; - // The function decl if needed. - tree fndecl_; -}; - -// A variable. - -class Variable -{ - public: - Variable(Type*, Expression*, bool is_global, bool is_parameter, - bool is_receiver, source_location); - - // Get the type of the variable. - Type* - type(); - - Type* - type() const; - - // Return whether the type is defined yet. - bool - has_type() const - { return this->type_ != NULL; } - - // Get the initial value. - Expression* - init() const - { return this->init_; } - - // Return whether there are any preinit statements. - bool - has_pre_init() const - { return this->preinit_ != NULL; } - - // Return the preinit statements if any. - Block* - preinit() const - { return this->preinit_; } - - // Return whether this is a global variable. - bool - is_global() const - { return this->is_global_; } - - // Return whether this is a function parameter. - bool - is_parameter() const - { return this->is_parameter_; } - - // Return whether this is the receiver parameter of a method. - bool - is_receiver() const - { return this->is_receiver_; } - - // Change this parameter to be a receiver. This is used when - // creating the thunks created for functions which call recover. - void - set_is_receiver() - { - go_assert(this->is_parameter_); - this->is_receiver_ = true; - } - - // Change this parameter to not be a receiver. This is used when - // creating the thunks created for functions which call recover. - void - set_is_not_receiver() - { - go_assert(this->is_parameter_); - this->is_receiver_ = false; - } - - // Return whether this is the varargs parameter of a function. - bool - is_varargs_parameter() const - { return this->is_varargs_parameter_; } - - // Whether this variable's address is taken. - bool - is_address_taken() const - { return this->is_address_taken_; } - - // Whether this variable should live in the heap. - bool - is_in_heap() const - { return this->is_address_taken_ && !this->is_global_; } - - // Get the source location of the variable's declaration. - source_location - location() const - { return this->location_; } - - // Record that this is the varargs parameter of a function. - void - set_is_varargs_parameter() - { - go_assert(this->is_parameter_); - this->is_varargs_parameter_ = true; - } - - // Clear the initial value; used for error handling. - void - clear_init() - { this->init_ = NULL; } - - // Set the initial value; used for converting shortcuts. - void - set_init(Expression* init) - { this->init_ = init; } - - // Get the preinit block, a block of statements to be run before the - // initialization expression. - Block* - preinit_block(Gogo*); - - // Add a statement to be run before the initialization expression. - // This is only used for global variables. - void - add_preinit_statement(Gogo*, Statement*); - - // Lower the initialization expression after parsing is complete. - void - lower_init_expression(Gogo*, Named_object*); - - // A special case: the init value is used only to determine the - // type. This is used if the variable is defined using := with the - // comma-ok form of a map index or a receive expression. The init - // value is actually the map index expression or receive expression. - // We use this because we may not know the right type at parse time. - void - set_type_from_init_tuple() - { this->type_from_init_tuple_ = true; } - - // Another special case: the init value is used only to determine - // the type. This is used if the variable is defined using := with - // a range clause. The init value is the range expression. The - // type of the variable is the index type of the range expression - // (i.e., the first value returned by a range). - void - set_type_from_range_index() - { this->type_from_range_index_ = true; } - - // Another special case: like set_type_from_range_index, but the - // type is the value type of the range expression (i.e., the second - // value returned by a range). - void - set_type_from_range_value() - { this->type_from_range_value_ = true; } - - // Another special case: the init value is used only to determine - // the type. This is used if the variable is defined using := with - // a case in a select statement. The init value is the channel. - // The type of the variable is the channel's element type. - void - set_type_from_chan_element() - { this->type_from_chan_element_ = true; } - - // After we lower the select statement, we once again set the type - // from the initialization expression. - void - clear_type_from_chan_element() - { - go_assert(this->type_from_chan_element_); - this->type_from_chan_element_ = false; - } - - // Note that this variable was created for a type switch clause. - void - set_is_type_switch_var() - { this->is_type_switch_var_ = true; } - - // Traverse the initializer expression. - int - traverse_expression(Traverse*); - - // Determine the type of the variable if necessary. - void - determine_type(); - - // Note that something takes the address of this variable. - void - set_address_taken() - { this->is_address_taken_ = true; } - - // Get the backend representation of the variable. - Bvariable* - get_backend_variable(Gogo*, Named_object*, const Package*, - const std::string&); - - // Get the initial value of the variable as a tree. This may only - // be called if has_pre_init() returns false. - tree - get_init_tree(Gogo*, Named_object* function); - - // Return a series of statements which sets the value of the - // variable in DECL. This should only be called is has_pre_init() - // returns true. DECL may be NULL for a sink variable. - tree - get_init_block(Gogo*, Named_object* function, tree decl); - - // Export the variable. - void - export_var(Export*, const std::string& name) const; - - // Import a variable. - static void - import_var(Import*, std::string* pname, Type** ptype); - - private: - // The type of a tuple. - Type* - type_from_tuple(Expression*, bool) const; - - // The type of a range. - Type* - type_from_range(Expression*, bool, bool) const; - - // The element type of a channel. - Type* - type_from_chan_element(Expression*, bool) const; - - // The variable's type. This may be NULL if the type is set from - // the expression. - Type* type_; - // The initial value. This may be NULL if the variable should be - // initialized to the default value for the type. - Expression* init_; - // Statements to run before the init statement. - Block* preinit_; - // Location of variable definition. - source_location location_; - // Backend representation. - Bvariable* backend_; - // Whether this is a global variable. - bool is_global_ : 1; - // Whether this is a function parameter. - bool is_parameter_ : 1; - // Whether this is the receiver parameter of a method. - bool is_receiver_ : 1; - // Whether this is the varargs parameter of a function. - bool is_varargs_parameter_ : 1; - // Whether something takes the address of this variable. - bool is_address_taken_ : 1; - // True if we have seen this variable in a traversal. - bool seen_ : 1; - // True if we have lowered the initialization expression. - bool init_is_lowered_ : 1; - // True if init is a tuple used to set the type. - bool type_from_init_tuple_ : 1; - // True if init is a range clause and the type is the index type. - bool type_from_range_index_ : 1; - // True if init is a range clause and the type is the value type. - bool type_from_range_value_ : 1; - // True if init is a channel and the type is the channel's element type. - bool type_from_chan_element_ : 1; - // True if this is a variable created for a type switch case. - bool is_type_switch_var_ : 1; - // True if we have determined types. - bool determined_type_ : 1; -}; - -// A variable which is really the name for a function return value, or -// part of one. - -class Result_variable -{ - public: - Result_variable(Type* type, Function* function, int index, - source_location location) - : type_(type), function_(function), index_(index), location_(location), - backend_(NULL), is_address_taken_(false) - { } - - // Get the type of the result variable. - Type* - type() const - { return this->type_; } - - // Get the function that this is associated with. - Function* - function() const - { return this->function_; } - - // Index in the list of function results. - int - index() const - { return this->index_; } - - // The location of the variable definition. - source_location - location() const - { return this->location_; } - - // Whether this variable's address is taken. - bool - is_address_taken() const - { return this->is_address_taken_; } - - // Note that something takes the address of this variable. - void - set_address_taken() - { this->is_address_taken_ = true; } - - // Whether this variable should live in the heap. - bool - is_in_heap() const - { return this->is_address_taken_; } - - // Set the function. This is used when cloning functions which call - // recover. - void - set_function(Function* function) - { this->function_ = function; } - - // Get the backend representation of the variable. - Bvariable* - get_backend_variable(Gogo*, Named_object*, const std::string&); - - private: - // Type of result variable. - Type* type_; - // Function with which this is associated. - Function* function_; - // Index in list of results. - int index_; - // Where the result variable is defined. - source_location location_; - // Backend representation. - Bvariable* backend_; - // Whether something takes the address of this variable. - bool is_address_taken_; -}; - -// The value we keep for a named constant. This lets us hold a type -// and an expression. - -class Named_constant -{ - public: - Named_constant(Type* type, Expression* expr, int iota_value, - source_location location) - : type_(type), expr_(expr), iota_value_(iota_value), location_(location), - lowering_(false) - { } - - Type* - type() const - { return this->type_; } - - Expression* - expr() const - { return this->expr_; } - - int - iota_value() const - { return this->iota_value_; } - - source_location - location() const - { return this->location_; } - - // Whether we are lowering. - bool - lowering() const - { return this->lowering_; } - - // Set that we are lowering. - void - set_lowering() - { this->lowering_ = true; } - - // We are no longer lowering. - void - clear_lowering() - { this->lowering_ = false; } - - // Traverse the expression. - int - traverse_expression(Traverse*); - - // Determine the type of the constant if necessary. - void - determine_type(); - - // Indicate that we found and reported an error for this constant. - void - set_error(); - - // Export the constant. - void - export_const(Export*, const std::string& name) const; - - // Import a constant. - static void - import_const(Import*, std::string*, Type**, Expression**); - - private: - // The type of the constant. - Type* type_; - // The expression for the constant. - Expression* expr_; - // If the predeclared constant iota is used in EXPR_, this is the - // value it will have. We do this because at parse time we don't - // know whether the name "iota" will refer to the predeclared - // constant or to something else. We put in the right value in when - // we lower. - int iota_value_; - // The location of the definition. - source_location location_; - // Whether we are currently lowering this constant. - bool lowering_; -}; - -// A type declaration. - -class Type_declaration -{ - public: - Type_declaration(source_location location) - : location_(location), in_function_(NULL), methods_(), - issued_warning_(false) - { } - - // Return the location. - source_location - location() const - { return this->location_; } - - // Return the function in which this type is declared. This will - // return NULL for a type declared in global scope. - Named_object* - in_function() - { return this->in_function_; } - - // Set the function in which this type is declared. - void - set_in_function(Named_object* f) - { this->in_function_ = f; } - - // Add a method to this type. This is used when methods are defined - // before the type. - Named_object* - add_method(const std::string& name, Function* function); - - // Add a method declaration to this type. - Named_object* - add_method_declaration(const std::string& name, Function_type* type, - source_location location); - - // Return whether any methods were defined. - bool - has_methods() const; - - // Define methods when the real type is known. - void - define_methods(Named_type*); - - // This is called if we are trying to use this type. It returns - // true if we should issue a warning. - bool - using_type(); - - private: - typedef std::vector Methods; - - // The location of the type declaration. - source_location location_; - // If this type is declared in a function, a pointer back to the - // function in which it is defined. - Named_object* in_function_; - // Methods defined before the type is defined. - Methods methods_; - // True if we have issued a warning about a use of this type - // declaration when it is undefined. - bool issued_warning_; -}; - -// An unknown object. These are created by the parser for forward -// references to names which have not been seen before. In a correct -// program, these will always point to a real definition by the end of -// the parse. Because they point to another Named_object, these may -// only be referenced by Unknown_expression objects. - -class Unknown_name -{ - public: - Unknown_name(source_location location) - : location_(location), real_named_object_(NULL) - { } - - // Return the location where this name was first seen. - source_location - location() const - { return this->location_; } - - // Return the real named object that this points to, or NULL if it - // was never resolved. - Named_object* - real_named_object() const - { return this->real_named_object_; } - - // Set the real named object that this points to. - void - set_real_named_object(Named_object* no); - - private: - // The location where this name was first seen. - source_location location_; - // The real named object when it is known. - Named_object* - real_named_object_; -}; - -// A named object named. This is the result of a declaration. We -// don't use a superclass because they all have to be handled -// differently. - -class Named_object -{ - public: - enum Classification - { - // An uninitialized Named_object. We should never see this. - NAMED_OBJECT_UNINITIALIZED, - // An unknown name. This is used for forward references. In a - // correct program, these will all be resolved by the end of the - // parse. - NAMED_OBJECT_UNKNOWN, - // A const. - NAMED_OBJECT_CONST, - // A type. - NAMED_OBJECT_TYPE, - // A forward type declaration. - NAMED_OBJECT_TYPE_DECLARATION, - // A var. - NAMED_OBJECT_VAR, - // A result variable in a function. - NAMED_OBJECT_RESULT_VAR, - // The blank identifier--the special variable named _. - NAMED_OBJECT_SINK, - // A func. - NAMED_OBJECT_FUNC, - // A forward func declaration. - NAMED_OBJECT_FUNC_DECLARATION, - // A package. - NAMED_OBJECT_PACKAGE - }; - - // Return the classification. - Classification - classification() const - { return this->classification_; } - - // Classifiers. - - bool - is_unknown() const - { return this->classification_ == NAMED_OBJECT_UNKNOWN; } - - bool - is_const() const - { return this->classification_ == NAMED_OBJECT_CONST; } - - bool - is_type() const - { return this->classification_ == NAMED_OBJECT_TYPE; } - - bool - is_type_declaration() const - { return this->classification_ == NAMED_OBJECT_TYPE_DECLARATION; } - - bool - is_variable() const - { return this->classification_ == NAMED_OBJECT_VAR; } - - bool - is_result_variable() const - { return this->classification_ == NAMED_OBJECT_RESULT_VAR; } - - bool - is_sink() const - { return this->classification_ == NAMED_OBJECT_SINK; } - - bool - is_function() const - { return this->classification_ == NAMED_OBJECT_FUNC; } - - bool - is_function_declaration() const - { return this->classification_ == NAMED_OBJECT_FUNC_DECLARATION; } - - bool - is_package() const - { return this->classification_ == NAMED_OBJECT_PACKAGE; } - - // Creators. - - static Named_object* - make_unknown_name(const std::string& name, source_location); - - static Named_object* - make_constant(const Typed_identifier&, const Package*, Expression*, - int iota_value); - - static Named_object* - make_type(const std::string&, const Package*, Type*, source_location); - - static Named_object* - make_type_declaration(const std::string&, const Package*, source_location); - - static Named_object* - make_variable(const std::string&, const Package*, Variable*); - - static Named_object* - make_result_variable(const std::string&, Result_variable*); - - static Named_object* - make_sink(); - - static Named_object* - make_function(const std::string&, const Package*, Function*); - - static Named_object* - make_function_declaration(const std::string&, const Package*, Function_type*, - source_location); - - static Named_object* - make_package(const std::string& alias, Package* package); - - // Getters. - - Unknown_name* - unknown_value() - { - go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN); - return this->u_.unknown_value; - } - - const Unknown_name* - unknown_value() const - { - go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN); - return this->u_.unknown_value; - } - - Named_constant* - const_value() - { - go_assert(this->classification_ == NAMED_OBJECT_CONST); - return this->u_.const_value; - } - - const Named_constant* - const_value() const - { - go_assert(this->classification_ == NAMED_OBJECT_CONST); - return this->u_.const_value; - } - - Named_type* - type_value() - { - go_assert(this->classification_ == NAMED_OBJECT_TYPE); - return this->u_.type_value; - } - - const Named_type* - type_value() const - { - go_assert(this->classification_ == NAMED_OBJECT_TYPE); - return this->u_.type_value; - } - - Type_declaration* - type_declaration_value() - { - go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION); - return this->u_.type_declaration; - } - - const Type_declaration* - type_declaration_value() const - { - go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION); - return this->u_.type_declaration; - } - - Variable* - var_value() - { - go_assert(this->classification_ == NAMED_OBJECT_VAR); - return this->u_.var_value; - } - - const Variable* - var_value() const - { - go_assert(this->classification_ == NAMED_OBJECT_VAR); - return this->u_.var_value; - } - - Result_variable* - result_var_value() - { - go_assert(this->classification_ == NAMED_OBJECT_RESULT_VAR); - return this->u_.result_var_value; - } - - const Result_variable* - result_var_value() const - { - go_assert(this->classification_ == NAMED_OBJECT_RESULT_VAR); - return this->u_.result_var_value; - } - - Function* - func_value() - { - go_assert(this->classification_ == NAMED_OBJECT_FUNC); - return this->u_.func_value; - } - - const Function* - func_value() const - { - go_assert(this->classification_ == NAMED_OBJECT_FUNC); - return this->u_.func_value; - } - - Function_declaration* - func_declaration_value() - { - go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION); - return this->u_.func_declaration_value; - } - - const Function_declaration* - func_declaration_value() const - { - go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION); - return this->u_.func_declaration_value; - } - - Package* - package_value() - { - go_assert(this->classification_ == NAMED_OBJECT_PACKAGE); - return this->u_.package_value; - } - - const Package* - package_value() const - { - go_assert(this->classification_ == NAMED_OBJECT_PACKAGE); - return this->u_.package_value; - } - - const std::string& - name() const - { return this->name_; } - - // Return the name to use in an error message. The difference is - // that if this Named_object is defined in a different package, this - // will return PACKAGE.NAME. - std::string - message_name() const; - - const Package* - package() const - { return this->package_; } - - // Resolve an unknown value if possible. This returns the same - // Named_object or a new one. - Named_object* - resolve() - { - Named_object* ret = this; - if (this->is_unknown()) - { - Named_object* r = this->unknown_value()->real_named_object(); - if (r != NULL) - ret = r; - } - return ret; - } - - const Named_object* - resolve() const - { - const Named_object* ret = this; - if (this->is_unknown()) - { - const Named_object* r = this->unknown_value()->real_named_object(); - if (r != NULL) - ret = r; - } - return ret; - } - - // The location where this object was defined or referenced. - source_location - location() const; - - // Convert a variable to the backend representation. - Bvariable* - get_backend_variable(Gogo*, Named_object* function); - - // Return a tree for the external identifier for this object. - tree - get_id(Gogo*); - - // Return a tree representing this object. - tree - get_tree(Gogo*, Named_object* function); - - // Define a type declaration. - void - set_type_value(Named_type*); - - // Define a function declaration. - void - set_function_value(Function*); - - // Declare an unknown name as a type declaration. - void - declare_as_type(); - - // Export this object. - void - export_named_object(Export*) const; - - private: - Named_object(const std::string&, const Package*, Classification); - - // The name of the object. - std::string name_; - // The package that this object is in. This is NULL if it is in the - // file we are compiling. - const Package* package_; - // The type of object this is. - Classification classification_; - // The real data. - union - { - Unknown_name* unknown_value; - Named_constant* const_value; - Named_type* type_value; - Type_declaration* type_declaration; - Variable* var_value; - Result_variable* result_var_value; - Function* func_value; - Function_declaration* func_declaration_value; - Package* package_value; - } u_; - // The DECL tree for this object if we have already converted it. - tree tree_; -}; - -// A binding contour. This binds names to objects. - -class Bindings -{ - public: - // Type for mapping from names to objects. - typedef Unordered_map(std::string, Named_object*) Contour; - - Bindings(Bindings* enclosing); - - // Add an unknown name. - Named_object* - add_unknown_name(const std::string& name, source_location location) - { - return this->add_named_object(Named_object::make_unknown_name(name, - location)); - } - - // Add a constant. - Named_object* - add_constant(const Typed_identifier& tid, const Package* package, - Expression* expr, int iota_value) - { - return this->add_named_object(Named_object::make_constant(tid, package, - expr, - iota_value)); - } - - // Add a type. - Named_object* - add_type(const std::string& name, const Package* package, Type* type, - source_location location) - { - return this->add_named_object(Named_object::make_type(name, package, type, - location)); - } - - // Add a named type. This is used for builtin types, and to add an - // imported type to the global scope. - Named_object* - add_named_type(Named_type* named_type); - - // Add a type declaration. - Named_object* - add_type_declaration(const std::string& name, const Package* package, - source_location location) - { - Named_object* no = Named_object::make_type_declaration(name, package, - location); - return this->add_named_object(no); - } - - // Add a variable. - Named_object* - add_variable(const std::string& name, const Package* package, - Variable* variable) - { - return this->add_named_object(Named_object::make_variable(name, package, - variable)); - } - - // Add a result variable. - Named_object* - add_result_variable(const std::string& name, Result_variable* result) - { - return this->add_named_object(Named_object::make_result_variable(name, - result)); - } - - // Add a function. - Named_object* - add_function(const std::string& name, const Package*, Function* function); - - // Add a function declaration. - Named_object* - add_function_declaration(const std::string& name, const Package* package, - Function_type* type, source_location location); - - // Add a package. The location is the location of the import - // statement. - Named_object* - add_package(const std::string& alias, Package* package) - { - Named_object* no = Named_object::make_package(alias, package); - return this->add_named_object(no); - } - - // Define a type which was already declared. - void - define_type(Named_object*, Named_type*); - - // Add a method to the list of objects. This is not added to the - // lookup table. - void - add_method(Named_object*); - - // Add a named object to this binding. - Named_object* - add_named_object(Named_object* no) - { return this->add_named_object_to_contour(&this->bindings_, no); } - - // Clear all names in file scope from the bindings. - void - clear_file_scope(); - - // Look up a name in this binding contour and in any enclosing - // binding contours. This returns NULL if the name is not found. - Named_object* - lookup(const std::string&) const; - - // Look up a name in this binding contour without looking in any - // enclosing binding contours. Returns NULL if the name is not found. - Named_object* - lookup_local(const std::string&) const; - - // Remove a name. - void - remove_binding(Named_object*); - - // Traverse the tree. See the Traverse class. - int - traverse(Traverse*, bool is_global); - - // Iterate over definitions. This does not include things which - // were only declared. - - typedef std::vector::const_iterator - const_definitions_iterator; - - const_definitions_iterator - begin_definitions() const - { return this->named_objects_.begin(); } - - const_definitions_iterator - end_definitions() const - { return this->named_objects_.end(); } - - // Return the number of definitions. - size_t - size_definitions() const - { return this->named_objects_.size(); } - - // Return whether there are no definitions. - bool - empty_definitions() const - { return this->named_objects_.empty(); } - - // Iterate over declarations. This is everything that has been - // declared, which includes everything which has been defined. - - typedef Contour::const_iterator const_declarations_iterator; - - const_declarations_iterator - begin_declarations() const - { return this->bindings_.begin(); } - - const_declarations_iterator - end_declarations() const - { return this->bindings_.end(); } - - // Return the number of declarations. - size_t - size_declarations() const - { return this->bindings_.size(); } - - // Return whether there are no declarations. - bool - empty_declarations() const - { return this->bindings_.empty(); } - - // Return the first declaration. - Named_object* - first_declaration() - { return this->bindings_.empty() ? NULL : this->bindings_.begin()->second; } - - private: - Named_object* - add_named_object_to_contour(Contour*, Named_object*); - - Named_object* - new_definition(Named_object*, Named_object*); - - // Enclosing bindings. - Bindings* enclosing_; - // The list of objects. - std::vector named_objects_; - // The mapping from names to objects. - Contour bindings_; -}; - -// A label. - -class Label -{ - public: - Label(const std::string& name) - : name_(name), location_(0), is_used_(false), blabel_(NULL) - { } - - // Return the label's name. - const std::string& - name() const - { return this->name_; } - - // Return whether the label has been defined. - bool - is_defined() const - { return this->location_ != 0; } - - // Return whether the label has been used. - bool - is_used() const - { return this->is_used_; } - - // Record that the label is used. - void - set_is_used() - { this->is_used_ = true; } - - // Return the location of the definition. - source_location - location() const - { return this->location_; } - - // Define the label at LOCATION. - void - define(source_location location) - { - go_assert(this->location_ == 0); - this->location_ = location; - } - - // Return the backend representation for this label. - Blabel* - get_backend_label(Translate_context*); - - // Return an expression for the address of this label. This is used - // to get the return address of a deferred function to see whether - // the function may call recover. - Bexpression* - get_addr(Translate_context*, source_location location); - - private: - // The name of the label. - std::string name_; - // The location of the definition. This is 0 if the label has not - // yet been defined. - source_location location_; - // Whether the label has been used. - bool is_used_; - // The backend representation. - Blabel* blabel_; -}; - -// An unnamed label. These are used when lowering loops. - -class Unnamed_label -{ - public: - Unnamed_label(source_location location) - : location_(location), blabel_(NULL) - { } - - // Get the location where the label is defined. - source_location - location() const - { return this->location_; } - - // Set the location where the label is defined. - void - set_location(source_location location) - { this->location_ = location; } - - // Return a statement which defines this label. - Bstatement* - get_definition(Translate_context*); - - // Return a goto to this label from LOCATION. - Bstatement* - get_goto(Translate_context*, source_location location); - - private: - // Return the backend representation. - Blabel* - get_blabel(Translate_context*); - - // The location where the label is defined. - source_location location_; - // The backend representation of this label. - Blabel* blabel_; -}; - -// An imported package. - -class Package -{ - public: - Package(const std::string& name, const std::string& unique_prefix, - source_location location); - - // The real name of this package. This may be different from the - // name in the associated Named_object if the import statement used - // an alias. - const std::string& - name() const - { return this->name_; } - - // Return the location of the import statement. - source_location - location() const - { return this->location_; } - - // Get the unique prefix used for all symbols exported from this - // package. - const std::string& - unique_prefix() const - { - go_assert(!this->unique_prefix_.empty()); - return this->unique_prefix_; - } - - // The priority of this package. The init function of packages with - // lower priority must be run before the init function of packages - // with higher priority. - int - priority() const - { return this->priority_; } - - // Set the priority. - void - set_priority(int priority); - - // Return the bindings. - Bindings* - bindings() - { return this->bindings_; } - - // Whether some symbol from the package was used. - bool - used() const - { return this->used_; } - - // Note that some symbol from this package was used. - void - set_used() const - { this->used_ = true; } - - // Clear the used field for the next file. - void - clear_used() - { this->used_ = false; } - - // Whether this package was imported in the current file. - bool - is_imported() const - { return this->is_imported_; } - - // Note that this package was imported in the current file. - void - set_is_imported() - { this->is_imported_ = true; } - - // Clear the imported field for the next file. - void - clear_is_imported() - { this->is_imported_ = false; } - - // Whether this package was imported with a name of "_". - bool - uses_sink_alias() const - { return this->uses_sink_alias_; } - - // Note that this package was imported with a name of "_". - void - set_uses_sink_alias() - { this->uses_sink_alias_ = true; } - - // Clear the sink alias field for the next file. - void - clear_uses_sink_alias() - { this->uses_sink_alias_ = false; } - - // Look up a name in the package. Returns NULL if the name is not - // found. - Named_object* - lookup(const std::string& name) const - { return this->bindings_->lookup(name); } - - // Set the location of the package. This is used if it is seen in a - // different import before it is really imported. - void - set_location(source_location location) - { this->location_ = location; } - - // Add a constant to the package. - Named_object* - add_constant(const Typed_identifier& tid, Expression* expr) - { return this->bindings_->add_constant(tid, this, expr, 0); } - - // Add a type to the package. - Named_object* - add_type(const std::string& name, Type* type, source_location location) - { return this->bindings_->add_type(name, this, type, location); } - - // Add a type declaration to the package. - Named_object* - add_type_declaration(const std::string& name, source_location location) - { return this->bindings_->add_type_declaration(name, this, location); } - - // Add a variable to the package. - Named_object* - add_variable(const std::string& name, Variable* variable) - { return this->bindings_->add_variable(name, this, variable); } - - // Add a function declaration to the package. - Named_object* - add_function_declaration(const std::string& name, Function_type* type, - source_location loc) - { return this->bindings_->add_function_declaration(name, this, type, loc); } - - // Determine types of constants. - void - determine_types(); - - private: - // The real name of this package. - std::string name_; - // The unique prefix for all exported global symbols. - std::string unique_prefix_; - // The names in this package. - Bindings* bindings_; - // The priority of this package. A package has a priority higher - // than the priority of all of the packages that it imports. This - // is used to run init functions in the right order. - int priority_; - // The location of the import statement. - source_location location_; - // True if some name from this package was used. This is mutable - // because we can use a package even if we have a const pointer to - // it. - mutable bool used_; - // True if this package was imported in the current file. - bool is_imported_; - // True if this package was imported with a name of "_". - bool uses_sink_alias_; -}; - -// Return codes for the traversal functions. This is not an enum -// because we want to be able to declare traversal functions in other -// header files without including this one. - -// Continue traversal as usual. -const int TRAVERSE_CONTINUE = -1; - -// Exit traversal. -const int TRAVERSE_EXIT = 0; - -// Continue traversal, but skip components of the current object. -// E.g., if this is returned by Traverse::statement, we do not -// traverse the expressions in the statement even if -// traverse_expressions is set in the traverse_mask. -const int TRAVERSE_SKIP_COMPONENTS = 1; - -// This class is used when traversing the parse tree. The caller uses -// a subclass which overrides functions as desired. - -class Traverse -{ - public: - // These bitmasks say what to traverse. - static const unsigned int traverse_variables = 0x1; - static const unsigned int traverse_constants = 0x2; - static const unsigned int traverse_functions = 0x4; - static const unsigned int traverse_blocks = 0x8; - static const unsigned int traverse_statements = 0x10; - static const unsigned int traverse_expressions = 0x20; - static const unsigned int traverse_types = 0x40; - - Traverse(unsigned int traverse_mask) - : traverse_mask_(traverse_mask), types_seen_(NULL), expressions_seen_(NULL) - { } - - virtual ~Traverse(); - - // The bitmask of what to traverse. - unsigned int - traverse_mask() const - { return this->traverse_mask_; } - - // Record that we are going to traverse a type. This returns true - // if the type has already been seen in this traversal. This is - // required because types, unlike expressions, can form a circular - // graph. - bool - remember_type(const Type*); - - // Record that we are going to see an expression. This returns true - // if the expression has already been seen in this traversal. This - // is only needed for cases where multiple expressions can point to - // a single one. - bool - remember_expression(const Expression*); - - // These functions return one of the TRAVERSE codes defined above. - - // If traverse_variables is set in the mask, this is called for - // every variable in the tree. - virtual int - variable(Named_object*); - - // If traverse_constants is set in the mask, this is called for - // every named constant in the tree. The bool parameter is true for - // a global constant. - virtual int - constant(Named_object*, bool); - - // If traverse_functions is set in the mask, this is called for - // every function in the tree. - virtual int - function(Named_object*); - - // If traverse_blocks is set in the mask, this is called for every - // block in the tree. - virtual int - block(Block*); - - // If traverse_statements is set in the mask, this is called for - // every statement in the tree. - virtual int - statement(Block*, size_t* index, Statement*); - - // If traverse_expressions is set in the mask, this is called for - // every expression in the tree. - virtual int - expression(Expression**); - - // If traverse_types is set in the mask, this is called for every - // type in the tree. - virtual int - type(Type*); - - private: - typedef Unordered_set_hash(const Type*, Type_hash_identical, - Type_identical) Types_seen; - - typedef Unordered_set(const Expression*) Expressions_seen; - - // Bitmask of what sort of objects to traverse. - unsigned int traverse_mask_; - // Types which have been seen in this traversal. - Types_seen* types_seen_; - // Expressions which have been seen in this traversal. - Expressions_seen* expressions_seen_; -}; - -// When translating the gogo IR into the backend data structure, this -// is the context we pass down the blocks and statements. - -class Translate_context -{ - public: - Translate_context(Gogo* gogo, Named_object* function, Block* block, - Bblock* bblock) - : gogo_(gogo), backend_(gogo->backend()), function_(function), - block_(block), bblock_(bblock), is_const_(false) - { } - - // Accessors. - - Gogo* - gogo() - { return this->gogo_; } - - Backend* - backend() - { return this->backend_; } - - Named_object* - function() - { return this->function_; } - - Block* - block() - { return this->block_; } - - Bblock* - bblock() - { return this->bblock_; } - - bool - is_const() - { return this->is_const_; } - - // Make a constant context. - void - set_is_const() - { this->is_const_ = true; } - - private: - // The IR for the entire compilation unit. - Gogo* gogo_; - // The generator for the backend data structures. - Backend* backend_; - // The function we are currently translating. NULL if not in a - // function, e.g., the initializer of a global variable. - Named_object* function_; - // The block we are currently translating. NULL if not in a - // function. - Block *block_; - // The backend representation of the current block. NULL if block_ - // is NULL. - Bblock* bblock_; - // Whether this is being evaluated in a constant context. This is - // used for type descriptor initializers. - bool is_const_; -}; - -// Runtime error codes. These must match the values in -// libgo/runtime/go-runtime-error.c. - -// Slice index out of bounds: negative or larger than the length of -// the slice. -static const int RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS = 0; - -// Array index out of bounds. -static const int RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS = 1; - -// String index out of bounds. -static const int RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS = 2; - -// Slice slice out of bounds: negative or larger than the length of -// the slice or high bound less than low bound. -static const int RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS = 3; - -// Array slice out of bounds. -static const int RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS = 4; - -// String slice out of bounds. -static const int RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS = 5; - -// Dereference of nil pointer. This is used when there is a -// dereference of a pointer to a very large struct or array, to ensure -// that a gigantic array is not used a proxy to access random memory -// locations. -static const int RUNTIME_ERROR_NIL_DEREFERENCE = 6; - -// Slice length or capacity out of bounds in make: negative or -// overflow or length greater than capacity. -static const int RUNTIME_ERROR_MAKE_SLICE_OUT_OF_BOUNDS = 7; - -// Map capacity out of bounds in make: negative or overflow. -static const int RUNTIME_ERROR_MAKE_MAP_OUT_OF_BOUNDS = 8; - -// Channel capacity out of bounds in make: negative or overflow. -static const int RUNTIME_ERROR_MAKE_CHAN_OUT_OF_BOUNDS = 9; - -// This is used by some of the langhooks. -extern Gogo* go_get_gogo(); - -// Whether we have seen any errors. FIXME: Replace with a backend -// interface. -extern bool saw_errors(); - -#endif // !defined(GO_GOGO_H) diff --git a/gcc/go/gofrontend/gogo.h.working b/gcc/go/gofrontend/gogo.h.working deleted file mode 100644 index 7a887a54296..00000000000 --- a/gcc/go/gofrontend/gogo.h.working +++ /dev/null @@ -1,2537 +0,0 @@ -// gogo.h -- Go frontend parsed representation. -*- C++ -*- - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#ifndef GO_GOGO_H -#define GO_GOGO_H - -class Traverse; -class Type; -class Type_hash_identical; -class Type_equal; -class Type_identical; -class Typed_identifier; -class Typed_identifier_list; -class Function_type; -class Expression; -class Statement; -class Block; -class Function; -class Bindings; -class Package; -class Variable; -class Pointer_type; -class Struct_type; -class Struct_field; -class Struct_field_list; -class Array_type; -class Map_type; -class Channel_type; -class Interface_type; -class Named_type; -class Forward_declaration_type; -class Method; -class Methods; -class Named_object; -class Label; -class Translate_context; -class Export; -class Import; - -// This file declares the basic classes used to hold the internal -// representation of Go which is built by the parser. - -// An initialization function for an imported package. This is a -// magic function which initializes variables and runs the "init" -// function. - -class Import_init -{ - public: - Import_init(const std::string& package_name, const std::string& init_name, - int priority) - : package_name_(package_name), init_name_(init_name), priority_(priority) - { } - - // The name of the package being imported. - const std::string& - package_name() const - { return this->package_name_; } - - // The name of the package's init function. - const std::string& - init_name() const - { return this->init_name_; } - - // The priority of the initialization function. Functions with a - // lower priority number must be run first. - int - priority() const - { return this->priority_; } - - private: - // The name of the package being imported. - std::string package_name_; - // The name of the package's init function. - std::string init_name_; - // The priority. - int priority_; -}; - -// For sorting purposes. - -inline bool -operator<(const Import_init& i1, const Import_init& i2) -{ - if (i1.priority() < i2.priority()) - return true; - if (i1.priority() > i2.priority()) - return false; - if (i1.package_name() != i2.package_name()) - return i1.package_name() < i2.package_name(); - return i1.init_name() < i2.init_name(); -} - -// The holder for the internal representation of the entire -// compilation unit. - -class Gogo -{ - public: - // Create the IR, passing in the sizes of the types "int" and - // "uintptr" in bits. - Gogo(int int_type_size, int pointer_size); - - // Get the package name. - const std::string& - package_name() const; - - // Set the package name. - void - set_package_name(const std::string&, source_location); - - // Return whether this is the "main" package. - bool - is_main_package() const; - - // If necessary, adjust the name to use for a hidden symbol. We add - // a prefix of the package name, so that hidden symbols in different - // packages do not collide. - std::string - pack_hidden_name(const std::string& name, bool is_exported) const - { - return (is_exported - ? name - : ('.' + this->unique_prefix() - + '.' + this->package_name() - + '.' + name)); - } - - // Unpack a name which may have been hidden. Returns the - // user-visible name of the object. - static std::string - unpack_hidden_name(const std::string& name) - { return name[0] != '.' ? name : name.substr(name.rfind('.') + 1); } - - // Return whether a possibly packed name is hidden. - static bool - is_hidden_name(const std::string& name) - { return name[0] == '.'; } - - // Return the package prefix of a hidden name. - static std::string - hidden_name_prefix(const std::string& name) - { - gcc_assert(Gogo::is_hidden_name(name)); - return name.substr(1, name.rfind('.') - 1); - } - - // Given a name which may or may not have been hidden, return the - // name to use in an error message. - static std::string - message_name(const std::string& name); - - // Return whether a name is the blank identifier _. - static bool - is_sink_name(const std::string& name) - { - return (name[0] == '.' - && name[name.length() - 1] == '_' - && name[name.length() - 2] == '.'); - } - - // Return the unique prefix to use for all exported symbols. - const std::string& - unique_prefix() const; - - // Set the unique prefix. - void - set_unique_prefix(const std::string&); - - // Return the priority to use for the package we are compiling. - // This is two more than the largest priority of any package we - // import. - int - package_priority() const; - - // Import a package. FILENAME is the file name argument, LOCAL_NAME - // is the local name to give to the package. If LOCAL_NAME is empty - // the declarations are added to the global scope. - void - import_package(const std::string& filename, const std::string& local_name, - bool is_local_name_exported, source_location); - - // Whether we are the global binding level. - bool - in_global_scope() const; - - // Look up a name in the current binding contours. - Named_object* - lookup(const std::string&, Named_object** pfunction) const; - - // Look up a name in the current block. - Named_object* - lookup_in_block(const std::string&) const; - - // Look up a name in the global namespace--the universal scope. - Named_object* - lookup_global(const char*) const; - - // Add a new imported package. REAL_NAME is the real name of the - // package. ALIAS is the alias of the package; this may be the same - // as REAL_NAME. This sets *PADD_TO_GLOBALS if symbols added to - // this package should be added to the global namespace; this is - // true if the alias is ".". LOCATION is the location of the import - // statement. This returns the new package, or NULL on error. - Package* - add_imported_package(const std::string& real_name, const std::string& alias, - bool is_alias_exported, - const std::string& unique_prefix, - source_location location, - bool* padd_to_globals); - - // Register a package. This package may or may not be imported. - // This returns the Package structure for the package, creating if - // it necessary. - Package* - register_package(const std::string& name, const std::string& unique_prefix, - source_location); - - // Start compiling a function. ADD_METHOD_TO_TYPE is true if a - // method function should be added to the type of its receiver. - Named_object* - start_function(const std::string& name, Function_type* type, - bool add_method_to_type, source_location); - - // Finish compiling a function. - void - finish_function(source_location); - - // Return the current function. - Named_object* - current_function() const; - - // Start a new block. This is not initially associated with a - // function. - void - start_block(source_location); - - // Finish the current block and return it. - Block* - finish_block(source_location); - - // Declare an unknown name. This is used while parsing. The name - // must be resolved by the end of the parse. Unknown names are - // always added at the package level. - Named_object* - add_unknown_name(const std::string& name, source_location); - - // Declare a function. - Named_object* - declare_function(const std::string&, Function_type*, source_location); - - // Add a label. - Label* - add_label_definition(const std::string&, source_location); - - // Add a label reference. - Label* - add_label_reference(const std::string&); - - // Add a statement to the current block. - void - add_statement(Statement*); - - // Add a block to the current block. - void - add_block(Block*, source_location); - - // Add a constant. - Named_object* - add_constant(const Typed_identifier&, Expression*, int iota_value); - - // Add a type. - void - add_type(const std::string&, Type*, source_location); - - // Add a named type. This is used for builtin types, and to add an - // imported type to the global scope. - void - add_named_type(Named_type*); - - // Declare a type. - Named_object* - declare_type(const std::string&, source_location); - - // Declare a type at the package level. This is used when the - // parser sees an unknown name where a type name is required. - Named_object* - declare_package_type(const std::string&, source_location); - - // Define a type which was already declared. - void - define_type(Named_object*, Named_type*); - - // Add a variable. - Named_object* - add_variable(const std::string&, Variable*); - - // Add a sink--a reference to the blank identifier _. - Named_object* - add_sink(); - - // Add a named object to the current namespace. This is used for - // import . "package". - void - add_named_object(Named_object*); - - // Return a name to use for a thunk function. A thunk function is - // one we create during the compilation, for a go statement or a - // defer statement or a method expression. - static std::string - thunk_name(); - - // Return whether an object is a thunk. - static bool - is_thunk(const Named_object*); - - // Note that we've seen an interface type. This is used to build - // all required interface method tables. - void - record_interface_type(Interface_type*); - - // Note that we need an initialization function. - void - set_need_init_fn() - { this->need_init_fn_ = true; } - - // Clear out all names in file scope. This is called when we start - // parsing a new file. - void - clear_file_scope(); - - // Traverse the tree. See the Traverse class. - void - traverse(Traverse*); - - // Define the predeclared global names. - void - define_global_names(); - - // Verify and complete all types. - void - verify_types(); - - // Lower the parse tree. - void - lower_parse_tree(); - - // Lower all the statements in a block. - void - lower_block(Named_object* function, Block*); - - // Lower an expression. - void - lower_expression(Named_object* function, Expression**); - - // Lower a constant. - void - lower_constant(Named_object*); - - // Finalize the method lists and build stub methods for named types. - void - finalize_methods(); - - // Work out the types to use for unspecified variables and - // constants. - void - determine_types(); - - // Type check the program. - void - check_types(); - - // Check the types in a single block. This is used for complicated - // go statements. - void - check_types_in_block(Block*); - - // Check for return statements. - void - check_return_statements(); - - // Do all exports. - void - do_exports(); - - // Add an import control function for an imported package to the - // list. - void - add_import_init_fn(const std::string& package_name, - const std::string& init_name, int prio); - - // Turn short-cut operators (&&, ||) into explicit if statements. - void - remove_shortcuts(); - - // Use temporary variables to force order of evaluation. - void - order_evaluations(); - - // Build thunks for functions which call recover. - void - build_recover_thunks(); - - // Simplify statements which might use thunks: go and defer - // statements. - void - simplify_thunk_statements(); - - // Convert named types to the backend representation. - void - convert_named_types(); - - // Convert named types in a list of bindings. - void - convert_named_types_in_bindings(Bindings*); - - // True if named types have been converted to the backend - // representation. - bool - named_types_are_converted() const - { return this->named_types_are_converted_; } - - // Write out the global values. - void - write_globals(); - - // Build a call to a builtin function. PDECL should point to a NULL - // initialized static pointer which will hold the fndecl. NAME is - // the name of the function. NARGS is the number of arguments. - // RETTYPE is the return type. It is followed by NARGS pairs of - // type and argument (both trees). - static tree - call_builtin(tree* pdecl, source_location, const char* name, int nargs, - tree rettype, ...); - - // Build a call to the runtime error function. - static tree - runtime_error(int code, source_location); - - // Build a builtin struct with a list of fields. - static tree - builtin_struct(tree* ptype, const char* struct_name, tree struct_type, - int nfields, ...); - - // Mark a function declaration as a builtin library function. - static void - mark_fndecl_as_builtin_library(tree fndecl); - - // Build the type of the struct that holds a slice for the given - // element type. - tree - slice_type_tree(tree element_type_tree); - - // Given a tree for a slice type, return the tree for the element - // type. - static tree - slice_element_type_tree(tree slice_type_tree); - - // Build a constructor for a slice. SLICE_TYPE_TREE is the type of - // the slice. VALUES points to the values. COUNT is the size, - // CAPACITY is the capacity. If CAPACITY is NULL, it is set to - // COUNT. - static tree - slice_constructor(tree slice_type_tree, tree values, tree count, - tree capacity); - - // Build a constructor for an empty slice. SLICE_TYPE_TREE is the - // type of the slice. - static tree - empty_slice_constructor(tree slice_type_tree); - - // Build a map descriptor. - tree - map_descriptor(Map_type*); - - // Return a tree for the type of a map descriptor. This is struct - // __go_map_descriptor in libgo/runtime/map.h. This is the same for - // all map types. - tree - map_descriptor_type(); - - // Build a type descriptor for TYPE using INITIALIZER as the type - // descriptor. This builds a new decl stored in *PDECL. - void - build_type_descriptor_decl(const Type*, Expression* initializer, - tree* pdecl); - - // Build required interface method tables. - void - build_interface_method_tables(); - - // Build an interface method table for a type: a list of function - // pointers, one for each interface method. This returns a decl. - tree - interface_method_table_for_type(const Interface_type*, Named_type*, - bool is_pointer); - - // Return a tree which allocate SIZE bytes to hold values of type - // TYPE. - tree - allocate_memory(Type *type, tree size, source_location); - - // Return a type to use for pointer to const char. - static tree - const_char_pointer_type_tree(); - - // Build a string constant with the right type. - static tree - string_constant_tree(const std::string&); - - // Build a Go string constant. This returns a pointer to the - // constant. - tree - go_string_constant_tree(const std::string&); - - // Send a value on a channel. - static tree - send_on_channel(tree channel, tree val, bool blocking, bool for_select, - source_location); - - // Receive a value from a channel. - static tree - receive_from_channel(tree type_tree, tree channel, bool for_select, - source_location); - - // Return a tree for receiving an integer on a channel. - static tree - receive_as_64bit_integer(tree type, tree channel, bool blocking, - bool for_select); - - - // Make a trampoline which calls FNADDR passing CLOSURE. - tree - make_trampoline(tree fnaddr, tree closure, source_location); - - private: - // During parsing, we keep a stack of functions. Each function on - // the stack is one that we are currently parsing. For each - // function, we keep track of the current stack of blocks. - struct Open_function - { - // The function. - Named_object* function; - // The stack of active blocks in the function. - std::vector blocks; - }; - - // The stack of functions. - typedef std::vector Open_functions; - - // Create trees for implicit builtin functions. - void - define_builtin_function_trees(); - - // Set up the built-in unsafe package. - void - import_unsafe(const std::string&, bool is_exported, source_location); - - // Add a new imported package. - Named_object* - add_package(const std::string& real_name, const std::string& alias, - const std::string& unique_prefix, source_location location); - - // Return the current binding contour. - Bindings* - current_bindings(); - - const Bindings* - current_bindings() const; - - // Return the current block. - Block* - current_block(); - - // Get the name of the magic initialization function. - const std::string& - get_init_fn_name(); - - // Get the decl for the magic initialization function. - tree - initialization_function_decl(); - - // Write the magic initialization function. - void - write_initialization_function(tree fndecl, tree init_stmt_list); - - // Initialize imported packages. - void - init_imports(tree*); - - // Register variables with the garbage collector. - void - register_gc_vars(const std::vector&, tree*); - - // Build a pointer to a Go string constant. This returns a pointer - // to the pointer. - tree - ptr_go_string_constant_tree(const std::string&); - - // Return the name to use for a type descriptor decl for an unnamed - // type. - std::string - unnamed_type_descriptor_decl_name(const Type* type); - - // Return the name to use for a type descriptor decl for a type - // named NO, defined in IN_FUNCTION. - std::string - type_descriptor_decl_name(const Named_object* no, - const Named_object* in_function); - - // Where a type descriptor should be defined. - enum Type_descriptor_location - { - // Defined in this file. - TYPE_DESCRIPTOR_DEFINED, - // Defined in some other file. - TYPE_DESCRIPTOR_UNDEFINED, - // Common definition which may occur in multiple files. - TYPE_DESCRIPTOR_COMMON - }; - - // Return where the decl for TYPE should be defined. - Type_descriptor_location - type_descriptor_location(const Type* type); - - // Return the type of a trampoline. - static tree - trampoline_type_tree(); - - // Type used to map import names to packages. - typedef std::map Imports; - - // Type used to map package names to packages. - typedef std::map Packages; - - // Type used to map special names in the sys package. - typedef std::map Sys_names; - - // Hash table mapping map types to map descriptor decls. - typedef Unordered_map_hash(const Map_type*, tree, Type_hash_identical, - Type_identical) Map_descriptors; - - // Map unnamed types to type descriptor decls. - typedef Unordered_map_hash(const Type*, tree, Type_hash_identical, - Type_identical) Type_descriptor_decls; - - // The package we are compiling. - Package* package_; - // The list of currently open functions during parsing. - Open_functions functions_; - // The global binding contour. This includes the builtin functions - // and the package we are compiling. - Bindings* globals_; - // Mapping from import file names to packages. - Imports imports_; - // Whether the magic unsafe package was imported. - bool imported_unsafe_; - // Mapping from package names we have seen to packages. This does - // not include the package we are compiling. - Packages packages_; - // Mapping from map types to map descriptors. - Map_descriptors* map_descriptors_; - // Mapping from unnamed types to type descriptor decls. - Type_descriptor_decls* type_descriptor_decls_; - // The functions named "init", if there are any. - std::vector init_functions_; - // Whether we need a magic initialization function. - bool need_init_fn_; - // The name of the magic initialization function. - std::string init_fn_name_; - // A list of import control variables for packages that we import. - std::set imported_init_fns_; - // The unique prefix used for all global symbols. - std::string unique_prefix_; - // Whether an explicit unique prefix was set by -fgo-prefix. - bool unique_prefix_specified_; - // A list of interface types defined while parsing. - std::vector interface_types_; - // Whether named types have been converted. - bool named_types_are_converted_; -}; - -// A block of statements. - -class Block -{ - public: - Block(Block* enclosing, source_location); - - // Return the enclosing block. - const Block* - enclosing() const - { return this->enclosing_; } - - // Return the bindings of the block. - Bindings* - bindings() - { return this->bindings_; } - - const Bindings* - bindings() const - { return this->bindings_; } - - // Look at the block's statements. - const std::vector* - statements() const - { return &this->statements_; } - - // Return the start location. This is normally the location of the - // left curly brace which starts the block. - source_location - start_location() const - { return this->start_location_; } - - // Return the end location. This is normally the location of the - // right curly brace which ends the block. - source_location - end_location() const - { return this->end_location_; } - - // Add a statement to the block. - void - add_statement(Statement*); - - // Add a statement to the front of the block. - void - add_statement_at_front(Statement*); - - // Replace a statement in a block. - void - replace_statement(size_t index, Statement*); - - // Add a Statement before statement number INDEX. - void - insert_statement_before(size_t index, Statement*); - - // Add a Statement after statement number INDEX. - void - insert_statement_after(size_t index, Statement*); - - // Set the end location of the block. - void - set_end_location(source_location location) - { this->end_location_ = location; } - - // Traverse the tree. - int - traverse(Traverse*); - - // Set final types for unspecified variables and constants. - void - determine_types(); - - // Return true if execution of this block may fall through to the - // next block. - bool - may_fall_through() const; - - // Return a tree of the code in this block. - tree - get_tree(Translate_context*); - - // Iterate over statements. - - typedef std::vector::iterator iterator; - - iterator - begin() - { return this->statements_.begin(); } - - iterator - end() - { return this->statements_.end(); } - - private: - // Enclosing block. - Block* enclosing_; - // Statements in the block. - std::vector statements_; - // Binding contour. - Bindings* bindings_; - // Location of start of block. - source_location start_location_; - // Location of end of block. - source_location end_location_; -}; - -// A function. - -class Function -{ - public: - Function(Function_type* type, Function*, Block*, source_location); - - // Return the function's type. - Function_type* - type() const - { return this->type_; } - - // Return the enclosing function if there is one. - Function* - enclosing() - { return this->enclosing_; } - - // Set the enclosing function. This is used when building thunks - // for functions which call recover. - void - set_enclosing(Function* enclosing) - { - gcc_assert(this->enclosing_ == NULL); - this->enclosing_ = enclosing; - } - - // Create the named result variables in the outer block. - void - create_named_result_variables(Gogo*); - - // Update the named result variables when cloning a function which - // calls recover. - void - update_named_result_variables(); - - // Add a new field to the closure variable. - void - add_closure_field(Named_object* var, source_location loc) - { this->closure_fields_.push_back(std::make_pair(var, loc)); } - - // Whether this function needs a closure. - bool - needs_closure() const - { return !this->closure_fields_.empty(); } - - // Return the closure variable, creating it if necessary. This is - // passed to the function as a static chain parameter. - Named_object* - closure_var(); - - // Set the closure variable. This is used when building thunks for - // functions which call recover. - void - set_closure_var(Named_object* v) - { - gcc_assert(this->closure_var_ == NULL); - this->closure_var_ = v; - } - - // Return the variable for a reference to field INDEX in the closure - // variable. - Named_object* - enclosing_var(unsigned int index) - { - gcc_assert(index < this->closure_fields_.size()); - return closure_fields_[index].first; - } - - // Set the type of the closure variable if there is one. - void - set_closure_type(); - - // Get the block of statements associated with the function. - Block* - block() const - { return this->block_; } - - // Get the location of the start of the function. - source_location - location() const - { return this->location_; } - - // Return whether this function is actually a method. - bool - is_method() const; - - // Add a label definition to the function. - Label* - add_label_definition(const std::string& label_name, source_location); - - // Add a label reference to a function. - Label* - add_label_reference(const std::string& label_name); - - // Whether this function calls the predeclared recover function. - bool - calls_recover() const - { return this->calls_recover_; } - - // Record that this function calls the predeclared recover function. - // This is set during the lowering pass. - void - set_calls_recover() - { this->calls_recover_ = true; } - - // Whether this is a recover thunk function. - bool - is_recover_thunk() const - { return this->is_recover_thunk_; } - - // Record that this is a thunk built for a function which calls - // recover. - void - set_is_recover_thunk() - { this->is_recover_thunk_ = true; } - - // Whether this function already has a recover thunk. - bool - has_recover_thunk() const - { return this->has_recover_thunk_; } - - // Record that this function already has a recover thunk. - void - set_has_recover_thunk() - { this->has_recover_thunk_ = true; } - - // Swap with another function. Used only for the thunk which calls - // recover. - void - swap_for_recover(Function *); - - // Traverse the tree. - int - traverse(Traverse*); - - // Determine types in the function. - void - determine_types(); - - // Return the function's decl given an identifier. - tree - get_or_make_decl(Gogo*, Named_object*, tree id); - - // Return the function's decl after it has been built. - tree - get_decl() const - { - gcc_assert(this->fndecl_ != NULL); - return this->fndecl_; - } - - // Set the function decl to hold a tree of the function code. - void - build_tree(Gogo*, Named_object*); - - // Get the value to return when not explicitly specified. May also - // add statements to execute first to STMT_LIST. - tree - return_value(Gogo*, Named_object*, source_location, tree* stmt_list) const; - - // Get a tree for the variable holding the defer stack. - tree - defer_stack(source_location); - - // Export the function. - void - export_func(Export*, const std::string& name) const; - - // Export a function with a type. - static void - export_func_with_type(Export*, const std::string& name, - const Function_type*); - - // Import a function. - static void - import_func(Import*, std::string* pname, Typed_identifier** receiver, - Typed_identifier_list** pparameters, - Typed_identifier_list** presults, bool* is_varargs); - - private: - // Type for mapping from label names to Label objects. - typedef Unordered_map(std::string, Label*) Labels; - - tree - make_receiver_parm_decl(Gogo*, Named_object*, tree); - - tree - copy_parm_to_heap(Gogo*, Named_object*, tree); - - void - build_defer_wrapper(Gogo*, Named_object*, tree*, tree*); - - typedef std::vector Named_results; - - typedef std::vector > Closure_fields; - - // The function's type. - Function_type* type_; - // The enclosing function. This is NULL when there isn't one, which - // is the normal case. - Function* enclosing_; - // The named result variables, if any. - Named_results* named_results_; - // If there is a closure, this is the list of variables which appear - // in the closure. This is created by the parser, and then resolved - // to a real type when we lower parse trees. - Closure_fields closure_fields_; - // The closure variable, passed as a parameter using the static - // chain parameter. Normally NULL. - Named_object* closure_var_; - // The outer block of statements in the function. - Block* block_; - // The source location of the start of the function. - source_location location_; - // Labels defined or referenced in the function. - Labels labels_; - // The function decl. - tree fndecl_; - // A variable holding the defer stack variable. This is NULL unless - // we actually need a defer stack. - tree defer_stack_; - // True if this function calls the predeclared recover function. - bool calls_recover_; - // True if this a thunk built for a function which calls recover. - bool is_recover_thunk_; - // True if this function already has a recover thunk. - bool has_recover_thunk_; -}; - -// A function declaration. - -class Function_declaration -{ - public: - Function_declaration(Function_type* fntype, source_location location) - : fntype_(fntype), location_(location), asm_name_(), fndecl_(NULL) - { } - - Function_type* - type() const - { return this->fntype_; } - - source_location - location() const - { return this->location_; } - - const std::string& - asm_name() const - { return this->asm_name_; } - - // Set the assembler name. - void - set_asm_name(const std::string& asm_name) - { this->asm_name_ = asm_name; } - - // Return a decl for the function given an identifier. - tree - get_or_make_decl(Gogo*, Named_object*, tree id); - - // Export a function declaration. - void - export_func(Export* exp, const std::string& name) const - { Function::export_func_with_type(exp, name, this->fntype_); } - - private: - // The type of the function. - Function_type* fntype_; - // The location of the declaration. - source_location location_; - // The assembler name: this is the name to use in references to the - // function. This is normally empty. - std::string asm_name_; - // The function decl if needed. - tree fndecl_; -}; - -// A variable. - -class Variable -{ - public: - Variable(Type*, Expression*, bool is_global, bool is_parameter, - bool is_receiver, source_location); - - // Get the type of the variable. - Type* - type(); - - Type* - type() const; - - // Return whether the type is defined yet. - bool - has_type() const - { return this->type_ != NULL; } - - // Get the initial value. - Expression* - init() const - { return this->init_; } - - // Return whether there are any preinit statements. - bool - has_pre_init() const - { return this->preinit_ != NULL; } - - // Return the preinit statements if any. - Block* - preinit() const - { return this->preinit_; } - - // Return whether this is a global variable. - bool - is_global() const - { return this->is_global_; } - - // Return whether this is a function parameter. - bool - is_parameter() const - { return this->is_parameter_; } - - // Return whether this is the receiver parameter of a method. - bool - is_receiver() const - { return this->is_receiver_; } - - // Change this parameter to be a receiver. This is used when - // creating the thunks created for functions which call recover. - void - set_is_receiver() - { - gcc_assert(this->is_parameter_); - this->is_receiver_ = true; - } - - // Change this parameter to not be a receiver. This is used when - // creating the thunks created for functions which call recover. - void - set_is_not_receiver() - { - gcc_assert(this->is_parameter_); - this->is_receiver_ = false; - } - - // Return whether this is the varargs parameter of a function. - bool - is_varargs_parameter() const - { return this->is_varargs_parameter_; } - - // Whether this variable's address is taken. - bool - is_address_taken() const - { return this->is_address_taken_; } - - // Whether this variable should live in the heap. - bool - is_in_heap() const - { return this->is_address_taken_ && !this->is_global_; } - - // Get the source location of the variable's declaration. - source_location - location() const - { return this->location_; } - - // Record that this is the varargs parameter of a function. - void - set_is_varargs_parameter() - { - gcc_assert(this->is_parameter_); - this->is_varargs_parameter_ = true; - } - - // Clear the initial value; used for error handling. - void - clear_init() - { this->init_ = NULL; } - - // Set the initial value; used for converting shortcuts. - void - set_init(Expression* init) - { this->init_ = init; } - - // Get the preinit block, a block of statements to be run before the - // initialization expression. - Block* - preinit_block(Gogo*); - - // Add a statement to be run before the initialization expression. - // This is only used for global variables. - void - add_preinit_statement(Gogo*, Statement*); - - // Lower the initialization expression after parsing is complete. - void - lower_init_expression(Gogo*, Named_object*); - - // A special case: the init value is used only to determine the - // type. This is used if the variable is defined using := with the - // comma-ok form of a map index or a receive expression. The init - // value is actually the map index expression or receive expression. - // We use this because we may not know the right type at parse time. - void - set_type_from_init_tuple() - { this->type_from_init_tuple_ = true; } - - // Another special case: the init value is used only to determine - // the type. This is used if the variable is defined using := with - // a range clause. The init value is the range expression. The - // type of the variable is the index type of the range expression - // (i.e., the first value returned by a range). - void - set_type_from_range_index() - { this->type_from_range_index_ = true; } - - // Another special case: like set_type_from_range_index, but the - // type is the value type of the range expression (i.e., the second - // value returned by a range). - void - set_type_from_range_value() - { this->type_from_range_value_ = true; } - - // Another special case: the init value is used only to determine - // the type. This is used if the variable is defined using := with - // a case in a select statement. The init value is the channel. - // The type of the variable is the channel's element type. - void - set_type_from_chan_element() - { this->type_from_chan_element_ = true; } - - // After we lower the select statement, we once again set the type - // from the initialization expression. - void - clear_type_from_chan_element() - { - gcc_assert(this->type_from_chan_element_); - this->type_from_chan_element_ = false; - } - - // Note that this variable was created for a type switch clause. - void - set_is_type_switch_var() - { this->is_type_switch_var_ = true; } - - // Traverse the initializer expression. - int - traverse_expression(Traverse*); - - // Determine the type of the variable if necessary. - void - determine_type(); - - // Note that something takes the address of this variable. - void - set_address_taken() - { this->is_address_taken_ = true; } - - // Get the initial value of the variable as a tree. This may only - // be called if has_pre_init() returns false. - tree - get_init_tree(Gogo*, Named_object* function); - - // Return a series of statements which sets the value of the - // variable in DECL. This should only be called is has_pre_init() - // returns true. DECL may be NULL for a sink variable. - tree - get_init_block(Gogo*, Named_object* function, tree decl); - - // Export the variable. - void - export_var(Export*, const std::string& name) const; - - // Import a variable. - static void - import_var(Import*, std::string* pname, Type** ptype); - - private: - // The type of a tuple. - Type* - type_from_tuple(Expression*, bool) const; - - // The type of a range. - Type* - type_from_range(Expression*, bool, bool) const; - - // The element type of a channel. - Type* - type_from_chan_element(Expression*, bool) const; - - // The variable's type. This may be NULL if the type is set from - // the expression. - Type* type_; - // The initial value. This may be NULL if the variable should be - // initialized to the default value for the type. - Expression* init_; - // Statements to run before the init statement. - Block* preinit_; - // Location of variable definition. - source_location location_; - // Whether this is a global variable. - bool is_global_ : 1; - // Whether this is a function parameter. - bool is_parameter_ : 1; - // Whether this is the receiver parameter of a method. - bool is_receiver_ : 1; - // Whether this is the varargs parameter of a function. - bool is_varargs_parameter_ : 1; - // Whether something takes the address of this variable. - bool is_address_taken_ : 1; - // True if we have seen this variable in a traversal. - bool seen_ : 1; - // True if we have lowered the initialization expression. - bool init_is_lowered_ : 1; - // True if init is a tuple used to set the type. - bool type_from_init_tuple_ : 1; - // True if init is a range clause and the type is the index type. - bool type_from_range_index_ : 1; - // True if init is a range clause and the type is the value type. - bool type_from_range_value_ : 1; - // True if init is a channel and the type is the channel's element type. - bool type_from_chan_element_ : 1; - // True if this is a variable created for a type switch case. - bool is_type_switch_var_ : 1; - // True if we have determined types. - bool determined_type_ : 1; -}; - -// A variable which is really the name for a function return value, or -// part of one. - -class Result_variable -{ - public: - Result_variable(Type* type, Function* function, int index) - : type_(type), function_(function), index_(index), - is_address_taken_(false) - { } - - // Get the type of the result variable. - Type* - type() const - { return this->type_; } - - // Get the function that this is associated with. - Function* - function() const - { return this->function_; } - - // Index in the list of function results. - int - index() const - { return this->index_; } - - // Whether this variable's address is taken. - bool - is_address_taken() const - { return this->is_address_taken_; } - - // Note that something takes the address of this variable. - void - set_address_taken() - { this->is_address_taken_ = true; } - - // Whether this variable should live in the heap. - bool - is_in_heap() const - { return this->is_address_taken_; } - - // Set the function. This is used when cloning functions which call - // recover. - void - set_function(Function* function) - { this->function_ = function; } - - private: - // Type of result variable. - Type* type_; - // Function with which this is associated. - Function* function_; - // Index in list of results. - int index_; - // Whether something takes the address of this variable. - bool is_address_taken_; -}; - -// The value we keep for a named constant. This lets us hold a type -// and an expression. - -class Named_constant -{ - public: - Named_constant(Type* type, Expression* expr, int iota_value, - source_location location) - : type_(type), expr_(expr), iota_value_(iota_value), location_(location), - lowering_(false) - { } - - Type* - type() const - { return this->type_; } - - Expression* - expr() const - { return this->expr_; } - - int - iota_value() const - { return this->iota_value_; } - - source_location - location() const - { return this->location_; } - - // Whether we are lowering. - bool - lowering() const - { return this->lowering_; } - - // Set that we are lowering. - void - set_lowering() - { this->lowering_ = true; } - - // We are no longer lowering. - void - clear_lowering() - { this->lowering_ = false; } - - // Traverse the expression. - int - traverse_expression(Traverse*); - - // Determine the type of the constant if necessary. - void - determine_type(); - - // Indicate that we found and reported an error for this constant. - void - set_error(); - - // Export the constant. - void - export_const(Export*, const std::string& name) const; - - // Import a constant. - static void - import_const(Import*, std::string*, Type**, Expression**); - - private: - // The type of the constant. - Type* type_; - // The expression for the constant. - Expression* expr_; - // If the predeclared constant iota is used in EXPR_, this is the - // value it will have. We do this because at parse time we don't - // know whether the name "iota" will refer to the predeclared - // constant or to something else. We put in the right value in when - // we lower. - int iota_value_; - // The location of the definition. - source_location location_; - // Whether we are currently lowering this constant. - bool lowering_; -}; - -// A type declaration. - -class Type_declaration -{ - public: - Type_declaration(source_location location) - : location_(location), in_function_(NULL), methods_(), - issued_warning_(false) - { } - - // Return the location. - source_location - location() const - { return this->location_; } - - // Return the function in which this type is declared. This will - // return NULL for a type declared in global scope. - Named_object* - in_function() - { return this->in_function_; } - - // Set the function in which this type is declared. - void - set_in_function(Named_object* f) - { this->in_function_ = f; } - - // Add a method to this type. This is used when methods are defined - // before the type. - Named_object* - add_method(const std::string& name, Function* function); - - // Add a method declaration to this type. - Named_object* - add_method_declaration(const std::string& name, Function_type* type, - source_location location); - - // Return whether any methods were defined. - bool - has_methods() const; - - // Define methods when the real type is known. - void - define_methods(Named_type*); - - // This is called if we are trying to use this type. It returns - // true if we should issue a warning. - bool - using_type(); - - private: - typedef std::vector Methods; - - // The location of the type declaration. - source_location location_; - // If this type is declared in a function, a pointer back to the - // function in which it is defined. - Named_object* in_function_; - // Methods defined before the type is defined. - Methods methods_; - // True if we have issued a warning about a use of this type - // declaration when it is undefined. - bool issued_warning_; -}; - -// An unknown object. These are created by the parser for forward -// references to names which have not been seen before. In a correct -// program, these will always point to a real definition by the end of -// the parse. Because they point to another Named_object, these may -// only be referenced by Unknown_expression objects. - -class Unknown_name -{ - public: - Unknown_name(source_location location) - : location_(location), real_named_object_(NULL) - { } - - // Return the location where this name was first seen. - source_location - location() const - { return this->location_; } - - // Return the real named object that this points to, or NULL if it - // was never resolved. - Named_object* - real_named_object() const - { return this->real_named_object_; } - - // Set the real named object that this points to. - void - set_real_named_object(Named_object* no); - - private: - // The location where this name was first seen. - source_location location_; - // The real named object when it is known. - Named_object* - real_named_object_; -}; - -// A named object named. This is the result of a declaration. We -// don't use a superclass because they all have to be handled -// differently. - -class Named_object -{ - public: - enum Classification - { - // An uninitialized Named_object. We should never see this. - NAMED_OBJECT_UNINITIALIZED, - // An unknown name. This is used for forward references. In a - // correct program, these will all be resolved by the end of the - // parse. - NAMED_OBJECT_UNKNOWN, - // A const. - NAMED_OBJECT_CONST, - // A type. - NAMED_OBJECT_TYPE, - // A forward type declaration. - NAMED_OBJECT_TYPE_DECLARATION, - // A var. - NAMED_OBJECT_VAR, - // A result variable in a function. - NAMED_OBJECT_RESULT_VAR, - // The blank identifier--the special variable named _. - NAMED_OBJECT_SINK, - // A func. - NAMED_OBJECT_FUNC, - // A forward func declaration. - NAMED_OBJECT_FUNC_DECLARATION, - // A package. - NAMED_OBJECT_PACKAGE - }; - - // Return the classification. - Classification - classification() const - { return this->classification_; } - - // Classifiers. - - bool - is_unknown() const - { return this->classification_ == NAMED_OBJECT_UNKNOWN; } - - bool - is_const() const - { return this->classification_ == NAMED_OBJECT_CONST; } - - bool - is_type() const - { return this->classification_ == NAMED_OBJECT_TYPE; } - - bool - is_type_declaration() const - { return this->classification_ == NAMED_OBJECT_TYPE_DECLARATION; } - - bool - is_variable() const - { return this->classification_ == NAMED_OBJECT_VAR; } - - bool - is_result_variable() const - { return this->classification_ == NAMED_OBJECT_RESULT_VAR; } - - bool - is_sink() const - { return this->classification_ == NAMED_OBJECT_SINK; } - - bool - is_function() const - { return this->classification_ == NAMED_OBJECT_FUNC; } - - bool - is_function_declaration() const - { return this->classification_ == NAMED_OBJECT_FUNC_DECLARATION; } - - bool - is_package() const - { return this->classification_ == NAMED_OBJECT_PACKAGE; } - - // Creators. - - static Named_object* - make_unknown_name(const std::string& name, source_location); - - static Named_object* - make_constant(const Typed_identifier&, const Package*, Expression*, - int iota_value); - - static Named_object* - make_type(const std::string&, const Package*, Type*, source_location); - - static Named_object* - make_type_declaration(const std::string&, const Package*, source_location); - - static Named_object* - make_variable(const std::string&, const Package*, Variable*); - - static Named_object* - make_result_variable(const std::string&, Result_variable*); - - static Named_object* - make_sink(); - - static Named_object* - make_function(const std::string&, const Package*, Function*); - - static Named_object* - make_function_declaration(const std::string&, const Package*, Function_type*, - source_location); - - static Named_object* - make_package(const std::string& alias, Package* package); - - // Getters. - - Unknown_name* - unknown_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_UNKNOWN); - return this->u_.unknown_value; - } - - const Unknown_name* - unknown_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_UNKNOWN); - return this->u_.unknown_value; - } - - Named_constant* - const_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_CONST); - return this->u_.const_value; - } - - const Named_constant* - const_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_CONST); - return this->u_.const_value; - } - - Named_type* - type_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_TYPE); - return this->u_.type_value; - } - - const Named_type* - type_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_TYPE); - return this->u_.type_value; - } - - Type_declaration* - type_declaration_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION); - return this->u_.type_declaration; - } - - const Type_declaration* - type_declaration_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION); - return this->u_.type_declaration; - } - - Variable* - var_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_VAR); - return this->u_.var_value; - } - - const Variable* - var_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_VAR); - return this->u_.var_value; - } - - Result_variable* - result_var_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_RESULT_VAR); - return this->u_.result_var_value; - } - - const Result_variable* - result_var_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_RESULT_VAR); - return this->u_.result_var_value; - } - - Function* - func_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_FUNC); - return this->u_.func_value; - } - - const Function* - func_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_FUNC); - return this->u_.func_value; - } - - Function_declaration* - func_declaration_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION); - return this->u_.func_declaration_value; - } - - const Function_declaration* - func_declaration_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION); - return this->u_.func_declaration_value; - } - - Package* - package_value() - { - gcc_assert(this->classification_ == NAMED_OBJECT_PACKAGE); - return this->u_.package_value; - } - - const Package* - package_value() const - { - gcc_assert(this->classification_ == NAMED_OBJECT_PACKAGE); - return this->u_.package_value; - } - - const std::string& - name() const - { return this->name_; } - - // Return the name to use in an error message. The difference is - // that if this Named_object is defined in a different package, this - // will return PACKAGE.NAME. - std::string - message_name() const; - - const Package* - package() const - { return this->package_; } - - // Resolve an unknown value if possible. This returns the same - // Named_object or a new one. - Named_object* - resolve() - { - Named_object* ret = this; - if (this->is_unknown()) - { - Named_object* r = this->unknown_value()->real_named_object(); - if (r != NULL) - ret = r; - } - return ret; - } - - const Named_object* - resolve() const - { - const Named_object* ret = this; - if (this->is_unknown()) - { - const Named_object* r = this->unknown_value()->real_named_object(); - if (r != NULL) - ret = r; - } - return ret; - } - - // The location where this object was defined or referenced. - source_location - location() const; - - // Return a tree for the external identifier for this object. - tree - get_id(Gogo*); - - // Return a tree representing this object. - tree - get_tree(Gogo*, Named_object* function); - - // Define a type declaration. - void - set_type_value(Named_type*); - - // Define a function declaration. - void - set_function_value(Function*); - - // Declare an unknown name as a type declaration. - void - declare_as_type(); - - // Export this object. - void - export_named_object(Export*) const; - - private: - Named_object(const std::string&, const Package*, Classification); - - // The name of the object. - std::string name_; - // The package that this object is in. This is NULL if it is in the - // file we are compiling. - const Package* package_; - // The type of object this is. - Classification classification_; - // The real data. - union - { - Unknown_name* unknown_value; - Named_constant* const_value; - Named_type* type_value; - Type_declaration* type_declaration; - Variable* var_value; - Result_variable* result_var_value; - Function* func_value; - Function_declaration* func_declaration_value; - Package* package_value; - } u_; - // The DECL tree for this object if we have already converted it. - tree tree_; -}; - -// A binding contour. This binds names to objects. - -class Bindings -{ - public: - // Type for mapping from names to objects. - typedef Unordered_map(std::string, Named_object*) Contour; - - Bindings(Bindings* enclosing); - - // Add an unknown name. - Named_object* - add_unknown_name(const std::string& name, source_location location) - { - return this->add_named_object(Named_object::make_unknown_name(name, - location)); - } - - // Add a constant. - Named_object* - add_constant(const Typed_identifier& tid, const Package* package, - Expression* expr, int iota_value) - { - return this->add_named_object(Named_object::make_constant(tid, package, - expr, - iota_value)); - } - - // Add a type. - Named_object* - add_type(const std::string& name, const Package* package, Type* type, - source_location location) - { - return this->add_named_object(Named_object::make_type(name, package, type, - location)); - } - - // Add a named type. This is used for builtin types, and to add an - // imported type to the global scope. - Named_object* - add_named_type(Named_type* named_type); - - // Add a type declaration. - Named_object* - add_type_declaration(const std::string& name, const Package* package, - source_location location) - { - Named_object* no = Named_object::make_type_declaration(name, package, - location); - return this->add_named_object(no); - } - - // Add a variable. - Named_object* - add_variable(const std::string& name, const Package* package, - Variable* variable) - { - return this->add_named_object(Named_object::make_variable(name, package, - variable)); - } - - // Add a result variable. - Named_object* - add_result_variable(const std::string& name, Result_variable* result) - { - return this->add_named_object(Named_object::make_result_variable(name, - result)); - } - - // Add a function. - Named_object* - add_function(const std::string& name, const Package*, Function* function); - - // Add a function declaration. - Named_object* - add_function_declaration(const std::string& name, const Package* package, - Function_type* type, source_location location); - - // Add a package. The location is the location of the import - // statement. - Named_object* - add_package(const std::string& alias, Package* package) - { - Named_object* no = Named_object::make_package(alias, package); - return this->add_named_object(no); - } - - // Define a type which was already declared. - void - define_type(Named_object*, Named_type*); - - // Add a method to the list of objects. This is not added to the - // lookup table. - void - add_method(Named_object*); - - // Add a named object to this binding. - Named_object* - add_named_object(Named_object* no) - { return this->add_named_object_to_contour(&this->bindings_, no); } - - // Clear all names in file scope from the bindings. - void - clear_file_scope(); - - // Look up a name in this binding contour and in any enclosing - // binding contours. This returns NULL if the name is not found. - Named_object* - lookup(const std::string&) const; - - // Look up a name in this binding contour without looking in any - // enclosing binding contours. Returns NULL if the name is not found. - Named_object* - lookup_local(const std::string&) const; - - // Remove a name. - void - remove_binding(Named_object*); - - // Traverse the tree. See the Traverse class. - int - traverse(Traverse*, bool is_global); - - // Iterate over definitions. This does not include things which - // were only declared. - - typedef std::vector::const_iterator - const_definitions_iterator; - - const_definitions_iterator - begin_definitions() const - { return this->named_objects_.begin(); } - - const_definitions_iterator - end_definitions() const - { return this->named_objects_.end(); } - - // Return the number of definitions. - size_t - size_definitions() const - { return this->named_objects_.size(); } - - // Return whether there are no definitions. - bool - empty_definitions() const - { return this->named_objects_.empty(); } - - // Iterate over declarations. This is everything that has been - // declared, which includes everything which has been defined. - - typedef Contour::const_iterator const_declarations_iterator; - - const_declarations_iterator - begin_declarations() const - { return this->bindings_.begin(); } - - const_declarations_iterator - end_declarations() const - { return this->bindings_.end(); } - - // Return the number of declarations. - size_t - size_declarations() const - { return this->bindings_.size(); } - - // Return whether there are no declarations. - bool - empty_declarations() const - { return this->bindings_.empty(); } - - // Return the first declaration. - Named_object* - first_declaration() - { return this->bindings_.empty() ? NULL : this->bindings_.begin()->second; } - - private: - Named_object* - add_named_object_to_contour(Contour*, Named_object*); - - Named_object* - new_definition(Named_object*, Named_object*); - - // Enclosing bindings. - Bindings* enclosing_; - // The list of objects. - std::vector named_objects_; - // The mapping from names to objects. - Contour bindings_; -}; - -// A label. - -class Label -{ - public: - Label(const std::string& name) - : name_(name), location_(0), decl_(NULL) - { } - - // Return the label's name. - const std::string& - name() const - { return this->name_; } - - // Return whether the label has been defined. - bool - is_defined() const - { return this->location_ != 0; } - - // Return the location of the definition. - source_location - location() const - { return this->location_; } - - // Define the label at LOCATION. - void - define(source_location location) - { - gcc_assert(this->location_ == 0); - this->location_ = location; - } - - // Return the LABEL_DECL for this decl. - tree - get_decl(); - - // Return an expression for the address of this label. - tree - get_addr(source_location location); - - private: - // The name of the label. - std::string name_; - // The location of the definition. This is 0 if the label has not - // yet been defined. - source_location location_; - // The LABEL_DECL. - tree decl_; -}; - -// An unnamed label. These are used when lowering loops. - -class Unnamed_label -{ - public: - Unnamed_label(source_location location) - : location_(location), decl_(NULL) - { } - - // Get the location where the label is defined. - source_location - location() const - { return this->location_; } - - // Set the location where the label is defined. - void - set_location(source_location location) - { this->location_ = location; } - - // Return a statement which defines this label. - tree - get_definition(); - - // Return a goto to this label from LOCATION. - tree - get_goto(source_location location); - - private: - // Return the LABEL_DECL to use with GOTO_EXPR. - tree - get_decl(); - - // The location where the label is defined. - source_location location_; - // The LABEL_DECL. - tree decl_; -}; - -// An imported package. - -class Package -{ - public: - Package(const std::string& name, const std::string& unique_prefix, - source_location location); - - // The real name of this package. This may be different from the - // name in the associated Named_object if the import statement used - // an alias. - const std::string& - name() const - { return this->name_; } - - // Return the location of the import statement. - source_location - location() const - { return this->location_; } - - // Get the unique prefix used for all symbols exported from this - // package. - const std::string& - unique_prefix() const - { - gcc_assert(!this->unique_prefix_.empty()); - return this->unique_prefix_; - } - - // The priority of this package. The init function of packages with - // lower priority must be run before the init function of packages - // with higher priority. - int - priority() const - { return this->priority_; } - - // Set the priority. - void - set_priority(int priority); - - // Return the bindings. - Bindings* - bindings() - { return this->bindings_; } - - // Whether some symbol from the package was used. - bool - used() const - { return this->used_; } - - // Note that some symbol from this package was used. - void - set_used() const - { this->used_ = true; } - - // Clear the used field for the next file. - void - clear_used() - { this->used_ = false; } - - // Whether this package was imported in the current file. - bool - is_imported() const - { return this->is_imported_; } - - // Note that this package was imported in the current file. - void - set_is_imported() - { this->is_imported_ = true; } - - // Clear the imported field for the next file. - void - clear_is_imported() - { this->is_imported_ = false; } - - // Whether this package was imported with a name of "_". - bool - uses_sink_alias() const - { return this->uses_sink_alias_; } - - // Note that this package was imported with a name of "_". - void - set_uses_sink_alias() - { this->uses_sink_alias_ = true; } - - // Clear the sink alias field for the next file. - void - clear_uses_sink_alias() - { this->uses_sink_alias_ = false; } - - // Look up a name in the package. Returns NULL if the name is not - // found. - Named_object* - lookup(const std::string& name) const - { return this->bindings_->lookup(name); } - - // Set the location of the package. This is used if it is seen in a - // different import before it is really imported. - void - set_location(source_location location) - { this->location_ = location; } - - // Add a constant to the package. - Named_object* - add_constant(const Typed_identifier& tid, Expression* expr) - { return this->bindings_->add_constant(tid, this, expr, 0); } - - // Add a type to the package. - Named_object* - add_type(const std::string& name, Type* type, source_location location) - { return this->bindings_->add_type(name, this, type, location); } - - // Add a type declaration to the package. - Named_object* - add_type_declaration(const std::string& name, source_location location) - { return this->bindings_->add_type_declaration(name, this, location); } - - // Add a variable to the package. - Named_object* - add_variable(const std::string& name, Variable* variable) - { return this->bindings_->add_variable(name, this, variable); } - - // Add a function declaration to the package. - Named_object* - add_function_declaration(const std::string& name, Function_type* type, - source_location loc) - { return this->bindings_->add_function_declaration(name, this, type, loc); } - - // Determine types of constants. - void - determine_types(); - - private: - // The real name of this package. - std::string name_; - // The unique prefix for all exported global symbols. - std::string unique_prefix_; - // The names in this package. - Bindings* bindings_; - // The priority of this package. A package has a priority higher - // than the priority of all of the packages that it imports. This - // is used to run init functions in the right order. - int priority_; - // The location of the import statement. - source_location location_; - // True if some name from this package was used. This is mutable - // because we can use a package even if we have a const pointer to - // it. - mutable bool used_; - // True if this package was imported in the current file. - bool is_imported_; - // True if this package was imported with a name of "_". - bool uses_sink_alias_; -}; - -// Return codes for the traversal functions. This is not an enum -// because we want to be able to declare traversal functions in other -// header files without including this one. - -// Continue traversal as usual. -const int TRAVERSE_CONTINUE = -1; - -// Exit traversal. -const int TRAVERSE_EXIT = 0; - -// Continue traversal, but skip components of the current object. -// E.g., if this is returned by Traverse::statement, we do not -// traverse the expressions in the statement even if -// traverse_expressions is set in the traverse_mask. -const int TRAVERSE_SKIP_COMPONENTS = 1; - -// This class is used when traversing the parse tree. The caller uses -// a subclass which overrides functions as desired. - -class Traverse -{ - public: - // These bitmasks say what to traverse. - static const unsigned int traverse_variables = 0x1; - static const unsigned int traverse_constants = 0x2; - static const unsigned int traverse_functions = 0x4; - static const unsigned int traverse_blocks = 0x8; - static const unsigned int traverse_statements = 0x10; - static const unsigned int traverse_expressions = 0x20; - static const unsigned int traverse_types = 0x40; - - Traverse(unsigned int traverse_mask) - : traverse_mask_(traverse_mask), types_seen_(NULL), expressions_seen_(NULL) - { } - - virtual ~Traverse(); - - // The bitmask of what to traverse. - unsigned int - traverse_mask() const - { return this->traverse_mask_; } - - // Record that we are going to traverse a type. This returns true - // if the type has already been seen in this traversal. This is - // required because types, unlike expressions, can form a circular - // graph. - bool - remember_type(const Type*); - - // Record that we are going to see an expression. This returns true - // if the expression has already been seen in this traversal. This - // is only needed for cases where multiple expressions can point to - // a single one. - bool - remember_expression(const Expression*); - - // These functions return one of the TRAVERSE codes defined above. - - // If traverse_variables is set in the mask, this is called for - // every variable in the tree. - virtual int - variable(Named_object*); - - // If traverse_constants is set in the mask, this is called for - // every named constant in the tree. The bool parameter is true for - // a global constant. - virtual int - constant(Named_object*, bool); - - // If traverse_functions is set in the mask, this is called for - // every function in the tree. - virtual int - function(Named_object*); - - // If traverse_blocks is set in the mask, this is called for every - // block in the tree. - virtual int - block(Block*); - - // If traverse_statements is set in the mask, this is called for - // every statement in the tree. - virtual int - statement(Block*, size_t* index, Statement*); - - // If traverse_expressions is set in the mask, this is called for - // every expression in the tree. - virtual int - expression(Expression**); - - // If traverse_types is set in the mask, this is called for every - // type in the tree. - virtual int - type(Type*); - - private: - typedef Unordered_set_hash(const Type*, Type_hash_identical, - Type_identical) Types_seen; - - typedef Unordered_set(const Expression*) Expressions_seen; - - // Bitmask of what sort of objects to traverse. - unsigned int traverse_mask_; - // Types which have been seen in this traversal. - Types_seen* types_seen_; - // Expressions which have been seen in this traversal. - Expressions_seen* expressions_seen_; -}; - -// When translating the gogo IR into trees, this is the context we -// pass down the blocks and statements. - -class Translate_context -{ - public: - Translate_context(Gogo* gogo, Named_object* function, Block* block, - tree block_tree) - : gogo_(gogo), function_(function), block_(block), block_tree_(block_tree), - is_const_(false) - { } - - // Accessors. - - Gogo* - gogo() - { return this->gogo_; } - - Named_object* - function() - { return this->function_; } - - Block* - block() - { return this->block_; } - - tree - block_tree() - { return this->block_tree_; } - - bool - is_const() - { return this->is_const_; } - - // Make a constant context. - void - set_is_const() - { this->is_const_ = true; } - - private: - // The IR for the entire compilation unit. - Gogo* gogo_; - // The function we are currently translating. - Named_object* function_; - // The block we are currently translating. - Block *block_; - // The BLOCK node for the current block. - tree block_tree_; - // Whether this is being evaluated in a constant context. This is - // used for type descriptor initializers. - bool is_const_; -}; - -// Runtime error codes. These must match the values in -// libgo/runtime/go-runtime-error.c. - -// Slice index out of bounds: negative or larger than the length of -// the slice. -static const int RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS = 0; - -// Array index out of bounds. -static const int RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS = 1; - -// String index out of bounds. -static const int RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS = 2; - -// Slice slice out of bounds: negative or larger than the length of -// the slice or high bound less than low bound. -static const int RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS = 3; - -// Array slice out of bounds. -static const int RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS = 4; - -// String slice out of bounds. -static const int RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS = 5; - -// Dereference of nil pointer. This is used when there is a -// dereference of a pointer to a very large struct or array, to ensure -// that a gigantic array is not used a proxy to access random memory -// locations. -static const int RUNTIME_ERROR_NIL_DEREFERENCE = 6; - -// Slice length or capacity out of bounds in make: negative or -// overflow or length greater than capacity. -static const int RUNTIME_ERROR_MAKE_SLICE_OUT_OF_BOUNDS = 7; - -// Map capacity out of bounds in make: negative or overflow. -static const int RUNTIME_ERROR_MAKE_MAP_OUT_OF_BOUNDS = 8; - -// Channel capacity out of bounds in make: negative or overflow. -static const int RUNTIME_ERROR_MAKE_CHAN_OUT_OF_BOUNDS = 9; - -// This is used by some of the langhooks. -extern Gogo* go_get_gogo(); - -// Whether we have seen any errors. FIXME: Replace with a backend -// interface. -extern bool saw_errors(); - -#endif // !defined(GO_GOGO_H) diff --git a/gcc/go/gofrontend/parse.cc.merge-left.r167407 b/gcc/go/gofrontend/parse.cc.merge-left.r167407 deleted file mode 100644 index c8b55c56214..00000000000 --- a/gcc/go/gofrontend/parse.cc.merge-left.r167407 +++ /dev/null @@ -1,4730 +0,0 @@ -// parse.cc -- Go frontend parser. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include "lex.h" -#include "gogo.h" -#include "types.h" -#include "statements.h" -#include "expressions.h" -#include "parse.h" - -// Struct Parse::Enclosing_var_comparison. - -// Return true if v1 should be considered to be less than v2. - -bool -Parse::Enclosing_var_comparison::operator()(const Enclosing_var& v1, - const Enclosing_var& v2) -{ - if (v1.var() == v2.var()) - return false; - - const std::string& n1(v1.var()->name()); - const std::string& n2(v2.var()->name()); - int i = n1.compare(n2); - if (i < 0) - return true; - else if (i > 0) - return false; - - // If we get here it means that a single nested function refers to - // two different variables defined in enclosing functions, and both - // variables have the same name. I think this is impossible. - gcc_unreachable(); -} - -// Class Parse. - -Parse::Parse(Lex* lex, Gogo* gogo) - : lex_(lex), - token_(Token::make_invalid_token(0)), - unget_token_(Token::make_invalid_token(0)), - unget_token_valid_(false), - gogo_(gogo), - break_stack_(), - continue_stack_(), - iota_(0), - enclosing_vars_() -{ -} - -// Return the current token. - -const Token* -Parse::peek_token() -{ - if (this->unget_token_valid_) - return &this->unget_token_; - if (this->token_.is_invalid()) - this->token_ = this->lex_->next_token(); - return &this->token_; -} - -// Advance to the next token and return it. - -const Token* -Parse::advance_token() -{ - if (this->unget_token_valid_) - { - this->unget_token_valid_ = false; - if (!this->token_.is_invalid()) - return &this->token_; - } - this->token_ = this->lex_->next_token(); - return &this->token_; -} - -// Push a token back on the input stream. - -void -Parse::unget_token(const Token& token) -{ - gcc_assert(!this->unget_token_valid_); - this->unget_token_ = token; - this->unget_token_valid_ = true; -} - -// The location of the current token. - -source_location -Parse::location() -{ - return this->peek_token()->location(); -} - -// IdentifierList = identifier { "," identifier } . - -void -Parse::identifier_list(Typed_identifier_list* til) -{ - const Token* token = this->peek_token(); - while (true) - { - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return; - } - std::string name = - this->gogo_->pack_hidden_name(token->identifier(), - token->is_identifier_exported()); - til->push_back(Typed_identifier(name, NULL, token->location())); - token = this->advance_token(); - if (!token->is_op(OPERATOR_COMMA)) - return; - token = this->advance_token(); - } -} - -// ExpressionList = Expression { "," Expression } . - -// If MAY_BE_SINK is true, the expressions in the list may be "_". - -Expression_list* -Parse::expression_list(Expression* first, bool may_be_sink) -{ - Expression_list* ret = new Expression_list(); - if (first != NULL) - ret->push_back(first); - while (true) - { - ret->push_back(this->expression(PRECEDENCE_NORMAL, may_be_sink, true, - NULL)); - - const Token* token = this->peek_token(); - if (!token->is_op(OPERATOR_COMMA)) - return ret; - - // Most expression lists permit a trailing comma. - source_location location = token->location(); - this->advance_token(); - if (!this->expression_may_start_here()) - { - this->unget_token(Token::make_operator_token(OPERATOR_COMMA, - location)); - return ret; - } - } -} - -// QualifiedIdent = [ PackageName "." ] identifier . -// PackageName = identifier . - -// This sets *PNAME to the identifier and sets *PPACKAGE to the -// package or NULL if there isn't one. This returns true on success, -// false on failure in which case it will have emitted an error -// message. - -bool -Parse::qualified_ident(std::string* pname, Named_object** ppackage) -{ - const Token* token = this->peek_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return false; - } - - std::string name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - name = this->gogo_->pack_hidden_name(name, is_exported); - - token = this->advance_token(); - if (!token->is_op(OPERATOR_DOT)) - { - *pname = name; - *ppackage = NULL; - return true; - } - - Named_object* package = this->gogo_->lookup(name, NULL); - if (package == NULL || !package->is_package()) - { - error_at(this->location(), "expected package"); - // We expect . IDENTIFIER; skip both. - if (this->advance_token()->is_identifier()) - this->advance_token(); - return false; - } - - package->package_value()->set_used(); - - token = this->advance_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return false; - } - - name = token->identifier(); - - if (name == "_") - { - error_at(this->location(), "invalid use of %<_%>"); - name = "blank"; - } - - if (package->name() == this->gogo_->package_name()) - name = this->gogo_->pack_hidden_name(name, - token->is_identifier_exported()); - - *pname = name; - *ppackage = package; - - this->advance_token(); - - return true; -} - -// Type = TypeName | TypeLit | "(" Type ")" . -// TypeLit = -// ArrayType | StructType | PointerType | FunctionType | InterfaceType | -// SliceType | MapType | ChannelType . - -Type* -Parse::type() -{ - const Token* token = this->peek_token(); - if (token->is_identifier()) - return this->type_name(true); - else if (token->is_op(OPERATOR_LSQUARE)) - return this->array_type(false); - else if (token->is_keyword(KEYWORD_CHAN) - || token->is_op(OPERATOR_CHANOP)) - return this->channel_type(); - else if (token->is_keyword(KEYWORD_INTERFACE)) - return this->interface_type(); - else if (token->is_keyword(KEYWORD_FUNC)) - { - source_location location = token->location(); - this->advance_token(); - return this->signature(NULL, location); - } - else if (token->is_keyword(KEYWORD_MAP)) - return this->map_type(); - else if (token->is_keyword(KEYWORD_STRUCT)) - return this->struct_type(); - else if (token->is_op(OPERATOR_MULT)) - return this->pointer_type(); - else if (token->is_op(OPERATOR_LPAREN)) - { - this->advance_token(); - Type* ret = this->type(); - if (this->peek_token()->is_op(OPERATOR_RPAREN)) - this->advance_token(); - else - { - if (!ret->is_error_type()) - error_at(this->location(), "expected %<)%>"); - } - return ret; - } - else - { - error_at(token->location(), "expected type"); - return Type::make_error_type(); - } -} - -bool -Parse::type_may_start_here() -{ - const Token* token = this->peek_token(); - return (token->is_identifier() - || token->is_op(OPERATOR_LSQUARE) - || token->is_op(OPERATOR_CHANOP) - || token->is_keyword(KEYWORD_CHAN) - || token->is_keyword(KEYWORD_INTERFACE) - || token->is_keyword(KEYWORD_FUNC) - || token->is_keyword(KEYWORD_MAP) - || token->is_keyword(KEYWORD_STRUCT) - || token->is_op(OPERATOR_MULT) - || token->is_op(OPERATOR_LPAREN)); -} - -// TypeName = QualifiedIdent . - -// If MAY_BE_NIL is true, then an identifier with the value of the -// predefined constant nil is accepted, returning the nil type. - -Type* -Parse::type_name(bool issue_error) -{ - source_location location = this->location(); - - std::string name; - Named_object* package; - if (!this->qualified_ident(&name, &package)) - return Type::make_error_type(); - - Named_object* named_object; - if (package == NULL) - named_object = this->gogo_->lookup(name, NULL); - else - { - named_object = package->package_value()->lookup(name); - if (named_object == NULL - && issue_error - && package->name() != this->gogo_->package_name()) - { - // Check whether the name is there but hidden. - std::string s = ('.' + package->package_value()->unique_prefix() - + '.' + package->package_value()->name() - + '.' + name); - named_object = package->package_value()->lookup(s); - if (named_object != NULL) - { - const std::string& packname(package->package_value()->name()); - error_at(location, "invalid reference to hidden type %<%s.%s%>", - Gogo::message_name(packname).c_str(), - Gogo::message_name(name).c_str()); - issue_error = false; - } - } - } - - bool ok = true; - if (named_object == NULL) - { - if (package != NULL) - ok = false; - else - named_object = this->gogo_->add_unknown_name(name, location); - } - else if (named_object->is_type()) - { - if (!named_object->type_value()->is_visible()) - ok = false; - } - else if (named_object->is_unknown() || named_object->is_type_declaration()) - ; - else - ok = false; - - if (!ok) - { - if (issue_error) - error_at(location, "expected type"); - return Type::make_error_type(); - } - - if (named_object->is_type()) - return named_object->type_value(); - else if (named_object->is_unknown() || named_object->is_type_declaration()) - return Type::make_forward_declaration(named_object); - else - gcc_unreachable(); -} - -// ArrayType = "[" [ ArrayLength ] "]" ElementType . -// ArrayLength = Expression . -// ElementType = CompleteType . - -Type* -Parse::array_type(bool may_use_ellipsis) -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_LSQUARE)); - const Token* token = this->advance_token(); - - Expression* length = NULL; - if (token->is_op(OPERATOR_RSQUARE)) - this->advance_token(); - else - { - if (!token->is_op(OPERATOR_ELLIPSIS)) - length = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - else if (may_use_ellipsis) - { - // An ellipsis is used in composite literals to represent a - // fixed array of the size of the number of elements. We - // use a length of nil to represent this, and change the - // length when parsing the composite literal. - length = Expression::make_nil(this->location()); - this->advance_token(); - } - else - { - error_at(this->location(), - "use of %<[...]%> outside of array literal"); - length = Expression::make_error(this->location()); - this->advance_token(); - } - if (!this->peek_token()->is_op(OPERATOR_RSQUARE)) - { - error_at(this->location(), "expected %<]%>"); - return Type::make_error_type(); - } - this->advance_token(); - } - - Type* element_type = this->type(); - - return Type::make_array_type(element_type, length); -} - -// MapType = "map" "[" KeyType "]" ValueType . -// KeyType = CompleteType . -// ValueType = CompleteType . - -Type* -Parse::map_type() -{ - source_location location = this->location(); - gcc_assert(this->peek_token()->is_keyword(KEYWORD_MAP)); - if (!this->advance_token()->is_op(OPERATOR_LSQUARE)) - { - error_at(this->location(), "expected %<[%>"); - return Type::make_error_type(); - } - this->advance_token(); - - Type* key_type = this->type(); - - if (!this->peek_token()->is_op(OPERATOR_RSQUARE)) - { - error_at(this->location(), "expected %<]%>"); - return Type::make_error_type(); - } - this->advance_token(); - - Type* value_type = this->type(); - - if (key_type->is_error_type() || value_type->is_error_type()) - return Type::make_error_type(); - - return Type::make_map_type(key_type, value_type, location); -} - -// StructType = "struct" "{" { FieldDecl ";" } "}" . - -Type* -Parse::struct_type() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_STRUCT)); - source_location location = this->location(); - if (!this->advance_token()->is_op(OPERATOR_LCURLY)) - { - source_location token_loc = this->location(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(token_loc, "unexpected semicolon or newline before %<{%>"); - else - { - error_at(this->location(), "expected %<{%>"); - return Type::make_error_type(); - } - } - this->advance_token(); - - Struct_field_list* sfl = new Struct_field_list; - while (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - this->field_decl(sfl); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - else if (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - error_at(this->location(), "expected %<;%> or %<}%> or newline"); - if (!this->skip_past_error(OPERATOR_RCURLY)) - return Type::make_error_type(); - } - } - this->advance_token(); - - for (Struct_field_list::const_iterator pi = sfl->begin(); - pi != sfl->end(); - ++pi) - { - if (pi->type()->is_error_type()) - return pi->type(); - for (Struct_field_list::const_iterator pj = pi + 1; - pj != sfl->end(); - ++pj) - { - if (pi->field_name() == pj->field_name() - && !Gogo::is_sink_name(pi->field_name())) - error_at(pi->location(), "duplicate field name %<%s%>", - Gogo::message_name(pi->field_name()).c_str()); - } - } - - return Type::make_struct_type(sfl, location); -} - -// FieldDecl = (IdentifierList CompleteType | TypeName) [ Tag ] . -// Tag = string_lit . - -void -Parse::field_decl(Struct_field_list* sfl) -{ - const Token* token = this->peek_token(); - source_location location = token->location(); - bool is_anonymous; - bool is_anonymous_pointer; - if (token->is_op(OPERATOR_MULT)) - { - is_anonymous = true; - is_anonymous_pointer = true; - } - else if (token->is_identifier()) - { - std::string id = token->identifier(); - bool is_id_exported = token->is_identifier_exported(); - source_location id_location = token->location(); - token = this->advance_token(); - is_anonymous = (token->is_op(OPERATOR_SEMICOLON) - || token->is_op(OPERATOR_RCURLY) - || token->is_op(OPERATOR_DOT) - || token->is_string()); - is_anonymous_pointer = false; - this->unget_token(Token::make_identifier_token(id, is_id_exported, - id_location)); - } - else - { - error_at(this->location(), "expected field name"); - while (!token->is_op(OPERATOR_SEMICOLON) - && !token->is_op(OPERATOR_RCURLY) - && !token->is_eof()) - token = this->advance_token(); - return; - } - - if (is_anonymous) - { - if (is_anonymous_pointer) - { - this->advance_token(); - if (!this->peek_token()->is_identifier()) - { - error_at(this->location(), "expected field name"); - while (!token->is_op(OPERATOR_SEMICOLON) - && !token->is_op(OPERATOR_RCURLY) - && !token->is_eof()) - token = this->advance_token(); - return; - } - } - Type* type = this->type_name(true); - - std::string tag; - if (this->peek_token()->is_string()) - { - tag = this->peek_token()->string_value(); - this->advance_token(); - } - - if (!type->is_error_type()) - { - if (is_anonymous_pointer) - type = Type::make_pointer_type(type); - sfl->push_back(Struct_field(Typed_identifier("", type, location))); - if (!tag.empty()) - sfl->back().set_tag(tag); - } - } - else - { - Typed_identifier_list til; - while (true) - { - token = this->peek_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return; - } - std::string name = - this->gogo_->pack_hidden_name(token->identifier(), - token->is_identifier_exported()); - til.push_back(Typed_identifier(name, NULL, token->location())); - if (!this->advance_token()->is_op(OPERATOR_COMMA)) - break; - this->advance_token(); - } - - Type* type = this->type(); - - std::string tag; - if (this->peek_token()->is_string()) - { - tag = this->peek_token()->string_value(); - this->advance_token(); - } - - for (Typed_identifier_list::iterator p = til.begin(); - p != til.end(); - ++p) - { - p->set_type(type); - sfl->push_back(Struct_field(*p)); - if (!tag.empty()) - sfl->back().set_tag(tag); - } - } -} - -// PointerType = "*" Type . - -Type* -Parse::pointer_type() -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_MULT)); - this->advance_token(); - Type* type = this->type(); - if (type->is_error_type()) - return type; - return Type::make_pointer_type(type); -} - -// ChannelType = Channel | SendChannel | RecvChannel . -// Channel = "chan" ElementType . -// SendChannel = "chan" "<-" ElementType . -// RecvChannel = "<-" "chan" ElementType . - -Type* -Parse::channel_type() -{ - const Token* token = this->peek_token(); - bool send = true; - bool receive = true; - if (token->is_op(OPERATOR_CHANOP)) - { - if (!this->advance_token()->is_keyword(KEYWORD_CHAN)) - { - error_at(this->location(), "expected %"); - return Type::make_error_type(); - } - send = false; - this->advance_token(); - } - else - { - gcc_assert(token->is_keyword(KEYWORD_CHAN)); - if (this->advance_token()->is_op(OPERATOR_CHANOP)) - { - receive = false; - this->advance_token(); - } - } - Type* element_type = this->type(); - return Type::make_channel_type(send, receive, element_type); -} - -// Signature = Parameters [ Result ] . - -// RECEIVER is the receiver if there is one, or NULL. LOCATION is the -// location of the start of the type. - -Function_type* -Parse::signature(Typed_identifier* receiver, source_location location) -{ - bool is_varargs = false; - Typed_identifier_list* params = this->parameters(&is_varargs); - - Typed_identifier_list* result = NULL; - if (this->peek_token()->is_op(OPERATOR_LPAREN) - || this->type_may_start_here()) - result = this->result(); - - Function_type* ret = Type::make_function_type(receiver, params, result, - location); - if (is_varargs) - ret->set_is_varargs(); - return ret; -} - -// Parameters = "(" [ ParameterList [ "," ] ] ")" . - -Typed_identifier_list* -Parse::parameters(bool* is_varargs) -{ - if (!this->peek_token()->is_op(OPERATOR_LPAREN)) - { - error_at(this->location(), "expected %<(%>"); - return NULL; - } - - Typed_identifier_list* params = NULL; - - const Token* token = this->advance_token(); - if (!token->is_op(OPERATOR_RPAREN)) - { - params = this->parameter_list(is_varargs); - token = this->peek_token(); - } - - // The optional trailing comma is picked up in parameter_list. - - if (!token->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "expected %<)%>"); - else - this->advance_token(); - - return params; -} - -// ParameterList = ParameterDecl { "," ParameterDecl } . - -// This sets *IS_VARARGS if the list ends with an ellipsis. -// IS_VARARGS will be NULL if varargs are not permitted. - -// We pick up an optional trailing comma. - -Typed_identifier_list* -Parse::parameter_list(bool* is_varargs) -{ - source_location location = this->location(); - Typed_identifier_list* ret = new Typed_identifier_list(); - - // If we see an identifier and then a comma, then we don't know - // whether we are looking at a list of identifiers followed by a - // type, or a list of types given by name. We have to do an - // arbitrary lookahead to figure it out. - - bool parameters_have_names; - const Token* token = this->peek_token(); - if (!token->is_identifier()) - { - // This must be a type which starts with something like '*'. - parameters_have_names = false; - } - else - { - std::string name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - token = this->advance_token(); - if (!token->is_op(OPERATOR_COMMA)) - { - if (token->is_op(OPERATOR_DOT)) - { - // This is a qualified identifier, which must turn out - // to be a type. - parameters_have_names = false; - } - else if (token->is_op(OPERATOR_RPAREN)) - { - // A single identifier followed by a parenthesis must be - // a type name. - parameters_have_names = false; - } - else - { - // An identifier followed by something other than a - // comma or a dot or a right parenthesis must be a - // parameter name followed by a type. - parameters_have_names = true; - } - - this->unget_token(Token::make_identifier_token(name, is_exported, - location)); - } - else - { - // An identifier followed by a comma may be the first in a - // list of parameter names followed by a type, or it may be - // the first in a list of types without parameter names. To - // find out we gather as many identifiers separated by - // commas as we can. - std::string id_name = this->gogo_->pack_hidden_name(name, - is_exported); - ret->push_back(Typed_identifier(id_name, NULL, location)); - bool just_saw_comma = true; - while (this->advance_token()->is_identifier()) - { - name = this->peek_token()->identifier(); - is_exported = this->peek_token()->is_identifier_exported(); - location = this->peek_token()->location(); - id_name = this->gogo_->pack_hidden_name(name, is_exported); - ret->push_back(Typed_identifier(id_name, NULL, location)); - if (!this->advance_token()->is_op(OPERATOR_COMMA)) - { - just_saw_comma = false; - break; - } - } - - if (just_saw_comma) - { - // We saw ID1 "," ID2 "," followed by something which - // was not an identifier. We must be seeing the start - // of a type, and ID1 and ID2 must be types, and the - // parameters don't have names. - parameters_have_names = false; - } - else if (this->peek_token()->is_op(OPERATOR_RPAREN)) - { - // We saw ID1 "," ID2 ")". ID1 and ID2 must be types, - // and the parameters don't have names. - parameters_have_names = false; - } - else if (this->peek_token()->is_op(OPERATOR_DOT)) - { - // We saw ID1 "," ID2 ".". ID2 must be a package name, - // ID1 must be a type, and the parameters don't have - // names. - parameters_have_names = false; - this->unget_token(Token::make_identifier_token(name, is_exported, - location)); - ret->pop_back(); - just_saw_comma = true; - } - else - { - // We saw ID1 "," ID2 followed by something other than - // ",", ".", or ")". We must be looking at the start of - // a type, and ID1 and ID2 must be parameter names. - parameters_have_names = true; - } - - if (parameters_have_names) - { - gcc_assert(!just_saw_comma); - // We have just seen ID1, ID2 xxx. - Type* type; - if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS)) - type = this->type(); - else - { - error_at(this->location(), "%<...%> only permits one name"); - this->advance_token(); - type = this->type(); - } - for (size_t i = 0; i < ret->size(); ++i) - ret->set_type(i, type); - if (!this->peek_token()->is_op(OPERATOR_COMMA)) - return ret; - if (this->advance_token()->is_op(OPERATOR_RPAREN)) - return ret; - } - else - { - Typed_identifier_list* tret = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator p = ret->begin(); - p != ret->end(); - ++p) - { - Named_object* no = this->gogo_->lookup(p->name(), NULL); - Type* type; - if (no == NULL) - no = this->gogo_->add_unknown_name(p->name(), - p->location()); - - if (no->is_type()) - type = no->type_value(); - else if (no->is_unknown() || no->is_type_declaration()) - type = Type::make_forward_declaration(no); - else - { - error_at(p->location(), "expected %<%s%> to be a type", - Gogo::message_name(p->name()).c_str()); - type = Type::make_error_type(); - } - tret->push_back(Typed_identifier("", type, p->location())); - } - delete ret; - ret = tret; - if (!just_saw_comma - || this->peek_token()->is_op(OPERATOR_RPAREN)) - return ret; - } - } - } - - bool mix_error = false; - this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error); - while (this->peek_token()->is_op(OPERATOR_COMMA)) - { - if (is_varargs != NULL && *is_varargs) - error_at(this->location(), "%<...%> must be last parameter"); - if (this->advance_token()->is_op(OPERATOR_RPAREN)) - break; - this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error); - } - if (mix_error) - error_at(location, "invalid named/anonymous mix"); - return ret; -} - -// ParameterDecl = [ IdentifierList ] [ "..." ] Type . - -void -Parse::parameter_decl(bool parameters_have_names, - Typed_identifier_list* til, - bool* is_varargs, - bool* mix_error) -{ - if (!parameters_have_names) - { - Type* type; - source_location location = this->location(); - if (!this->peek_token()->is_identifier()) - { - if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS)) - type = this->type(); - else - { - if (is_varargs == NULL) - error_at(this->location(), "invalid use of %<...%>"); - else - *is_varargs = true; - this->advance_token(); - if (is_varargs == NULL - && this->peek_token()->is_op(OPERATOR_RPAREN)) - type = Type::make_error_type(); - else - { - Type* element_type = this->type(); - type = Type::make_array_type(element_type, NULL); - } - } - } - else - { - type = this->type_name(false); - if (type->is_error_type() - || (!this->peek_token()->is_op(OPERATOR_COMMA) - && !this->peek_token()->is_op(OPERATOR_RPAREN))) - { - *mix_error = true; - while (!this->peek_token()->is_op(OPERATOR_COMMA) - && !this->peek_token()->is_op(OPERATOR_RPAREN)) - this->advance_token(); - } - } - if (!type->is_error_type()) - til->push_back(Typed_identifier("", type, location)); - } - else - { - size_t orig_count = til->size(); - if (this->peek_token()->is_identifier()) - this->identifier_list(til); - else - *mix_error = true; - size_t new_count = til->size(); - - Type* type; - if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS)) - type = this->type(); - else - { - if (is_varargs == NULL) - error_at(this->location(), "invalid use of %<...%>"); - else if (new_count > orig_count + 1) - error_at(this->location(), "%<...%> only permits one name"); - else - *is_varargs = true; - this->advance_token(); - Type* element_type = this->type(); - type = Type::make_array_type(element_type, NULL); - } - for (size_t i = orig_count; i < new_count; ++i) - til->set_type(i, type); - } -} - -// Result = Parameters | Type . - -Typed_identifier_list* -Parse::result() -{ - if (this->peek_token()->is_op(OPERATOR_LPAREN)) - return this->parameters(NULL); - else - { - source_location location = this->location(); - Typed_identifier_list* til = new Typed_identifier_list(); - Type* type = this->type(); - til->push_back(Typed_identifier("", type, location)); - return til; - } -} - -// Block = "{" [ StatementList ] "}" . - -// Returns the location of the closing brace. - -source_location -Parse::block() -{ - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - { - source_location loc = this->location(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(loc, "unexpected semicolon or newline before %<{%>"); - else - { - error_at(this->location(), "expected %<{%>"); - return UNKNOWN_LOCATION; - } - } - - const Token* token = this->advance_token(); - - if (!token->is_op(OPERATOR_RCURLY)) - { - this->statement_list(); - token = this->peek_token(); - if (!token->is_op(OPERATOR_RCURLY)) - { - if (!token->is_eof() || !saw_errors()) - error_at(this->location(), "expected %<}%>"); - - // Skip ahead to the end of the block, in hopes of avoiding - // lots of meaningless errors. - source_location ret = token->location(); - int nest = 0; - while (!token->is_eof()) - { - if (token->is_op(OPERATOR_LCURLY)) - ++nest; - else if (token->is_op(OPERATOR_RCURLY)) - { - --nest; - if (nest < 0) - { - this->advance_token(); - break; - } - } - token = this->advance_token(); - ret = token->location(); - } - return ret; - } - } - - source_location ret = token->location(); - this->advance_token(); - return ret; -} - -// InterfaceType = "interface" "{" [ MethodSpecList ] "}" . -// MethodSpecList = MethodSpec { ";" MethodSpec } [ ";" ] . - -Type* -Parse::interface_type() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_INTERFACE)); - source_location location = this->location(); - - if (!this->advance_token()->is_op(OPERATOR_LCURLY)) - { - source_location token_loc = this->location(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(token_loc, "unexpected semicolon or newline before %<{%>"); - else - { - error_at(this->location(), "expected %<{%>"); - return Type::make_error_type(); - } - } - this->advance_token(); - - Typed_identifier_list* methods = new Typed_identifier_list(); - if (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - this->method_spec(methods); - while (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - if (this->advance_token()->is_op(OPERATOR_RCURLY)) - break; - this->method_spec(methods); - } - if (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - error_at(this->location(), "expected %<}%>"); - while (!this->advance_token()->is_op(OPERATOR_RCURLY)) - { - if (this->peek_token()->is_eof()) - return Type::make_error_type(); - } - } - } - this->advance_token(); - - if (methods->empty()) - { - delete methods; - methods = NULL; - } - - Interface_type* ret = Type::make_interface_type(methods, location); - this->gogo_->record_interface_type(ret); - return ret; -} - -// MethodSpec = MethodName Signature | InterfaceTypeName . -// MethodName = identifier . -// InterfaceTypeName = TypeName . - -bool -Parse::method_spec(Typed_identifier_list* methods) -{ - const Token* token = this->peek_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return false; - } - - std::string name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - - if (this->advance_token()->is_op(OPERATOR_LPAREN)) - { - // This is a MethodName. - name = this->gogo_->pack_hidden_name(name, is_exported); - Function_type* type = this->signature(NULL, location); - methods->push_back(Typed_identifier(name, type, location)); - } - else - { - this->unget_token(Token::make_identifier_token(name, is_exported, - location)); - Type* type = this->type_name(false); - if (type->is_error_type() - || (!this->peek_token()->is_op(OPERATOR_SEMICOLON) - && !this->peek_token()->is_op(OPERATOR_RCURLY))) - { - if (this->peek_token()->is_op(OPERATOR_COMMA)) - error_at(this->location(), - "name list not allowed in interface type"); - else - error_at(location, "expected signature or type name"); - token = this->peek_token(); - while (!token->is_eof() - && !token->is_op(OPERATOR_SEMICOLON) - && !token->is_op(OPERATOR_RCURLY)) - token = this->advance_token(); - return false; - } - // This must be an interface type, but we can't check that now. - // We check it and pull out the methods in - // Interface_type::do_verify. - methods->push_back(Typed_identifier("", type, location)); - } - - return false; -} - -// Declaration = ConstDecl | TypeDecl | VarDecl | FunctionDecl | MethodDecl . - -void -Parse::declaration() -{ - const Token* token = this->peek_token(); - if (token->is_keyword(KEYWORD_CONST)) - this->const_decl(); - else if (token->is_keyword(KEYWORD_TYPE)) - this->type_decl(); - else if (token->is_keyword(KEYWORD_VAR)) - this->var_decl(); - else if (token->is_keyword(KEYWORD_FUNC)) - this->function_decl(); - else - { - error_at(this->location(), "expected declaration"); - this->advance_token(); - } -} - -bool -Parse::declaration_may_start_here() -{ - const Token* token = this->peek_token(); - return (token->is_keyword(KEYWORD_CONST) - || token->is_keyword(KEYWORD_TYPE) - || token->is_keyword(KEYWORD_VAR) - || token->is_keyword(KEYWORD_FUNC)); -} - -// Decl

= P | "(" [ List

] ")" . - -void -Parse::decl(void (Parse::*pfn)(void*), void* varg) -{ - if (!this->peek_token()->is_op(OPERATOR_LPAREN)) - (this->*pfn)(varg); - else - { - if (!this->advance_token()->is_op(OPERATOR_RPAREN)) - { - this->list(pfn, varg, true); - if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - { - error_at(this->location(), "missing %<)%>"); - while (!this->advance_token()->is_op(OPERATOR_RPAREN)) - { - if (this->peek_token()->is_eof()) - return; - } - } - } - this->advance_token(); - } -} - -// List

= P { ";" P } [ ";" ] . - -// In order to pick up the trailing semicolon we need to know what -// might follow. This is either a '}' or a ')'. - -void -Parse::list(void (Parse::*pfn)(void*), void* varg, bool follow_is_paren) -{ - (this->*pfn)(varg); - Operator follow = follow_is_paren ? OPERATOR_RPAREN : OPERATOR_RCURLY; - while (this->peek_token()->is_op(OPERATOR_SEMICOLON) - || this->peek_token()->is_op(OPERATOR_COMMA)) - { - if (this->peek_token()->is_op(OPERATOR_COMMA)) - error_at(this->location(), "unexpected comma"); - if (this->advance_token()->is_op(follow)) - break; - (this->*pfn)(varg); - } -} - -// ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) . - -void -Parse::const_decl() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_CONST)); - this->advance_token(); - this->reset_iota(); - - Type* last_type = NULL; - Expression_list* last_expr_list = NULL; - - if (!this->peek_token()->is_op(OPERATOR_LPAREN)) - this->const_spec(&last_type, &last_expr_list); - else - { - this->advance_token(); - while (!this->peek_token()->is_op(OPERATOR_RPAREN)) - { - this->const_spec(&last_type, &last_expr_list); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - else if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - { - error_at(this->location(), "expected %<;%> or %<)%> or newline"); - if (!this->skip_past_error(OPERATOR_RPAREN)) - return; - } - } - this->advance_token(); - } - - if (last_expr_list != NULL) - delete last_expr_list; -} - -// ConstSpec = IdentifierList [ [ CompleteType ] "=" ExpressionList ] . - -void -Parse::const_spec(Type** last_type, Expression_list** last_expr_list) -{ - Typed_identifier_list til; - this->identifier_list(&til); - - Type* type = NULL; - if (this->type_may_start_here()) - { - type = this->type(); - *last_type = NULL; - *last_expr_list = NULL; - } - - Expression_list *expr_list; - if (!this->peek_token()->is_op(OPERATOR_EQ)) - { - if (*last_expr_list == NULL) - { - error_at(this->location(), "expected %<=%>"); - return; - } - type = *last_type; - expr_list = new Expression_list; - for (Expression_list::const_iterator p = (*last_expr_list)->begin(); - p != (*last_expr_list)->end(); - ++p) - expr_list->push_back((*p)->copy()); - } - else - { - this->advance_token(); - expr_list = this->expression_list(NULL, false); - *last_type = type; - if (*last_expr_list != NULL) - delete *last_expr_list; - *last_expr_list = expr_list; - } - - Expression_list::const_iterator pe = expr_list->begin(); - for (Typed_identifier_list::iterator pi = til.begin(); - pi != til.end(); - ++pi, ++pe) - { - if (pe == expr_list->end()) - { - error_at(this->location(), "not enough initializers"); - return; - } - if (type != NULL) - pi->set_type(type); - - if (!Gogo::is_sink_name(pi->name())) - this->gogo_->add_constant(*pi, *pe, this->iota_value()); - } - if (pe != expr_list->end()) - error_at(this->location(), "too many initializers"); - - this->increment_iota(); - - return; -} - -// TypeDecl = "type" Decl . - -void -Parse::type_decl() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_TYPE)); - this->advance_token(); - this->decl(&Parse::type_spec, NULL); -} - -// TypeSpec = identifier Type . - -void -Parse::type_spec(void*) -{ - const Token* token = this->peek_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return; - } - std::string name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - token = this->advance_token(); - - // The scope of the type name starts at the point where the - // identifier appears in the source code. We implement this by - // declaring the type before we read the type definition. - Named_object* named_type = NULL; - if (name != "_") - { - name = this->gogo_->pack_hidden_name(name, is_exported); - named_type = this->gogo_->declare_type(name, location); - } - - Type* type; - if (!this->peek_token()->is_op(OPERATOR_SEMICOLON)) - type = this->type(); - else - { - error_at(this->location(), - "unexpected semicolon or newline in type declaration"); - type = Type::make_error_type(); - this->advance_token(); - } - - if (type->is_error_type()) - { - while (!this->peek_token()->is_op(OPERATOR_SEMICOLON) - && !this->peek_token()->is_eof()) - this->advance_token(); - } - - if (name != "_") - { - if (named_type->is_type_declaration()) - { - Type* ftype = type->forwarded(); - if (ftype->forward_declaration_type() != NULL - && (ftype->forward_declaration_type()->named_object() - == named_type)) - { - error_at(location, "invalid recursive type"); - type = Type::make_error_type(); - } - - this->gogo_->define_type(named_type, - Type::make_named_type(named_type, type, - location)); - gcc_assert(named_type->package() == NULL); - } - else - { - // This will probably give a redefinition error. - this->gogo_->add_type(name, type, location); - } - } -} - -// VarDecl = "var" Decl . - -void -Parse::var_decl() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_VAR)); - this->advance_token(); - this->decl(&Parse::var_spec, NULL); -} - -// VarSpec = IdentifierList -// ( CompleteType [ "=" ExpressionList ] | "=" ExpressionList ) . - -void -Parse::var_spec(void*) -{ - // Get the variable names. - Typed_identifier_list til; - this->identifier_list(&til); - - source_location location = this->location(); - - Type* type = NULL; - Expression_list* init = NULL; - if (!this->peek_token()->is_op(OPERATOR_EQ)) - { - type = this->type(); - if (type->is_error_type()) - { - while (!this->peek_token()->is_op(OPERATOR_EQ) - && !this->peek_token()->is_op(OPERATOR_SEMICOLON) - && !this->peek_token()->is_eof()) - this->advance_token(); - } - if (this->peek_token()->is_op(OPERATOR_EQ)) - { - this->advance_token(); - init = this->expression_list(NULL, false); - } - } - else - { - this->advance_token(); - init = this->expression_list(NULL, false); - } - - this->init_vars(&til, type, init, false, location); - - if (init != NULL) - delete init; -} - -// Create variables. TIL is a list of variable names. If TYPE is not -// NULL, it is the type of all the variables. If INIT is not NULL, it -// is an initializer list for the variables. - -void -Parse::init_vars(const Typed_identifier_list* til, Type* type, - Expression_list* init, bool is_coloneq, - source_location location) -{ - // Check for an initialization which can yield multiple values. - if (init != NULL && init->size() == 1 && til->size() > 1) - { - if (this->init_vars_from_call(til, type, *init->begin(), is_coloneq, - location)) - return; - if (this->init_vars_from_map(til, type, *init->begin(), is_coloneq, - location)) - return; - if (this->init_vars_from_receive(til, type, *init->begin(), is_coloneq, - location)) - return; - if (this->init_vars_from_type_guard(til, type, *init->begin(), - is_coloneq, location)) - return; - } - - if (init != NULL && init->size() != til->size()) - { - if (init->empty() || !init->front()->is_error_expression()) - error_at(location, "wrong number of initializations"); - init = NULL; - if (type == NULL) - type = Type::make_error_type(); - } - - // Note that INIT was already parsed with the old name bindings, so - // we don't have to worry that it will accidentally refer to the - // newly declared variables. - - Expression_list::const_iterator pexpr; - if (init != NULL) - pexpr = init->begin(); - bool any_new = false; - for (Typed_identifier_list::const_iterator p = til->begin(); - p != til->end(); - ++p) - { - if (init != NULL) - gcc_assert(pexpr != init->end()); - this->init_var(*p, type, init == NULL ? NULL : *pexpr, is_coloneq, - false, &any_new); - if (init != NULL) - ++pexpr; - } - if (init != NULL) - gcc_assert(pexpr == init->end()); - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); -} - -// See if we need to initialize a list of variables from a function -// call. This returns true if we have set up the variables and the -// initialization. - -bool -Parse::init_vars_from_call(const Typed_identifier_list* vars, Type* type, - Expression* expr, bool is_coloneq, - source_location location) -{ - Call_expression* call = expr->call_expression(); - if (call == NULL) - return false; - - // This is a function call. We can't check here whether it returns - // the right number of values, but it might. Declare the variables, - // and then assign the results of the call to them. - - unsigned int index = 0; - bool any_new = false; - for (Typed_identifier_list::const_iterator pv = vars->begin(); - pv != vars->end(); - ++pv, ++index) - { - Expression* init = Expression::make_call_result(call, index); - this->init_var(*pv, type, init, is_coloneq, false, &any_new); - } - - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); - - return true; -} - -// See if we need to initialize a pair of values from a map index -// expression. This returns true if we have set up the variables and -// the initialization. - -bool -Parse::init_vars_from_map(const Typed_identifier_list* vars, Type* type, - Expression* expr, bool is_coloneq, - source_location location) -{ - Index_expression* index = expr->index_expression(); - if (index == NULL) - return false; - if (vars->size() != 2) - return false; - - // This is an index which is being assigned to two variables. It - // must be a map index. Declare the variables, and then assign the - // results of the map index. - bool any_new = false; - Typed_identifier_list::const_iterator p = vars->begin(); - Expression* init = type == NULL ? index : NULL; - Named_object* val_no = this->init_var(*p, type, init, is_coloneq, - type == NULL, &any_new); - if (type == NULL && any_new && val_no->is_variable()) - val_no->var_value()->set_type_from_init_tuple(); - Expression* val_var = Expression::make_var_reference(val_no, location); - - ++p; - Type* var_type = type; - if (var_type == NULL) - var_type = Type::lookup_bool_type(); - Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false, - &any_new); - Expression* present_var = Expression::make_var_reference(no, location); - - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); - - Statement* s = Statement::make_tuple_map_assignment(val_var, present_var, - index, location); - - if (!this->gogo_->in_global_scope()) - this->gogo_->add_statement(s); - else - val_no->var_value()->add_preinit_statement(s); - - return true; -} - -// See if we need to initialize a pair of values from a receive -// expression. This returns true if we have set up the variables and -// the initialization. - -bool -Parse::init_vars_from_receive(const Typed_identifier_list* vars, Type* type, - Expression* expr, bool is_coloneq, - source_location location) -{ - Receive_expression* receive = expr->receive_expression(); - if (receive == NULL) - return false; - if (vars->size() != 2) - return false; - - // This is a receive expression which is being assigned to two - // variables. Declare the variables, and then assign the results of - // the receive. - bool any_new = false; - Typed_identifier_list::const_iterator p = vars->begin(); - Expression* init = type == NULL ? receive : NULL; - Named_object* val_no = this->init_var(*p, type, init, is_coloneq, - type == NULL, &any_new); - if (type == NULL && any_new && val_no->is_variable()) - val_no->var_value()->set_type_from_init_tuple(); - Expression* val_var = Expression::make_var_reference(val_no, location); - - ++p; - Type* var_type = type; - if (var_type == NULL) - var_type = Type::lookup_bool_type(); - Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false, - &any_new); - Expression* received_var = Expression::make_var_reference(no, location); - - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); - - Statement* s = Statement::make_tuple_receive_assignment(val_var, - received_var, - receive->channel(), - location); - - if (!this->gogo_->in_global_scope()) - this->gogo_->add_statement(s); - else - val_no->var_value()->add_preinit_statement(s); - - return true; -} - -// See if we need to initialize a pair of values from a type guard -// expression. This returns true if we have set up the variables and -// the initialization. - -bool -Parse::init_vars_from_type_guard(const Typed_identifier_list* vars, - Type* type, Expression* expr, - bool is_coloneq, source_location location) -{ - Type_guard_expression* type_guard = expr->type_guard_expression(); - if (type_guard == NULL) - return false; - if (vars->size() != 2) - return false; - - // This is a type guard expression which is being assigned to two - // variables. Declare the variables, and then assign the results of - // the type guard. - bool any_new = false; - Typed_identifier_list::const_iterator p = vars->begin(); - Type* var_type = type; - if (var_type == NULL) - var_type = type_guard->type(); - Named_object* val_no = this->init_var(*p, var_type, NULL, is_coloneq, false, - &any_new); - Expression* val_var = Expression::make_var_reference(val_no, location); - - ++p; - var_type = type; - if (var_type == NULL) - var_type = Type::lookup_bool_type(); - Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false, - &any_new); - Expression* ok_var = Expression::make_var_reference(no, location); - - Expression* texpr = type_guard->expr(); - Type* t = type_guard->type(); - Statement* s = Statement::make_tuple_type_guard_assignment(val_var, ok_var, - texpr, t, - location); - - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); - - if (!this->gogo_->in_global_scope()) - this->gogo_->add_statement(s); - else - val_no->var_value()->add_preinit_statement(s); - - return true; -} - -// Create a single variable. If IS_COLONEQ is true, we permit -// redeclarations in the same block, and we set *IS_NEW when we find a -// new variable which is not a redeclaration. - -Named_object* -Parse::init_var(const Typed_identifier& tid, Type* type, Expression* init, - bool is_coloneq, bool type_from_init, bool* is_new) -{ - source_location location = tid.location(); - - if (Gogo::is_sink_name(tid.name())) - { - if (!type_from_init && init != NULL) - { - if (!this->gogo_->in_global_scope()) - this->gogo_->add_statement(Statement::make_statement(init)); - else - { - // Create a dummy global variable to force the - // initializer to be run in the right place. - Variable* var = new Variable(type, init, true, false, false, - location); - static int count; - char buf[30]; - snprintf(buf, sizeof buf, "_.%d", count); - ++count; - return this->gogo_->add_variable(buf, var); - } - } - return this->gogo_->add_sink(); - } - - if (is_coloneq) - { - Named_object* no = this->gogo_->lookup_in_block(tid.name()); - if (no != NULL - && (no->is_variable() || no->is_result_variable())) - { - // INIT may be NULL even when IS_COLONEQ is true for cases - // like v, ok := x.(int). - if (!type_from_init && init != NULL) - { - Expression *v = Expression::make_var_reference(no, location); - Statement *s = Statement::make_assignment(v, init, location); - this->gogo_->add_statement(s); - } - return no; - } - } - *is_new = true; - Variable* var = new Variable(type, init, this->gogo_->in_global_scope(), - false, false, location); - return this->gogo_->add_variable(tid.name(), var); -} - -// SimpleVarDecl = identifier ":=" Expression . - -// We've already seen the identifier. - -// FIXME: We also have to implement -// IdentifierList ":=" ExpressionList -// In order to support both "a, b := 1, 0" and "a, b = 1, 0" we accept -// tuple assignments here as well. - -// If P_RANGE_CLAUSE is not NULL, then this will recognize a -// RangeClause. - -// If P_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -void -Parse::simple_var_decl_or_assignment(const std::string& name, - source_location location, - Range_clause* p_range_clause, - Type_switch* p_type_switch) -{ - Typed_identifier_list til; - til.push_back(Typed_identifier(name, NULL, location)); - - // We've seen one identifier. If we see a comma now, this could be - // "a, *p = 1, 2". - if (this->peek_token()->is_op(OPERATOR_COMMA)) - { - gcc_assert(p_type_switch == NULL); - while (true) - { - const Token* token = this->advance_token(); - if (!token->is_identifier()) - break; - - std::string id = token->identifier(); - bool is_id_exported = token->is_identifier_exported(); - source_location id_location = token->location(); - - token = this->advance_token(); - if (!token->is_op(OPERATOR_COMMA)) - { - if (token->is_op(OPERATOR_COLONEQ)) - { - id = this->gogo_->pack_hidden_name(id, is_id_exported); - til.push_back(Typed_identifier(id, NULL, location)); - } - else - this->unget_token(Token::make_identifier_token(id, - is_id_exported, - id_location)); - break; - } - - id = this->gogo_->pack_hidden_name(id, is_id_exported); - til.push_back(Typed_identifier(id, NULL, location)); - } - - // We have a comma separated list of identifiers in TIL. If the - // next token is COLONEQ, then this is a simple var decl, and we - // have the complete list of identifiers. If the next token is - // not COLONEQ, then the only valid parse is a tuple assignment. - // The list of identifiers we have so far is really a list of - // expressions. There are more expressions following. - - if (!this->peek_token()->is_op(OPERATOR_COLONEQ)) - { - Expression_list* exprs = new Expression_list; - for (Typed_identifier_list::const_iterator p = til.begin(); - p != til.end(); - ++p) - exprs->push_back(this->id_to_expression(p->name(), - p->location())); - - Expression_list* more_exprs = this->expression_list(NULL, true); - for (Expression_list::const_iterator p = more_exprs->begin(); - p != more_exprs->end(); - ++p) - exprs->push_back(*p); - delete more_exprs; - - this->tuple_assignment(exprs, p_range_clause); - return; - } - } - - gcc_assert(this->peek_token()->is_op(OPERATOR_COLONEQ)); - const Token* token = this->advance_token(); - - if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE)) - { - this->range_clause_decl(&til, p_range_clause); - return; - } - - Expression_list* init; - if (p_type_switch == NULL) - init = this->expression_list(NULL, false); - else - { - bool is_type_switch = false; - Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, - &is_type_switch); - if (is_type_switch) - { - p_type_switch->found = true; - p_type_switch->name = name; - p_type_switch->location = location; - p_type_switch->expr = expr; - return; - } - - if (!this->peek_token()->is_op(OPERATOR_COMMA)) - { - init = new Expression_list(); - init->push_back(expr); - } - else - { - this->advance_token(); - init = this->expression_list(expr, false); - } - } - - this->init_vars(&til, NULL, init, true, location); -} - -// FunctionDecl = "func" identifier Signature [ Block ] . -// MethodDecl = "func" Receiver identifier Signature [ Block ] . - -// gcc extension: -// FunctionDecl = "func" identifier Signature -// __asm__ "(" string_lit ")" . -// This extension means a function whose real name is the identifier -// inside the asm. - -void -Parse::function_decl() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_FUNC)); - source_location location = this->location(); - const Token* token = this->advance_token(); - - Typed_identifier* rec = NULL; - if (token->is_op(OPERATOR_LPAREN)) - { - rec = this->receiver(); - token = this->peek_token(); - } - - if (!token->is_identifier()) - { - error_at(this->location(), "expected function name"); - return; - } - - std::string name = - this->gogo_->pack_hidden_name(token->identifier(), - token->is_identifier_exported()); - - this->advance_token(); - - Function_type* fntype = this->signature(rec, this->location()); - - Named_object* named_object = NULL; - - if (this->peek_token()->is_keyword(KEYWORD_ASM)) - { - if (!this->advance_token()->is_op(OPERATOR_LPAREN)) - { - error_at(this->location(), "expected %<(%>"); - return; - } - token = this->advance_token(); - if (!token->is_string()) - { - error_at(this->location(), "expected string"); - return; - } - std::string asm_name = token->string_value(); - if (!this->advance_token()->is_op(OPERATOR_RPAREN)) - { - error_at(this->location(), "expected %<)%>"); - return; - } - this->advance_token(); - named_object = this->gogo_->declare_function(name, fntype, location); - if (named_object->is_function_declaration()) - named_object->func_declaration_value()->set_asm_name(asm_name); - } - - // Check for the easy error of a newline before the opening brace. - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - source_location semi_loc = this->location(); - if (this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(this->location(), - "unexpected semicolon or newline before %<{%>"); - else - this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON, - semi_loc)); - } - - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - { - if (named_object == NULL) - named_object = this->gogo_->declare_function(name, fntype, location); - } - else - { - this->gogo_->start_function(name, fntype, true, location); - source_location end_loc = this->block(); - this->gogo_->finish_function(end_loc); - } -} - -// Receiver = "(" [ identifier ] [ "*" ] BaseTypeName ")" . -// BaseTypeName = identifier . - -Typed_identifier* -Parse::receiver() -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_LPAREN)); - - std::string name; - const Token* token = this->advance_token(); - source_location location = token->location(); - if (!token->is_op(OPERATOR_MULT)) - { - if (!token->is_identifier()) - { - error_at(this->location(), "method has no receiver"); - while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN)) - token = this->advance_token(); - if (!token->is_eof()) - this->advance_token(); - return NULL; - } - name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - token = this->advance_token(); - if (!token->is_op(OPERATOR_DOT) && !token->is_op(OPERATOR_RPAREN)) - { - // An identifier followed by something other than a dot or a - // right parenthesis must be a receiver name followed by a - // type. - name = this->gogo_->pack_hidden_name(name, is_exported); - } - else - { - // This must be a type name. - this->unget_token(Token::make_identifier_token(name, is_exported, - location)); - token = this->peek_token(); - name.clear(); - } - } - - // Here the receiver name is in NAME (it is empty if the receiver is - // unnamed) and TOKEN is the first token in the type. - - bool is_pointer = false; - if (token->is_op(OPERATOR_MULT)) - { - is_pointer = true; - token = this->advance_token(); - } - - if (!token->is_identifier()) - { - error_at(this->location(), "expected receiver name or type"); - int c = token->is_op(OPERATOR_LPAREN) ? 1 : 0; - while (!token->is_eof()) - { - token = this->advance_token(); - if (token->is_op(OPERATOR_LPAREN)) - ++c; - else if (token->is_op(OPERATOR_RPAREN)) - { - if (c == 0) - break; - --c; - } - } - if (!token->is_eof()) - this->advance_token(); - return NULL; - } - - Type* type = this->type_name(true); - - if (is_pointer && !type->is_error_type()) - type = Type::make_pointer_type(type); - - if (this->peek_token()->is_op(OPERATOR_RPAREN)) - this->advance_token(); - else - { - if (this->peek_token()->is_op(OPERATOR_COMMA)) - error_at(this->location(), "method has multiple receivers"); - else - error_at(this->location(), "expected %<)%>"); - while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN)) - token = this->advance_token(); - if (!token->is_eof()) - this->advance_token(); - return NULL; - } - - return new Typed_identifier(name, type, location); -} - -// Operand = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" . -// Literal = BasicLit | CompositeLit | FunctionLit . -// BasicLit = int_lit | float_lit | imaginary_lit | char_lit | string_lit . - -// If MAY_BE_SINK is true, this operand may be "_". - -Expression* -Parse::operand(bool may_be_sink) -{ - const Token* token = this->peek_token(); - Expression* ret; - switch (token->classification()) - { - case Token::TOKEN_IDENTIFIER: - { - source_location location = token->location(); - std::string id = token->identifier(); - bool is_exported = token->is_identifier_exported(); - std::string packed = this->gogo_->pack_hidden_name(id, is_exported); - - Named_object* in_function; - Named_object* named_object = this->gogo_->lookup(packed, &in_function); - - Package* package = NULL; - if (named_object != NULL && named_object->is_package()) - { - if (!this->advance_token()->is_op(OPERATOR_DOT) - || !this->advance_token()->is_identifier()) - { - error_at(location, "unexpected reference to package"); - return Expression::make_error(location); - } - package = named_object->package_value(); - package->set_used(); - id = this->peek_token()->identifier(); - is_exported = this->peek_token()->is_identifier_exported(); - packed = this->gogo_->pack_hidden_name(id, is_exported); - named_object = package->lookup(packed); - location = this->location(); - gcc_assert(in_function == NULL); - } - - this->advance_token(); - - if (named_object != NULL - && named_object->is_type() - && !named_object->type_value()->is_visible()) - { - gcc_assert(package != NULL); - error_at(location, "invalid reference to hidden type %<%s.%s%>", - Gogo::message_name(package->name()).c_str(), - Gogo::message_name(id).c_str()); - return Expression::make_error(location); - } - - - if (named_object == NULL) - { - if (package != NULL) - { - std::string n1 = Gogo::message_name(package->name()); - std::string n2 = Gogo::message_name(id); - if (!is_exported) - error_at(location, - ("invalid reference to unexported identifier " - "%<%s.%s%>"), - n1.c_str(), n2.c_str()); - else - error_at(location, - "reference to undefined identifier %<%s.%s%>", - n1.c_str(), n2.c_str()); - return Expression::make_error(location); - } - - named_object = this->gogo_->add_unknown_name(packed, location); - } - - if (in_function != NULL - && in_function != this->gogo_->current_function() - && (named_object->is_variable() - || named_object->is_result_variable())) - return this->enclosing_var_reference(in_function, named_object, - location); - - switch (named_object->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - return Expression::make_const_reference(named_object, location); - case Named_object::NAMED_OBJECT_TYPE: - return Expression::make_type(named_object->type_value(), location); - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - { - Type* t = Type::make_forward_declaration(named_object); - return Expression::make_type(t, location); - } - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - return Expression::make_var_reference(named_object, location); - case Named_object::NAMED_OBJECT_SINK: - if (may_be_sink) - return Expression::make_sink(location); - else - { - error_at(location, "cannot use _ as value"); - return Expression::make_error(location); - } - case Named_object::NAMED_OBJECT_FUNC: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - return Expression::make_func_reference(named_object, NULL, - location); - case Named_object::NAMED_OBJECT_UNKNOWN: - return Expression::make_unknown_reference(named_object, location); - default: - gcc_unreachable(); - } - } - gcc_unreachable(); - - case Token::TOKEN_STRING: - ret = Expression::make_string(token->string_value(), token->location()); - this->advance_token(); - return ret; - - case Token::TOKEN_INTEGER: - ret = Expression::make_integer(token->integer_value(), NULL, - token->location()); - this->advance_token(); - return ret; - - case Token::TOKEN_FLOAT: - ret = Expression::make_float(token->float_value(), NULL, - token->location()); - this->advance_token(); - return ret; - - case Token::TOKEN_IMAGINARY: - { - mpfr_t zero; - mpfr_init_set_ui(zero, 0, GMP_RNDN); - ret = Expression::make_complex(&zero, token->imaginary_value(), - NULL, token->location()); - mpfr_clear(zero); - this->advance_token(); - return ret; - } - - case Token::TOKEN_KEYWORD: - switch (token->keyword()) - { - case KEYWORD_FUNC: - return this->function_lit(); - case KEYWORD_CHAN: - case KEYWORD_INTERFACE: - case KEYWORD_MAP: - case KEYWORD_STRUCT: - { - source_location location = token->location(); - return Expression::make_type(this->type(), location); - } - default: - break; - } - break; - - case Token::TOKEN_OPERATOR: - if (token->is_op(OPERATOR_LPAREN)) - { - this->advance_token(); - ret = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "missing %<)%>"); - else - this->advance_token(); - return ret; - } - else if (token->is_op(OPERATOR_LSQUARE)) - { - // Here we call array_type directly, as this is the only - // case where an ellipsis is permitted for an array type. - source_location location = token->location(); - return Expression::make_type(this->array_type(true), location); - } - break; - - default: - break; - } - - error_at(this->location(), "expected operand"); - return Expression::make_error(this->location()); -} - -// Handle a reference to a variable in an enclosing function. We add -// it to a list of such variables. We return a reference to a field -// in a struct which will be passed on the static chain when calling -// the current function. - -Expression* -Parse::enclosing_var_reference(Named_object* in_function, Named_object* var, - source_location location) -{ - gcc_assert(var->is_variable() || var->is_result_variable()); - - Named_object* this_function = this->gogo_->current_function(); - Named_object* closure = this_function->func_value()->closure_var(); - - Enclosing_var ev(var, in_function, this->enclosing_vars_.size()); - std::pair ins = - this->enclosing_vars_.insert(ev); - if (ins.second) - { - // This is a variable we have not seen before. Add a new field - // to the closure type. - this_function->func_value()->add_closure_field(var, location); - } - - Expression* closure_ref = Expression::make_var_reference(closure, - location); - closure_ref = Expression::make_unary(OPERATOR_MULT, closure_ref, location); - - // The closure structure holds pointers to the variables, so we need - // to introduce an indirection. - Expression* e = Expression::make_field_reference(closure_ref, - ins.first->index(), - location); - e = Expression::make_unary(OPERATOR_MULT, e, location); - return e; -} - -// CompositeLit = LiteralType LiteralValue . -// LiteralType = StructType | ArrayType | "[" "..." "]" ElementType | -// SliceType | MapType | TypeName . -// LiteralValue = "{" [ ElementList [ "," ] ] "}" . -// ElementList = Element { "," Element } . -// Element = [ Key ":" ] Value . -// Key = Expression . -// Value = Expression | LiteralValue . - -// We have already seen the type if there is one, and we are now -// looking at the LiteralValue. The case "[" "..." "]" ElementType -// will be seen here as an array type whose length is "nil". The -// DEPTH parameter is non-zero if this is an embedded composite -// literal and the type was omitted. It gives the number of steps up -// to the type which was provided. E.g., in [][]int{{1}} it will be -// 1. In [][][]int{{{1}}} it will be 2. - -Expression* -Parse::composite_lit(Type* type, int depth, source_location location) -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_LCURLY)); - this->advance_token(); - - if (this->peek_token()->is_op(OPERATOR_RCURLY)) - { - this->advance_token(); - return Expression::make_composite_literal(type, depth, false, NULL, - location); - } - - bool has_keys = false; - Expression_list* vals = new Expression_list; - while (true) - { - Expression* val; - bool is_type_omitted = false; - - const Token* token = this->peek_token(); - - if (!token->is_op(OPERATOR_LCURLY)) - val = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - else - { - // This must be a composite literal inside another composite - // literal, with the type omitted for the inner one. - val = this->composite_lit(type, depth + 1, token->location()); - is_type_omitted = true; - } - - token = this->peek_token(); - if (!token->is_op(OPERATOR_COLON)) - { - if (has_keys) - vals->push_back(NULL); - } - else - { - if (is_type_omitted && !val->is_error_expression()) - { - error_at(this->location(), "unexpected %<:%>"); - val = Expression::make_error(this->location()); - } - - this->advance_token(); - - if (!has_keys && !vals->empty()) - { - Expression_list* newvals = new Expression_list; - for (Expression_list::const_iterator p = vals->begin(); - p != vals->end(); - ++p) - { - newvals->push_back(NULL); - newvals->push_back(*p); - } - delete vals; - vals = newvals; - } - has_keys = true; - - if (val->unknown_expression() != NULL) - val->unknown_expression()->set_is_composite_literal_key(); - - vals->push_back(val); - - if (!token->is_op(OPERATOR_LCURLY)) - val = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - else - { - // This must be a composite literal inside another - // composite literal, with the type omitted for the - // inner one. - val = this->composite_lit(type, depth + 1, token->location()); - } - - token = this->peek_token(); - } - - vals->push_back(val); - - if (token->is_op(OPERATOR_COMMA)) - { - if (this->advance_token()->is_op(OPERATOR_RCURLY)) - { - this->advance_token(); - break; - } - } - else if (token->is_op(OPERATOR_RCURLY)) - { - this->advance_token(); - break; - } - else - { - error_at(this->location(), "expected %<,%> or %<}%>"); - - int depth = 0; - while (!token->is_eof() - && (depth > 0 || !token->is_op(OPERATOR_RCURLY))) - { - if (token->is_op(OPERATOR_LCURLY)) - ++depth; - else if (token->is_op(OPERATOR_RCURLY)) - --depth; - token = this->advance_token(); - } - if (token->is_op(OPERATOR_RCURLY)) - this->advance_token(); - - return Expression::make_error(location); - } - } - - return Expression::make_composite_literal(type, depth, has_keys, vals, - location); -} - -// FunctionLit = "func" Signature Block . - -Expression* -Parse::function_lit() -{ - source_location location = this->location(); - gcc_assert(this->peek_token()->is_keyword(KEYWORD_FUNC)); - this->advance_token(); - - Enclosing_vars hold_enclosing_vars; - hold_enclosing_vars.swap(this->enclosing_vars_); - - Function_type* type = this->signature(NULL, location); - - // For a function literal, the next token must be a '{'. If we - // don't see that, then we may have a type expression. - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - return Expression::make_type(type, location); - - Named_object* no = this->gogo_->start_function("", type, true, location); - - source_location end_loc = this->block(); - - this->gogo_->finish_function(end_loc); - - hold_enclosing_vars.swap(this->enclosing_vars_); - - Expression* closure = this->create_closure(no, &hold_enclosing_vars, - location); - - return Expression::make_func_reference(no, closure, location); -} - -// Create a closure for the nested function FUNCTION. This is based -// on ENCLOSING_VARS, which is a list of all variables defined in -// enclosing functions and referenced from FUNCTION. A closure is the -// address of a struct which contains the addresses of all the -// referenced variables. This returns NULL if no closure is required. - -Expression* -Parse::create_closure(Named_object* function, Enclosing_vars* enclosing_vars, - source_location location) -{ - if (enclosing_vars->empty()) - return NULL; - - // Get the variables in order by their field index. - - size_t enclosing_var_count = enclosing_vars->size(); - std::vector ev(enclosing_var_count); - for (Enclosing_vars::const_iterator p = enclosing_vars->begin(); - p != enclosing_vars->end(); - ++p) - ev[p->index()] = *p; - - // Build an initializer for a composite literal of the closure's - // type. - - Named_object* enclosing_function = this->gogo_->current_function(); - Expression_list* initializer = new Expression_list; - for (size_t i = 0; i < enclosing_var_count; ++i) - { - gcc_assert(ev[i].index() == i); - Named_object* var = ev[i].var(); - Expression* ref; - if (ev[i].in_function() == enclosing_function) - ref = Expression::make_var_reference(var, location); - else - ref = this->enclosing_var_reference(ev[i].in_function(), var, - location); - Expression* refaddr = Expression::make_unary(OPERATOR_AND, ref, - location); - initializer->push_back(refaddr); - } - - Named_object* closure_var = function->func_value()->closure_var(); - Struct_type* st = closure_var->var_value()->type()->deref()->struct_type(); - Expression* cv = Expression::make_struct_composite_literal(st, initializer, - location); - return Expression::make_heap_composite(cv, location); -} - -// PrimaryExpr = Operand { Selector | Index | Slice | TypeGuard | Call } . - -// If MAY_BE_SINK is true, this expression may be "_". - -// If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite -// literal. - -// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::primary_expr(bool may_be_sink, bool may_be_composite_lit, - bool* is_type_switch) -{ - source_location start_loc = this->location(); - bool is_parenthesized = this->peek_token()->is_op(OPERATOR_LPAREN); - - Expression* ret = this->operand(may_be_sink); - - // An unknown name followed by a curly brace must be a composite - // literal, and the unknown name must be a type. - if (may_be_composite_lit - && !is_parenthesized - && ret->unknown_expression() != NULL - && this->peek_token()->is_op(OPERATOR_LCURLY)) - { - Named_object* no = ret->unknown_expression()->named_object(); - Type* type = Type::make_forward_declaration(no); - ret = Expression::make_type(type, ret->location()); - } - - // We handle composite literals and type casts here, as it is the - // easiest way to handle types which are in parentheses, as in - // "((uint))(1)". - if (ret->is_type_expression()) - { - if (this->peek_token()->is_op(OPERATOR_LCURLY)) - { - if (is_parenthesized) - error_at(start_loc, - "cannot parenthesize type in composite literal"); - ret = this->composite_lit(ret->type(), 0, ret->location()); - } - else if (this->peek_token()->is_op(OPERATOR_LPAREN)) - { - source_location loc = this->location(); - this->advance_token(); - Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, - NULL); - if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "expected %<)%>"); - else - this->advance_token(); - if (expr->is_error_expression()) - return expr; - ret = Expression::make_cast(ret->type(), expr, loc); - } - } - - while (true) - { - const Token* token = this->peek_token(); - if (token->is_op(OPERATOR_LPAREN)) - ret = this->call(this->verify_not_sink(ret)); - else if (token->is_op(OPERATOR_DOT)) - { - ret = this->selector(this->verify_not_sink(ret), is_type_switch); - if (is_type_switch != NULL && *is_type_switch) - break; - } - else if (token->is_op(OPERATOR_LSQUARE)) - ret = this->index(this->verify_not_sink(ret)); - else - break; - } - - return ret; -} - -// Selector = "." identifier . -// TypeGuard = "." "(" QualifiedIdent ")" . - -// Note that Operand can expand to QualifiedIdent, which contains a -// ".". That is handled directly in operand when it sees a package -// name. - -// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::selector(Expression* left, bool* is_type_switch) -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_DOT)); - source_location location = this->location(); - - const Token* token = this->advance_token(); - if (token->is_identifier()) - { - // This could be a field in a struct, or a method in an - // interface, or a method associated with a type. We can't know - // which until we have seen all the types. - std::string name = - this->gogo_->pack_hidden_name(token->identifier(), - token->is_identifier_exported()); - if (token->identifier() == "_") - { - error_at(this->location(), "invalid use of %<_%>"); - name = this->gogo_->pack_hidden_name("blank", false); - } - this->advance_token(); - return Expression::make_selector(left, name, location); - } - else if (token->is_op(OPERATOR_LPAREN)) - { - this->advance_token(); - Type* type = NULL; - if (is_type_switch == NULL - || !this->peek_token()->is_keyword(KEYWORD_TYPE)) - type = this->type(); - else - { - *is_type_switch = true; - this->advance_token(); - } - if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "missing %<)%>"); - else - this->advance_token(); - if (is_type_switch != NULL && *is_type_switch) - return left; - return Expression::make_type_guard(left, type, location); - } - else - { - error_at(this->location(), "expected identifier or %<(%>"); - return left; - } -} - -// Index = "[" Expression "]" . -// Slice = "[" Expression ":" [ Expression ] "]" . - -Expression* -Parse::index(Expression* expr) -{ - source_location location = this->location(); - gcc_assert(this->peek_token()->is_op(OPERATOR_LSQUARE)); - this->advance_token(); - - Expression* start; - if (!this->peek_token()->is_op(OPERATOR_COLON)) - start = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - else - { - mpz_t zero; - mpz_init_set_ui(zero, 0); - start = Expression::make_integer(&zero, NULL, location); - mpz_clear(zero); - } - - Expression* end = NULL; - if (this->peek_token()->is_op(OPERATOR_COLON)) - { - // We use nil to indicate a missing high expression. - if (this->advance_token()->is_op(OPERATOR_RSQUARE)) - end = Expression::make_nil(this->location()); - else - end = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - } - if (!this->peek_token()->is_op(OPERATOR_RSQUARE)) - error_at(this->location(), "missing %<]%>"); - else - this->advance_token(); - return Expression::make_index(expr, start, end, location); -} - -// Call = "(" [ ArgumentList [ "," ] ] ")" . -// ArgumentList = ExpressionList [ "..." ] . - -Expression* -Parse::call(Expression* func) -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_LPAREN)); - Expression_list* args = NULL; - bool is_varargs = false; - const Token* token = this->advance_token(); - if (!token->is_op(OPERATOR_RPAREN)) - { - args = this->expression_list(NULL, false); - token = this->peek_token(); - if (token->is_op(OPERATOR_ELLIPSIS)) - { - is_varargs = true; - token = this->advance_token(); - } - } - if (token->is_op(OPERATOR_COMMA)) - token = this->advance_token(); - if (!token->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "missing %<)%>"); - else - this->advance_token(); - if (func->is_error_expression()) - return func; - return Expression::make_call(func, args, is_varargs, func->location()); -} - -// Return an expression for a single unqualified identifier. - -Expression* -Parse::id_to_expression(const std::string& name, source_location location) -{ - Named_object* in_function; - Named_object* named_object = this->gogo_->lookup(name, &in_function); - if (named_object == NULL) - named_object = this->gogo_->add_unknown_name(name, location); - - if (in_function != NULL - && in_function != this->gogo_->current_function() - && (named_object->is_variable() || named_object->is_result_variable())) - return this->enclosing_var_reference(in_function, named_object, - location); - - switch (named_object->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - return Expression::make_const_reference(named_object, location); - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - return Expression::make_var_reference(named_object, location); - case Named_object::NAMED_OBJECT_SINK: - return Expression::make_sink(location); - case Named_object::NAMED_OBJECT_FUNC: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - return Expression::make_func_reference(named_object, NULL, location); - case Named_object::NAMED_OBJECT_UNKNOWN: - return Expression::make_unknown_reference(named_object, location); - default: - error_at(this->location(), "unexpected type of identifier"); - return Expression::make_error(location); - } -} - -// Expression = UnaryExpr { binary_op Expression } . - -// PRECEDENCE is the precedence of the current operator. - -// If MAY_BE_SINK is true, this expression may be "_". - -// If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite -// literal. - -// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::expression(Precedence precedence, bool may_be_sink, - bool may_be_composite_lit, bool* is_type_switch) -{ - Expression* left = this->unary_expr(may_be_sink, may_be_composite_lit, - is_type_switch); - - while (true) - { - if (is_type_switch != NULL && *is_type_switch) - return left; - - const Token* token = this->peek_token(); - if (token->classification() != Token::TOKEN_OPERATOR) - { - // Not a binary_op. - return left; - } - - Precedence right_precedence; - switch (token->op()) - { - case OPERATOR_OROR: - right_precedence = PRECEDENCE_OROR; - break; - case OPERATOR_ANDAND: - right_precedence = PRECEDENCE_ANDAND; - break; - case OPERATOR_CHANOP: - right_precedence = PRECEDENCE_CHANOP; - break; - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - right_precedence = PRECEDENCE_RELOP; - break; - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_OR: - case OPERATOR_XOR: - right_precedence = PRECEDENCE_ADDOP; - break; - case OPERATOR_MULT: - case OPERATOR_DIV: - case OPERATOR_MOD: - case OPERATOR_LSHIFT: - case OPERATOR_RSHIFT: - case OPERATOR_AND: - case OPERATOR_BITCLEAR: - right_precedence = PRECEDENCE_MULOP; - break; - default: - right_precedence = PRECEDENCE_INVALID; - break; - } - - if (right_precedence == PRECEDENCE_INVALID) - { - // Not a binary_op. - return left; - } - - Operator op = token->op(); - source_location binop_location = token->location(); - - if (precedence >= right_precedence) - { - // We've already seen A * B, and we see + C. We want to - // return so that A * B becomes a group. - return left; - } - - this->advance_token(); - - left = this->verify_not_sink(left); - Expression* right = this->expression(right_precedence, false, - may_be_composite_lit, - is_type_switch); - if (op == OPERATOR_CHANOP) - left = Expression::make_send(left, right, binop_location); - else - left = Expression::make_binary(op, left, right, binop_location); - } -} - -bool -Parse::expression_may_start_here() -{ - const Token* token = this->peek_token(); - switch (token->classification()) - { - case Token::TOKEN_INVALID: - case Token::TOKEN_EOF: - return false; - case Token::TOKEN_KEYWORD: - switch (token->keyword()) - { - case KEYWORD_CHAN: - case KEYWORD_FUNC: - case KEYWORD_MAP: - case KEYWORD_STRUCT: - case KEYWORD_INTERFACE: - return true; - default: - return false; - } - case Token::TOKEN_IDENTIFIER: - return true; - case Token::TOKEN_STRING: - return true; - case Token::TOKEN_OPERATOR: - switch (token->op()) - { - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_NOT: - case OPERATOR_XOR: - case OPERATOR_MULT: - case OPERATOR_CHANOP: - case OPERATOR_AND: - case OPERATOR_LPAREN: - case OPERATOR_LSQUARE: - return true; - default: - return false; - } - case Token::TOKEN_INTEGER: - case Token::TOKEN_FLOAT: - case Token::TOKEN_IMAGINARY: - return true; - default: - gcc_unreachable(); - } -} - -// UnaryExpr = unary_op UnaryExpr | PrimaryExpr . - -// If MAY_BE_SINK is true, this expression may be "_". - -// If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite -// literal. - -// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::unary_expr(bool may_be_sink, bool may_be_composite_lit, - bool* is_type_switch) -{ - const Token* token = this->peek_token(); - if (token->is_op(OPERATOR_PLUS) - || token->is_op(OPERATOR_MINUS) - || token->is_op(OPERATOR_NOT) - || token->is_op(OPERATOR_XOR) - || token->is_op(OPERATOR_CHANOP) - || token->is_op(OPERATOR_MULT) - || token->is_op(OPERATOR_AND)) - { - source_location location = token->location(); - Operator op = token->op(); - this->advance_token(); - - if (op == OPERATOR_CHANOP - && this->peek_token()->is_keyword(KEYWORD_CHAN)) - { - // This is "<- chan" which must be the start of a type. - this->unget_token(Token::make_operator_token(op, location)); - return Expression::make_type(this->type(), location); - } - - Expression* expr = this->unary_expr(false, may_be_composite_lit, - is_type_switch); - if (expr->is_error_expression()) - ; - else if (op == OPERATOR_MULT && expr->is_type_expression()) - expr = Expression::make_type(Type::make_pointer_type(expr->type()), - location); - else if (op == OPERATOR_AND && expr->is_composite_literal()) - expr = Expression::make_heap_composite(expr, location); - else if (op != OPERATOR_CHANOP) - expr = Expression::make_unary(op, expr, location); - else - expr = Expression::make_receive(expr, location); - return expr; - } - else - return this->primary_expr(may_be_sink, may_be_composite_lit, - is_type_switch); -} - -// Statement = -// Declaration | LabeledStmt | SimpleStmt | -// GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt | -// FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt | -// DeferStmt . - -// LABEL is the label of this statement if it has one. - -void -Parse::statement(const Label* label) -{ - const Token* token = this->peek_token(); - switch (token->classification()) - { - case Token::TOKEN_KEYWORD: - { - switch (token->keyword()) - { - case KEYWORD_CONST: - case KEYWORD_TYPE: - case KEYWORD_VAR: - this->declaration(); - break; - case KEYWORD_FUNC: - case KEYWORD_MAP: - case KEYWORD_STRUCT: - case KEYWORD_INTERFACE: - this->simple_stat(true, false, NULL, NULL); - break; - case KEYWORD_GO: - case KEYWORD_DEFER: - this->go_or_defer_stat(); - break; - case KEYWORD_RETURN: - this->return_stat(); - break; - case KEYWORD_BREAK: - this->break_stat(); - break; - case KEYWORD_CONTINUE: - this->continue_stat(); - break; - case KEYWORD_GOTO: - this->goto_stat(); - break; - case KEYWORD_IF: - this->if_stat(); - break; - case KEYWORD_SWITCH: - this->switch_stat(label); - break; - case KEYWORD_SELECT: - this->select_stat(label); - break; - case KEYWORD_FOR: - this->for_stat(label); - break; - default: - error_at(this->location(), "expected statement"); - this->advance_token(); - break; - } - } - break; - - case Token::TOKEN_IDENTIFIER: - { - std::string identifier = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - if (this->advance_token()->is_op(OPERATOR_COLON)) - { - this->advance_token(); - this->labeled_stmt(identifier, location); - } - else - { - this->unget_token(Token::make_identifier_token(identifier, - is_exported, - location)); - this->simple_stat(true, false, NULL, NULL); - } - } - break; - - case Token::TOKEN_OPERATOR: - if (token->is_op(OPERATOR_LCURLY)) - { - source_location location = token->location(); - this->gogo_->start_block(location); - source_location end_loc = this->block(); - this->gogo_->add_block(this->gogo_->finish_block(end_loc), - location); - } - else if (!token->is_op(OPERATOR_SEMICOLON)) - this->simple_stat(true, false, NULL, NULL); - break; - - case Token::TOKEN_STRING: - case Token::TOKEN_INTEGER: - case Token::TOKEN_FLOAT: - case Token::TOKEN_IMAGINARY: - this->simple_stat(true, false, NULL, NULL); - break; - - default: - error_at(this->location(), "expected statement"); - this->advance_token(); - break; - } -} - -bool -Parse::statement_may_start_here() -{ - const Token* token = this->peek_token(); - switch (token->classification()) - { - case Token::TOKEN_KEYWORD: - { - switch (token->keyword()) - { - case KEYWORD_CONST: - case KEYWORD_TYPE: - case KEYWORD_VAR: - case KEYWORD_FUNC: - case KEYWORD_MAP: - case KEYWORD_STRUCT: - case KEYWORD_INTERFACE: - case KEYWORD_GO: - case KEYWORD_DEFER: - case KEYWORD_RETURN: - case KEYWORD_BREAK: - case KEYWORD_CONTINUE: - case KEYWORD_GOTO: - case KEYWORD_IF: - case KEYWORD_SWITCH: - case KEYWORD_SELECT: - case KEYWORD_FOR: - return true; - - default: - return false; - } - } - break; - - case Token::TOKEN_IDENTIFIER: - return true; - - case Token::TOKEN_OPERATOR: - if (token->is_op(OPERATOR_LCURLY) - || token->is_op(OPERATOR_SEMICOLON)) - return true; - else - return this->expression_may_start_here(); - - case Token::TOKEN_STRING: - case Token::TOKEN_INTEGER: - case Token::TOKEN_FLOAT: - case Token::TOKEN_IMAGINARY: - return true; - - default: - return false; - } -} - -// LabeledStmt = Label ":" Statement . -// Label = identifier . - -void -Parse::labeled_stmt(const std::string& label_name, source_location location) -{ - Label* label = this->gogo_->add_label_definition(label_name, location); - - if (this->peek_token()->is_op(OPERATOR_RCURLY)) - { - // This is a label at the end of a block. A program is - // permitted to omit a semicolon here. - return; - } - - if (!this->statement_may_start_here()) - { - error_at(location, "missing statement after label"); - this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON, - location)); - return; - } - - this->statement(label); -} - -// SimpleStat = -// ExpressionStat | IncDecStat | Assignment | SimpleVarDecl . - -// In order to make this work for if and switch statements, if -// RETURN_EXP is true, and we see an ExpressionStat, we return the -// expression rather than adding an expression statement to the -// current block. If we see something other than an ExpressionStat, -// we add the statement and return NULL. - -// If P_RANGE_CLAUSE is not NULL, then this will recognize a -// RangeClause. - -// If P_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::simple_stat(bool may_be_composite_lit, bool return_exp, - Range_clause* p_range_clause, Type_switch* p_type_switch) -{ - const Token* token = this->peek_token(); - - // An identifier follow by := is a SimpleVarDecl. - if (token->is_identifier()) - { - std::string identifier = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - - token = this->advance_token(); - if (token->is_op(OPERATOR_COLONEQ) - || token->is_op(OPERATOR_COMMA)) - { - identifier = this->gogo_->pack_hidden_name(identifier, is_exported); - this->simple_var_decl_or_assignment(identifier, location, - p_range_clause, - (token->is_op(OPERATOR_COLONEQ) - ? p_type_switch - : NULL)); - return NULL; - } - - this->unget_token(Token::make_identifier_token(identifier, is_exported, - location)); - } - - Expression* exp = this->expression(PRECEDENCE_NORMAL, true, - may_be_composite_lit, - (p_type_switch == NULL - ? NULL - : &p_type_switch->found)); - if (p_type_switch != NULL && p_type_switch->found) - { - p_type_switch->name.clear(); - p_type_switch->location = exp->location(); - p_type_switch->expr = this->verify_not_sink(exp); - return NULL; - } - token = this->peek_token(); - if (token->is_op(OPERATOR_PLUSPLUS) || token->is_op(OPERATOR_MINUSMINUS)) - this->inc_dec_stat(this->verify_not_sink(exp)); - else if (token->is_op(OPERATOR_COMMA) - || token->is_op(OPERATOR_EQ)) - this->assignment(exp, p_range_clause); - else if (token->is_op(OPERATOR_PLUSEQ) - || token->is_op(OPERATOR_MINUSEQ) - || token->is_op(OPERATOR_OREQ) - || token->is_op(OPERATOR_XOREQ) - || token->is_op(OPERATOR_MULTEQ) - || token->is_op(OPERATOR_DIVEQ) - || token->is_op(OPERATOR_MODEQ) - || token->is_op(OPERATOR_LSHIFTEQ) - || token->is_op(OPERATOR_RSHIFTEQ) - || token->is_op(OPERATOR_ANDEQ) - || token->is_op(OPERATOR_BITCLEAREQ)) - this->assignment(this->verify_not_sink(exp), p_range_clause); - else if (return_exp) - return this->verify_not_sink(exp); - else - this->expression_stat(this->verify_not_sink(exp)); - - return NULL; -} - -bool -Parse::simple_stat_may_start_here() -{ - return this->expression_may_start_here(); -} - -// Parse { Statement ";" } which is used in a few places. The list of -// statements may end with a right curly brace, in which case the -// semicolon may be omitted. - -void -Parse::statement_list() -{ - while (this->statement_may_start_here()) - { - this->statement(NULL); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - else if (this->peek_token()->is_op(OPERATOR_RCURLY)) - break; - else - { - if (!this->peek_token()->is_eof() || !saw_errors()) - error_at(this->location(), "expected %<;%> or %<}%> or newline"); - if (!this->skip_past_error(OPERATOR_RCURLY)) - return; - } - } -} - -bool -Parse::statement_list_may_start_here() -{ - return this->statement_may_start_here(); -} - -// ExpressionStat = Expression . - -void -Parse::expression_stat(Expression* exp) -{ - exp->discarding_value(); - this->gogo_->add_statement(Statement::make_statement(exp)); -} - -// IncDecStat = Expression ( "++" | "--" ) . - -void -Parse::inc_dec_stat(Expression* exp) -{ - const Token* token = this->peek_token(); - - // Lvalue maps require special handling. - if (exp->index_expression() != NULL) - exp->index_expression()->set_is_lvalue(); - - if (token->is_op(OPERATOR_PLUSPLUS)) - this->gogo_->add_statement(Statement::make_inc_statement(exp)); - else if (token->is_op(OPERATOR_MINUSMINUS)) - this->gogo_->add_statement(Statement::make_dec_statement(exp)); - else - gcc_unreachable(); - this->advance_token(); -} - -// Assignment = ExpressionList assign_op ExpressionList . - -// EXP is an expression that we have already parsed. - -// If RANGE_CLAUSE is not NULL, then this will recognize a -// RangeClause. - -void -Parse::assignment(Expression* expr, Range_clause* p_range_clause) -{ - Expression_list* vars; - if (!this->peek_token()->is_op(OPERATOR_COMMA)) - { - vars = new Expression_list(); - vars->push_back(expr); - } - else - { - this->advance_token(); - vars = this->expression_list(expr, true); - } - - this->tuple_assignment(vars, p_range_clause); -} - -// An assignment statement. LHS is the list of expressions which -// appear on the left hand side. - -// If RANGE_CLAUSE is not NULL, then this will recognize a -// RangeClause. - -void -Parse::tuple_assignment(Expression_list* lhs, Range_clause* p_range_clause) -{ - const Token* token = this->peek_token(); - if (!token->is_op(OPERATOR_EQ) - && !token->is_op(OPERATOR_PLUSEQ) - && !token->is_op(OPERATOR_MINUSEQ) - && !token->is_op(OPERATOR_OREQ) - && !token->is_op(OPERATOR_XOREQ) - && !token->is_op(OPERATOR_MULTEQ) - && !token->is_op(OPERATOR_DIVEQ) - && !token->is_op(OPERATOR_MODEQ) - && !token->is_op(OPERATOR_LSHIFTEQ) - && !token->is_op(OPERATOR_RSHIFTEQ) - && !token->is_op(OPERATOR_ANDEQ) - && !token->is_op(OPERATOR_BITCLEAREQ)) - { - error_at(this->location(), "expected assignment operator"); - return; - } - Operator op = token->op(); - source_location location = token->location(); - - token = this->advance_token(); - - if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE)) - { - if (op != OPERATOR_EQ) - error_at(this->location(), "range clause requires %<=%>"); - this->range_clause_expr(lhs, p_range_clause); - return; - } - - Expression_list* vals = this->expression_list(NULL, false); - - // We've parsed everything; check for errors. - if (lhs == NULL || vals == NULL) - return; - for (Expression_list::const_iterator pe = lhs->begin(); - pe != lhs->end(); - ++pe) - { - if ((*pe)->is_error_expression()) - return; - if (op != OPERATOR_EQ && (*pe)->is_sink_expression()) - error_at((*pe)->location(), "cannot use _ as value"); - } - for (Expression_list::const_iterator pe = vals->begin(); - pe != vals->end(); - ++pe) - { - if ((*pe)->is_error_expression()) - return; - } - - // Map expressions act differently when they are lvalues. - for (Expression_list::iterator plv = lhs->begin(); - plv != lhs->end(); - ++plv) - if ((*plv)->index_expression() != NULL) - (*plv)->index_expression()->set_is_lvalue(); - - Call_expression* call; - Index_expression* map_index; - Receive_expression* receive; - Type_guard_expression* type_guard; - if (lhs->size() == vals->size()) - { - Statement* s; - if (lhs->size() > 1) - { - if (op != OPERATOR_EQ) - error_at(location, "multiple values only permitted with %<=%>"); - s = Statement::make_tuple_assignment(lhs, vals, location); - } - else - { - if (op == OPERATOR_EQ) - s = Statement::make_assignment(lhs->front(), vals->front(), - location); - else - s = Statement::make_assignment_operation(op, lhs->front(), - vals->front(), location); - delete lhs; - delete vals; - } - this->gogo_->add_statement(s); - } - else if (vals->size() == 1 - && (call = (*vals->begin())->call_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "multiple results only permitted with %<=%>"); - delete vals; - vals = new Expression_list; - for (unsigned int i = 0; i < lhs->size(); ++i) - vals->push_back(Expression::make_call_result(call, i)); - Statement* s = Statement::make_tuple_assignment(lhs, vals, location); - this->gogo_->add_statement(s); - } - else if (lhs->size() == 2 - && vals->size() == 1 - && (map_index = (*vals->begin())->index_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "two values from map requires %<=%>"); - Expression* val = lhs->front(); - Expression* present = lhs->back(); - Statement* s = Statement::make_tuple_map_assignment(val, present, - map_index, location); - this->gogo_->add_statement(s); - } - else if (lhs->size() == 1 - && vals->size() == 2 - && (map_index = lhs->front()->index_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "assigning tuple to map index requires %<=%>"); - Expression* val = vals->front(); - Expression* should_set = vals->back(); - Statement* s = Statement::make_map_assignment(map_index, val, should_set, - location); - this->gogo_->add_statement(s); - } - else if (lhs->size() == 2 - && vals->size() == 1 - && (receive = (*vals->begin())->receive_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "two values from receive requires %<=%>"); - Expression* val = lhs->front(); - Expression* success = lhs->back(); - Expression* channel = receive->channel(); - Statement* s = Statement::make_tuple_receive_assignment(val, success, - channel, - location); - this->gogo_->add_statement(s); - } - else if (lhs->size() == 2 - && vals->size() == 1 - && (type_guard = (*vals->begin())->type_guard_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "two values from type guard requires %<=%>"); - Expression* val = lhs->front(); - Expression* ok = lhs->back(); - Expression* expr = type_guard->expr(); - Type* type = type_guard->type(); - Statement* s = Statement::make_tuple_type_guard_assignment(val, ok, - expr, type, - location); - this->gogo_->add_statement(s); - } - else - { - error_at(location, "number of variables does not match number of values"); - } -} - -// GoStat = "go" Expression . -// DeferStat = "defer" Expression . - -void -Parse::go_or_defer_stat() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_GO) - || this->peek_token()->is_keyword(KEYWORD_DEFER)); - bool is_go = this->peek_token()->is_keyword(KEYWORD_GO); - source_location stat_location = this->location(); - this->advance_token(); - source_location expr_location = this->location(); - Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - Call_expression* call_expr = expr->call_expression(); - if (call_expr == NULL) - { - error_at(expr_location, "expected call expression"); - return; - } - - // Make it easier to simplify go/defer statements by putting every - // statement in its own block. - this->gogo_->start_block(stat_location); - Statement* stat; - if (is_go) - stat = Statement::make_go_statement(call_expr, stat_location); - else - stat = Statement::make_defer_statement(call_expr, stat_location); - this->gogo_->add_statement(stat); - this->gogo_->add_block(this->gogo_->finish_block(stat_location), - stat_location); -} - -// ReturnStat = "return" [ ExpressionList ] . - -void -Parse::return_stat() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_RETURN)); - source_location location = this->location(); - this->advance_token(); - Expression_list* vals = NULL; - if (this->expression_may_start_here()) - vals = this->expression_list(NULL, false); - const Function* function = this->gogo_->current_function()->func_value(); - const Typed_identifier_list* results = function->type()->results(); - this->gogo_->add_statement(Statement::make_return_statement(results, vals, - location)); -} - -// IfStat = "if" [ [ SimpleStat ] ";" ] [ Condition ] -// Block [ "else" Statement ] . - -void -Parse::if_stat() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_IF)); - source_location location = this->location(); - this->advance_token(); - - this->gogo_->start_block(location); - - Expression* cond = NULL; - if (this->simple_stat_may_start_here()) - cond = this->simple_stat(false, true, NULL, NULL); - if (cond != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - // The SimpleStat is an expression statement. - this->expression_stat(cond); - cond = NULL; - } - if (cond == NULL) - { - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - cond = this->expression(PRECEDENCE_NORMAL, false, false, NULL); - } - - this->gogo_->start_block(this->location()); - source_location end_loc = this->block(); - Block* then_block = this->gogo_->finish_block(end_loc); - - // Check for the easy error of a newline before "else". - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - source_location semi_loc = this->location(); - if (this->advance_token()->is_keyword(KEYWORD_ELSE)) - error_at(this->location(), - "unexpected semicolon or newline before %"); - else - this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON, - semi_loc)); - } - - Block* else_block = NULL; - if (this->peek_token()->is_keyword(KEYWORD_ELSE)) - { - this->advance_token(); - // We create a block to gather the statement. - this->gogo_->start_block(this->location()); - this->statement(NULL); - else_block = this->gogo_->finish_block(this->location()); - } - - this->gogo_->add_statement(Statement::make_if_statement(cond, then_block, - else_block, - location)); - - this->gogo_->add_block(this->gogo_->finish_block(this->location()), - location); -} - -// SwitchStmt = ExprSwitchStmt | TypeSwitchStmt . -// ExprSwitchStmt = "switch" [ [ SimpleStat ] ";" ] [ Expression ] -// "{" { ExprCaseClause } "}" . -// TypeSwitchStmt = "switch" [ [ SimpleStat ] ";" ] TypeSwitchGuard -// "{" { TypeCaseClause } "}" . -// TypeSwitchGuard = [ identifier ":=" ] Expression "." "(" "type" ")" . - -void -Parse::switch_stat(const Label* label) -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_SWITCH)); - source_location location = this->location(); - this->advance_token(); - - this->gogo_->start_block(location); - - Expression* switch_val = NULL; - Type_switch type_switch; - if (this->simple_stat_may_start_here()) - switch_val = this->simple_stat(false, true, NULL, &type_switch); - if (switch_val != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - // The SimpleStat is an expression statement. - this->expression_stat(switch_val); - switch_val = NULL; - } - if (switch_val == NULL && !type_switch.found) - { - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - { - if (this->peek_token()->is_identifier()) - { - const Token* token = this->peek_token(); - std::string identifier = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location id_loc = token->location(); - - token = this->advance_token(); - bool is_coloneq = token->is_op(OPERATOR_COLONEQ); - this->unget_token(Token::make_identifier_token(identifier, - is_exported, - id_loc)); - if (is_coloneq) - { - // This must be a TypeSwitchGuard. - switch_val = this->simple_stat(false, true, NULL, - &type_switch); - if (!type_switch.found - && !switch_val->is_error_expression()) - { - error_at(id_loc, "expected type switch assignment"); - switch_val = Expression::make_error(id_loc); - } - } - } - if (switch_val == NULL && !type_switch.found) - { - switch_val = this->expression(PRECEDENCE_NORMAL, false, false, - &type_switch.found); - if (type_switch.found) - { - type_switch.name.clear(); - type_switch.expr = switch_val; - type_switch.location = switch_val->location(); - } - } - } - } - - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - { - source_location token_loc = this->location(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(token_loc, "unexpected semicolon or newline before %<{%>"); - else - { - error_at(this->location(), "expected %<{%>"); - this->gogo_->add_block(this->gogo_->finish_block(this->location()), - location); - return; - } - } - this->advance_token(); - - Statement* statement; - if (type_switch.found) - statement = this->type_switch_body(label, type_switch, location); - else - statement = this->expr_switch_body(label, switch_val, location); - - if (statement != NULL) - this->gogo_->add_statement(statement); - - this->gogo_->add_block(this->gogo_->finish_block(this->location()), - location); -} - -// The body of an expression switch. -// "{" { ExprCaseClause } "}" - -Statement* -Parse::expr_switch_body(const Label* label, Expression* switch_val, - source_location location) -{ - Switch_statement* statement = Statement::make_switch_statement(switch_val, - location); - - this->push_break_statement(statement, label); - - Case_clauses* case_clauses = new Case_clauses(); - while (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - if (this->peek_token()->is_eof()) - { - if (!saw_errors()) - error_at(this->location(), "missing %<}%>"); - return NULL; - } - this->expr_case_clause(case_clauses); - } - this->advance_token(); - - statement->add_clauses(case_clauses); - - this->pop_break_statement(); - - return statement; -} - -// ExprCaseClause = ExprSwitchCase ":" [ StatementList ] . -// FallthroughStat = "fallthrough" . - -void -Parse::expr_case_clause(Case_clauses* clauses) -{ - source_location location = this->location(); - - bool is_default = false; - Expression_list* vals = this->expr_switch_case(&is_default); - - if (!this->peek_token()->is_op(OPERATOR_COLON)) - { - if (!saw_errors()) - error_at(this->location(), "expected %<:%>"); - return; - } - else - this->advance_token(); - - Block* statements = NULL; - if (this->statement_list_may_start_here()) - { - this->gogo_->start_block(this->location()); - this->statement_list(); - statements = this->gogo_->finish_block(this->location()); - } - - bool is_fallthrough = false; - if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH)) - { - is_fallthrough = true; - if (this->advance_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - } - - if (is_default || vals != NULL) - clauses->add(vals, is_default, statements, is_fallthrough, location); -} - -// ExprSwitchCase = "case" ExpressionList | "default" . - -Expression_list* -Parse::expr_switch_case(bool* is_default) -{ - const Token* token = this->peek_token(); - if (token->is_keyword(KEYWORD_CASE)) - { - this->advance_token(); - return this->expression_list(NULL, false); - } - else if (token->is_keyword(KEYWORD_DEFAULT)) - { - this->advance_token(); - *is_default = true; - return NULL; - } - else - { - if (!saw_errors()) - error_at(this->location(), "expected % or %"); - if (!token->is_op(OPERATOR_RCURLY)) - this->advance_token(); - return NULL; - } -} - -// The body of a type switch. -// "{" { TypeCaseClause } "}" . - -Statement* -Parse::type_switch_body(const Label* label, const Type_switch& type_switch, - source_location location) -{ - Named_object* switch_no = NULL; - if (!type_switch.name.empty()) - { - Variable* switch_var = new Variable(NULL, type_switch.expr, false, false, - false, type_switch.location); - switch_no = this->gogo_->add_variable(type_switch.name, switch_var); - } - - Type_switch_statement* statement = - Statement::make_type_switch_statement(switch_no, - (switch_no == NULL - ? type_switch.expr - : NULL), - location); - - this->push_break_statement(statement, label); - - Type_case_clauses* case_clauses = new Type_case_clauses(); - while (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - if (this->peek_token()->is_eof()) - { - error_at(this->location(), "missing %<}%>"); - return NULL; - } - this->type_case_clause(switch_no, case_clauses); - } - this->advance_token(); - - statement->add_clauses(case_clauses); - - this->pop_break_statement(); - - return statement; -} - -// TypeCaseClause = TypeSwitchCase ":" [ StatementList ] . - -void -Parse::type_case_clause(Named_object* switch_no, Type_case_clauses* clauses) -{ - source_location location = this->location(); - - std::vector types; - bool is_default = false; - this->type_switch_case(&types, &is_default); - - if (!this->peek_token()->is_op(OPERATOR_COLON)) - error_at(this->location(), "expected %<:%>"); - else - this->advance_token(); - - Block* statements = NULL; - if (this->statement_list_may_start_here()) - { - this->gogo_->start_block(this->location()); - if (switch_no != NULL && types.size() == 1) - { - Type* type = types.front(); - Expression* init = Expression::make_var_reference(switch_no, - location); - init = Expression::make_type_guard(init, type, location); - Variable* v = new Variable(type, init, false, false, false, - location); - v->set_is_type_switch_var(); - this->gogo_->add_variable(switch_no->name(), v); - } - this->statement_list(); - statements = this->gogo_->finish_block(this->location()); - } - - if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH)) - { - error_at(this->location(), - "fallthrough is not permitted in a type switch"); - if (this->advance_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - } - - if (is_default) - { - gcc_assert(types.empty()); - clauses->add(NULL, false, true, statements, location); - } - else if (!types.empty()) - { - for (std::vector::const_iterator p = types.begin(); - p + 1 != types.end(); - ++p) - clauses->add(*p, true, false, NULL, location); - clauses->add(types.back(), false, false, statements, location); - } -} - -// TypeSwitchCase = "case" type | "default" - -// We accept a comma separated list of types. - -void -Parse::type_switch_case(std::vector* types, bool* is_default) -{ - const Token* token = this->peek_token(); - if (token->is_keyword(KEYWORD_CASE)) - { - this->advance_token(); - while (true) - { - Type* t = this->type(); - if (!t->is_error_type()) - types->push_back(t); - if (!this->peek_token()->is_op(OPERATOR_COMMA)) - break; - this->advance_token(); - } - } - else if (token->is_keyword(KEYWORD_DEFAULT)) - { - this->advance_token(); - *is_default = true; - } - else - { - error_at(this->location(), "expected % or %"); - if (!token->is_op(OPERATOR_RCURLY)) - this->advance_token(); - } -} - -// SelectStat = "select" "{" { CommClause } "}" . - -void -Parse::select_stat(const Label* label) -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_SELECT)); - source_location location = this->location(); - const Token* token = this->advance_token(); - - if (!token->is_op(OPERATOR_LCURLY)) - { - source_location token_loc = token->location(); - if (token->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(token_loc, "unexpected semicolon or newline before %<{%>"); - else - { - error_at(this->location(), "expected %<{%>"); - return; - } - } - this->advance_token(); - - Select_statement* statement = Statement::make_select_statement(location); - - this->push_break_statement(statement, label); - - Select_clauses* select_clauses = new Select_clauses(); - while (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - if (this->peek_token()->is_eof()) - { - error_at(this->location(), "expected %<}%>"); - return; - } - this->comm_clause(select_clauses); - } - - this->advance_token(); - - statement->add_clauses(select_clauses); - - this->pop_break_statement(); - - this->gogo_->add_statement(statement); -} - -// CommClause = CommCase [ StatementList ] . - -void -Parse::comm_clause(Select_clauses* clauses) -{ - source_location location = this->location(); - bool is_send = false; - Expression* channel = NULL; - Expression* val = NULL; - std::string varname; - bool is_default = false; - bool got_case = this->comm_case(&is_send, &channel, &val, &varname, - &is_default); - - Block* statements = NULL; - Named_object* var = NULL; - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - else if (this->statement_list_may_start_here()) - { - this->gogo_->start_block(this->location()); - - if (!varname.empty()) - { - // FIXME: LOCATION is slightly wrong here. - Variable* v = new Variable(NULL, channel, false, false, false, - location); - v->set_type_from_chan_element(); - var = this->gogo_->add_variable(varname, v); - } - - this->statement_list(); - statements = this->gogo_->finish_block(this->location()); - } - - if (got_case) - clauses->add(is_send, channel, val, var, is_default, statements, location); -} - -// CommCase = ( "default" | ( "case" ( SendExpr | RecvExpr) ) ) ":" . - -bool -Parse::comm_case(bool* is_send, Expression** channel, Expression** val, - std::string* varname, bool* is_default) -{ - const Token* token = this->peek_token(); - if (token->is_keyword(KEYWORD_DEFAULT)) - { - this->advance_token(); - *is_default = true; - } - else if (token->is_keyword(KEYWORD_CASE)) - { - this->advance_token(); - if (!this->send_or_recv_expr(is_send, channel, val, varname)) - return false; - } - else - { - error_at(this->location(), "expected % or %"); - if (!token->is_op(OPERATOR_RCURLY)) - this->advance_token(); - return false; - } - - if (!this->peek_token()->is_op(OPERATOR_COLON)) - { - error_at(this->location(), "expected colon"); - return false; - } - - this->advance_token(); - - return true; -} - -// SendExpr = Expression "<-" Expression . -// RecvExpr = [ Expression ( "=" | ":=" ) ] "<-" Expression . - -bool -Parse::send_or_recv_expr(bool* is_send, Expression** channel, Expression** val, - std::string* varname) -{ - const Token* token = this->peek_token(); - source_location location = token->location(); - if (token->is_identifier()) - { - std::string recv_var = token->identifier(); - bool is_var_exported = token->is_identifier_exported(); - if (!this->advance_token()->is_op(OPERATOR_COLONEQ)) - this->unget_token(Token::make_identifier_token(recv_var, - is_var_exported, - location)); - else - { - if (!this->advance_token()->is_op(OPERATOR_CHANOP)) - { - error_at(this->location(), "expected %<<-%>"); - return false; - } - *is_send = false; - *varname = this->gogo_->pack_hidden_name(recv_var, is_var_exported); - this->advance_token(); - *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - return true; - } - } - - if (this->peek_token()->is_op(OPERATOR_CHANOP)) - { - *is_send = false; - this->advance_token(); - *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - } - else - { - Expression* left = this->expression(PRECEDENCE_CHANOP, true, true, NULL); - - if (this->peek_token()->is_op(OPERATOR_EQ)) - { - if (!this->advance_token()->is_op(OPERATOR_CHANOP)) - { - error_at(this->location(), "missing %<<-%>"); - return false; - } - *is_send = false; - *val = left; - this->advance_token(); - *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - } - else if (this->peek_token()->is_op(OPERATOR_CHANOP)) - { - *is_send = true; - *channel = this->verify_not_sink(left); - this->advance_token(); - *val = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - } - else - { - error_at(this->location(), "expected %<<-%> or %<=%>"); - return false; - } - } - - return true; -} - -// ForStat = "for" [ Condition | ForClause | RangeClause ] Block . -// Condition = Expression . - -void -Parse::for_stat(const Label* label) -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_FOR)); - source_location location = this->location(); - const Token* token = this->advance_token(); - - // Open a block to hold any variables defined in the init statement - // of the for statement. - this->gogo_->start_block(location); - - Block* init = NULL; - Expression* cond = NULL; - Block* post = NULL; - Range_clause range_clause; - - if (!token->is_op(OPERATOR_LCURLY)) - { - if (token->is_keyword(KEYWORD_VAR)) - { - error_at(this->location(), - "var declaration not allowed in for initializer"); - this->var_decl(); - } - - if (token->is_op(OPERATOR_SEMICOLON)) - this->for_clause(&cond, &post); - else - { - // We might be looking at a Condition, an InitStat, or a - // RangeClause. - cond = this->simple_stat(false, true, &range_clause, NULL); - if (!this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - if (cond == NULL && !range_clause.found) - error_at(this->location(), "parse error in for statement"); - } - else - { - if (range_clause.found) - error_at(this->location(), "parse error after range clause"); - - if (cond != NULL) - { - // COND is actually an expression statement for - // InitStat at the start of a ForClause. - this->expression_stat(cond); - cond = NULL; - } - - this->for_clause(&cond, &post); - } - } - } - - // Build the For_statement and note that it is the current target - // for break and continue statements. - - For_statement* sfor; - For_range_statement* srange; - Statement* s; - if (!range_clause.found) - { - sfor = Statement::make_for_statement(init, cond, post, location); - s = sfor; - srange = NULL; - } - else - { - srange = Statement::make_for_range_statement(range_clause.index, - range_clause.value, - range_clause.range, - location); - s = srange; - sfor = NULL; - } - - this->push_break_statement(s, label); - this->push_continue_statement(s, label); - - // Gather the block of statements in the loop and add them to the - // For_statement. - - this->gogo_->start_block(this->location()); - source_location end_loc = this->block(); - Block* statements = this->gogo_->finish_block(end_loc); - - if (sfor != NULL) - sfor->add_statements(statements); - else - srange->add_statements(statements); - - // This is no longer the break/continue target. - this->pop_break_statement(); - this->pop_continue_statement(); - - // Add the For_statement to the list of statements, and close out - // the block we started to hold any variables defined in the for - // statement. - - this->gogo_->add_statement(s); - - this->gogo_->add_block(this->gogo_->finish_block(this->location()), - location); -} - -// ForClause = [ InitStat ] ";" [ Condition ] ";" [ PostStat ] . -// InitStat = SimpleStat . -// PostStat = SimpleStat . - -// We have already read InitStat at this point. - -void -Parse::for_clause(Expression** cond, Block** post) -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_SEMICOLON)); - this->advance_token(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - *cond = NULL; - else if (this->peek_token()->is_op(OPERATOR_LCURLY)) - { - error_at(this->location(), - "unexpected semicolon or newline before %<{%>"); - *cond = NULL; - *post = NULL; - return; - } - else - *cond = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - if (!this->peek_token()->is_op(OPERATOR_SEMICOLON)) - error_at(this->location(), "expected semicolon"); - else - this->advance_token(); - - if (this->peek_token()->is_op(OPERATOR_LCURLY)) - *post = NULL; - else - { - this->gogo_->start_block(this->location()); - this->simple_stat(false, false, NULL, NULL); - *post = this->gogo_->finish_block(this->location()); - } -} - -// RangeClause = IdentifierList ( "=" | ":=" ) "range" Expression . - -// This is the := version. It is called with a list of identifiers. - -void -Parse::range_clause_decl(const Typed_identifier_list* til, - Range_clause* p_range_clause) -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_RANGE)); - source_location location = this->location(); - - p_range_clause->found = true; - - gcc_assert(til->size() >= 1); - if (til->size() > 2) - error_at(this->location(), "too many variables for range clause"); - - this->advance_token(); - Expression* expr = this->expression(PRECEDENCE_NORMAL, false, false, NULL); - p_range_clause->range = expr; - - bool any_new = false; - - const Typed_identifier* pti = &til->front(); - Named_object* no = this->init_var(*pti, NULL, expr, true, true, &any_new); - if (any_new && no->is_variable()) - no->var_value()->set_type_from_range_index(); - p_range_clause->index = Expression::make_var_reference(no, location); - - if (til->size() == 1) - p_range_clause->value = NULL; - else - { - pti = &til->back(); - bool is_new = false; - no = this->init_var(*pti, NULL, expr, true, true, &is_new); - if (is_new && no->is_variable()) - no->var_value()->set_type_from_range_value(); - if (is_new) - any_new = true; - p_range_clause->value = Expression::make_var_reference(no, location); - } - - if (!any_new) - error_at(location, "variables redeclared but no variable is new"); -} - -// The = version of RangeClause. This is called with a list of -// expressions. - -void -Parse::range_clause_expr(const Expression_list* vals, - Range_clause* p_range_clause) -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_RANGE)); - - p_range_clause->found = true; - - gcc_assert(vals->size() >= 1); - if (vals->size() > 2) - error_at(this->location(), "too many variables for range clause"); - - this->advance_token(); - p_range_clause->range = this->expression(PRECEDENCE_NORMAL, false, false, - NULL); - - p_range_clause->index = vals->front(); - if (vals->size() == 1) - p_range_clause->value = NULL; - else - p_range_clause->value = vals->back(); -} - -// Push a statement on the break stack. - -void -Parse::push_break_statement(Statement* enclosing, const Label* label) -{ - this->break_stack_.push_back(std::make_pair(enclosing, label)); -} - -// Push a statement on the continue stack. - -void -Parse::push_continue_statement(Statement* enclosing, const Label* label) -{ - this->continue_stack_.push_back(std::make_pair(enclosing, label)); -} - -// Pop the break stack. - -void -Parse::pop_break_statement() -{ - this->break_stack_.pop_back(); -} - -// Pop the continue stack. - -void -Parse::pop_continue_statement() -{ - this->continue_stack_.pop_back(); -} - -// Find a break or continue statement given a label name. - -Statement* -Parse::find_bc_statement(const Bc_stack* bc_stack, const std::string& label) -{ - for (Bc_stack::const_reverse_iterator p = bc_stack->rbegin(); - p != bc_stack->rend(); - ++p) - if (p->second != NULL && p->second->name() == label) - return p->first; - return NULL; -} - -// BreakStat = "break" [ identifier ] . - -void -Parse::break_stat() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_BREAK)); - source_location location = this->location(); - - const Token* token = this->advance_token(); - Statement* enclosing; - if (!token->is_identifier()) - { - if (this->break_stack_.empty()) - { - error_at(this->location(), - "break statement not within for or switch or select"); - return; - } - enclosing = this->break_stack_.back().first; - } - else - { - enclosing = this->find_bc_statement(&this->break_stack_, - token->identifier()); - if (enclosing == NULL) - { - error_at(token->location(), - ("break label %qs not associated with " - "for or switch or select"), - Gogo::message_name(token->identifier()).c_str()); - this->advance_token(); - return; - } - this->advance_token(); - } - - Unnamed_label* label; - if (enclosing->classification() == Statement::STATEMENT_FOR) - label = enclosing->for_statement()->break_label(); - else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE) - label = enclosing->for_range_statement()->break_label(); - else if (enclosing->classification() == Statement::STATEMENT_SWITCH) - label = enclosing->switch_statement()->break_label(); - else if (enclosing->classification() == Statement::STATEMENT_TYPE_SWITCH) - label = enclosing->type_switch_statement()->break_label(); - else if (enclosing->classification() == Statement::STATEMENT_SELECT) - label = enclosing->select_statement()->break_label(); - else - gcc_unreachable(); - - this->gogo_->add_statement(Statement::make_break_statement(label, - location)); -} - -// ContinueStat = "continue" [ identifier ] . - -void -Parse::continue_stat() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_CONTINUE)); - source_location location = this->location(); - - const Token* token = this->advance_token(); - Statement* enclosing; - if (!token->is_identifier()) - { - if (this->continue_stack_.empty()) - { - error_at(this->location(), "continue statement not within for"); - return; - } - enclosing = this->continue_stack_.back().first; - } - else - { - enclosing = this->find_bc_statement(&this->continue_stack_, - token->identifier()); - if (enclosing == NULL) - { - error_at(token->location(), - "continue label %qs not associated with for", - Gogo::message_name(token->identifier()).c_str()); - this->advance_token(); - return; - } - this->advance_token(); - } - - Unnamed_label* label; - if (enclosing->classification() == Statement::STATEMENT_FOR) - label = enclosing->for_statement()->continue_label(); - else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE) - label = enclosing->for_range_statement()->continue_label(); - else - gcc_unreachable(); - - this->gogo_->add_statement(Statement::make_continue_statement(label, - location)); -} - -// GotoStat = "goto" identifier . - -void -Parse::goto_stat() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_GOTO)); - source_location location = this->location(); - const Token* token = this->advance_token(); - if (!token->is_identifier()) - error_at(this->location(), "expected label for goto"); - else - { - Label* label = this->gogo_->add_label_reference(token->identifier()); - Statement* s = Statement::make_goto_statement(label, location); - this->gogo_->add_statement(s); - this->advance_token(); - } -} - -// PackageClause = "package" PackageName . - -void -Parse::package_clause() -{ - const Token* token = this->peek_token(); - source_location location = token->location(); - std::string name; - if (!token->is_keyword(KEYWORD_PACKAGE)) - { - error_at(this->location(), "program must start with package clause"); - name = "ERROR"; - } - else - { - token = this->advance_token(); - if (token->is_identifier()) - { - name = token->identifier(); - if (name == "_") - { - error_at(this->location(), "invalid package name _"); - name = "blank"; - } - this->advance_token(); - } - else - { - error_at(this->location(), "package name must be an identifier"); - name = "ERROR"; - } - } - this->gogo_->set_package_name(name, location); -} - -// ImportDecl = "import" Decl . - -void -Parse::import_decl() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_IMPORT)); - this->advance_token(); - this->decl(&Parse::import_spec, NULL); -} - -// ImportSpec = [ "." | PackageName ] PackageFileName . - -void -Parse::import_spec(void*) -{ - const Token* token = this->peek_token(); - source_location location = token->location(); - - std::string local_name; - bool is_local_name_exported = false; - if (token->is_op(OPERATOR_DOT)) - { - local_name = "."; - token = this->advance_token(); - } - else if (token->is_identifier()) - { - local_name = token->identifier(); - is_local_name_exported = token->is_identifier_exported(); - token = this->advance_token(); - } - - if (!token->is_string()) - { - error_at(this->location(), "missing import package name"); - return; - } - - this->gogo_->import_package(token->string_value(), local_name, - is_local_name_exported, location); - - this->advance_token(); -} - -// SourceFile = PackageClause ";" { ImportDecl ";" } -// { TopLevelDecl ";" } . - -void -Parse::program() -{ - this->package_clause(); - - const Token* token = this->peek_token(); - if (token->is_op(OPERATOR_SEMICOLON)) - token = this->advance_token(); - else - error_at(this->location(), - "expected %<;%> or newline after package clause"); - - while (token->is_keyword(KEYWORD_IMPORT)) - { - this->import_decl(); - token = this->peek_token(); - if (token->is_op(OPERATOR_SEMICOLON)) - token = this->advance_token(); - else - error_at(this->location(), - "expected %<;%> or newline after import declaration"); - } - - while (!token->is_eof()) - { - if (this->declaration_may_start_here()) - this->declaration(); - else - { - error_at(this->location(), "expected declaration"); - do - this->advance_token(); - while (!this->peek_token()->is_eof() - && !this->peek_token()->is_op(OPERATOR_SEMICOLON) - && !this->peek_token()->is_op(OPERATOR_RCURLY)); - if (!this->peek_token()->is_eof() - && !this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - } - token = this->peek_token(); - if (token->is_op(OPERATOR_SEMICOLON)) - token = this->advance_token(); - else if (!token->is_eof() || !saw_errors()) - { - error_at(this->location(), - "expected %<;%> or newline after top level declaration"); - this->skip_past_error(OPERATOR_INVALID); - } - } -} - -// Reset the current iota value. - -void -Parse::reset_iota() -{ - this->iota_ = 0; -} - -// Return the current iota value. - -int -Parse::iota_value() -{ - return this->iota_; -} - -// Increment the current iota value. - -void -Parse::increment_iota() -{ - ++this->iota_; -} - -// Skip forward to a semicolon or OP. OP will normally be -// OPERATOR_RPAREN or OPERATOR_RCURLY. If we find a semicolon, move -// past it and return. If we find OP, it will be the next token to -// read. Return true if we are OK, false if we found EOF. - -bool -Parse::skip_past_error(Operator op) -{ - const Token* token = this->peek_token(); - while (!token->is_op(op)) - { - if (token->is_eof()) - return false; - if (token->is_op(OPERATOR_SEMICOLON)) - { - this->advance_token(); - return true; - } - token = this->advance_token(); - } - return true; -} - -// Check that an expression is not a sink. - -Expression* -Parse::verify_not_sink(Expression* expr) -{ - if (expr->is_sink_expression()) - { - error_at(expr->location(), "cannot use _ as value"); - expr = Expression::make_error(expr->location()); - } - return expr; -} diff --git a/gcc/go/gofrontend/parse.cc.merge-right.r172891 b/gcc/go/gofrontend/parse.cc.merge-right.r172891 deleted file mode 100644 index eeb4f5da347..00000000000 --- a/gcc/go/gofrontend/parse.cc.merge-right.r172891 +++ /dev/null @@ -1,5131 +0,0 @@ -// parse.cc -- Go frontend parser. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include "lex.h" -#include "gogo.h" -#include "types.h" -#include "statements.h" -#include "expressions.h" -#include "parse.h" - -// Struct Parse::Enclosing_var_comparison. - -// Return true if v1 should be considered to be less than v2. - -bool -Parse::Enclosing_var_comparison::operator()(const Enclosing_var& v1, - const Enclosing_var& v2) -{ - if (v1.var() == v2.var()) - return false; - - const std::string& n1(v1.var()->name()); - const std::string& n2(v2.var()->name()); - int i = n1.compare(n2); - if (i < 0) - return true; - else if (i > 0) - return false; - - // If we get here it means that a single nested function refers to - // two different variables defined in enclosing functions, and both - // variables have the same name. I think this is impossible. - go_unreachable(); -} - -// Class Parse. - -Parse::Parse(Lex* lex, Gogo* gogo) - : lex_(lex), - token_(Token::make_invalid_token(0)), - unget_token_(Token::make_invalid_token(0)), - unget_token_valid_(false), - gogo_(gogo), - break_stack_(NULL), - continue_stack_(NULL), - iota_(0), - enclosing_vars_() -{ -} - -// Return the current token. - -const Token* -Parse::peek_token() -{ - if (this->unget_token_valid_) - return &this->unget_token_; - if (this->token_.is_invalid()) - this->token_ = this->lex_->next_token(); - return &this->token_; -} - -// Advance to the next token and return it. - -const Token* -Parse::advance_token() -{ - if (this->unget_token_valid_) - { - this->unget_token_valid_ = false; - if (!this->token_.is_invalid()) - return &this->token_; - } - this->token_ = this->lex_->next_token(); - return &this->token_; -} - -// Push a token back on the input stream. - -void -Parse::unget_token(const Token& token) -{ - go_assert(!this->unget_token_valid_); - this->unget_token_ = token; - this->unget_token_valid_ = true; -} - -// The location of the current token. - -source_location -Parse::location() -{ - return this->peek_token()->location(); -} - -// IdentifierList = identifier { "," identifier } . - -void -Parse::identifier_list(Typed_identifier_list* til) -{ - const Token* token = this->peek_token(); - while (true) - { - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return; - } - std::string name = - this->gogo_->pack_hidden_name(token->identifier(), - token->is_identifier_exported()); - til->push_back(Typed_identifier(name, NULL, token->location())); - token = this->advance_token(); - if (!token->is_op(OPERATOR_COMMA)) - return; - token = this->advance_token(); - } -} - -// ExpressionList = Expression { "," Expression } . - -// If MAY_BE_SINK is true, the expressions in the list may be "_". - -Expression_list* -Parse::expression_list(Expression* first, bool may_be_sink) -{ - Expression_list* ret = new Expression_list(); - if (first != NULL) - ret->push_back(first); - while (true) - { - ret->push_back(this->expression(PRECEDENCE_NORMAL, may_be_sink, true, - NULL)); - - const Token* token = this->peek_token(); - if (!token->is_op(OPERATOR_COMMA)) - return ret; - - // Most expression lists permit a trailing comma. - source_location location = token->location(); - this->advance_token(); - if (!this->expression_may_start_here()) - { - this->unget_token(Token::make_operator_token(OPERATOR_COMMA, - location)); - return ret; - } - } -} - -// QualifiedIdent = [ PackageName "." ] identifier . -// PackageName = identifier . - -// This sets *PNAME to the identifier and sets *PPACKAGE to the -// package or NULL if there isn't one. This returns true on success, -// false on failure in which case it will have emitted an error -// message. - -bool -Parse::qualified_ident(std::string* pname, Named_object** ppackage) -{ - const Token* token = this->peek_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return false; - } - - std::string name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - name = this->gogo_->pack_hidden_name(name, is_exported); - - token = this->advance_token(); - if (!token->is_op(OPERATOR_DOT)) - { - *pname = name; - *ppackage = NULL; - return true; - } - - Named_object* package = this->gogo_->lookup(name, NULL); - if (package == NULL || !package->is_package()) - { - error_at(this->location(), "expected package"); - // We expect . IDENTIFIER; skip both. - if (this->advance_token()->is_identifier()) - this->advance_token(); - return false; - } - - package->package_value()->set_used(); - - token = this->advance_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return false; - } - - name = token->identifier(); - - if (name == "_") - { - error_at(this->location(), "invalid use of %<_%>"); - name = "blank"; - } - - if (package->name() == this->gogo_->package_name()) - name = this->gogo_->pack_hidden_name(name, - token->is_identifier_exported()); - - *pname = name; - *ppackage = package; - - this->advance_token(); - - return true; -} - -// Type = TypeName | TypeLit | "(" Type ")" . -// TypeLit = -// ArrayType | StructType | PointerType | FunctionType | InterfaceType | -// SliceType | MapType | ChannelType . - -Type* -Parse::type() -{ - const Token* token = this->peek_token(); - if (token->is_identifier()) - return this->type_name(true); - else if (token->is_op(OPERATOR_LSQUARE)) - return this->array_type(false); - else if (token->is_keyword(KEYWORD_CHAN) - || token->is_op(OPERATOR_CHANOP)) - return this->channel_type(); - else if (token->is_keyword(KEYWORD_INTERFACE)) - return this->interface_type(); - else if (token->is_keyword(KEYWORD_FUNC)) - { - source_location location = token->location(); - this->advance_token(); - Type* type = this->signature(NULL, location); - if (type == NULL) - return Type::make_error_type(); - return type; - } - else if (token->is_keyword(KEYWORD_MAP)) - return this->map_type(); - else if (token->is_keyword(KEYWORD_STRUCT)) - return this->struct_type(); - else if (token->is_op(OPERATOR_MULT)) - return this->pointer_type(); - else if (token->is_op(OPERATOR_LPAREN)) - { - this->advance_token(); - Type* ret = this->type(); - if (this->peek_token()->is_op(OPERATOR_RPAREN)) - this->advance_token(); - else - { - if (!ret->is_error_type()) - error_at(this->location(), "expected %<)%>"); - } - return ret; - } - else - { - error_at(token->location(), "expected type"); - return Type::make_error_type(); - } -} - -bool -Parse::type_may_start_here() -{ - const Token* token = this->peek_token(); - return (token->is_identifier() - || token->is_op(OPERATOR_LSQUARE) - || token->is_op(OPERATOR_CHANOP) - || token->is_keyword(KEYWORD_CHAN) - || token->is_keyword(KEYWORD_INTERFACE) - || token->is_keyword(KEYWORD_FUNC) - || token->is_keyword(KEYWORD_MAP) - || token->is_keyword(KEYWORD_STRUCT) - || token->is_op(OPERATOR_MULT) - || token->is_op(OPERATOR_LPAREN)); -} - -// TypeName = QualifiedIdent . - -// If MAY_BE_NIL is true, then an identifier with the value of the -// predefined constant nil is accepted, returning the nil type. - -Type* -Parse::type_name(bool issue_error) -{ - source_location location = this->location(); - - std::string name; - Named_object* package; - if (!this->qualified_ident(&name, &package)) - return Type::make_error_type(); - - Named_object* named_object; - if (package == NULL) - named_object = this->gogo_->lookup(name, NULL); - else - { - named_object = package->package_value()->lookup(name); - if (named_object == NULL - && issue_error - && package->name() != this->gogo_->package_name()) - { - // Check whether the name is there but hidden. - std::string s = ('.' + package->package_value()->unique_prefix() - + '.' + package->package_value()->name() - + '.' + name); - named_object = package->package_value()->lookup(s); - if (named_object != NULL) - { - const std::string& packname(package->package_value()->name()); - error_at(location, "invalid reference to hidden type %<%s.%s%>", - Gogo::message_name(packname).c_str(), - Gogo::message_name(name).c_str()); - issue_error = false; - } - } - } - - bool ok = true; - if (named_object == NULL) - { - if (package != NULL) - ok = false; - else - named_object = this->gogo_->add_unknown_name(name, location); - } - else if (named_object->is_type()) - { - if (!named_object->type_value()->is_visible()) - ok = false; - } - else if (named_object->is_unknown() || named_object->is_type_declaration()) - ; - else - ok = false; - - if (!ok) - { - if (issue_error) - error_at(location, "expected type"); - return Type::make_error_type(); - } - - if (named_object->is_type()) - return named_object->type_value(); - else if (named_object->is_unknown() || named_object->is_type_declaration()) - return Type::make_forward_declaration(named_object); - else - go_unreachable(); -} - -// ArrayType = "[" [ ArrayLength ] "]" ElementType . -// ArrayLength = Expression . -// ElementType = CompleteType . - -Type* -Parse::array_type(bool may_use_ellipsis) -{ - go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE)); - const Token* token = this->advance_token(); - - Expression* length = NULL; - if (token->is_op(OPERATOR_RSQUARE)) - this->advance_token(); - else - { - if (!token->is_op(OPERATOR_ELLIPSIS)) - length = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - else if (may_use_ellipsis) - { - // An ellipsis is used in composite literals to represent a - // fixed array of the size of the number of elements. We - // use a length of nil to represent this, and change the - // length when parsing the composite literal. - length = Expression::make_nil(this->location()); - this->advance_token(); - } - else - { - error_at(this->location(), - "use of %<[...]%> outside of array literal"); - length = Expression::make_error(this->location()); - this->advance_token(); - } - if (!this->peek_token()->is_op(OPERATOR_RSQUARE)) - { - error_at(this->location(), "expected %<]%>"); - return Type::make_error_type(); - } - this->advance_token(); - } - - Type* element_type = this->type(); - - return Type::make_array_type(element_type, length); -} - -// MapType = "map" "[" KeyType "]" ValueType . -// KeyType = CompleteType . -// ValueType = CompleteType . - -Type* -Parse::map_type() -{ - source_location location = this->location(); - go_assert(this->peek_token()->is_keyword(KEYWORD_MAP)); - if (!this->advance_token()->is_op(OPERATOR_LSQUARE)) - { - error_at(this->location(), "expected %<[%>"); - return Type::make_error_type(); - } - this->advance_token(); - - Type* key_type = this->type(); - - if (!this->peek_token()->is_op(OPERATOR_RSQUARE)) - { - error_at(this->location(), "expected %<]%>"); - return Type::make_error_type(); - } - this->advance_token(); - - Type* value_type = this->type(); - - if (key_type->is_error_type() || value_type->is_error_type()) - return Type::make_error_type(); - - return Type::make_map_type(key_type, value_type, location); -} - -// StructType = "struct" "{" { FieldDecl ";" } "}" . - -Type* -Parse::struct_type() -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_STRUCT)); - source_location location = this->location(); - if (!this->advance_token()->is_op(OPERATOR_LCURLY)) - { - source_location token_loc = this->location(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(token_loc, "unexpected semicolon or newline before %<{%>"); - else - { - error_at(this->location(), "expected %<{%>"); - return Type::make_error_type(); - } - } - this->advance_token(); - - Struct_field_list* sfl = new Struct_field_list; - while (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - this->field_decl(sfl); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - else if (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - error_at(this->location(), "expected %<;%> or %<}%> or newline"); - if (!this->skip_past_error(OPERATOR_RCURLY)) - return Type::make_error_type(); - } - } - this->advance_token(); - - for (Struct_field_list::const_iterator pi = sfl->begin(); - pi != sfl->end(); - ++pi) - { - if (pi->type()->is_error_type()) - return pi->type(); - for (Struct_field_list::const_iterator pj = pi + 1; - pj != sfl->end(); - ++pj) - { - if (pi->field_name() == pj->field_name() - && !Gogo::is_sink_name(pi->field_name())) - error_at(pi->location(), "duplicate field name %<%s%>", - Gogo::message_name(pi->field_name()).c_str()); - } - } - - return Type::make_struct_type(sfl, location); -} - -// FieldDecl = (IdentifierList CompleteType | TypeName) [ Tag ] . -// Tag = string_lit . - -void -Parse::field_decl(Struct_field_list* sfl) -{ - const Token* token = this->peek_token(); - source_location location = token->location(); - bool is_anonymous; - bool is_anonymous_pointer; - if (token->is_op(OPERATOR_MULT)) - { - is_anonymous = true; - is_anonymous_pointer = true; - } - else if (token->is_identifier()) - { - std::string id = token->identifier(); - bool is_id_exported = token->is_identifier_exported(); - source_location id_location = token->location(); - token = this->advance_token(); - is_anonymous = (token->is_op(OPERATOR_SEMICOLON) - || token->is_op(OPERATOR_RCURLY) - || token->is_op(OPERATOR_DOT) - || token->is_string()); - is_anonymous_pointer = false; - this->unget_token(Token::make_identifier_token(id, is_id_exported, - id_location)); - } - else - { - error_at(this->location(), "expected field name"); - while (!token->is_op(OPERATOR_SEMICOLON) - && !token->is_op(OPERATOR_RCURLY) - && !token->is_eof()) - token = this->advance_token(); - return; - } - - if (is_anonymous) - { - if (is_anonymous_pointer) - { - this->advance_token(); - if (!this->peek_token()->is_identifier()) - { - error_at(this->location(), "expected field name"); - while (!token->is_op(OPERATOR_SEMICOLON) - && !token->is_op(OPERATOR_RCURLY) - && !token->is_eof()) - token = this->advance_token(); - return; - } - } - Type* type = this->type_name(true); - - std::string tag; - if (this->peek_token()->is_string()) - { - tag = this->peek_token()->string_value(); - this->advance_token(); - } - - if (!type->is_error_type()) - { - if (is_anonymous_pointer) - type = Type::make_pointer_type(type); - sfl->push_back(Struct_field(Typed_identifier("", type, location))); - if (!tag.empty()) - sfl->back().set_tag(tag); - } - } - else - { - Typed_identifier_list til; - while (true) - { - token = this->peek_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return; - } - std::string name = - this->gogo_->pack_hidden_name(token->identifier(), - token->is_identifier_exported()); - til.push_back(Typed_identifier(name, NULL, token->location())); - if (!this->advance_token()->is_op(OPERATOR_COMMA)) - break; - this->advance_token(); - } - - Type* type = this->type(); - - std::string tag; - if (this->peek_token()->is_string()) - { - tag = this->peek_token()->string_value(); - this->advance_token(); - } - - for (Typed_identifier_list::iterator p = til.begin(); - p != til.end(); - ++p) - { - p->set_type(type); - sfl->push_back(Struct_field(*p)); - if (!tag.empty()) - sfl->back().set_tag(tag); - } - } -} - -// PointerType = "*" Type . - -Type* -Parse::pointer_type() -{ - go_assert(this->peek_token()->is_op(OPERATOR_MULT)); - this->advance_token(); - Type* type = this->type(); - if (type->is_error_type()) - return type; - return Type::make_pointer_type(type); -} - -// ChannelType = Channel | SendChannel | RecvChannel . -// Channel = "chan" ElementType . -// SendChannel = "chan" "<-" ElementType . -// RecvChannel = "<-" "chan" ElementType . - -Type* -Parse::channel_type() -{ - const Token* token = this->peek_token(); - bool send = true; - bool receive = true; - if (token->is_op(OPERATOR_CHANOP)) - { - if (!this->advance_token()->is_keyword(KEYWORD_CHAN)) - { - error_at(this->location(), "expected %"); - return Type::make_error_type(); - } - send = false; - this->advance_token(); - } - else - { - go_assert(token->is_keyword(KEYWORD_CHAN)); - if (this->advance_token()->is_op(OPERATOR_CHANOP)) - { - receive = false; - this->advance_token(); - } - } - - // Better error messages for the common error of omitting the - // channel element type. - if (!this->type_may_start_here()) - { - token = this->peek_token(); - if (token->is_op(OPERATOR_RCURLY)) - error_at(this->location(), "unexpected %<}%> in channel type"); - else if (token->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "unexpected %<)%> in channel type"); - else if (token->is_op(OPERATOR_COMMA)) - error_at(this->location(), "unexpected comma in channel type"); - else - error_at(this->location(), "expected channel element type"); - return Type::make_error_type(); - } - - Type* element_type = this->type(); - return Type::make_channel_type(send, receive, element_type); -} - -// Signature = Parameters [ Result ] . - -// RECEIVER is the receiver if there is one, or NULL. LOCATION is the -// location of the start of the type. - -// This returns NULL on a parse error. - -Function_type* -Parse::signature(Typed_identifier* receiver, source_location location) -{ - bool is_varargs = false; - Typed_identifier_list* params; - bool params_ok = this->parameters(¶ms, &is_varargs); - - Typed_identifier_list* result = NULL; - if (this->peek_token()->is_op(OPERATOR_LPAREN) - || this->type_may_start_here()) - { - if (!this->result(&result)) - return NULL; - } - - if (!params_ok) - return NULL; - - Function_type* ret = Type::make_function_type(receiver, params, result, - location); - if (is_varargs) - ret->set_is_varargs(); - return ret; -} - -// Parameters = "(" [ ParameterList [ "," ] ] ")" . - -// This returns false on a parse error. - -bool -Parse::parameters(Typed_identifier_list** pparams, bool* is_varargs) -{ - *pparams = NULL; - - if (!this->peek_token()->is_op(OPERATOR_LPAREN)) - { - error_at(this->location(), "expected %<(%>"); - return false; - } - - Typed_identifier_list* params = NULL; - bool saw_error = false; - - const Token* token = this->advance_token(); - if (!token->is_op(OPERATOR_RPAREN)) - { - params = this->parameter_list(is_varargs); - if (params == NULL) - saw_error = true; - token = this->peek_token(); - } - - // The optional trailing comma is picked up in parameter_list. - - if (!token->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "expected %<)%>"); - else - this->advance_token(); - - if (saw_error) - return false; - - *pparams = params; - return true; -} - -// ParameterList = ParameterDecl { "," ParameterDecl } . - -// This sets *IS_VARARGS if the list ends with an ellipsis. -// IS_VARARGS will be NULL if varargs are not permitted. - -// We pick up an optional trailing comma. - -// This returns NULL if some error is seen. - -Typed_identifier_list* -Parse::parameter_list(bool* is_varargs) -{ - source_location location = this->location(); - Typed_identifier_list* ret = new Typed_identifier_list(); - - bool saw_error = false; - - // If we see an identifier and then a comma, then we don't know - // whether we are looking at a list of identifiers followed by a - // type, or a list of types given by name. We have to do an - // arbitrary lookahead to figure it out. - - bool parameters_have_names; - const Token* token = this->peek_token(); - if (!token->is_identifier()) - { - // This must be a type which starts with something like '*'. - parameters_have_names = false; - } - else - { - std::string name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - token = this->advance_token(); - if (!token->is_op(OPERATOR_COMMA)) - { - if (token->is_op(OPERATOR_DOT)) - { - // This is a qualified identifier, which must turn out - // to be a type. - parameters_have_names = false; - } - else if (token->is_op(OPERATOR_RPAREN)) - { - // A single identifier followed by a parenthesis must be - // a type name. - parameters_have_names = false; - } - else - { - // An identifier followed by something other than a - // comma or a dot or a right parenthesis must be a - // parameter name followed by a type. - parameters_have_names = true; - } - - this->unget_token(Token::make_identifier_token(name, is_exported, - location)); - } - else - { - // An identifier followed by a comma may be the first in a - // list of parameter names followed by a type, or it may be - // the first in a list of types without parameter names. To - // find out we gather as many identifiers separated by - // commas as we can. - std::string id_name = this->gogo_->pack_hidden_name(name, - is_exported); - ret->push_back(Typed_identifier(id_name, NULL, location)); - bool just_saw_comma = true; - while (this->advance_token()->is_identifier()) - { - name = this->peek_token()->identifier(); - is_exported = this->peek_token()->is_identifier_exported(); - location = this->peek_token()->location(); - id_name = this->gogo_->pack_hidden_name(name, is_exported); - ret->push_back(Typed_identifier(id_name, NULL, location)); - if (!this->advance_token()->is_op(OPERATOR_COMMA)) - { - just_saw_comma = false; - break; - } - } - - if (just_saw_comma) - { - // We saw ID1 "," ID2 "," followed by something which - // was not an identifier. We must be seeing the start - // of a type, and ID1 and ID2 must be types, and the - // parameters don't have names. - parameters_have_names = false; - } - else if (this->peek_token()->is_op(OPERATOR_RPAREN)) - { - // We saw ID1 "," ID2 ")". ID1 and ID2 must be types, - // and the parameters don't have names. - parameters_have_names = false; - } - else if (this->peek_token()->is_op(OPERATOR_DOT)) - { - // We saw ID1 "," ID2 ".". ID2 must be a package name, - // ID1 must be a type, and the parameters don't have - // names. - parameters_have_names = false; - this->unget_token(Token::make_identifier_token(name, is_exported, - location)); - ret->pop_back(); - just_saw_comma = true; - } - else - { - // We saw ID1 "," ID2 followed by something other than - // ",", ".", or ")". We must be looking at the start of - // a type, and ID1 and ID2 must be parameter names. - parameters_have_names = true; - } - - if (parameters_have_names) - { - go_assert(!just_saw_comma); - // We have just seen ID1, ID2 xxx. - Type* type; - if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS)) - type = this->type(); - else - { - error_at(this->location(), "%<...%> only permits one name"); - saw_error = true; - this->advance_token(); - type = this->type(); - } - for (size_t i = 0; i < ret->size(); ++i) - ret->set_type(i, type); - if (!this->peek_token()->is_op(OPERATOR_COMMA)) - return saw_error ? NULL : ret; - if (this->advance_token()->is_op(OPERATOR_RPAREN)) - return saw_error ? NULL : ret; - } - else - { - Typed_identifier_list* tret = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator p = ret->begin(); - p != ret->end(); - ++p) - { - Named_object* no = this->gogo_->lookup(p->name(), NULL); - Type* type; - if (no == NULL) - no = this->gogo_->add_unknown_name(p->name(), - p->location()); - - if (no->is_type()) - type = no->type_value(); - else if (no->is_unknown() || no->is_type_declaration()) - type = Type::make_forward_declaration(no); - else - { - error_at(p->location(), "expected %<%s%> to be a type", - Gogo::message_name(p->name()).c_str()); - saw_error = true; - type = Type::make_error_type(); - } - tret->push_back(Typed_identifier("", type, p->location())); - } - delete ret; - ret = tret; - if (!just_saw_comma - || this->peek_token()->is_op(OPERATOR_RPAREN)) - return saw_error ? NULL : ret; - } - } - } - - bool mix_error = false; - this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error); - while (this->peek_token()->is_op(OPERATOR_COMMA)) - { - if (is_varargs != NULL && *is_varargs) - { - error_at(this->location(), "%<...%> must be last parameter"); - saw_error = true; - } - if (this->advance_token()->is_op(OPERATOR_RPAREN)) - break; - this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error); - } - if (mix_error) - { - error_at(location, "invalid named/anonymous mix"); - saw_error = true; - } - if (saw_error) - { - delete ret; - return NULL; - } - return ret; -} - -// ParameterDecl = [ IdentifierList ] [ "..." ] Type . - -void -Parse::parameter_decl(bool parameters_have_names, - Typed_identifier_list* til, - bool* is_varargs, - bool* mix_error) -{ - if (!parameters_have_names) - { - Type* type; - source_location location = this->location(); - if (!this->peek_token()->is_identifier()) - { - if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS)) - type = this->type(); - else - { - if (is_varargs == NULL) - error_at(this->location(), "invalid use of %<...%>"); - else - *is_varargs = true; - this->advance_token(); - if (is_varargs == NULL - && this->peek_token()->is_op(OPERATOR_RPAREN)) - type = Type::make_error_type(); - else - { - Type* element_type = this->type(); - type = Type::make_array_type(element_type, NULL); - } - } - } - else - { - type = this->type_name(false); - if (type->is_error_type() - || (!this->peek_token()->is_op(OPERATOR_COMMA) - && !this->peek_token()->is_op(OPERATOR_RPAREN))) - { - *mix_error = true; - while (!this->peek_token()->is_op(OPERATOR_COMMA) - && !this->peek_token()->is_op(OPERATOR_RPAREN)) - this->advance_token(); - } - } - if (!type->is_error_type()) - til->push_back(Typed_identifier("", type, location)); - } - else - { - size_t orig_count = til->size(); - if (this->peek_token()->is_identifier()) - this->identifier_list(til); - else - *mix_error = true; - size_t new_count = til->size(); - - Type* type; - if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS)) - type = this->type(); - else - { - if (is_varargs == NULL) - error_at(this->location(), "invalid use of %<...%>"); - else if (new_count > orig_count + 1) - error_at(this->location(), "%<...%> only permits one name"); - else - *is_varargs = true; - this->advance_token(); - Type* element_type = this->type(); - type = Type::make_array_type(element_type, NULL); - } - for (size_t i = orig_count; i < new_count; ++i) - til->set_type(i, type); - } -} - -// Result = Parameters | Type . - -// This returns false on a parse error. - -bool -Parse::result(Typed_identifier_list** presults) -{ - if (this->peek_token()->is_op(OPERATOR_LPAREN)) - return this->parameters(presults, NULL); - else - { - source_location location = this->location(); - Type* type = this->type(); - if (type->is_error_type()) - { - *presults = NULL; - return false; - } - Typed_identifier_list* til = new Typed_identifier_list(); - til->push_back(Typed_identifier("", type, location)); - *presults = til; - return true; - } -} - -// Block = "{" [ StatementList ] "}" . - -// Returns the location of the closing brace. - -source_location -Parse::block() -{ - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - { - source_location loc = this->location(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(loc, "unexpected semicolon or newline before %<{%>"); - else - { - error_at(this->location(), "expected %<{%>"); - return UNKNOWN_LOCATION; - } - } - - const Token* token = this->advance_token(); - - if (!token->is_op(OPERATOR_RCURLY)) - { - this->statement_list(); - token = this->peek_token(); - if (!token->is_op(OPERATOR_RCURLY)) - { - if (!token->is_eof() || !saw_errors()) - error_at(this->location(), "expected %<}%>"); - - // Skip ahead to the end of the block, in hopes of avoiding - // lots of meaningless errors. - source_location ret = token->location(); - int nest = 0; - while (!token->is_eof()) - { - if (token->is_op(OPERATOR_LCURLY)) - ++nest; - else if (token->is_op(OPERATOR_RCURLY)) - { - --nest; - if (nest < 0) - { - this->advance_token(); - break; - } - } - token = this->advance_token(); - ret = token->location(); - } - return ret; - } - } - - source_location ret = token->location(); - this->advance_token(); - return ret; -} - -// InterfaceType = "interface" "{" [ MethodSpecList ] "}" . -// MethodSpecList = MethodSpec { ";" MethodSpec } [ ";" ] . - -Type* -Parse::interface_type() -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_INTERFACE)); - source_location location = this->location(); - - if (!this->advance_token()->is_op(OPERATOR_LCURLY)) - { - source_location token_loc = this->location(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(token_loc, "unexpected semicolon or newline before %<{%>"); - else - { - error_at(this->location(), "expected %<{%>"); - return Type::make_error_type(); - } - } - this->advance_token(); - - Typed_identifier_list* methods = new Typed_identifier_list(); - if (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - this->method_spec(methods); - while (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - if (this->advance_token()->is_op(OPERATOR_RCURLY)) - break; - this->method_spec(methods); - } - if (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - error_at(this->location(), "expected %<}%>"); - while (!this->advance_token()->is_op(OPERATOR_RCURLY)) - { - if (this->peek_token()->is_eof()) - return Type::make_error_type(); - } - } - } - this->advance_token(); - - if (methods->empty()) - { - delete methods; - methods = NULL; - } - - Interface_type* ret = Type::make_interface_type(methods, location); - this->gogo_->record_interface_type(ret); - return ret; -} - -// MethodSpec = MethodName Signature | InterfaceTypeName . -// MethodName = identifier . -// InterfaceTypeName = TypeName . - -void -Parse::method_spec(Typed_identifier_list* methods) -{ - const Token* token = this->peek_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return; - } - - std::string name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - - if (this->advance_token()->is_op(OPERATOR_LPAREN)) - { - // This is a MethodName. - name = this->gogo_->pack_hidden_name(name, is_exported); - Type* type = this->signature(NULL, location); - if (type == NULL) - return; - methods->push_back(Typed_identifier(name, type, location)); - } - else - { - this->unget_token(Token::make_identifier_token(name, is_exported, - location)); - Type* type = this->type_name(false); - if (type->is_error_type() - || (!this->peek_token()->is_op(OPERATOR_SEMICOLON) - && !this->peek_token()->is_op(OPERATOR_RCURLY))) - { - if (this->peek_token()->is_op(OPERATOR_COMMA)) - error_at(this->location(), - "name list not allowed in interface type"); - else - error_at(location, "expected signature or type name"); - token = this->peek_token(); - while (!token->is_eof() - && !token->is_op(OPERATOR_SEMICOLON) - && !token->is_op(OPERATOR_RCURLY)) - token = this->advance_token(); - return; - } - // This must be an interface type, but we can't check that now. - // We check it and pull out the methods in - // Interface_type::do_verify. - methods->push_back(Typed_identifier("", type, location)); - } -} - -// Declaration = ConstDecl | TypeDecl | VarDecl | FunctionDecl | MethodDecl . - -void -Parse::declaration() -{ - const Token* token = this->peek_token(); - if (token->is_keyword(KEYWORD_CONST)) - this->const_decl(); - else if (token->is_keyword(KEYWORD_TYPE)) - this->type_decl(); - else if (token->is_keyword(KEYWORD_VAR)) - this->var_decl(); - else if (token->is_keyword(KEYWORD_FUNC)) - this->function_decl(); - else - { - error_at(this->location(), "expected declaration"); - this->advance_token(); - } -} - -bool -Parse::declaration_may_start_here() -{ - const Token* token = this->peek_token(); - return (token->is_keyword(KEYWORD_CONST) - || token->is_keyword(KEYWORD_TYPE) - || token->is_keyword(KEYWORD_VAR) - || token->is_keyword(KEYWORD_FUNC)); -} - -// Decl

= P | "(" [ List

] ")" . - -void -Parse::decl(void (Parse::*pfn)(void*), void* varg) -{ - if (!this->peek_token()->is_op(OPERATOR_LPAREN)) - (this->*pfn)(varg); - else - { - if (!this->advance_token()->is_op(OPERATOR_RPAREN)) - { - this->list(pfn, varg, true); - if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - { - error_at(this->location(), "missing %<)%>"); - while (!this->advance_token()->is_op(OPERATOR_RPAREN)) - { - if (this->peek_token()->is_eof()) - return; - } - } - } - this->advance_token(); - } -} - -// List

= P { ";" P } [ ";" ] . - -// In order to pick up the trailing semicolon we need to know what -// might follow. This is either a '}' or a ')'. - -void -Parse::list(void (Parse::*pfn)(void*), void* varg, bool follow_is_paren) -{ - (this->*pfn)(varg); - Operator follow = follow_is_paren ? OPERATOR_RPAREN : OPERATOR_RCURLY; - while (this->peek_token()->is_op(OPERATOR_SEMICOLON) - || this->peek_token()->is_op(OPERATOR_COMMA)) - { - if (this->peek_token()->is_op(OPERATOR_COMMA)) - error_at(this->location(), "unexpected comma"); - if (this->advance_token()->is_op(follow)) - break; - (this->*pfn)(varg); - } -} - -// ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) . - -void -Parse::const_decl() -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_CONST)); - this->advance_token(); - this->reset_iota(); - - Type* last_type = NULL; - Expression_list* last_expr_list = NULL; - - if (!this->peek_token()->is_op(OPERATOR_LPAREN)) - this->const_spec(&last_type, &last_expr_list); - else - { - this->advance_token(); - while (!this->peek_token()->is_op(OPERATOR_RPAREN)) - { - this->const_spec(&last_type, &last_expr_list); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - else if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - { - error_at(this->location(), "expected %<;%> or %<)%> or newline"); - if (!this->skip_past_error(OPERATOR_RPAREN)) - return; - } - } - this->advance_token(); - } - - if (last_expr_list != NULL) - delete last_expr_list; -} - -// ConstSpec = IdentifierList [ [ CompleteType ] "=" ExpressionList ] . - -void -Parse::const_spec(Type** last_type, Expression_list** last_expr_list) -{ - Typed_identifier_list til; - this->identifier_list(&til); - - Type* type = NULL; - if (this->type_may_start_here()) - { - type = this->type(); - *last_type = NULL; - *last_expr_list = NULL; - } - - Expression_list *expr_list; - if (!this->peek_token()->is_op(OPERATOR_EQ)) - { - if (*last_expr_list == NULL) - { - error_at(this->location(), "expected %<=%>"); - return; - } - type = *last_type; - expr_list = new Expression_list; - for (Expression_list::const_iterator p = (*last_expr_list)->begin(); - p != (*last_expr_list)->end(); - ++p) - expr_list->push_back((*p)->copy()); - } - else - { - this->advance_token(); - expr_list = this->expression_list(NULL, false); - *last_type = type; - if (*last_expr_list != NULL) - delete *last_expr_list; - *last_expr_list = expr_list; - } - - Expression_list::const_iterator pe = expr_list->begin(); - for (Typed_identifier_list::iterator pi = til.begin(); - pi != til.end(); - ++pi, ++pe) - { - if (pe == expr_list->end()) - { - error_at(this->location(), "not enough initializers"); - return; - } - if (type != NULL) - pi->set_type(type); - - if (!Gogo::is_sink_name(pi->name())) - this->gogo_->add_constant(*pi, *pe, this->iota_value()); - } - if (pe != expr_list->end()) - error_at(this->location(), "too many initializers"); - - this->increment_iota(); - - return; -} - -// TypeDecl = "type" Decl . - -void -Parse::type_decl() -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_TYPE)); - this->advance_token(); - this->decl(&Parse::type_spec, NULL); -} - -// TypeSpec = identifier Type . - -void -Parse::type_spec(void*) -{ - const Token* token = this->peek_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return; - } - std::string name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - token = this->advance_token(); - - // The scope of the type name starts at the point where the - // identifier appears in the source code. We implement this by - // declaring the type before we read the type definition. - Named_object* named_type = NULL; - if (name != "_") - { - name = this->gogo_->pack_hidden_name(name, is_exported); - named_type = this->gogo_->declare_type(name, location); - } - - Type* type; - if (!this->peek_token()->is_op(OPERATOR_SEMICOLON)) - type = this->type(); - else - { - error_at(this->location(), - "unexpected semicolon or newline in type declaration"); - type = Type::make_error_type(); - this->advance_token(); - } - - if (type->is_error_type()) - { - while (!this->peek_token()->is_op(OPERATOR_SEMICOLON) - && !this->peek_token()->is_eof()) - this->advance_token(); - } - - if (name != "_") - { - if (named_type->is_type_declaration()) - { - Type* ftype = type->forwarded(); - if (ftype->forward_declaration_type() != NULL - && (ftype->forward_declaration_type()->named_object() - == named_type)) - { - error_at(location, "invalid recursive type"); - type = Type::make_error_type(); - } - - this->gogo_->define_type(named_type, - Type::make_named_type(named_type, type, - location)); - go_assert(named_type->package() == NULL); - } - else - { - // This will probably give a redefinition error. - this->gogo_->add_type(name, type, location); - } - } -} - -// VarDecl = "var" Decl . - -void -Parse::var_decl() -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_VAR)); - this->advance_token(); - this->decl(&Parse::var_spec, NULL); -} - -// VarSpec = IdentifierList -// ( CompleteType [ "=" ExpressionList ] | "=" ExpressionList ) . - -void -Parse::var_spec(void*) -{ - // Get the variable names. - Typed_identifier_list til; - this->identifier_list(&til); - - source_location location = this->location(); - - Type* type = NULL; - Expression_list* init = NULL; - if (!this->peek_token()->is_op(OPERATOR_EQ)) - { - type = this->type(); - if (type->is_error_type()) - { - while (!this->peek_token()->is_op(OPERATOR_EQ) - && !this->peek_token()->is_op(OPERATOR_SEMICOLON) - && !this->peek_token()->is_eof()) - this->advance_token(); - } - if (this->peek_token()->is_op(OPERATOR_EQ)) - { - this->advance_token(); - init = this->expression_list(NULL, false); - } - } - else - { - this->advance_token(); - init = this->expression_list(NULL, false); - } - - this->init_vars(&til, type, init, false, location); - - if (init != NULL) - delete init; -} - -// Create variables. TIL is a list of variable names. If TYPE is not -// NULL, it is the type of all the variables. If INIT is not NULL, it -// is an initializer list for the variables. - -void -Parse::init_vars(const Typed_identifier_list* til, Type* type, - Expression_list* init, bool is_coloneq, - source_location location) -{ - // Check for an initialization which can yield multiple values. - if (init != NULL && init->size() == 1 && til->size() > 1) - { - if (this->init_vars_from_call(til, type, *init->begin(), is_coloneq, - location)) - return; - if (this->init_vars_from_map(til, type, *init->begin(), is_coloneq, - location)) - return; - if (this->init_vars_from_receive(til, type, *init->begin(), is_coloneq, - location)) - return; - if (this->init_vars_from_type_guard(til, type, *init->begin(), - is_coloneq, location)) - return; - } - - if (init != NULL && init->size() != til->size()) - { - if (init->empty() || !init->front()->is_error_expression()) - error_at(location, "wrong number of initializations"); - init = NULL; - if (type == NULL) - type = Type::make_error_type(); - } - - // Note that INIT was already parsed with the old name bindings, so - // we don't have to worry that it will accidentally refer to the - // newly declared variables. - - Expression_list::const_iterator pexpr; - if (init != NULL) - pexpr = init->begin(); - bool any_new = false; - for (Typed_identifier_list::const_iterator p = til->begin(); - p != til->end(); - ++p) - { - if (init != NULL) - go_assert(pexpr != init->end()); - this->init_var(*p, type, init == NULL ? NULL : *pexpr, is_coloneq, - false, &any_new); - if (init != NULL) - ++pexpr; - } - if (init != NULL) - go_assert(pexpr == init->end()); - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); -} - -// See if we need to initialize a list of variables from a function -// call. This returns true if we have set up the variables and the -// initialization. - -bool -Parse::init_vars_from_call(const Typed_identifier_list* vars, Type* type, - Expression* expr, bool is_coloneq, - source_location location) -{ - Call_expression* call = expr->call_expression(); - if (call == NULL) - return false; - - // This is a function call. We can't check here whether it returns - // the right number of values, but it might. Declare the variables, - // and then assign the results of the call to them. - - unsigned int index = 0; - bool any_new = false; - for (Typed_identifier_list::const_iterator pv = vars->begin(); - pv != vars->end(); - ++pv, ++index) - { - Expression* init = Expression::make_call_result(call, index); - this->init_var(*pv, type, init, is_coloneq, false, &any_new); - } - - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); - - return true; -} - -// See if we need to initialize a pair of values from a map index -// expression. This returns true if we have set up the variables and -// the initialization. - -bool -Parse::init_vars_from_map(const Typed_identifier_list* vars, Type* type, - Expression* expr, bool is_coloneq, - source_location location) -{ - Index_expression* index = expr->index_expression(); - if (index == NULL) - return false; - if (vars->size() != 2) - return false; - - // This is an index which is being assigned to two variables. It - // must be a map index. Declare the variables, and then assign the - // results of the map index. - bool any_new = false; - Typed_identifier_list::const_iterator p = vars->begin(); - Expression* init = type == NULL ? index : NULL; - Named_object* val_no = this->init_var(*p, type, init, is_coloneq, - type == NULL, &any_new); - if (type == NULL && any_new && val_no->is_variable()) - val_no->var_value()->set_type_from_init_tuple(); - Expression* val_var = Expression::make_var_reference(val_no, location); - - ++p; - Type* var_type = type; - if (var_type == NULL) - var_type = Type::lookup_bool_type(); - Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false, - &any_new); - Expression* present_var = Expression::make_var_reference(no, location); - - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); - - Statement* s = Statement::make_tuple_map_assignment(val_var, present_var, - index, location); - - if (!this->gogo_->in_global_scope()) - this->gogo_->add_statement(s); - else if (!val_no->is_sink()) - { - if (val_no->is_variable()) - val_no->var_value()->add_preinit_statement(this->gogo_, s); - } - else if (!no->is_sink()) - { - if (no->is_variable()) - no->var_value()->add_preinit_statement(this->gogo_, s); - } - else - { - // Execute the map index expression just so that we can fail if - // the map is nil. - Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(), - NULL, location); - dummy->var_value()->add_preinit_statement(this->gogo_, s); - } - - return true; -} - -// See if we need to initialize a pair of values from a receive -// expression. This returns true if we have set up the variables and -// the initialization. - -bool -Parse::init_vars_from_receive(const Typed_identifier_list* vars, Type* type, - Expression* expr, bool is_coloneq, - source_location location) -{ - Receive_expression* receive = expr->receive_expression(); - if (receive == NULL) - return false; - if (vars->size() != 2) - return false; - - // This is a receive expression which is being assigned to two - // variables. Declare the variables, and then assign the results of - // the receive. - bool any_new = false; - Typed_identifier_list::const_iterator p = vars->begin(); - Expression* init = type == NULL ? receive : NULL; - Named_object* val_no = this->init_var(*p, type, init, is_coloneq, - type == NULL, &any_new); - if (type == NULL && any_new && val_no->is_variable()) - val_no->var_value()->set_type_from_init_tuple(); - Expression* val_var = Expression::make_var_reference(val_no, location); - - ++p; - Type* var_type = type; - if (var_type == NULL) - var_type = Type::lookup_bool_type(); - Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false, - &any_new); - Expression* received_var = Expression::make_var_reference(no, location); - - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); - - Statement* s = Statement::make_tuple_receive_assignment(val_var, - received_var, - receive->channel(), - false, - location); - - if (!this->gogo_->in_global_scope()) - this->gogo_->add_statement(s); - else if (!val_no->is_sink()) - { - if (val_no->is_variable()) - val_no->var_value()->add_preinit_statement(this->gogo_, s); - } - else if (!no->is_sink()) - { - if (no->is_variable()) - no->var_value()->add_preinit_statement(this->gogo_, s); - } - else - { - Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(), - NULL, location); - dummy->var_value()->add_preinit_statement(this->gogo_, s); - } - - return true; -} - -// See if we need to initialize a pair of values from a type guard -// expression. This returns true if we have set up the variables and -// the initialization. - -bool -Parse::init_vars_from_type_guard(const Typed_identifier_list* vars, - Type* type, Expression* expr, - bool is_coloneq, source_location location) -{ - Type_guard_expression* type_guard = expr->type_guard_expression(); - if (type_guard == NULL) - return false; - if (vars->size() != 2) - return false; - - // This is a type guard expression which is being assigned to two - // variables. Declare the variables, and then assign the results of - // the type guard. - bool any_new = false; - Typed_identifier_list::const_iterator p = vars->begin(); - Type* var_type = type; - if (var_type == NULL) - var_type = type_guard->type(); - Named_object* val_no = this->init_var(*p, var_type, NULL, is_coloneq, false, - &any_new); - Expression* val_var = Expression::make_var_reference(val_no, location); - - ++p; - var_type = type; - if (var_type == NULL) - var_type = Type::lookup_bool_type(); - Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false, - &any_new); - Expression* ok_var = Expression::make_var_reference(no, location); - - Expression* texpr = type_guard->expr(); - Type* t = type_guard->type(); - Statement* s = Statement::make_tuple_type_guard_assignment(val_var, ok_var, - texpr, t, - location); - - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); - - if (!this->gogo_->in_global_scope()) - this->gogo_->add_statement(s); - else if (!val_no->is_sink()) - { - if (val_no->is_variable()) - val_no->var_value()->add_preinit_statement(this->gogo_, s); - } - else if (!no->is_sink()) - { - if (no->is_variable()) - no->var_value()->add_preinit_statement(this->gogo_, s); - } - else - { - Named_object* dummy = this->create_dummy_global(type, NULL, location); - dummy->var_value()->add_preinit_statement(this->gogo_, s); - } - - return true; -} - -// Create a single variable. If IS_COLONEQ is true, we permit -// redeclarations in the same block, and we set *IS_NEW when we find a -// new variable which is not a redeclaration. - -Named_object* -Parse::init_var(const Typed_identifier& tid, Type* type, Expression* init, - bool is_coloneq, bool type_from_init, bool* is_new) -{ - source_location location = tid.location(); - - if (Gogo::is_sink_name(tid.name())) - { - if (!type_from_init && init != NULL) - { - if (!this->gogo_->in_global_scope()) - this->gogo_->add_statement(Statement::make_statement(init)); - else - return this->create_dummy_global(type, init, location); - } - return this->gogo_->add_sink(); - } - - if (is_coloneq) - { - Named_object* no = this->gogo_->lookup_in_block(tid.name()); - if (no != NULL - && (no->is_variable() || no->is_result_variable())) - { - // INIT may be NULL even when IS_COLONEQ is true for cases - // like v, ok := x.(int). - if (!type_from_init && init != NULL) - { - Expression *v = Expression::make_var_reference(no, location); - Statement *s = Statement::make_assignment(v, init, location); - this->gogo_->add_statement(s); - } - return no; - } - } - *is_new = true; - Variable* var = new Variable(type, init, this->gogo_->in_global_scope(), - false, false, location); - Named_object* no = this->gogo_->add_variable(tid.name(), var); - if (!no->is_variable()) - { - // The name is already defined, so we just gave an error. - return this->gogo_->add_sink(); - } - return no; -} - -// Create a dummy global variable to force an initializer to be run in -// the right place. This is used when a sink variable is initialized -// at global scope. - -Named_object* -Parse::create_dummy_global(Type* type, Expression* init, - source_location location) -{ - if (type == NULL && init == NULL) - type = Type::lookup_bool_type(); - Variable* var = new Variable(type, init, true, false, false, location); - static int count; - char buf[30]; - snprintf(buf, sizeof buf, "_.%d", count); - ++count; - return this->gogo_->add_variable(buf, var); -} - -// SimpleVarDecl = identifier ":=" Expression . - -// We've already seen the identifier. - -// FIXME: We also have to implement -// IdentifierList ":=" ExpressionList -// In order to support both "a, b := 1, 0" and "a, b = 1, 0" we accept -// tuple assignments here as well. - -// If P_RANGE_CLAUSE is not NULL, then this will recognize a -// RangeClause. - -// If P_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -void -Parse::simple_var_decl_or_assignment(const std::string& name, - source_location location, - Range_clause* p_range_clause, - Type_switch* p_type_switch) -{ - Typed_identifier_list til; - til.push_back(Typed_identifier(name, NULL, location)); - - // We've seen one identifier. If we see a comma now, this could be - // "a, *p = 1, 2". - if (this->peek_token()->is_op(OPERATOR_COMMA)) - { - go_assert(p_type_switch == NULL); - while (true) - { - const Token* token = this->advance_token(); - if (!token->is_identifier()) - break; - - std::string id = token->identifier(); - bool is_id_exported = token->is_identifier_exported(); - source_location id_location = token->location(); - - token = this->advance_token(); - if (!token->is_op(OPERATOR_COMMA)) - { - if (token->is_op(OPERATOR_COLONEQ)) - { - id = this->gogo_->pack_hidden_name(id, is_id_exported); - til.push_back(Typed_identifier(id, NULL, location)); - } - else - this->unget_token(Token::make_identifier_token(id, - is_id_exported, - id_location)); - break; - } - - id = this->gogo_->pack_hidden_name(id, is_id_exported); - til.push_back(Typed_identifier(id, NULL, location)); - } - - // We have a comma separated list of identifiers in TIL. If the - // next token is COLONEQ, then this is a simple var decl, and we - // have the complete list of identifiers. If the next token is - // not COLONEQ, then the only valid parse is a tuple assignment. - // The list of identifiers we have so far is really a list of - // expressions. There are more expressions following. - - if (!this->peek_token()->is_op(OPERATOR_COLONEQ)) - { - Expression_list* exprs = new Expression_list; - for (Typed_identifier_list::const_iterator p = til.begin(); - p != til.end(); - ++p) - exprs->push_back(this->id_to_expression(p->name(), - p->location())); - - Expression_list* more_exprs = this->expression_list(NULL, true); - for (Expression_list::const_iterator p = more_exprs->begin(); - p != more_exprs->end(); - ++p) - exprs->push_back(*p); - delete more_exprs; - - this->tuple_assignment(exprs, p_range_clause); - return; - } - } - - go_assert(this->peek_token()->is_op(OPERATOR_COLONEQ)); - const Token* token = this->advance_token(); - - if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE)) - { - this->range_clause_decl(&til, p_range_clause); - return; - } - - Expression_list* init; - if (p_type_switch == NULL) - init = this->expression_list(NULL, false); - else - { - bool is_type_switch = false; - Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, - &is_type_switch); - if (is_type_switch) - { - p_type_switch->found = true; - p_type_switch->name = name; - p_type_switch->location = location; - p_type_switch->expr = expr; - return; - } - - if (!this->peek_token()->is_op(OPERATOR_COMMA)) - { - init = new Expression_list(); - init->push_back(expr); - } - else - { - this->advance_token(); - init = this->expression_list(expr, false); - } - } - - this->init_vars(&til, NULL, init, true, location); -} - -// FunctionDecl = "func" identifier Signature [ Block ] . -// MethodDecl = "func" Receiver identifier Signature [ Block ] . - -// gcc extension: -// FunctionDecl = "func" identifier Signature -// __asm__ "(" string_lit ")" . -// This extension means a function whose real name is the identifier -// inside the asm. - -void -Parse::function_decl() -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC)); - source_location location = this->location(); - const Token* token = this->advance_token(); - - Typed_identifier* rec = NULL; - if (token->is_op(OPERATOR_LPAREN)) - { - rec = this->receiver(); - token = this->peek_token(); - } - - if (!token->is_identifier()) - { - error_at(this->location(), "expected function name"); - return; - } - - std::string name = - this->gogo_->pack_hidden_name(token->identifier(), - token->is_identifier_exported()); - - this->advance_token(); - - Function_type* fntype = this->signature(rec, this->location()); - if (fntype == NULL) - return; - - Named_object* named_object = NULL; - - if (this->peek_token()->is_keyword(KEYWORD_ASM)) - { - if (!this->advance_token()->is_op(OPERATOR_LPAREN)) - { - error_at(this->location(), "expected %<(%>"); - return; - } - token = this->advance_token(); - if (!token->is_string()) - { - error_at(this->location(), "expected string"); - return; - } - std::string asm_name = token->string_value(); - if (!this->advance_token()->is_op(OPERATOR_RPAREN)) - { - error_at(this->location(), "expected %<)%>"); - return; - } - this->advance_token(); - if (!Gogo::is_sink_name(name)) - { - named_object = this->gogo_->declare_function(name, fntype, location); - if (named_object->is_function_declaration()) - named_object->func_declaration_value()->set_asm_name(asm_name); - } - } - - // Check for the easy error of a newline before the opening brace. - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - source_location semi_loc = this->location(); - if (this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(this->location(), - "unexpected semicolon or newline before %<{%>"); - else - this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON, - semi_loc)); - } - - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - { - if (named_object == NULL && !Gogo::is_sink_name(name)) - this->gogo_->declare_function(name, fntype, location); - } - else - { - this->gogo_->start_function(name, fntype, true, location); - source_location end_loc = this->block(); - this->gogo_->finish_function(end_loc); - } -} - -// Receiver = "(" [ identifier ] [ "*" ] BaseTypeName ")" . -// BaseTypeName = identifier . - -Typed_identifier* -Parse::receiver() -{ - go_assert(this->peek_token()->is_op(OPERATOR_LPAREN)); - - std::string name; - const Token* token = this->advance_token(); - source_location location = token->location(); - if (!token->is_op(OPERATOR_MULT)) - { - if (!token->is_identifier()) - { - error_at(this->location(), "method has no receiver"); - while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN)) - token = this->advance_token(); - if (!token->is_eof()) - this->advance_token(); - return NULL; - } - name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - token = this->advance_token(); - if (!token->is_op(OPERATOR_DOT) && !token->is_op(OPERATOR_RPAREN)) - { - // An identifier followed by something other than a dot or a - // right parenthesis must be a receiver name followed by a - // type. - name = this->gogo_->pack_hidden_name(name, is_exported); - } - else - { - // This must be a type name. - this->unget_token(Token::make_identifier_token(name, is_exported, - location)); - token = this->peek_token(); - name.clear(); - } - } - - // Here the receiver name is in NAME (it is empty if the receiver is - // unnamed) and TOKEN is the first token in the type. - - bool is_pointer = false; - if (token->is_op(OPERATOR_MULT)) - { - is_pointer = true; - token = this->advance_token(); - } - - if (!token->is_identifier()) - { - error_at(this->location(), "expected receiver name or type"); - int c = token->is_op(OPERATOR_LPAREN) ? 1 : 0; - while (!token->is_eof()) - { - token = this->advance_token(); - if (token->is_op(OPERATOR_LPAREN)) - ++c; - else if (token->is_op(OPERATOR_RPAREN)) - { - if (c == 0) - break; - --c; - } - } - if (!token->is_eof()) - this->advance_token(); - return NULL; - } - - Type* type = this->type_name(true); - - if (is_pointer && !type->is_error_type()) - type = Type::make_pointer_type(type); - - if (this->peek_token()->is_op(OPERATOR_RPAREN)) - this->advance_token(); - else - { - if (this->peek_token()->is_op(OPERATOR_COMMA)) - error_at(this->location(), "method has multiple receivers"); - else - error_at(this->location(), "expected %<)%>"); - while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN)) - token = this->advance_token(); - if (!token->is_eof()) - this->advance_token(); - return NULL; - } - - return new Typed_identifier(name, type, location); -} - -// Operand = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" . -// Literal = BasicLit | CompositeLit | FunctionLit . -// BasicLit = int_lit | float_lit | imaginary_lit | char_lit | string_lit . - -// If MAY_BE_SINK is true, this operand may be "_". - -Expression* -Parse::operand(bool may_be_sink) -{ - const Token* token = this->peek_token(); - Expression* ret; - switch (token->classification()) - { - case Token::TOKEN_IDENTIFIER: - { - source_location location = token->location(); - std::string id = token->identifier(); - bool is_exported = token->is_identifier_exported(); - std::string packed = this->gogo_->pack_hidden_name(id, is_exported); - - Named_object* in_function; - Named_object* named_object = this->gogo_->lookup(packed, &in_function); - - Package* package = NULL; - if (named_object != NULL && named_object->is_package()) - { - if (!this->advance_token()->is_op(OPERATOR_DOT) - || !this->advance_token()->is_identifier()) - { - error_at(location, "unexpected reference to package"); - return Expression::make_error(location); - } - package = named_object->package_value(); - package->set_used(); - id = this->peek_token()->identifier(); - is_exported = this->peek_token()->is_identifier_exported(); - packed = this->gogo_->pack_hidden_name(id, is_exported); - named_object = package->lookup(packed); - location = this->location(); - go_assert(in_function == NULL); - } - - this->advance_token(); - - if (named_object != NULL - && named_object->is_type() - && !named_object->type_value()->is_visible()) - { - go_assert(package != NULL); - error_at(location, "invalid reference to hidden type %<%s.%s%>", - Gogo::message_name(package->name()).c_str(), - Gogo::message_name(id).c_str()); - return Expression::make_error(location); - } - - - if (named_object == NULL) - { - if (package != NULL) - { - std::string n1 = Gogo::message_name(package->name()); - std::string n2 = Gogo::message_name(id); - if (!is_exported) - error_at(location, - ("invalid reference to unexported identifier " - "%<%s.%s%>"), - n1.c_str(), n2.c_str()); - else - error_at(location, - "reference to undefined identifier %<%s.%s%>", - n1.c_str(), n2.c_str()); - return Expression::make_error(location); - } - - named_object = this->gogo_->add_unknown_name(packed, location); - } - - if (in_function != NULL - && in_function != this->gogo_->current_function() - && (named_object->is_variable() - || named_object->is_result_variable())) - return this->enclosing_var_reference(in_function, named_object, - location); - - switch (named_object->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - return Expression::make_const_reference(named_object, location); - case Named_object::NAMED_OBJECT_TYPE: - return Expression::make_type(named_object->type_value(), location); - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - { - Type* t = Type::make_forward_declaration(named_object); - return Expression::make_type(t, location); - } - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - return Expression::make_var_reference(named_object, location); - case Named_object::NAMED_OBJECT_SINK: - if (may_be_sink) - return Expression::make_sink(location); - else - { - error_at(location, "cannot use _ as value"); - return Expression::make_error(location); - } - case Named_object::NAMED_OBJECT_FUNC: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - return Expression::make_func_reference(named_object, NULL, - location); - case Named_object::NAMED_OBJECT_UNKNOWN: - return Expression::make_unknown_reference(named_object, location); - default: - go_unreachable(); - } - } - go_unreachable(); - - case Token::TOKEN_STRING: - ret = Expression::make_string(token->string_value(), token->location()); - this->advance_token(); - return ret; - - case Token::TOKEN_INTEGER: - ret = Expression::make_integer(token->integer_value(), NULL, - token->location()); - this->advance_token(); - return ret; - - case Token::TOKEN_FLOAT: - ret = Expression::make_float(token->float_value(), NULL, - token->location()); - this->advance_token(); - return ret; - - case Token::TOKEN_IMAGINARY: - { - mpfr_t zero; - mpfr_init_set_ui(zero, 0, GMP_RNDN); - ret = Expression::make_complex(&zero, token->imaginary_value(), - NULL, token->location()); - mpfr_clear(zero); - this->advance_token(); - return ret; - } - - case Token::TOKEN_KEYWORD: - switch (token->keyword()) - { - case KEYWORD_FUNC: - return this->function_lit(); - case KEYWORD_CHAN: - case KEYWORD_INTERFACE: - case KEYWORD_MAP: - case KEYWORD_STRUCT: - { - source_location location = token->location(); - return Expression::make_type(this->type(), location); - } - default: - break; - } - break; - - case Token::TOKEN_OPERATOR: - if (token->is_op(OPERATOR_LPAREN)) - { - this->advance_token(); - ret = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "missing %<)%>"); - else - this->advance_token(); - return ret; - } - else if (token->is_op(OPERATOR_LSQUARE)) - { - // Here we call array_type directly, as this is the only - // case where an ellipsis is permitted for an array type. - source_location location = token->location(); - return Expression::make_type(this->array_type(true), location); - } - break; - - default: - break; - } - - error_at(this->location(), "expected operand"); - return Expression::make_error(this->location()); -} - -// Handle a reference to a variable in an enclosing function. We add -// it to a list of such variables. We return a reference to a field -// in a struct which will be passed on the static chain when calling -// the current function. - -Expression* -Parse::enclosing_var_reference(Named_object* in_function, Named_object* var, - source_location location) -{ - go_assert(var->is_variable() || var->is_result_variable()); - - Named_object* this_function = this->gogo_->current_function(); - Named_object* closure = this_function->func_value()->closure_var(); - - Enclosing_var ev(var, in_function, this->enclosing_vars_.size()); - std::pair ins = - this->enclosing_vars_.insert(ev); - if (ins.second) - { - // This is a variable we have not seen before. Add a new field - // to the closure type. - this_function->func_value()->add_closure_field(var, location); - } - - Expression* closure_ref = Expression::make_var_reference(closure, - location); - closure_ref = Expression::make_unary(OPERATOR_MULT, closure_ref, location); - - // The closure structure holds pointers to the variables, so we need - // to introduce an indirection. - Expression* e = Expression::make_field_reference(closure_ref, - ins.first->index(), - location); - e = Expression::make_unary(OPERATOR_MULT, e, location); - return e; -} - -// CompositeLit = LiteralType LiteralValue . -// LiteralType = StructType | ArrayType | "[" "..." "]" ElementType | -// SliceType | MapType | TypeName . -// LiteralValue = "{" [ ElementList [ "," ] ] "}" . -// ElementList = Element { "," Element } . -// Element = [ Key ":" ] Value . -// Key = Expression . -// Value = Expression | LiteralValue . - -// We have already seen the type if there is one, and we are now -// looking at the LiteralValue. The case "[" "..." "]" ElementType -// will be seen here as an array type whose length is "nil". The -// DEPTH parameter is non-zero if this is an embedded composite -// literal and the type was omitted. It gives the number of steps up -// to the type which was provided. E.g., in [][]int{{1}} it will be -// 1. In [][][]int{{{1}}} it will be 2. - -Expression* -Parse::composite_lit(Type* type, int depth, source_location location) -{ - go_assert(this->peek_token()->is_op(OPERATOR_LCURLY)); - this->advance_token(); - - if (this->peek_token()->is_op(OPERATOR_RCURLY)) - { - this->advance_token(); - return Expression::make_composite_literal(type, depth, false, NULL, - location); - } - - bool has_keys = false; - Expression_list* vals = new Expression_list; - while (true) - { - Expression* val; - bool is_type_omitted = false; - - const Token* token = this->peek_token(); - - if (!token->is_op(OPERATOR_LCURLY)) - val = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - else - { - // This must be a composite literal inside another composite - // literal, with the type omitted for the inner one. - val = this->composite_lit(type, depth + 1, token->location()); - is_type_omitted = true; - } - - token = this->peek_token(); - if (!token->is_op(OPERATOR_COLON)) - { - if (has_keys) - vals->push_back(NULL); - } - else - { - if (is_type_omitted && !val->is_error_expression()) - { - error_at(this->location(), "unexpected %<:%>"); - val = Expression::make_error(this->location()); - } - - this->advance_token(); - - if (!has_keys && !vals->empty()) - { - Expression_list* newvals = new Expression_list; - for (Expression_list::const_iterator p = vals->begin(); - p != vals->end(); - ++p) - { - newvals->push_back(NULL); - newvals->push_back(*p); - } - delete vals; - vals = newvals; - } - has_keys = true; - - if (val->unknown_expression() != NULL) - val->unknown_expression()->set_is_composite_literal_key(); - - vals->push_back(val); - - if (!token->is_op(OPERATOR_LCURLY)) - val = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - else - { - // This must be a composite literal inside another - // composite literal, with the type omitted for the - // inner one. - val = this->composite_lit(type, depth + 1, token->location()); - } - - token = this->peek_token(); - } - - vals->push_back(val); - - if (token->is_op(OPERATOR_COMMA)) - { - if (this->advance_token()->is_op(OPERATOR_RCURLY)) - { - this->advance_token(); - break; - } - } - else if (token->is_op(OPERATOR_RCURLY)) - { - this->advance_token(); - break; - } - else - { - error_at(this->location(), "expected %<,%> or %<}%>"); - - int depth = 0; - while (!token->is_eof() - && (depth > 0 || !token->is_op(OPERATOR_RCURLY))) - { - if (token->is_op(OPERATOR_LCURLY)) - ++depth; - else if (token->is_op(OPERATOR_RCURLY)) - --depth; - token = this->advance_token(); - } - if (token->is_op(OPERATOR_RCURLY)) - this->advance_token(); - - return Expression::make_error(location); - } - } - - return Expression::make_composite_literal(type, depth, has_keys, vals, - location); -} - -// FunctionLit = "func" Signature Block . - -Expression* -Parse::function_lit() -{ - source_location location = this->location(); - go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC)); - this->advance_token(); - - Enclosing_vars hold_enclosing_vars; - hold_enclosing_vars.swap(this->enclosing_vars_); - - Function_type* type = this->signature(NULL, location); - if (type == NULL) - type = Type::make_function_type(NULL, NULL, NULL, location); - - // For a function literal, the next token must be a '{'. If we - // don't see that, then we may have a type expression. - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - return Expression::make_type(type, location); - - Bc_stack* hold_break_stack = this->break_stack_; - Bc_stack* hold_continue_stack = this->continue_stack_; - this->break_stack_ = NULL; - this->continue_stack_ = NULL; - - Named_object* no = this->gogo_->start_function("", type, true, location); - - source_location end_loc = this->block(); - - this->gogo_->finish_function(end_loc); - - if (this->break_stack_ != NULL) - delete this->break_stack_; - if (this->continue_stack_ != NULL) - delete this->continue_stack_; - this->break_stack_ = hold_break_stack; - this->continue_stack_ = hold_continue_stack; - - hold_enclosing_vars.swap(this->enclosing_vars_); - - Expression* closure = this->create_closure(no, &hold_enclosing_vars, - location); - - return Expression::make_func_reference(no, closure, location); -} - -// Create a closure for the nested function FUNCTION. This is based -// on ENCLOSING_VARS, which is a list of all variables defined in -// enclosing functions and referenced from FUNCTION. A closure is the -// address of a struct which contains the addresses of all the -// referenced variables. This returns NULL if no closure is required. - -Expression* -Parse::create_closure(Named_object* function, Enclosing_vars* enclosing_vars, - source_location location) -{ - if (enclosing_vars->empty()) - return NULL; - - // Get the variables in order by their field index. - - size_t enclosing_var_count = enclosing_vars->size(); - std::vector ev(enclosing_var_count); - for (Enclosing_vars::const_iterator p = enclosing_vars->begin(); - p != enclosing_vars->end(); - ++p) - ev[p->index()] = *p; - - // Build an initializer for a composite literal of the closure's - // type. - - Named_object* enclosing_function = this->gogo_->current_function(); - Expression_list* initializer = new Expression_list; - for (size_t i = 0; i < enclosing_var_count; ++i) - { - go_assert(ev[i].index() == i); - Named_object* var = ev[i].var(); - Expression* ref; - if (ev[i].in_function() == enclosing_function) - ref = Expression::make_var_reference(var, location); - else - ref = this->enclosing_var_reference(ev[i].in_function(), var, - location); - Expression* refaddr = Expression::make_unary(OPERATOR_AND, ref, - location); - initializer->push_back(refaddr); - } - - Named_object* closure_var = function->func_value()->closure_var(); - Struct_type* st = closure_var->var_value()->type()->deref()->struct_type(); - Expression* cv = Expression::make_struct_composite_literal(st, initializer, - location); - return Expression::make_heap_composite(cv, location); -} - -// PrimaryExpr = Operand { Selector | Index | Slice | TypeGuard | Call } . - -// If MAY_BE_SINK is true, this expression may be "_". - -// If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite -// literal. - -// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::primary_expr(bool may_be_sink, bool may_be_composite_lit, - bool* is_type_switch) -{ - source_location start_loc = this->location(); - bool is_parenthesized = this->peek_token()->is_op(OPERATOR_LPAREN); - - Expression* ret = this->operand(may_be_sink); - - // An unknown name followed by a curly brace must be a composite - // literal, and the unknown name must be a type. - if (may_be_composite_lit - && !is_parenthesized - && ret->unknown_expression() != NULL - && this->peek_token()->is_op(OPERATOR_LCURLY)) - { - Named_object* no = ret->unknown_expression()->named_object(); - Type* type = Type::make_forward_declaration(no); - ret = Expression::make_type(type, ret->location()); - } - - // We handle composite literals and type casts here, as it is the - // easiest way to handle types which are in parentheses, as in - // "((uint))(1)". - if (ret->is_type_expression()) - { - if (this->peek_token()->is_op(OPERATOR_LCURLY)) - { - if (is_parenthesized) - error_at(start_loc, - "cannot parenthesize type in composite literal"); - ret = this->composite_lit(ret->type(), 0, ret->location()); - } - else if (this->peek_token()->is_op(OPERATOR_LPAREN)) - { - source_location loc = this->location(); - this->advance_token(); - Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, - NULL); - if (this->peek_token()->is_op(OPERATOR_ELLIPSIS)) - { - error_at(this->location(), - "invalid use of %<...%> in type conversion"); - this->advance_token(); - } - if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "expected %<)%>"); - else - this->advance_token(); - if (expr->is_error_expression()) - return expr; - ret = Expression::make_cast(ret->type(), expr, loc); - } - } - - while (true) - { - const Token* token = this->peek_token(); - if (token->is_op(OPERATOR_LPAREN)) - ret = this->call(this->verify_not_sink(ret)); - else if (token->is_op(OPERATOR_DOT)) - { - ret = this->selector(this->verify_not_sink(ret), is_type_switch); - if (is_type_switch != NULL && *is_type_switch) - break; - } - else if (token->is_op(OPERATOR_LSQUARE)) - ret = this->index(this->verify_not_sink(ret)); - else - break; - } - - return ret; -} - -// Selector = "." identifier . -// TypeGuard = "." "(" QualifiedIdent ")" . - -// Note that Operand can expand to QualifiedIdent, which contains a -// ".". That is handled directly in operand when it sees a package -// name. - -// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::selector(Expression* left, bool* is_type_switch) -{ - go_assert(this->peek_token()->is_op(OPERATOR_DOT)); - source_location location = this->location(); - - const Token* token = this->advance_token(); - if (token->is_identifier()) - { - // This could be a field in a struct, or a method in an - // interface, or a method associated with a type. We can't know - // which until we have seen all the types. - std::string name = - this->gogo_->pack_hidden_name(token->identifier(), - token->is_identifier_exported()); - if (token->identifier() == "_") - { - error_at(this->location(), "invalid use of %<_%>"); - name = this->gogo_->pack_hidden_name("blank", false); - } - this->advance_token(); - return Expression::make_selector(left, name, location); - } - else if (token->is_op(OPERATOR_LPAREN)) - { - this->advance_token(); - Type* type = NULL; - if (!this->peek_token()->is_keyword(KEYWORD_TYPE)) - type = this->type(); - else - { - if (is_type_switch != NULL) - *is_type_switch = true; - else - { - error_at(this->location(), - "use of %<.(type)%> outside type switch"); - type = Type::make_error_type(); - } - this->advance_token(); - } - if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "missing %<)%>"); - else - this->advance_token(); - if (is_type_switch != NULL && *is_type_switch) - return left; - return Expression::make_type_guard(left, type, location); - } - else - { - error_at(this->location(), "expected identifier or %<(%>"); - return left; - } -} - -// Index = "[" Expression "]" . -// Slice = "[" Expression ":" [ Expression ] "]" . - -Expression* -Parse::index(Expression* expr) -{ - source_location location = this->location(); - go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE)); - this->advance_token(); - - Expression* start; - if (!this->peek_token()->is_op(OPERATOR_COLON)) - start = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - else - { - mpz_t zero; - mpz_init_set_ui(zero, 0); - start = Expression::make_integer(&zero, NULL, location); - mpz_clear(zero); - } - - Expression* end = NULL; - if (this->peek_token()->is_op(OPERATOR_COLON)) - { - // We use nil to indicate a missing high expression. - if (this->advance_token()->is_op(OPERATOR_RSQUARE)) - end = Expression::make_nil(this->location()); - else - end = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - } - if (!this->peek_token()->is_op(OPERATOR_RSQUARE)) - error_at(this->location(), "missing %<]%>"); - else - this->advance_token(); - return Expression::make_index(expr, start, end, location); -} - -// Call = "(" [ ArgumentList [ "," ] ] ")" . -// ArgumentList = ExpressionList [ "..." ] . - -Expression* -Parse::call(Expression* func) -{ - go_assert(this->peek_token()->is_op(OPERATOR_LPAREN)); - Expression_list* args = NULL; - bool is_varargs = false; - const Token* token = this->advance_token(); - if (!token->is_op(OPERATOR_RPAREN)) - { - args = this->expression_list(NULL, false); - token = this->peek_token(); - if (token->is_op(OPERATOR_ELLIPSIS)) - { - is_varargs = true; - token = this->advance_token(); - } - } - if (token->is_op(OPERATOR_COMMA)) - token = this->advance_token(); - if (!token->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "missing %<)%>"); - else - this->advance_token(); - if (func->is_error_expression()) - return func; - return Expression::make_call(func, args, is_varargs, func->location()); -} - -// Return an expression for a single unqualified identifier. - -Expression* -Parse::id_to_expression(const std::string& name, source_location location) -{ - Named_object* in_function; - Named_object* named_object = this->gogo_->lookup(name, &in_function); - if (named_object == NULL) - named_object = this->gogo_->add_unknown_name(name, location); - - if (in_function != NULL - && in_function != this->gogo_->current_function() - && (named_object->is_variable() || named_object->is_result_variable())) - return this->enclosing_var_reference(in_function, named_object, - location); - - switch (named_object->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - return Expression::make_const_reference(named_object, location); - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - return Expression::make_var_reference(named_object, location); - case Named_object::NAMED_OBJECT_SINK: - return Expression::make_sink(location); - case Named_object::NAMED_OBJECT_FUNC: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - return Expression::make_func_reference(named_object, NULL, location); - case Named_object::NAMED_OBJECT_UNKNOWN: - return Expression::make_unknown_reference(named_object, location); - default: - error_at(this->location(), "unexpected type of identifier"); - return Expression::make_error(location); - } -} - -// Expression = UnaryExpr { binary_op Expression } . - -// PRECEDENCE is the precedence of the current operator. - -// If MAY_BE_SINK is true, this expression may be "_". - -// If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite -// literal. - -// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::expression(Precedence precedence, bool may_be_sink, - bool may_be_composite_lit, bool* is_type_switch) -{ - Expression* left = this->unary_expr(may_be_sink, may_be_composite_lit, - is_type_switch); - - while (true) - { - if (is_type_switch != NULL && *is_type_switch) - return left; - - const Token* token = this->peek_token(); - if (token->classification() != Token::TOKEN_OPERATOR) - { - // Not a binary_op. - return left; - } - - Precedence right_precedence; - switch (token->op()) - { - case OPERATOR_OROR: - right_precedence = PRECEDENCE_OROR; - break; - case OPERATOR_ANDAND: - right_precedence = PRECEDENCE_ANDAND; - break; - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - right_precedence = PRECEDENCE_RELOP; - break; - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_OR: - case OPERATOR_XOR: - right_precedence = PRECEDENCE_ADDOP; - break; - case OPERATOR_MULT: - case OPERATOR_DIV: - case OPERATOR_MOD: - case OPERATOR_LSHIFT: - case OPERATOR_RSHIFT: - case OPERATOR_AND: - case OPERATOR_BITCLEAR: - right_precedence = PRECEDENCE_MULOP; - break; - default: - right_precedence = PRECEDENCE_INVALID; - break; - } - - if (right_precedence == PRECEDENCE_INVALID) - { - // Not a binary_op. - return left; - } - - Operator op = token->op(); - source_location binop_location = token->location(); - - if (precedence >= right_precedence) - { - // We've already seen A * B, and we see + C. We want to - // return so that A * B becomes a group. - return left; - } - - this->advance_token(); - - left = this->verify_not_sink(left); - Expression* right = this->expression(right_precedence, false, - may_be_composite_lit, - NULL); - left = Expression::make_binary(op, left, right, binop_location); - } -} - -bool -Parse::expression_may_start_here() -{ - const Token* token = this->peek_token(); - switch (token->classification()) - { - case Token::TOKEN_INVALID: - case Token::TOKEN_EOF: - return false; - case Token::TOKEN_KEYWORD: - switch (token->keyword()) - { - case KEYWORD_CHAN: - case KEYWORD_FUNC: - case KEYWORD_MAP: - case KEYWORD_STRUCT: - case KEYWORD_INTERFACE: - return true; - default: - return false; - } - case Token::TOKEN_IDENTIFIER: - return true; - case Token::TOKEN_STRING: - return true; - case Token::TOKEN_OPERATOR: - switch (token->op()) - { - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_NOT: - case OPERATOR_XOR: - case OPERATOR_MULT: - case OPERATOR_CHANOP: - case OPERATOR_AND: - case OPERATOR_LPAREN: - case OPERATOR_LSQUARE: - return true; - default: - return false; - } - case Token::TOKEN_INTEGER: - case Token::TOKEN_FLOAT: - case Token::TOKEN_IMAGINARY: - return true; - default: - go_unreachable(); - } -} - -// UnaryExpr = unary_op UnaryExpr | PrimaryExpr . - -// If MAY_BE_SINK is true, this expression may be "_". - -// If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite -// literal. - -// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::unary_expr(bool may_be_sink, bool may_be_composite_lit, - bool* is_type_switch) -{ - const Token* token = this->peek_token(); - if (token->is_op(OPERATOR_PLUS) - || token->is_op(OPERATOR_MINUS) - || token->is_op(OPERATOR_NOT) - || token->is_op(OPERATOR_XOR) - || token->is_op(OPERATOR_CHANOP) - || token->is_op(OPERATOR_MULT) - || token->is_op(OPERATOR_AND)) - { - source_location location = token->location(); - Operator op = token->op(); - this->advance_token(); - - if (op == OPERATOR_CHANOP - && this->peek_token()->is_keyword(KEYWORD_CHAN)) - { - // This is "<- chan" which must be the start of a type. - this->unget_token(Token::make_operator_token(op, location)); - return Expression::make_type(this->type(), location); - } - - Expression* expr = this->unary_expr(false, may_be_composite_lit, NULL); - if (expr->is_error_expression()) - ; - else if (op == OPERATOR_MULT && expr->is_type_expression()) - expr = Expression::make_type(Type::make_pointer_type(expr->type()), - location); - else if (op == OPERATOR_AND && expr->is_composite_literal()) - expr = Expression::make_heap_composite(expr, location); - else if (op != OPERATOR_CHANOP) - expr = Expression::make_unary(op, expr, location); - else - expr = Expression::make_receive(expr, location); - return expr; - } - else - return this->primary_expr(may_be_sink, may_be_composite_lit, - is_type_switch); -} - -// Statement = -// Declaration | LabeledStmt | SimpleStmt | -// GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt | -// FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt | -// DeferStmt . - -// LABEL is the label of this statement if it has one. - -void -Parse::statement(Label* label) -{ - const Token* token = this->peek_token(); - switch (token->classification()) - { - case Token::TOKEN_KEYWORD: - { - switch (token->keyword()) - { - case KEYWORD_CONST: - case KEYWORD_TYPE: - case KEYWORD_VAR: - this->declaration(); - break; - case KEYWORD_FUNC: - case KEYWORD_MAP: - case KEYWORD_STRUCT: - case KEYWORD_INTERFACE: - this->simple_stat(true, NULL, NULL, NULL); - break; - case KEYWORD_GO: - case KEYWORD_DEFER: - this->go_or_defer_stat(); - break; - case KEYWORD_RETURN: - this->return_stat(); - break; - case KEYWORD_BREAK: - this->break_stat(); - break; - case KEYWORD_CONTINUE: - this->continue_stat(); - break; - case KEYWORD_GOTO: - this->goto_stat(); - break; - case KEYWORD_IF: - this->if_stat(); - break; - case KEYWORD_SWITCH: - this->switch_stat(label); - break; - case KEYWORD_SELECT: - this->select_stat(label); - break; - case KEYWORD_FOR: - this->for_stat(label); - break; - default: - error_at(this->location(), "expected statement"); - this->advance_token(); - break; - } - } - break; - - case Token::TOKEN_IDENTIFIER: - { - std::string identifier = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - if (this->advance_token()->is_op(OPERATOR_COLON)) - { - this->advance_token(); - this->labeled_stmt(identifier, location); - } - else - { - this->unget_token(Token::make_identifier_token(identifier, - is_exported, - location)); - this->simple_stat(true, NULL, NULL, NULL); - } - } - break; - - case Token::TOKEN_OPERATOR: - if (token->is_op(OPERATOR_LCURLY)) - { - source_location location = token->location(); - this->gogo_->start_block(location); - source_location end_loc = this->block(); - this->gogo_->add_block(this->gogo_->finish_block(end_loc), - location); - } - else if (!token->is_op(OPERATOR_SEMICOLON)) - this->simple_stat(true, NULL, NULL, NULL); - break; - - case Token::TOKEN_STRING: - case Token::TOKEN_INTEGER: - case Token::TOKEN_FLOAT: - case Token::TOKEN_IMAGINARY: - this->simple_stat(true, NULL, NULL, NULL); - break; - - default: - error_at(this->location(), "expected statement"); - this->advance_token(); - break; - } -} - -bool -Parse::statement_may_start_here() -{ - const Token* token = this->peek_token(); - switch (token->classification()) - { - case Token::TOKEN_KEYWORD: - { - switch (token->keyword()) - { - case KEYWORD_CONST: - case KEYWORD_TYPE: - case KEYWORD_VAR: - case KEYWORD_FUNC: - case KEYWORD_MAP: - case KEYWORD_STRUCT: - case KEYWORD_INTERFACE: - case KEYWORD_GO: - case KEYWORD_DEFER: - case KEYWORD_RETURN: - case KEYWORD_BREAK: - case KEYWORD_CONTINUE: - case KEYWORD_GOTO: - case KEYWORD_IF: - case KEYWORD_SWITCH: - case KEYWORD_SELECT: - case KEYWORD_FOR: - return true; - - default: - return false; - } - } - break; - - case Token::TOKEN_IDENTIFIER: - return true; - - case Token::TOKEN_OPERATOR: - if (token->is_op(OPERATOR_LCURLY) - || token->is_op(OPERATOR_SEMICOLON)) - return true; - else - return this->expression_may_start_here(); - - case Token::TOKEN_STRING: - case Token::TOKEN_INTEGER: - case Token::TOKEN_FLOAT: - case Token::TOKEN_IMAGINARY: - return true; - - default: - return false; - } -} - -// LabeledStmt = Label ":" Statement . -// Label = identifier . - -void -Parse::labeled_stmt(const std::string& label_name, source_location location) -{ - Label* label = this->gogo_->add_label_definition(label_name, location); - - if (this->peek_token()->is_op(OPERATOR_RCURLY)) - { - // This is a label at the end of a block. A program is - // permitted to omit a semicolon here. - return; - } - - if (!this->statement_may_start_here()) - { - // Mark the label as used to avoid a useless error about an - // unused label. - label->set_is_used(); - - error_at(location, "missing statement after label"); - this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON, - location)); - return; - } - - this->statement(label); -} - -// SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | -// Assignment | ShortVarDecl . - -// EmptyStmt was handled in Parse::statement. - -// In order to make this work for if and switch statements, if -// RETURN_EXP is not NULL, and we see an ExpressionStat, we return the -// expression rather than adding an expression statement to the -// current block. If we see something other than an ExpressionStat, -// we add the statement, set *RETURN_EXP to true if we saw a send -// statement, and return NULL. The handling of send statements is for -// better error messages. - -// If P_RANGE_CLAUSE is not NULL, then this will recognize a -// RangeClause. - -// If P_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::simple_stat(bool may_be_composite_lit, bool* return_exp, - Range_clause* p_range_clause, Type_switch* p_type_switch) -{ - const Token* token = this->peek_token(); - - // An identifier follow by := is a SimpleVarDecl. - if (token->is_identifier()) - { - std::string identifier = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - - token = this->advance_token(); - if (token->is_op(OPERATOR_COLONEQ) - || token->is_op(OPERATOR_COMMA)) - { - identifier = this->gogo_->pack_hidden_name(identifier, is_exported); - this->simple_var_decl_or_assignment(identifier, location, - p_range_clause, - (token->is_op(OPERATOR_COLONEQ) - ? p_type_switch - : NULL)); - return NULL; - } - - this->unget_token(Token::make_identifier_token(identifier, is_exported, - location)); - } - - Expression* exp = this->expression(PRECEDENCE_NORMAL, true, - may_be_composite_lit, - (p_type_switch == NULL - ? NULL - : &p_type_switch->found)); - if (p_type_switch != NULL && p_type_switch->found) - { - p_type_switch->name.clear(); - p_type_switch->location = exp->location(); - p_type_switch->expr = this->verify_not_sink(exp); - return NULL; - } - token = this->peek_token(); - if (token->is_op(OPERATOR_CHANOP)) - { - this->send_stmt(this->verify_not_sink(exp)); - if (return_exp != NULL) - *return_exp = true; - } - else if (token->is_op(OPERATOR_PLUSPLUS) - || token->is_op(OPERATOR_MINUSMINUS)) - this->inc_dec_stat(this->verify_not_sink(exp)); - else if (token->is_op(OPERATOR_COMMA) - || token->is_op(OPERATOR_EQ)) - this->assignment(exp, p_range_clause); - else if (token->is_op(OPERATOR_PLUSEQ) - || token->is_op(OPERATOR_MINUSEQ) - || token->is_op(OPERATOR_OREQ) - || token->is_op(OPERATOR_XOREQ) - || token->is_op(OPERATOR_MULTEQ) - || token->is_op(OPERATOR_DIVEQ) - || token->is_op(OPERATOR_MODEQ) - || token->is_op(OPERATOR_LSHIFTEQ) - || token->is_op(OPERATOR_RSHIFTEQ) - || token->is_op(OPERATOR_ANDEQ) - || token->is_op(OPERATOR_BITCLEAREQ)) - this->assignment(this->verify_not_sink(exp), p_range_clause); - else if (return_exp != NULL) - return this->verify_not_sink(exp); - else - this->expression_stat(this->verify_not_sink(exp)); - - return NULL; -} - -bool -Parse::simple_stat_may_start_here() -{ - return this->expression_may_start_here(); -} - -// Parse { Statement ";" } which is used in a few places. The list of -// statements may end with a right curly brace, in which case the -// semicolon may be omitted. - -void -Parse::statement_list() -{ - while (this->statement_may_start_here()) - { - this->statement(NULL); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - else if (this->peek_token()->is_op(OPERATOR_RCURLY)) - break; - else - { - if (!this->peek_token()->is_eof() || !saw_errors()) - error_at(this->location(), "expected %<;%> or %<}%> or newline"); - if (!this->skip_past_error(OPERATOR_RCURLY)) - return; - } - } -} - -bool -Parse::statement_list_may_start_here() -{ - return this->statement_may_start_here(); -} - -// ExpressionStat = Expression . - -void -Parse::expression_stat(Expression* exp) -{ - exp->discarding_value(); - this->gogo_->add_statement(Statement::make_statement(exp)); -} - -// SendStmt = Channel "<-" Expression . -// Channel = Expression . - -void -Parse::send_stmt(Expression* channel) -{ - go_assert(this->peek_token()->is_op(OPERATOR_CHANOP)); - source_location loc = this->location(); - this->advance_token(); - Expression* val = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - Statement* s = Statement::make_send_statement(channel, val, loc); - this->gogo_->add_statement(s); -} - -// IncDecStat = Expression ( "++" | "--" ) . - -void -Parse::inc_dec_stat(Expression* exp) -{ - const Token* token = this->peek_token(); - - // Lvalue maps require special handling. - if (exp->index_expression() != NULL) - exp->index_expression()->set_is_lvalue(); - - if (token->is_op(OPERATOR_PLUSPLUS)) - this->gogo_->add_statement(Statement::make_inc_statement(exp)); - else if (token->is_op(OPERATOR_MINUSMINUS)) - this->gogo_->add_statement(Statement::make_dec_statement(exp)); - else - go_unreachable(); - this->advance_token(); -} - -// Assignment = ExpressionList assign_op ExpressionList . - -// EXP is an expression that we have already parsed. - -// If RANGE_CLAUSE is not NULL, then this will recognize a -// RangeClause. - -void -Parse::assignment(Expression* expr, Range_clause* p_range_clause) -{ - Expression_list* vars; - if (!this->peek_token()->is_op(OPERATOR_COMMA)) - { - vars = new Expression_list(); - vars->push_back(expr); - } - else - { - this->advance_token(); - vars = this->expression_list(expr, true); - } - - this->tuple_assignment(vars, p_range_clause); -} - -// An assignment statement. LHS is the list of expressions which -// appear on the left hand side. - -// If RANGE_CLAUSE is not NULL, then this will recognize a -// RangeClause. - -void -Parse::tuple_assignment(Expression_list* lhs, Range_clause* p_range_clause) -{ - const Token* token = this->peek_token(); - if (!token->is_op(OPERATOR_EQ) - && !token->is_op(OPERATOR_PLUSEQ) - && !token->is_op(OPERATOR_MINUSEQ) - && !token->is_op(OPERATOR_OREQ) - && !token->is_op(OPERATOR_XOREQ) - && !token->is_op(OPERATOR_MULTEQ) - && !token->is_op(OPERATOR_DIVEQ) - && !token->is_op(OPERATOR_MODEQ) - && !token->is_op(OPERATOR_LSHIFTEQ) - && !token->is_op(OPERATOR_RSHIFTEQ) - && !token->is_op(OPERATOR_ANDEQ) - && !token->is_op(OPERATOR_BITCLEAREQ)) - { - error_at(this->location(), "expected assignment operator"); - return; - } - Operator op = token->op(); - source_location location = token->location(); - - token = this->advance_token(); - - if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE)) - { - if (op != OPERATOR_EQ) - error_at(this->location(), "range clause requires %<=%>"); - this->range_clause_expr(lhs, p_range_clause); - return; - } - - Expression_list* vals = this->expression_list(NULL, false); - - // We've parsed everything; check for errors. - if (lhs == NULL || vals == NULL) - return; - for (Expression_list::const_iterator pe = lhs->begin(); - pe != lhs->end(); - ++pe) - { - if ((*pe)->is_error_expression()) - return; - if (op != OPERATOR_EQ && (*pe)->is_sink_expression()) - error_at((*pe)->location(), "cannot use _ as value"); - } - for (Expression_list::const_iterator pe = vals->begin(); - pe != vals->end(); - ++pe) - { - if ((*pe)->is_error_expression()) - return; - } - - // Map expressions act differently when they are lvalues. - for (Expression_list::iterator plv = lhs->begin(); - plv != lhs->end(); - ++plv) - if ((*plv)->index_expression() != NULL) - (*plv)->index_expression()->set_is_lvalue(); - - Call_expression* call; - Index_expression* map_index; - Receive_expression* receive; - Type_guard_expression* type_guard; - if (lhs->size() == vals->size()) - { - Statement* s; - if (lhs->size() > 1) - { - if (op != OPERATOR_EQ) - error_at(location, "multiple values only permitted with %<=%>"); - s = Statement::make_tuple_assignment(lhs, vals, location); - } - else - { - if (op == OPERATOR_EQ) - s = Statement::make_assignment(lhs->front(), vals->front(), - location); - else - s = Statement::make_assignment_operation(op, lhs->front(), - vals->front(), location); - delete lhs; - delete vals; - } - this->gogo_->add_statement(s); - } - else if (vals->size() == 1 - && (call = (*vals->begin())->call_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "multiple results only permitted with %<=%>"); - delete vals; - vals = new Expression_list; - for (unsigned int i = 0; i < lhs->size(); ++i) - vals->push_back(Expression::make_call_result(call, i)); - Statement* s = Statement::make_tuple_assignment(lhs, vals, location); - this->gogo_->add_statement(s); - } - else if (lhs->size() == 2 - && vals->size() == 1 - && (map_index = (*vals->begin())->index_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "two values from map requires %<=%>"); - Expression* val = lhs->front(); - Expression* present = lhs->back(); - Statement* s = Statement::make_tuple_map_assignment(val, present, - map_index, location); - this->gogo_->add_statement(s); - } - else if (lhs->size() == 1 - && vals->size() == 2 - && (map_index = lhs->front()->index_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "assigning tuple to map index requires %<=%>"); - Expression* val = vals->front(); - Expression* should_set = vals->back(); - Statement* s = Statement::make_map_assignment(map_index, val, should_set, - location); - this->gogo_->add_statement(s); - } - else if (lhs->size() == 2 - && vals->size() == 1 - && (receive = (*vals->begin())->receive_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "two values from receive requires %<=%>"); - Expression* val = lhs->front(); - Expression* success = lhs->back(); - Expression* channel = receive->channel(); - Statement* s = Statement::make_tuple_receive_assignment(val, success, - channel, - false, - location); - this->gogo_->add_statement(s); - } - else if (lhs->size() == 2 - && vals->size() == 1 - && (type_guard = (*vals->begin())->type_guard_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "two values from type guard requires %<=%>"); - Expression* val = lhs->front(); - Expression* ok = lhs->back(); - Expression* expr = type_guard->expr(); - Type* type = type_guard->type(); - Statement* s = Statement::make_tuple_type_guard_assignment(val, ok, - expr, type, - location); - this->gogo_->add_statement(s); - } - else - { - error_at(location, "number of variables does not match number of values"); - } -} - -// GoStat = "go" Expression . -// DeferStat = "defer" Expression . - -void -Parse::go_or_defer_stat() -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_GO) - || this->peek_token()->is_keyword(KEYWORD_DEFER)); - bool is_go = this->peek_token()->is_keyword(KEYWORD_GO); - source_location stat_location = this->location(); - this->advance_token(); - source_location expr_location = this->location(); - Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - Call_expression* call_expr = expr->call_expression(); - if (call_expr == NULL) - { - error_at(expr_location, "expected call expression"); - return; - } - - // Make it easier to simplify go/defer statements by putting every - // statement in its own block. - this->gogo_->start_block(stat_location); - Statement* stat; - if (is_go) - stat = Statement::make_go_statement(call_expr, stat_location); - else - stat = Statement::make_defer_statement(call_expr, stat_location); - this->gogo_->add_statement(stat); - this->gogo_->add_block(this->gogo_->finish_block(stat_location), - stat_location); -} - -// ReturnStat = "return" [ ExpressionList ] . - -void -Parse::return_stat() -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_RETURN)); - source_location location = this->location(); - this->advance_token(); - Expression_list* vals = NULL; - if (this->expression_may_start_here()) - vals = this->expression_list(NULL, false); - this->gogo_->add_statement(Statement::make_return_statement(vals, location)); -} - -// IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" Statement ] . - -void -Parse::if_stat() -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_IF)); - source_location location = this->location(); - this->advance_token(); - - this->gogo_->start_block(location); - - bool saw_simple_stat = false; - Expression* cond = NULL; - bool saw_send_stmt; - if (this->simple_stat_may_start_here()) - { - cond = this->simple_stat(false, &saw_send_stmt, NULL, NULL); - saw_simple_stat = true; - } - if (cond != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - // The SimpleStat is an expression statement. - this->expression_stat(cond); - cond = NULL; - } - if (cond == NULL) - { - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - else if (saw_simple_stat) - { - if (saw_send_stmt) - error_at(this->location(), - ("send statement used as value; " - "use select for non-blocking send")); - else - error_at(this->location(), - "expected %<;%> after statement in if expression"); - if (!this->expression_may_start_here()) - cond = Expression::make_error(this->location()); - } - if (cond == NULL && this->peek_token()->is_op(OPERATOR_LCURLY)) - { - error_at(this->location(), - "missing condition in if statement"); - cond = Expression::make_error(this->location()); - } - if (cond == NULL) - cond = this->expression(PRECEDENCE_NORMAL, false, false, NULL); - } - - this->gogo_->start_block(this->location()); - source_location end_loc = this->block(); - Block* then_block = this->gogo_->finish_block(end_loc); - - // Check for the easy error of a newline before "else". - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - source_location semi_loc = this->location(); - if (this->advance_token()->is_keyword(KEYWORD_ELSE)) - error_at(this->location(), - "unexpected semicolon or newline before %"); - else - this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON, - semi_loc)); - } - - Block* else_block = NULL; - if (this->peek_token()->is_keyword(KEYWORD_ELSE)) - { - this->advance_token(); - // We create a block to gather the statement. - this->gogo_->start_block(this->location()); - this->statement(NULL); - else_block = this->gogo_->finish_block(this->location()); - } - - this->gogo_->add_statement(Statement::make_if_statement(cond, then_block, - else_block, - location)); - - this->gogo_->add_block(this->gogo_->finish_block(this->location()), - location); -} - -// SwitchStmt = ExprSwitchStmt | TypeSwitchStmt . -// ExprSwitchStmt = "switch" [ [ SimpleStat ] ";" ] [ Expression ] -// "{" { ExprCaseClause } "}" . -// TypeSwitchStmt = "switch" [ [ SimpleStat ] ";" ] TypeSwitchGuard -// "{" { TypeCaseClause } "}" . -// TypeSwitchGuard = [ identifier ":=" ] Expression "." "(" "type" ")" . - -void -Parse::switch_stat(Label* label) -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_SWITCH)); - source_location location = this->location(); - this->advance_token(); - - this->gogo_->start_block(location); - - bool saw_simple_stat = false; - Expression* switch_val = NULL; - bool saw_send_stmt; - Type_switch type_switch; - if (this->simple_stat_may_start_here()) - { - switch_val = this->simple_stat(false, &saw_send_stmt, NULL, - &type_switch); - saw_simple_stat = true; - } - if (switch_val != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - // The SimpleStat is an expression statement. - this->expression_stat(switch_val); - switch_val = NULL; - } - if (switch_val == NULL && !type_switch.found) - { - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - else if (saw_simple_stat) - { - if (saw_send_stmt) - error_at(this->location(), - ("send statement used as value; " - "use select for non-blocking send")); - else - error_at(this->location(), - "expected %<;%> after statement in switch expression"); - } - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - { - if (this->peek_token()->is_identifier()) - { - const Token* token = this->peek_token(); - std::string identifier = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location id_loc = token->location(); - - token = this->advance_token(); - bool is_coloneq = token->is_op(OPERATOR_COLONEQ); - this->unget_token(Token::make_identifier_token(identifier, - is_exported, - id_loc)); - if (is_coloneq) - { - // This must be a TypeSwitchGuard. - switch_val = this->simple_stat(false, &saw_send_stmt, NULL, - &type_switch); - if (!type_switch.found) - { - if (switch_val == NULL - || !switch_val->is_error_expression()) - { - error_at(id_loc, "expected type switch assignment"); - switch_val = Expression::make_error(id_loc); - } - } - } - } - if (switch_val == NULL && !type_switch.found) - { - switch_val = this->expression(PRECEDENCE_NORMAL, false, false, - &type_switch.found); - if (type_switch.found) - { - type_switch.name.clear(); - type_switch.expr = switch_val; - type_switch.location = switch_val->location(); - } - } - } - } - - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - { - source_location token_loc = this->location(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(token_loc, "unexpected semicolon or newline before %<{%>"); - else if (this->peek_token()->is_op(OPERATOR_COLONEQ)) - { - error_at(token_loc, "invalid variable name"); - this->advance_token(); - this->expression(PRECEDENCE_NORMAL, false, false, - &type_switch.found); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - return; - if (type_switch.found) - type_switch.expr = Expression::make_error(location); - } - else - { - error_at(this->location(), "expected %<{%>"); - this->gogo_->add_block(this->gogo_->finish_block(this->location()), - location); - return; - } - } - this->advance_token(); - - Statement* statement; - if (type_switch.found) - statement = this->type_switch_body(label, type_switch, location); - else - statement = this->expr_switch_body(label, switch_val, location); - - if (statement != NULL) - this->gogo_->add_statement(statement); - - this->gogo_->add_block(this->gogo_->finish_block(this->location()), - location); -} - -// The body of an expression switch. -// "{" { ExprCaseClause } "}" - -Statement* -Parse::expr_switch_body(Label* label, Expression* switch_val, - source_location location) -{ - Switch_statement* statement = Statement::make_switch_statement(switch_val, - location); - - this->push_break_statement(statement, label); - - Case_clauses* case_clauses = new Case_clauses(); - bool saw_default = false; - while (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - if (this->peek_token()->is_eof()) - { - if (!saw_errors()) - error_at(this->location(), "missing %<}%>"); - return NULL; - } - this->expr_case_clause(case_clauses, &saw_default); - } - this->advance_token(); - - statement->add_clauses(case_clauses); - - this->pop_break_statement(); - - return statement; -} - -// ExprCaseClause = ExprSwitchCase ":" [ StatementList ] . -// FallthroughStat = "fallthrough" . - -void -Parse::expr_case_clause(Case_clauses* clauses, bool* saw_default) -{ - source_location location = this->location(); - - bool is_default = false; - Expression_list* vals = this->expr_switch_case(&is_default); - - if (!this->peek_token()->is_op(OPERATOR_COLON)) - { - if (!saw_errors()) - error_at(this->location(), "expected %<:%>"); - return; - } - else - this->advance_token(); - - Block* statements = NULL; - if (this->statement_list_may_start_here()) - { - this->gogo_->start_block(this->location()); - this->statement_list(); - statements = this->gogo_->finish_block(this->location()); - } - - bool is_fallthrough = false; - if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH)) - { - is_fallthrough = true; - if (this->advance_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - } - - if (is_default) - { - if (*saw_default) - { - error_at(location, "multiple defaults in switch"); - return; - } - *saw_default = true; - } - - if (is_default || vals != NULL) - clauses->add(vals, is_default, statements, is_fallthrough, location); -} - -// ExprSwitchCase = "case" ExpressionList | "default" . - -Expression_list* -Parse::expr_switch_case(bool* is_default) -{ - const Token* token = this->peek_token(); - if (token->is_keyword(KEYWORD_CASE)) - { - this->advance_token(); - return this->expression_list(NULL, false); - } - else if (token->is_keyword(KEYWORD_DEFAULT)) - { - this->advance_token(); - *is_default = true; - return NULL; - } - else - { - if (!saw_errors()) - error_at(this->location(), "expected % or %"); - if (!token->is_op(OPERATOR_RCURLY)) - this->advance_token(); - return NULL; - } -} - -// The body of a type switch. -// "{" { TypeCaseClause } "}" . - -Statement* -Parse::type_switch_body(Label* label, const Type_switch& type_switch, - source_location location) -{ - Named_object* switch_no = NULL; - if (!type_switch.name.empty()) - { - Variable* switch_var = new Variable(NULL, type_switch.expr, false, false, - false, type_switch.location); - switch_no = this->gogo_->add_variable(type_switch.name, switch_var); - } - - Type_switch_statement* statement = - Statement::make_type_switch_statement(switch_no, - (switch_no == NULL - ? type_switch.expr - : NULL), - location); - - this->push_break_statement(statement, label); - - Type_case_clauses* case_clauses = new Type_case_clauses(); - bool saw_default = false; - while (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - if (this->peek_token()->is_eof()) - { - error_at(this->location(), "missing %<}%>"); - return NULL; - } - this->type_case_clause(switch_no, case_clauses, &saw_default); - } - this->advance_token(); - - statement->add_clauses(case_clauses); - - this->pop_break_statement(); - - return statement; -} - -// TypeCaseClause = TypeSwitchCase ":" [ StatementList ] . - -void -Parse::type_case_clause(Named_object* switch_no, Type_case_clauses* clauses, - bool* saw_default) -{ - source_location location = this->location(); - - std::vector types; - bool is_default = false; - this->type_switch_case(&types, &is_default); - - if (!this->peek_token()->is_op(OPERATOR_COLON)) - error_at(this->location(), "expected %<:%>"); - else - this->advance_token(); - - Block* statements = NULL; - if (this->statement_list_may_start_here()) - { - this->gogo_->start_block(this->location()); - if (switch_no != NULL && types.size() == 1) - { - Type* type = types.front(); - Expression* init = Expression::make_var_reference(switch_no, - location); - init = Expression::make_type_guard(init, type, location); - Variable* v = new Variable(type, init, false, false, false, - location); - v->set_is_type_switch_var(); - this->gogo_->add_variable(switch_no->name(), v); - } - this->statement_list(); - statements = this->gogo_->finish_block(this->location()); - } - - if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH)) - { - error_at(this->location(), - "fallthrough is not permitted in a type switch"); - if (this->advance_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - } - - if (is_default) - { - go_assert(types.empty()); - if (*saw_default) - { - error_at(location, "multiple defaults in type switch"); - return; - } - *saw_default = true; - clauses->add(NULL, false, true, statements, location); - } - else if (!types.empty()) - { - for (std::vector::const_iterator p = types.begin(); - p + 1 != types.end(); - ++p) - clauses->add(*p, true, false, NULL, location); - clauses->add(types.back(), false, false, statements, location); - } - else - clauses->add(Type::make_error_type(), false, false, statements, location); -} - -// TypeSwitchCase = "case" type | "default" - -// We accept a comma separated list of types. - -void -Parse::type_switch_case(std::vector* types, bool* is_default) -{ - const Token* token = this->peek_token(); - if (token->is_keyword(KEYWORD_CASE)) - { - this->advance_token(); - while (true) - { - Type* t = this->type(); - if (!t->is_error_type()) - types->push_back(t); - if (!this->peek_token()->is_op(OPERATOR_COMMA)) - break; - this->advance_token(); - } - } - else if (token->is_keyword(KEYWORD_DEFAULT)) - { - this->advance_token(); - *is_default = true; - } - else - { - error_at(this->location(), "expected % or %"); - if (!token->is_op(OPERATOR_RCURLY)) - this->advance_token(); - } -} - -// SelectStat = "select" "{" { CommClause } "}" . - -void -Parse::select_stat(Label* label) -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_SELECT)); - source_location location = this->location(); - const Token* token = this->advance_token(); - - if (!token->is_op(OPERATOR_LCURLY)) - { - source_location token_loc = token->location(); - if (token->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(token_loc, "unexpected semicolon or newline before %<{%>"); - else - { - error_at(this->location(), "expected %<{%>"); - return; - } - } - this->advance_token(); - - Select_statement* statement = Statement::make_select_statement(location); - - this->push_break_statement(statement, label); - - Select_clauses* select_clauses = new Select_clauses(); - bool saw_default = false; - while (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - if (this->peek_token()->is_eof()) - { - error_at(this->location(), "expected %<}%>"); - return; - } - this->comm_clause(select_clauses, &saw_default); - } - - this->advance_token(); - - statement->add_clauses(select_clauses); - - this->pop_break_statement(); - - this->gogo_->add_statement(statement); -} - -// CommClause = CommCase ":" { Statement ";" } . - -void -Parse::comm_clause(Select_clauses* clauses, bool* saw_default) -{ - source_location location = this->location(); - bool is_send = false; - Expression* channel = NULL; - Expression* val = NULL; - Expression* closed = NULL; - std::string varname; - std::string closedname; - bool is_default = false; - bool got_case = this->comm_case(&is_send, &channel, &val, &closed, - &varname, &closedname, &is_default); - - if (!is_send - && varname.empty() - && closedname.empty() - && val != NULL - && val->index_expression() != NULL) - val->index_expression()->set_is_lvalue(); - - if (this->peek_token()->is_op(OPERATOR_COLON)) - this->advance_token(); - else - error_at(this->location(), "expected colon"); - - this->gogo_->start_block(this->location()); - - Named_object* var = NULL; - if (!varname.empty()) - { - // FIXME: LOCATION is slightly wrong here. - Variable* v = new Variable(NULL, channel, false, false, false, - location); - v->set_type_from_chan_element(); - var = this->gogo_->add_variable(varname, v); - } - - Named_object* closedvar = NULL; - if (!closedname.empty()) - { - // FIXME: LOCATION is slightly wrong here. - Variable* v = new Variable(Type::lookup_bool_type(), NULL, - false, false, false, location); - closedvar = this->gogo_->add_variable(closedname, v); - } - - this->statement_list(); - - Block* statements = this->gogo_->finish_block(this->location()); - - if (is_default) - { - if (*saw_default) - { - error_at(location, "multiple defaults in select"); - return; - } - *saw_default = true; - } - - if (got_case) - clauses->add(is_send, channel, val, closed, var, closedvar, is_default, - statements, location); - else if (statements != NULL) - { - // Add the statements to make sure that any names they define - // are traversed. - this->gogo_->add_block(statements, location); - } -} - -// CommCase = "case" ( SendStmt | RecvStmt ) | "default" . - -bool -Parse::comm_case(bool* is_send, Expression** channel, Expression** val, - Expression** closed, std::string* varname, - std::string* closedname, bool* is_default) -{ - const Token* token = this->peek_token(); - if (token->is_keyword(KEYWORD_DEFAULT)) - { - this->advance_token(); - *is_default = true; - } - else if (token->is_keyword(KEYWORD_CASE)) - { - this->advance_token(); - if (!this->send_or_recv_stmt(is_send, channel, val, closed, varname, - closedname)) - return false; - } - else - { - error_at(this->location(), "expected % or %"); - if (!token->is_op(OPERATOR_RCURLY)) - this->advance_token(); - return false; - } - - return true; -} - -// RecvStmt = [ Expression [ "," Expression ] ( "=" | ":=" ) ] RecvExpr . -// RecvExpr = Expression . - -bool -Parse::send_or_recv_stmt(bool* is_send, Expression** channel, Expression** val, - Expression** closed, std::string* varname, - std::string* closedname) -{ - const Token* token = this->peek_token(); - bool saw_comma = false; - bool closed_is_id = false; - if (token->is_identifier()) - { - Gogo* gogo = this->gogo_; - std::string recv_var = token->identifier(); - bool is_rv_exported = token->is_identifier_exported(); - source_location recv_var_loc = token->location(); - token = this->advance_token(); - if (token->is_op(OPERATOR_COLONEQ)) - { - // case rv := <-c: - if (!this->advance_token()->is_op(OPERATOR_CHANOP)) - { - error_at(this->location(), "expected %<<-%>"); - return false; - } - if (recv_var == "_") - { - error_at(recv_var_loc, - "no new variables on left side of %<:=%>"); - recv_var = "blank"; - } - *is_send = false; - *varname = gogo->pack_hidden_name(recv_var, is_rv_exported); - this->advance_token(); - *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - return true; - } - else if (token->is_op(OPERATOR_COMMA)) - { - token = this->advance_token(); - if (token->is_identifier()) - { - std::string recv_closed = token->identifier(); - bool is_rc_exported = token->is_identifier_exported(); - source_location recv_closed_loc = token->location(); - closed_is_id = true; - - token = this->advance_token(); - if (token->is_op(OPERATOR_COLONEQ)) - { - // case rv, rc := <-c: - if (!this->advance_token()->is_op(OPERATOR_CHANOP)) - { - error_at(this->location(), "expected %<<-%>"); - return false; - } - if (recv_var == "_" && recv_closed == "_") - { - error_at(recv_var_loc, - "no new variables on left side of %<:=%>"); - recv_var = "blank"; - } - *is_send = false; - if (recv_var != "_") - *varname = gogo->pack_hidden_name(recv_var, - is_rv_exported); - if (recv_closed != "_") - *closedname = gogo->pack_hidden_name(recv_closed, - is_rc_exported); - this->advance_token(); - *channel = this->expression(PRECEDENCE_NORMAL, false, true, - NULL); - return true; - } - - this->unget_token(Token::make_identifier_token(recv_closed, - is_rc_exported, - recv_closed_loc)); - } - - *val = this->id_to_expression(gogo->pack_hidden_name(recv_var, - is_rv_exported), - recv_var_loc); - saw_comma = true; - } - else - this->unget_token(Token::make_identifier_token(recv_var, - is_rv_exported, - recv_var_loc)); - } - - // If SAW_COMMA is false, then we are looking at the start of the - // send or receive expression. If SAW_COMMA is true, then *VAL is - // set and we just read a comma. - - Expression* e; - if (saw_comma || !this->peek_token()->is_op(OPERATOR_CHANOP)) - e = this->expression(PRECEDENCE_NORMAL, true, true, NULL); - else - { - // case <-c: - *is_send = false; - this->advance_token(); - *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - - // The next token should be ':'. If it is '<-', then we have - // case <-c <- v: - // which is to say, send on a channel received from a channel. - if (!this->peek_token()->is_op(OPERATOR_CHANOP)) - return true; - - e = Expression::make_receive(*channel, (*channel)->location()); - } - - if (this->peek_token()->is_op(OPERATOR_EQ)) - { - if (!this->advance_token()->is_op(OPERATOR_CHANOP)) - { - error_at(this->location(), "missing %<<-%>"); - return false; - } - *is_send = false; - this->advance_token(); - *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - if (saw_comma) - { - // case v, e = <-c: - // *VAL is already set. - if (!e->is_sink_expression()) - *closed = e; - } - else - { - // case v = <-c: - if (!e->is_sink_expression()) - *val = e; - } - return true; - } - - if (saw_comma) - { - if (closed_is_id) - error_at(this->location(), "expected %<=%> or %<:=%>"); - else - error_at(this->location(), "expected %<=%>"); - return false; - } - - if (this->peek_token()->is_op(OPERATOR_CHANOP)) - { - // case c <- v: - *is_send = true; - *channel = this->verify_not_sink(e); - this->advance_token(); - *val = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - return true; - } - - error_at(this->location(), "expected %<<-%> or %<=%>"); - return false; -} - -// ForStat = "for" [ Condition | ForClause | RangeClause ] Block . -// Condition = Expression . - -void -Parse::for_stat(Label* label) -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_FOR)); - source_location location = this->location(); - const Token* token = this->advance_token(); - - // Open a block to hold any variables defined in the init statement - // of the for statement. - this->gogo_->start_block(location); - - Block* init = NULL; - Expression* cond = NULL; - Block* post = NULL; - Range_clause range_clause; - - if (!token->is_op(OPERATOR_LCURLY)) - { - if (token->is_keyword(KEYWORD_VAR)) - { - error_at(this->location(), - "var declaration not allowed in for initializer"); - this->var_decl(); - } - - if (token->is_op(OPERATOR_SEMICOLON)) - this->for_clause(&cond, &post); - else - { - // We might be looking at a Condition, an InitStat, or a - // RangeClause. - bool saw_send_stmt; - cond = this->simple_stat(false, &saw_send_stmt, &range_clause, NULL); - if (!this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - if (cond == NULL && !range_clause.found) - { - if (saw_send_stmt) - error_at(this->location(), - ("send statement used as value; " - "use select for non-blocking send")); - else - error_at(this->location(), "parse error in for statement"); - } - } - else - { - if (range_clause.found) - error_at(this->location(), "parse error after range clause"); - - if (cond != NULL) - { - // COND is actually an expression statement for - // InitStat at the start of a ForClause. - this->expression_stat(cond); - cond = NULL; - } - - this->for_clause(&cond, &post); - } - } - } - - // Build the For_statement and note that it is the current target - // for break and continue statements. - - For_statement* sfor; - For_range_statement* srange; - Statement* s; - if (!range_clause.found) - { - sfor = Statement::make_for_statement(init, cond, post, location); - s = sfor; - srange = NULL; - } - else - { - srange = Statement::make_for_range_statement(range_clause.index, - range_clause.value, - range_clause.range, - location); - s = srange; - sfor = NULL; - } - - this->push_break_statement(s, label); - this->push_continue_statement(s, label); - - // Gather the block of statements in the loop and add them to the - // For_statement. - - this->gogo_->start_block(this->location()); - source_location end_loc = this->block(); - Block* statements = this->gogo_->finish_block(end_loc); - - if (sfor != NULL) - sfor->add_statements(statements); - else - srange->add_statements(statements); - - // This is no longer the break/continue target. - this->pop_break_statement(); - this->pop_continue_statement(); - - // Add the For_statement to the list of statements, and close out - // the block we started to hold any variables defined in the for - // statement. - - this->gogo_->add_statement(s); - - this->gogo_->add_block(this->gogo_->finish_block(this->location()), - location); -} - -// ForClause = [ InitStat ] ";" [ Condition ] ";" [ PostStat ] . -// InitStat = SimpleStat . -// PostStat = SimpleStat . - -// We have already read InitStat at this point. - -void -Parse::for_clause(Expression** cond, Block** post) -{ - go_assert(this->peek_token()->is_op(OPERATOR_SEMICOLON)); - this->advance_token(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - *cond = NULL; - else if (this->peek_token()->is_op(OPERATOR_LCURLY)) - { - error_at(this->location(), - "unexpected semicolon or newline before %<{%>"); - *cond = NULL; - *post = NULL; - return; - } - else - *cond = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - if (!this->peek_token()->is_op(OPERATOR_SEMICOLON)) - error_at(this->location(), "expected semicolon"); - else - this->advance_token(); - - if (this->peek_token()->is_op(OPERATOR_LCURLY)) - *post = NULL; - else - { - this->gogo_->start_block(this->location()); - this->simple_stat(false, NULL, NULL, NULL); - *post = this->gogo_->finish_block(this->location()); - } -} - -// RangeClause = IdentifierList ( "=" | ":=" ) "range" Expression . - -// This is the := version. It is called with a list of identifiers. - -void -Parse::range_clause_decl(const Typed_identifier_list* til, - Range_clause* p_range_clause) -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE)); - source_location location = this->location(); - - p_range_clause->found = true; - - go_assert(til->size() >= 1); - if (til->size() > 2) - error_at(this->location(), "too many variables for range clause"); - - this->advance_token(); - Expression* expr = this->expression(PRECEDENCE_NORMAL, false, false, NULL); - p_range_clause->range = expr; - - bool any_new = false; - - const Typed_identifier* pti = &til->front(); - Named_object* no = this->init_var(*pti, NULL, expr, true, true, &any_new); - if (any_new && no->is_variable()) - no->var_value()->set_type_from_range_index(); - p_range_clause->index = Expression::make_var_reference(no, location); - - if (til->size() == 1) - p_range_clause->value = NULL; - else - { - pti = &til->back(); - bool is_new = false; - no = this->init_var(*pti, NULL, expr, true, true, &is_new); - if (is_new && no->is_variable()) - no->var_value()->set_type_from_range_value(); - if (is_new) - any_new = true; - p_range_clause->value = Expression::make_var_reference(no, location); - } - - if (!any_new) - error_at(location, "variables redeclared but no variable is new"); -} - -// The = version of RangeClause. This is called with a list of -// expressions. - -void -Parse::range_clause_expr(const Expression_list* vals, - Range_clause* p_range_clause) -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE)); - - p_range_clause->found = true; - - go_assert(vals->size() >= 1); - if (vals->size() > 2) - error_at(this->location(), "too many variables for range clause"); - - this->advance_token(); - p_range_clause->range = this->expression(PRECEDENCE_NORMAL, false, false, - NULL); - - p_range_clause->index = vals->front(); - if (vals->size() == 1) - p_range_clause->value = NULL; - else - p_range_clause->value = vals->back(); -} - -// Push a statement on the break stack. - -void -Parse::push_break_statement(Statement* enclosing, Label* label) -{ - if (this->break_stack_ == NULL) - this->break_stack_ = new Bc_stack(); - this->break_stack_->push_back(std::make_pair(enclosing, label)); -} - -// Push a statement on the continue stack. - -void -Parse::push_continue_statement(Statement* enclosing, Label* label) -{ - if (this->continue_stack_ == NULL) - this->continue_stack_ = new Bc_stack(); - this->continue_stack_->push_back(std::make_pair(enclosing, label)); -} - -// Pop the break stack. - -void -Parse::pop_break_statement() -{ - this->break_stack_->pop_back(); -} - -// Pop the continue stack. - -void -Parse::pop_continue_statement() -{ - this->continue_stack_->pop_back(); -} - -// Find a break or continue statement given a label name. - -Statement* -Parse::find_bc_statement(const Bc_stack* bc_stack, const std::string& label) -{ - if (bc_stack == NULL) - return NULL; - for (Bc_stack::const_reverse_iterator p = bc_stack->rbegin(); - p != bc_stack->rend(); - ++p) - { - if (p->second != NULL && p->second->name() == label) - { - p->second->set_is_used(); - return p->first; - } - } - return NULL; -} - -// BreakStat = "break" [ identifier ] . - -void -Parse::break_stat() -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_BREAK)); - source_location location = this->location(); - - const Token* token = this->advance_token(); - Statement* enclosing; - if (!token->is_identifier()) - { - if (this->break_stack_ == NULL || this->break_stack_->empty()) - { - error_at(this->location(), - "break statement not within for or switch or select"); - return; - } - enclosing = this->break_stack_->back().first; - } - else - { - enclosing = this->find_bc_statement(this->break_stack_, - token->identifier()); - if (enclosing == NULL) - { - // If there is a label with this name, mark it as used to - // avoid a useless error about an unused label. - this->gogo_->add_label_reference(token->identifier()); - - error_at(token->location(), "invalid break label %qs", - Gogo::message_name(token->identifier()).c_str()); - this->advance_token(); - return; - } - this->advance_token(); - } - - Unnamed_label* label; - if (enclosing->classification() == Statement::STATEMENT_FOR) - label = enclosing->for_statement()->break_label(); - else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE) - label = enclosing->for_range_statement()->break_label(); - else if (enclosing->classification() == Statement::STATEMENT_SWITCH) - label = enclosing->switch_statement()->break_label(); - else if (enclosing->classification() == Statement::STATEMENT_TYPE_SWITCH) - label = enclosing->type_switch_statement()->break_label(); - else if (enclosing->classification() == Statement::STATEMENT_SELECT) - label = enclosing->select_statement()->break_label(); - else - go_unreachable(); - - this->gogo_->add_statement(Statement::make_break_statement(label, - location)); -} - -// ContinueStat = "continue" [ identifier ] . - -void -Parse::continue_stat() -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_CONTINUE)); - source_location location = this->location(); - - const Token* token = this->advance_token(); - Statement* enclosing; - if (!token->is_identifier()) - { - if (this->continue_stack_ == NULL || this->continue_stack_->empty()) - { - error_at(this->location(), "continue statement not within for"); - return; - } - enclosing = this->continue_stack_->back().first; - } - else - { - enclosing = this->find_bc_statement(this->continue_stack_, - token->identifier()); - if (enclosing == NULL) - { - // If there is a label with this name, mark it as used to - // avoid a useless error about an unused label. - this->gogo_->add_label_reference(token->identifier()); - - error_at(token->location(), "invalid continue label %qs", - Gogo::message_name(token->identifier()).c_str()); - this->advance_token(); - return; - } - this->advance_token(); - } - - Unnamed_label* label; - if (enclosing->classification() == Statement::STATEMENT_FOR) - label = enclosing->for_statement()->continue_label(); - else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE) - label = enclosing->for_range_statement()->continue_label(); - else - go_unreachable(); - - this->gogo_->add_statement(Statement::make_continue_statement(label, - location)); -} - -// GotoStat = "goto" identifier . - -void -Parse::goto_stat() -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_GOTO)); - source_location location = this->location(); - const Token* token = this->advance_token(); - if (!token->is_identifier()) - error_at(this->location(), "expected label for goto"); - else - { - Label* label = this->gogo_->add_label_reference(token->identifier()); - Statement* s = Statement::make_goto_statement(label, location); - this->gogo_->add_statement(s); - this->advance_token(); - } -} - -// PackageClause = "package" PackageName . - -void -Parse::package_clause() -{ - const Token* token = this->peek_token(); - source_location location = token->location(); - std::string name; - if (!token->is_keyword(KEYWORD_PACKAGE)) - { - error_at(this->location(), "program must start with package clause"); - name = "ERROR"; - } - else - { - token = this->advance_token(); - if (token->is_identifier()) - { - name = token->identifier(); - if (name == "_") - { - error_at(this->location(), "invalid package name _"); - name = "blank"; - } - this->advance_token(); - } - else - { - error_at(this->location(), "package name must be an identifier"); - name = "ERROR"; - } - } - this->gogo_->set_package_name(name, location); -} - -// ImportDecl = "import" Decl . - -void -Parse::import_decl() -{ - go_assert(this->peek_token()->is_keyword(KEYWORD_IMPORT)); - this->advance_token(); - this->decl(&Parse::import_spec, NULL); -} - -// ImportSpec = [ "." | PackageName ] PackageFileName . - -void -Parse::import_spec(void*) -{ - const Token* token = this->peek_token(); - source_location location = token->location(); - - std::string local_name; - bool is_local_name_exported = false; - if (token->is_op(OPERATOR_DOT)) - { - local_name = "."; - token = this->advance_token(); - } - else if (token->is_identifier()) - { - local_name = token->identifier(); - is_local_name_exported = token->is_identifier_exported(); - token = this->advance_token(); - } - - if (!token->is_string()) - { - error_at(this->location(), "missing import package name"); - return; - } - - this->gogo_->import_package(token->string_value(), local_name, - is_local_name_exported, location); - - this->advance_token(); -} - -// SourceFile = PackageClause ";" { ImportDecl ";" } -// { TopLevelDecl ";" } . - -void -Parse::program() -{ - this->package_clause(); - - const Token* token = this->peek_token(); - if (token->is_op(OPERATOR_SEMICOLON)) - token = this->advance_token(); - else - error_at(this->location(), - "expected %<;%> or newline after package clause"); - - while (token->is_keyword(KEYWORD_IMPORT)) - { - this->import_decl(); - token = this->peek_token(); - if (token->is_op(OPERATOR_SEMICOLON)) - token = this->advance_token(); - else - error_at(this->location(), - "expected %<;%> or newline after import declaration"); - } - - while (!token->is_eof()) - { - if (this->declaration_may_start_here()) - this->declaration(); - else - { - error_at(this->location(), "expected declaration"); - do - this->advance_token(); - while (!this->peek_token()->is_eof() - && !this->peek_token()->is_op(OPERATOR_SEMICOLON) - && !this->peek_token()->is_op(OPERATOR_RCURLY)); - if (!this->peek_token()->is_eof() - && !this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - } - token = this->peek_token(); - if (token->is_op(OPERATOR_SEMICOLON)) - token = this->advance_token(); - else if (!token->is_eof() || !saw_errors()) - { - if (token->is_op(OPERATOR_CHANOP)) - error_at(this->location(), - ("send statement used as value; " - "use select for non-blocking send")); - else - error_at(this->location(), - "expected %<;%> or newline after top level declaration"); - this->skip_past_error(OPERATOR_INVALID); - } - } -} - -// Reset the current iota value. - -void -Parse::reset_iota() -{ - this->iota_ = 0; -} - -// Return the current iota value. - -int -Parse::iota_value() -{ - return this->iota_; -} - -// Increment the current iota value. - -void -Parse::increment_iota() -{ - ++this->iota_; -} - -// Skip forward to a semicolon or OP. OP will normally be -// OPERATOR_RPAREN or OPERATOR_RCURLY. If we find a semicolon, move -// past it and return. If we find OP, it will be the next token to -// read. Return true if we are OK, false if we found EOF. - -bool -Parse::skip_past_error(Operator op) -{ - const Token* token = this->peek_token(); - while (!token->is_op(op)) - { - if (token->is_eof()) - return false; - if (token->is_op(OPERATOR_SEMICOLON)) - { - this->advance_token(); - return true; - } - token = this->advance_token(); - } - return true; -} - -// Check that an expression is not a sink. - -Expression* -Parse::verify_not_sink(Expression* expr) -{ - if (expr->is_sink_expression()) - { - error_at(expr->location(), "cannot use _ as value"); - expr = Expression::make_error(expr->location()); - } - return expr; -} diff --git a/gcc/go/gofrontend/parse.cc.working b/gcc/go/gofrontend/parse.cc.working deleted file mode 100644 index f1b93429ff2..00000000000 --- a/gcc/go/gofrontend/parse.cc.working +++ /dev/null @@ -1,5015 +0,0 @@ -// parse.cc -- Go frontend parser. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include "lex.h" -#include "gogo.h" -#include "types.h" -#include "statements.h" -#include "expressions.h" -#include "parse.h" - -// Struct Parse::Enclosing_var_comparison. - -// Return true if v1 should be considered to be less than v2. - -bool -Parse::Enclosing_var_comparison::operator()(const Enclosing_var& v1, - const Enclosing_var& v2) -{ - if (v1.var() == v2.var()) - return false; - - const std::string& n1(v1.var()->name()); - const std::string& n2(v2.var()->name()); - int i = n1.compare(n2); - if (i < 0) - return true; - else if (i > 0) - return false; - - // If we get here it means that a single nested function refers to - // two different variables defined in enclosing functions, and both - // variables have the same name. I think this is impossible. - gcc_unreachable(); -} - -// Class Parse. - -Parse::Parse(Lex* lex, Gogo* gogo) - : lex_(lex), - token_(Token::make_invalid_token(0)), - unget_token_(Token::make_invalid_token(0)), - unget_token_valid_(false), - gogo_(gogo), - break_stack_(NULL), - continue_stack_(NULL), - iota_(0), - enclosing_vars_() -{ -} - -// Return the current token. - -const Token* -Parse::peek_token() -{ - if (this->unget_token_valid_) - return &this->unget_token_; - if (this->token_.is_invalid()) - this->token_ = this->lex_->next_token(); - return &this->token_; -} - -// Advance to the next token and return it. - -const Token* -Parse::advance_token() -{ - if (this->unget_token_valid_) - { - this->unget_token_valid_ = false; - if (!this->token_.is_invalid()) - return &this->token_; - } - this->token_ = this->lex_->next_token(); - return &this->token_; -} - -// Push a token back on the input stream. - -void -Parse::unget_token(const Token& token) -{ - gcc_assert(!this->unget_token_valid_); - this->unget_token_ = token; - this->unget_token_valid_ = true; -} - -// The location of the current token. - -source_location -Parse::location() -{ - return this->peek_token()->location(); -} - -// IdentifierList = identifier { "," identifier } . - -void -Parse::identifier_list(Typed_identifier_list* til) -{ - const Token* token = this->peek_token(); - while (true) - { - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return; - } - std::string name = - this->gogo_->pack_hidden_name(token->identifier(), - token->is_identifier_exported()); - til->push_back(Typed_identifier(name, NULL, token->location())); - token = this->advance_token(); - if (!token->is_op(OPERATOR_COMMA)) - return; - token = this->advance_token(); - } -} - -// ExpressionList = Expression { "," Expression } . - -// If MAY_BE_SINK is true, the expressions in the list may be "_". - -Expression_list* -Parse::expression_list(Expression* first, bool may_be_sink) -{ - Expression_list* ret = new Expression_list(); - if (first != NULL) - ret->push_back(first); - while (true) - { - ret->push_back(this->expression(PRECEDENCE_NORMAL, may_be_sink, true, - NULL)); - - const Token* token = this->peek_token(); - if (!token->is_op(OPERATOR_COMMA)) - return ret; - - // Most expression lists permit a trailing comma. - source_location location = token->location(); - this->advance_token(); - if (!this->expression_may_start_here()) - { - this->unget_token(Token::make_operator_token(OPERATOR_COMMA, - location)); - return ret; - } - } -} - -// QualifiedIdent = [ PackageName "." ] identifier . -// PackageName = identifier . - -// This sets *PNAME to the identifier and sets *PPACKAGE to the -// package or NULL if there isn't one. This returns true on success, -// false on failure in which case it will have emitted an error -// message. - -bool -Parse::qualified_ident(std::string* pname, Named_object** ppackage) -{ - const Token* token = this->peek_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return false; - } - - std::string name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - name = this->gogo_->pack_hidden_name(name, is_exported); - - token = this->advance_token(); - if (!token->is_op(OPERATOR_DOT)) - { - *pname = name; - *ppackage = NULL; - return true; - } - - Named_object* package = this->gogo_->lookup(name, NULL); - if (package == NULL || !package->is_package()) - { - error_at(this->location(), "expected package"); - // We expect . IDENTIFIER; skip both. - if (this->advance_token()->is_identifier()) - this->advance_token(); - return false; - } - - package->package_value()->set_used(); - - token = this->advance_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return false; - } - - name = token->identifier(); - - if (name == "_") - { - error_at(this->location(), "invalid use of %<_%>"); - name = "blank"; - } - - if (package->name() == this->gogo_->package_name()) - name = this->gogo_->pack_hidden_name(name, - token->is_identifier_exported()); - - *pname = name; - *ppackage = package; - - this->advance_token(); - - return true; -} - -// Type = TypeName | TypeLit | "(" Type ")" . -// TypeLit = -// ArrayType | StructType | PointerType | FunctionType | InterfaceType | -// SliceType | MapType | ChannelType . - -Type* -Parse::type() -{ - const Token* token = this->peek_token(); - if (token->is_identifier()) - return this->type_name(true); - else if (token->is_op(OPERATOR_LSQUARE)) - return this->array_type(false); - else if (token->is_keyword(KEYWORD_CHAN) - || token->is_op(OPERATOR_CHANOP)) - return this->channel_type(); - else if (token->is_keyword(KEYWORD_INTERFACE)) - return this->interface_type(); - else if (token->is_keyword(KEYWORD_FUNC)) - { - source_location location = token->location(); - this->advance_token(); - Type* type = this->signature(NULL, location); - if (type == NULL) - return Type::make_error_type(); - return type; - } - else if (token->is_keyword(KEYWORD_MAP)) - return this->map_type(); - else if (token->is_keyword(KEYWORD_STRUCT)) - return this->struct_type(); - else if (token->is_op(OPERATOR_MULT)) - return this->pointer_type(); - else if (token->is_op(OPERATOR_LPAREN)) - { - this->advance_token(); - Type* ret = this->type(); - if (this->peek_token()->is_op(OPERATOR_RPAREN)) - this->advance_token(); - else - { - if (!ret->is_error_type()) - error_at(this->location(), "expected %<)%>"); - } - return ret; - } - else - { - error_at(token->location(), "expected type"); - return Type::make_error_type(); - } -} - -bool -Parse::type_may_start_here() -{ - const Token* token = this->peek_token(); - return (token->is_identifier() - || token->is_op(OPERATOR_LSQUARE) - || token->is_op(OPERATOR_CHANOP) - || token->is_keyword(KEYWORD_CHAN) - || token->is_keyword(KEYWORD_INTERFACE) - || token->is_keyword(KEYWORD_FUNC) - || token->is_keyword(KEYWORD_MAP) - || token->is_keyword(KEYWORD_STRUCT) - || token->is_op(OPERATOR_MULT) - || token->is_op(OPERATOR_LPAREN)); -} - -// TypeName = QualifiedIdent . - -// If MAY_BE_NIL is true, then an identifier with the value of the -// predefined constant nil is accepted, returning the nil type. - -Type* -Parse::type_name(bool issue_error) -{ - source_location location = this->location(); - - std::string name; - Named_object* package; - if (!this->qualified_ident(&name, &package)) - return Type::make_error_type(); - - Named_object* named_object; - if (package == NULL) - named_object = this->gogo_->lookup(name, NULL); - else - { - named_object = package->package_value()->lookup(name); - if (named_object == NULL - && issue_error - && package->name() != this->gogo_->package_name()) - { - // Check whether the name is there but hidden. - std::string s = ('.' + package->package_value()->unique_prefix() - + '.' + package->package_value()->name() - + '.' + name); - named_object = package->package_value()->lookup(s); - if (named_object != NULL) - { - const std::string& packname(package->package_value()->name()); - error_at(location, "invalid reference to hidden type %<%s.%s%>", - Gogo::message_name(packname).c_str(), - Gogo::message_name(name).c_str()); - issue_error = false; - } - } - } - - bool ok = true; - if (named_object == NULL) - { - if (package != NULL) - ok = false; - else - named_object = this->gogo_->add_unknown_name(name, location); - } - else if (named_object->is_type()) - { - if (!named_object->type_value()->is_visible()) - ok = false; - } - else if (named_object->is_unknown() || named_object->is_type_declaration()) - ; - else - ok = false; - - if (!ok) - { - if (issue_error) - error_at(location, "expected type"); - return Type::make_error_type(); - } - - if (named_object->is_type()) - return named_object->type_value(); - else if (named_object->is_unknown() || named_object->is_type_declaration()) - return Type::make_forward_declaration(named_object); - else - gcc_unreachable(); -} - -// ArrayType = "[" [ ArrayLength ] "]" ElementType . -// ArrayLength = Expression . -// ElementType = CompleteType . - -Type* -Parse::array_type(bool may_use_ellipsis) -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_LSQUARE)); - const Token* token = this->advance_token(); - - Expression* length = NULL; - if (token->is_op(OPERATOR_RSQUARE)) - this->advance_token(); - else - { - if (!token->is_op(OPERATOR_ELLIPSIS)) - length = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - else if (may_use_ellipsis) - { - // An ellipsis is used in composite literals to represent a - // fixed array of the size of the number of elements. We - // use a length of nil to represent this, and change the - // length when parsing the composite literal. - length = Expression::make_nil(this->location()); - this->advance_token(); - } - else - { - error_at(this->location(), - "use of %<[...]%> outside of array literal"); - length = Expression::make_error(this->location()); - this->advance_token(); - } - if (!this->peek_token()->is_op(OPERATOR_RSQUARE)) - { - error_at(this->location(), "expected %<]%>"); - return Type::make_error_type(); - } - this->advance_token(); - } - - Type* element_type = this->type(); - - return Type::make_array_type(element_type, length); -} - -// MapType = "map" "[" KeyType "]" ValueType . -// KeyType = CompleteType . -// ValueType = CompleteType . - -Type* -Parse::map_type() -{ - source_location location = this->location(); - gcc_assert(this->peek_token()->is_keyword(KEYWORD_MAP)); - if (!this->advance_token()->is_op(OPERATOR_LSQUARE)) - { - error_at(this->location(), "expected %<[%>"); - return Type::make_error_type(); - } - this->advance_token(); - - Type* key_type = this->type(); - - if (!this->peek_token()->is_op(OPERATOR_RSQUARE)) - { - error_at(this->location(), "expected %<]%>"); - return Type::make_error_type(); - } - this->advance_token(); - - Type* value_type = this->type(); - - if (key_type->is_error_type() || value_type->is_error_type()) - return Type::make_error_type(); - - return Type::make_map_type(key_type, value_type, location); -} - -// StructType = "struct" "{" { FieldDecl ";" } "}" . - -Type* -Parse::struct_type() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_STRUCT)); - source_location location = this->location(); - if (!this->advance_token()->is_op(OPERATOR_LCURLY)) - { - source_location token_loc = this->location(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(token_loc, "unexpected semicolon or newline before %<{%>"); - else - { - error_at(this->location(), "expected %<{%>"); - return Type::make_error_type(); - } - } - this->advance_token(); - - Struct_field_list* sfl = new Struct_field_list; - while (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - this->field_decl(sfl); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - else if (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - error_at(this->location(), "expected %<;%> or %<}%> or newline"); - if (!this->skip_past_error(OPERATOR_RCURLY)) - return Type::make_error_type(); - } - } - this->advance_token(); - - for (Struct_field_list::const_iterator pi = sfl->begin(); - pi != sfl->end(); - ++pi) - { - if (pi->type()->is_error_type()) - return pi->type(); - for (Struct_field_list::const_iterator pj = pi + 1; - pj != sfl->end(); - ++pj) - { - if (pi->field_name() == pj->field_name() - && !Gogo::is_sink_name(pi->field_name())) - error_at(pi->location(), "duplicate field name %<%s%>", - Gogo::message_name(pi->field_name()).c_str()); - } - } - - return Type::make_struct_type(sfl, location); -} - -// FieldDecl = (IdentifierList CompleteType | TypeName) [ Tag ] . -// Tag = string_lit . - -void -Parse::field_decl(Struct_field_list* sfl) -{ - const Token* token = this->peek_token(); - source_location location = token->location(); - bool is_anonymous; - bool is_anonymous_pointer; - if (token->is_op(OPERATOR_MULT)) - { - is_anonymous = true; - is_anonymous_pointer = true; - } - else if (token->is_identifier()) - { - std::string id = token->identifier(); - bool is_id_exported = token->is_identifier_exported(); - source_location id_location = token->location(); - token = this->advance_token(); - is_anonymous = (token->is_op(OPERATOR_SEMICOLON) - || token->is_op(OPERATOR_RCURLY) - || token->is_op(OPERATOR_DOT) - || token->is_string()); - is_anonymous_pointer = false; - this->unget_token(Token::make_identifier_token(id, is_id_exported, - id_location)); - } - else - { - error_at(this->location(), "expected field name"); - while (!token->is_op(OPERATOR_SEMICOLON) - && !token->is_op(OPERATOR_RCURLY) - && !token->is_eof()) - token = this->advance_token(); - return; - } - - if (is_anonymous) - { - if (is_anonymous_pointer) - { - this->advance_token(); - if (!this->peek_token()->is_identifier()) - { - error_at(this->location(), "expected field name"); - while (!token->is_op(OPERATOR_SEMICOLON) - && !token->is_op(OPERATOR_RCURLY) - && !token->is_eof()) - token = this->advance_token(); - return; - } - } - Type* type = this->type_name(true); - - std::string tag; - if (this->peek_token()->is_string()) - { - tag = this->peek_token()->string_value(); - this->advance_token(); - } - - if (!type->is_error_type()) - { - if (is_anonymous_pointer) - type = Type::make_pointer_type(type); - sfl->push_back(Struct_field(Typed_identifier("", type, location))); - if (!tag.empty()) - sfl->back().set_tag(tag); - } - } - else - { - Typed_identifier_list til; - while (true) - { - token = this->peek_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return; - } - std::string name = - this->gogo_->pack_hidden_name(token->identifier(), - token->is_identifier_exported()); - til.push_back(Typed_identifier(name, NULL, token->location())); - if (!this->advance_token()->is_op(OPERATOR_COMMA)) - break; - this->advance_token(); - } - - Type* type = this->type(); - - std::string tag; - if (this->peek_token()->is_string()) - { - tag = this->peek_token()->string_value(); - this->advance_token(); - } - - for (Typed_identifier_list::iterator p = til.begin(); - p != til.end(); - ++p) - { - p->set_type(type); - sfl->push_back(Struct_field(*p)); - if (!tag.empty()) - sfl->back().set_tag(tag); - } - } -} - -// PointerType = "*" Type . - -Type* -Parse::pointer_type() -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_MULT)); - this->advance_token(); - Type* type = this->type(); - if (type->is_error_type()) - return type; - return Type::make_pointer_type(type); -} - -// ChannelType = Channel | SendChannel | RecvChannel . -// Channel = "chan" ElementType . -// SendChannel = "chan" "<-" ElementType . -// RecvChannel = "<-" "chan" ElementType . - -Type* -Parse::channel_type() -{ - const Token* token = this->peek_token(); - bool send = true; - bool receive = true; - if (token->is_op(OPERATOR_CHANOP)) - { - if (!this->advance_token()->is_keyword(KEYWORD_CHAN)) - { - error_at(this->location(), "expected %"); - return Type::make_error_type(); - } - send = false; - this->advance_token(); - } - else - { - gcc_assert(token->is_keyword(KEYWORD_CHAN)); - if (this->advance_token()->is_op(OPERATOR_CHANOP)) - { - receive = false; - this->advance_token(); - } - } - Type* element_type = this->type(); - return Type::make_channel_type(send, receive, element_type); -} - -// Signature = Parameters [ Result ] . - -// RECEIVER is the receiver if there is one, or NULL. LOCATION is the -// location of the start of the type. - -// This returns NULL on a parse error. - -Function_type* -Parse::signature(Typed_identifier* receiver, source_location location) -{ - bool is_varargs = false; - Typed_identifier_list* params; - bool params_ok = this->parameters(¶ms, &is_varargs); - - Typed_identifier_list* result = NULL; - if (this->peek_token()->is_op(OPERATOR_LPAREN) - || this->type_may_start_here()) - { - if (!this->result(&result)) - return NULL; - } - - if (!params_ok) - return NULL; - - Function_type* ret = Type::make_function_type(receiver, params, result, - location); - if (is_varargs) - ret->set_is_varargs(); - return ret; -} - -// Parameters = "(" [ ParameterList [ "," ] ] ")" . - -// This returns false on a parse error. - -bool -Parse::parameters(Typed_identifier_list** pparams, bool* is_varargs) -{ - *pparams = NULL; - - if (!this->peek_token()->is_op(OPERATOR_LPAREN)) - { - error_at(this->location(), "expected %<(%>"); - return false; - } - - Typed_identifier_list* params = NULL; - bool saw_error = false; - - const Token* token = this->advance_token(); - if (!token->is_op(OPERATOR_RPAREN)) - { - params = this->parameter_list(is_varargs); - if (params == NULL) - saw_error = true; - token = this->peek_token(); - } - - // The optional trailing comma is picked up in parameter_list. - - if (!token->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "expected %<)%>"); - else - this->advance_token(); - - if (saw_error) - return false; - - *pparams = params; - return true; -} - -// ParameterList = ParameterDecl { "," ParameterDecl } . - -// This sets *IS_VARARGS if the list ends with an ellipsis. -// IS_VARARGS will be NULL if varargs are not permitted. - -// We pick up an optional trailing comma. - -// This returns NULL if some error is seen. - -Typed_identifier_list* -Parse::parameter_list(bool* is_varargs) -{ - source_location location = this->location(); - Typed_identifier_list* ret = new Typed_identifier_list(); - - bool saw_error = false; - - // If we see an identifier and then a comma, then we don't know - // whether we are looking at a list of identifiers followed by a - // type, or a list of types given by name. We have to do an - // arbitrary lookahead to figure it out. - - bool parameters_have_names; - const Token* token = this->peek_token(); - if (!token->is_identifier()) - { - // This must be a type which starts with something like '*'. - parameters_have_names = false; - } - else - { - std::string name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - token = this->advance_token(); - if (!token->is_op(OPERATOR_COMMA)) - { - if (token->is_op(OPERATOR_DOT)) - { - // This is a qualified identifier, which must turn out - // to be a type. - parameters_have_names = false; - } - else if (token->is_op(OPERATOR_RPAREN)) - { - // A single identifier followed by a parenthesis must be - // a type name. - parameters_have_names = false; - } - else - { - // An identifier followed by something other than a - // comma or a dot or a right parenthesis must be a - // parameter name followed by a type. - parameters_have_names = true; - } - - this->unget_token(Token::make_identifier_token(name, is_exported, - location)); - } - else - { - // An identifier followed by a comma may be the first in a - // list of parameter names followed by a type, or it may be - // the first in a list of types without parameter names. To - // find out we gather as many identifiers separated by - // commas as we can. - std::string id_name = this->gogo_->pack_hidden_name(name, - is_exported); - ret->push_back(Typed_identifier(id_name, NULL, location)); - bool just_saw_comma = true; - while (this->advance_token()->is_identifier()) - { - name = this->peek_token()->identifier(); - is_exported = this->peek_token()->is_identifier_exported(); - location = this->peek_token()->location(); - id_name = this->gogo_->pack_hidden_name(name, is_exported); - ret->push_back(Typed_identifier(id_name, NULL, location)); - if (!this->advance_token()->is_op(OPERATOR_COMMA)) - { - just_saw_comma = false; - break; - } - } - - if (just_saw_comma) - { - // We saw ID1 "," ID2 "," followed by something which - // was not an identifier. We must be seeing the start - // of a type, and ID1 and ID2 must be types, and the - // parameters don't have names. - parameters_have_names = false; - } - else if (this->peek_token()->is_op(OPERATOR_RPAREN)) - { - // We saw ID1 "," ID2 ")". ID1 and ID2 must be types, - // and the parameters don't have names. - parameters_have_names = false; - } - else if (this->peek_token()->is_op(OPERATOR_DOT)) - { - // We saw ID1 "," ID2 ".". ID2 must be a package name, - // ID1 must be a type, and the parameters don't have - // names. - parameters_have_names = false; - this->unget_token(Token::make_identifier_token(name, is_exported, - location)); - ret->pop_back(); - just_saw_comma = true; - } - else - { - // We saw ID1 "," ID2 followed by something other than - // ",", ".", or ")". We must be looking at the start of - // a type, and ID1 and ID2 must be parameter names. - parameters_have_names = true; - } - - if (parameters_have_names) - { - gcc_assert(!just_saw_comma); - // We have just seen ID1, ID2 xxx. - Type* type; - if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS)) - type = this->type(); - else - { - error_at(this->location(), "%<...%> only permits one name"); - saw_error = true; - this->advance_token(); - type = this->type(); - } - for (size_t i = 0; i < ret->size(); ++i) - ret->set_type(i, type); - if (!this->peek_token()->is_op(OPERATOR_COMMA)) - return saw_error ? NULL : ret; - if (this->advance_token()->is_op(OPERATOR_RPAREN)) - return saw_error ? NULL : ret; - } - else - { - Typed_identifier_list* tret = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator p = ret->begin(); - p != ret->end(); - ++p) - { - Named_object* no = this->gogo_->lookup(p->name(), NULL); - Type* type; - if (no == NULL) - no = this->gogo_->add_unknown_name(p->name(), - p->location()); - - if (no->is_type()) - type = no->type_value(); - else if (no->is_unknown() || no->is_type_declaration()) - type = Type::make_forward_declaration(no); - else - { - error_at(p->location(), "expected %<%s%> to be a type", - Gogo::message_name(p->name()).c_str()); - saw_error = true; - type = Type::make_error_type(); - } - tret->push_back(Typed_identifier("", type, p->location())); - } - delete ret; - ret = tret; - if (!just_saw_comma - || this->peek_token()->is_op(OPERATOR_RPAREN)) - return saw_error ? NULL : ret; - } - } - } - - bool mix_error = false; - this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error); - while (this->peek_token()->is_op(OPERATOR_COMMA)) - { - if (is_varargs != NULL && *is_varargs) - { - error_at(this->location(), "%<...%> must be last parameter"); - saw_error = true; - } - if (this->advance_token()->is_op(OPERATOR_RPAREN)) - break; - this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error); - } - if (mix_error) - { - error_at(location, "invalid named/anonymous mix"); - saw_error = true; - } - if (saw_error) - { - delete ret; - return NULL; - } - return ret; -} - -// ParameterDecl = [ IdentifierList ] [ "..." ] Type . - -void -Parse::parameter_decl(bool parameters_have_names, - Typed_identifier_list* til, - bool* is_varargs, - bool* mix_error) -{ - if (!parameters_have_names) - { - Type* type; - source_location location = this->location(); - if (!this->peek_token()->is_identifier()) - { - if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS)) - type = this->type(); - else - { - if (is_varargs == NULL) - error_at(this->location(), "invalid use of %<...%>"); - else - *is_varargs = true; - this->advance_token(); - if (is_varargs == NULL - && this->peek_token()->is_op(OPERATOR_RPAREN)) - type = Type::make_error_type(); - else - { - Type* element_type = this->type(); - type = Type::make_array_type(element_type, NULL); - } - } - } - else - { - type = this->type_name(false); - if (type->is_error_type() - || (!this->peek_token()->is_op(OPERATOR_COMMA) - && !this->peek_token()->is_op(OPERATOR_RPAREN))) - { - *mix_error = true; - while (!this->peek_token()->is_op(OPERATOR_COMMA) - && !this->peek_token()->is_op(OPERATOR_RPAREN)) - this->advance_token(); - } - } - if (!type->is_error_type()) - til->push_back(Typed_identifier("", type, location)); - } - else - { - size_t orig_count = til->size(); - if (this->peek_token()->is_identifier()) - this->identifier_list(til); - else - *mix_error = true; - size_t new_count = til->size(); - - Type* type; - if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS)) - type = this->type(); - else - { - if (is_varargs == NULL) - error_at(this->location(), "invalid use of %<...%>"); - else if (new_count > orig_count + 1) - error_at(this->location(), "%<...%> only permits one name"); - else - *is_varargs = true; - this->advance_token(); - Type* element_type = this->type(); - type = Type::make_array_type(element_type, NULL); - } - for (size_t i = orig_count; i < new_count; ++i) - til->set_type(i, type); - } -} - -// Result = Parameters | Type . - -// This returns false on a parse error. - -bool -Parse::result(Typed_identifier_list** presults) -{ - if (this->peek_token()->is_op(OPERATOR_LPAREN)) - return this->parameters(presults, NULL); - else - { - source_location location = this->location(); - Type* type = this->type(); - if (type->is_error_type()) - { - *presults = NULL; - return false; - } - Typed_identifier_list* til = new Typed_identifier_list(); - til->push_back(Typed_identifier("", type, location)); - *presults = til; - return true; - } -} - -// Block = "{" [ StatementList ] "}" . - -// Returns the location of the closing brace. - -source_location -Parse::block() -{ - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - { - source_location loc = this->location(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(loc, "unexpected semicolon or newline before %<{%>"); - else - { - error_at(this->location(), "expected %<{%>"); - return UNKNOWN_LOCATION; - } - } - - const Token* token = this->advance_token(); - - if (!token->is_op(OPERATOR_RCURLY)) - { - this->statement_list(); - token = this->peek_token(); - if (!token->is_op(OPERATOR_RCURLY)) - { - if (!token->is_eof() || !saw_errors()) - error_at(this->location(), "expected %<}%>"); - - // Skip ahead to the end of the block, in hopes of avoiding - // lots of meaningless errors. - source_location ret = token->location(); - int nest = 0; - while (!token->is_eof()) - { - if (token->is_op(OPERATOR_LCURLY)) - ++nest; - else if (token->is_op(OPERATOR_RCURLY)) - { - --nest; - if (nest < 0) - { - this->advance_token(); - break; - } - } - token = this->advance_token(); - ret = token->location(); - } - return ret; - } - } - - source_location ret = token->location(); - this->advance_token(); - return ret; -} - -// InterfaceType = "interface" "{" [ MethodSpecList ] "}" . -// MethodSpecList = MethodSpec { ";" MethodSpec } [ ";" ] . - -Type* -Parse::interface_type() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_INTERFACE)); - source_location location = this->location(); - - if (!this->advance_token()->is_op(OPERATOR_LCURLY)) - { - source_location token_loc = this->location(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(token_loc, "unexpected semicolon or newline before %<{%>"); - else - { - error_at(this->location(), "expected %<{%>"); - return Type::make_error_type(); - } - } - this->advance_token(); - - Typed_identifier_list* methods = new Typed_identifier_list(); - if (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - this->method_spec(methods); - while (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - if (this->advance_token()->is_op(OPERATOR_RCURLY)) - break; - this->method_spec(methods); - } - if (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - error_at(this->location(), "expected %<}%>"); - while (!this->advance_token()->is_op(OPERATOR_RCURLY)) - { - if (this->peek_token()->is_eof()) - return Type::make_error_type(); - } - } - } - this->advance_token(); - - if (methods->empty()) - { - delete methods; - methods = NULL; - } - - Interface_type* ret = Type::make_interface_type(methods, location); - this->gogo_->record_interface_type(ret); - return ret; -} - -// MethodSpec = MethodName Signature | InterfaceTypeName . -// MethodName = identifier . -// InterfaceTypeName = TypeName . - -void -Parse::method_spec(Typed_identifier_list* methods) -{ - const Token* token = this->peek_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return; - } - - std::string name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - - if (this->advance_token()->is_op(OPERATOR_LPAREN)) - { - // This is a MethodName. - name = this->gogo_->pack_hidden_name(name, is_exported); - Type* type = this->signature(NULL, location); - if (type == NULL) - return; - methods->push_back(Typed_identifier(name, type, location)); - } - else - { - this->unget_token(Token::make_identifier_token(name, is_exported, - location)); - Type* type = this->type_name(false); - if (type->is_error_type() - || (!this->peek_token()->is_op(OPERATOR_SEMICOLON) - && !this->peek_token()->is_op(OPERATOR_RCURLY))) - { - if (this->peek_token()->is_op(OPERATOR_COMMA)) - error_at(this->location(), - "name list not allowed in interface type"); - else - error_at(location, "expected signature or type name"); - token = this->peek_token(); - while (!token->is_eof() - && !token->is_op(OPERATOR_SEMICOLON) - && !token->is_op(OPERATOR_RCURLY)) - token = this->advance_token(); - return; - } - // This must be an interface type, but we can't check that now. - // We check it and pull out the methods in - // Interface_type::do_verify. - methods->push_back(Typed_identifier("", type, location)); - } -} - -// Declaration = ConstDecl | TypeDecl | VarDecl | FunctionDecl | MethodDecl . - -void -Parse::declaration() -{ - const Token* token = this->peek_token(); - if (token->is_keyword(KEYWORD_CONST)) - this->const_decl(); - else if (token->is_keyword(KEYWORD_TYPE)) - this->type_decl(); - else if (token->is_keyword(KEYWORD_VAR)) - this->var_decl(); - else if (token->is_keyword(KEYWORD_FUNC)) - this->function_decl(); - else - { - error_at(this->location(), "expected declaration"); - this->advance_token(); - } -} - -bool -Parse::declaration_may_start_here() -{ - const Token* token = this->peek_token(); - return (token->is_keyword(KEYWORD_CONST) - || token->is_keyword(KEYWORD_TYPE) - || token->is_keyword(KEYWORD_VAR) - || token->is_keyword(KEYWORD_FUNC)); -} - -// Decl

= P | "(" [ List

] ")" . - -void -Parse::decl(void (Parse::*pfn)(void*), void* varg) -{ - if (!this->peek_token()->is_op(OPERATOR_LPAREN)) - (this->*pfn)(varg); - else - { - if (!this->advance_token()->is_op(OPERATOR_RPAREN)) - { - this->list(pfn, varg, true); - if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - { - error_at(this->location(), "missing %<)%>"); - while (!this->advance_token()->is_op(OPERATOR_RPAREN)) - { - if (this->peek_token()->is_eof()) - return; - } - } - } - this->advance_token(); - } -} - -// List

= P { ";" P } [ ";" ] . - -// In order to pick up the trailing semicolon we need to know what -// might follow. This is either a '}' or a ')'. - -void -Parse::list(void (Parse::*pfn)(void*), void* varg, bool follow_is_paren) -{ - (this->*pfn)(varg); - Operator follow = follow_is_paren ? OPERATOR_RPAREN : OPERATOR_RCURLY; - while (this->peek_token()->is_op(OPERATOR_SEMICOLON) - || this->peek_token()->is_op(OPERATOR_COMMA)) - { - if (this->peek_token()->is_op(OPERATOR_COMMA)) - error_at(this->location(), "unexpected comma"); - if (this->advance_token()->is_op(follow)) - break; - (this->*pfn)(varg); - } -} - -// ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) . - -void -Parse::const_decl() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_CONST)); - this->advance_token(); - this->reset_iota(); - - Type* last_type = NULL; - Expression_list* last_expr_list = NULL; - - if (!this->peek_token()->is_op(OPERATOR_LPAREN)) - this->const_spec(&last_type, &last_expr_list); - else - { - this->advance_token(); - while (!this->peek_token()->is_op(OPERATOR_RPAREN)) - { - this->const_spec(&last_type, &last_expr_list); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - else if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - { - error_at(this->location(), "expected %<;%> or %<)%> or newline"); - if (!this->skip_past_error(OPERATOR_RPAREN)) - return; - } - } - this->advance_token(); - } - - if (last_expr_list != NULL) - delete last_expr_list; -} - -// ConstSpec = IdentifierList [ [ CompleteType ] "=" ExpressionList ] . - -void -Parse::const_spec(Type** last_type, Expression_list** last_expr_list) -{ - Typed_identifier_list til; - this->identifier_list(&til); - - Type* type = NULL; - if (this->type_may_start_here()) - { - type = this->type(); - *last_type = NULL; - *last_expr_list = NULL; - } - - Expression_list *expr_list; - if (!this->peek_token()->is_op(OPERATOR_EQ)) - { - if (*last_expr_list == NULL) - { - error_at(this->location(), "expected %<=%>"); - return; - } - type = *last_type; - expr_list = new Expression_list; - for (Expression_list::const_iterator p = (*last_expr_list)->begin(); - p != (*last_expr_list)->end(); - ++p) - expr_list->push_back((*p)->copy()); - } - else - { - this->advance_token(); - expr_list = this->expression_list(NULL, false); - *last_type = type; - if (*last_expr_list != NULL) - delete *last_expr_list; - *last_expr_list = expr_list; - } - - Expression_list::const_iterator pe = expr_list->begin(); - for (Typed_identifier_list::iterator pi = til.begin(); - pi != til.end(); - ++pi, ++pe) - { - if (pe == expr_list->end()) - { - error_at(this->location(), "not enough initializers"); - return; - } - if (type != NULL) - pi->set_type(type); - - if (!Gogo::is_sink_name(pi->name())) - this->gogo_->add_constant(*pi, *pe, this->iota_value()); - } - if (pe != expr_list->end()) - error_at(this->location(), "too many initializers"); - - this->increment_iota(); - - return; -} - -// TypeDecl = "type" Decl . - -void -Parse::type_decl() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_TYPE)); - this->advance_token(); - this->decl(&Parse::type_spec, NULL); -} - -// TypeSpec = identifier Type . - -void -Parse::type_spec(void*) -{ - const Token* token = this->peek_token(); - if (!token->is_identifier()) - { - error_at(this->location(), "expected identifier"); - return; - } - std::string name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - token = this->advance_token(); - - // The scope of the type name starts at the point where the - // identifier appears in the source code. We implement this by - // declaring the type before we read the type definition. - Named_object* named_type = NULL; - if (name != "_") - { - name = this->gogo_->pack_hidden_name(name, is_exported); - named_type = this->gogo_->declare_type(name, location); - } - - Type* type; - if (!this->peek_token()->is_op(OPERATOR_SEMICOLON)) - type = this->type(); - else - { - error_at(this->location(), - "unexpected semicolon or newline in type declaration"); - type = Type::make_error_type(); - this->advance_token(); - } - - if (type->is_error_type()) - { - while (!this->peek_token()->is_op(OPERATOR_SEMICOLON) - && !this->peek_token()->is_eof()) - this->advance_token(); - } - - if (name != "_") - { - if (named_type->is_type_declaration()) - { - Type* ftype = type->forwarded(); - if (ftype->forward_declaration_type() != NULL - && (ftype->forward_declaration_type()->named_object() - == named_type)) - { - error_at(location, "invalid recursive type"); - type = Type::make_error_type(); - } - - this->gogo_->define_type(named_type, - Type::make_named_type(named_type, type, - location)); - gcc_assert(named_type->package() == NULL); - } - else - { - // This will probably give a redefinition error. - this->gogo_->add_type(name, type, location); - } - } -} - -// VarDecl = "var" Decl . - -void -Parse::var_decl() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_VAR)); - this->advance_token(); - this->decl(&Parse::var_spec, NULL); -} - -// VarSpec = IdentifierList -// ( CompleteType [ "=" ExpressionList ] | "=" ExpressionList ) . - -void -Parse::var_spec(void*) -{ - // Get the variable names. - Typed_identifier_list til; - this->identifier_list(&til); - - source_location location = this->location(); - - Type* type = NULL; - Expression_list* init = NULL; - if (!this->peek_token()->is_op(OPERATOR_EQ)) - { - type = this->type(); - if (type->is_error_type()) - { - while (!this->peek_token()->is_op(OPERATOR_EQ) - && !this->peek_token()->is_op(OPERATOR_SEMICOLON) - && !this->peek_token()->is_eof()) - this->advance_token(); - } - if (this->peek_token()->is_op(OPERATOR_EQ)) - { - this->advance_token(); - init = this->expression_list(NULL, false); - } - } - else - { - this->advance_token(); - init = this->expression_list(NULL, false); - } - - this->init_vars(&til, type, init, false, location); - - if (init != NULL) - delete init; -} - -// Create variables. TIL is a list of variable names. If TYPE is not -// NULL, it is the type of all the variables. If INIT is not NULL, it -// is an initializer list for the variables. - -void -Parse::init_vars(const Typed_identifier_list* til, Type* type, - Expression_list* init, bool is_coloneq, - source_location location) -{ - // Check for an initialization which can yield multiple values. - if (init != NULL && init->size() == 1 && til->size() > 1) - { - if (this->init_vars_from_call(til, type, *init->begin(), is_coloneq, - location)) - return; - if (this->init_vars_from_map(til, type, *init->begin(), is_coloneq, - location)) - return; - if (this->init_vars_from_receive(til, type, *init->begin(), is_coloneq, - location)) - return; - if (this->init_vars_from_type_guard(til, type, *init->begin(), - is_coloneq, location)) - return; - } - - if (init != NULL && init->size() != til->size()) - { - if (init->empty() || !init->front()->is_error_expression()) - error_at(location, "wrong number of initializations"); - init = NULL; - if (type == NULL) - type = Type::make_error_type(); - } - - // Note that INIT was already parsed with the old name bindings, so - // we don't have to worry that it will accidentally refer to the - // newly declared variables. - - Expression_list::const_iterator pexpr; - if (init != NULL) - pexpr = init->begin(); - bool any_new = false; - for (Typed_identifier_list::const_iterator p = til->begin(); - p != til->end(); - ++p) - { - if (init != NULL) - gcc_assert(pexpr != init->end()); - this->init_var(*p, type, init == NULL ? NULL : *pexpr, is_coloneq, - false, &any_new); - if (init != NULL) - ++pexpr; - } - if (init != NULL) - gcc_assert(pexpr == init->end()); - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); -} - -// See if we need to initialize a list of variables from a function -// call. This returns true if we have set up the variables and the -// initialization. - -bool -Parse::init_vars_from_call(const Typed_identifier_list* vars, Type* type, - Expression* expr, bool is_coloneq, - source_location location) -{ - Call_expression* call = expr->call_expression(); - if (call == NULL) - return false; - - // This is a function call. We can't check here whether it returns - // the right number of values, but it might. Declare the variables, - // and then assign the results of the call to them. - - unsigned int index = 0; - bool any_new = false; - for (Typed_identifier_list::const_iterator pv = vars->begin(); - pv != vars->end(); - ++pv, ++index) - { - Expression* init = Expression::make_call_result(call, index); - this->init_var(*pv, type, init, is_coloneq, false, &any_new); - } - - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); - - return true; -} - -// See if we need to initialize a pair of values from a map index -// expression. This returns true if we have set up the variables and -// the initialization. - -bool -Parse::init_vars_from_map(const Typed_identifier_list* vars, Type* type, - Expression* expr, bool is_coloneq, - source_location location) -{ - Index_expression* index = expr->index_expression(); - if (index == NULL) - return false; - if (vars->size() != 2) - return false; - - // This is an index which is being assigned to two variables. It - // must be a map index. Declare the variables, and then assign the - // results of the map index. - bool any_new = false; - Typed_identifier_list::const_iterator p = vars->begin(); - Expression* init = type == NULL ? index : NULL; - Named_object* val_no = this->init_var(*p, type, init, is_coloneq, - type == NULL, &any_new); - if (type == NULL && any_new && val_no->is_variable()) - val_no->var_value()->set_type_from_init_tuple(); - Expression* val_var = Expression::make_var_reference(val_no, location); - - ++p; - Type* var_type = type; - if (var_type == NULL) - var_type = Type::lookup_bool_type(); - Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false, - &any_new); - Expression* present_var = Expression::make_var_reference(no, location); - - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); - - Statement* s = Statement::make_tuple_map_assignment(val_var, present_var, - index, location); - - if (!this->gogo_->in_global_scope()) - this->gogo_->add_statement(s); - else if (!val_no->is_sink()) - { - if (val_no->is_variable()) - val_no->var_value()->add_preinit_statement(this->gogo_, s); - } - else if (!no->is_sink()) - { - if (no->is_variable()) - no->var_value()->add_preinit_statement(this->gogo_, s); - } - else - { - // Execute the map index expression just so that we can fail if - // the map is nil. - Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(), - NULL, location); - dummy->var_value()->add_preinit_statement(this->gogo_, s); - } - - return true; -} - -// See if we need to initialize a pair of values from a receive -// expression. This returns true if we have set up the variables and -// the initialization. - -bool -Parse::init_vars_from_receive(const Typed_identifier_list* vars, Type* type, - Expression* expr, bool is_coloneq, - source_location location) -{ - Receive_expression* receive = expr->receive_expression(); - if (receive == NULL) - return false; - if (vars->size() != 2) - return false; - - // This is a receive expression which is being assigned to two - // variables. Declare the variables, and then assign the results of - // the receive. - bool any_new = false; - Typed_identifier_list::const_iterator p = vars->begin(); - Expression* init = type == NULL ? receive : NULL; - Named_object* val_no = this->init_var(*p, type, init, is_coloneq, - type == NULL, &any_new); - if (type == NULL && any_new && val_no->is_variable()) - val_no->var_value()->set_type_from_init_tuple(); - Expression* val_var = Expression::make_var_reference(val_no, location); - - ++p; - Type* var_type = type; - if (var_type == NULL) - var_type = Type::lookup_bool_type(); - Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false, - &any_new); - Expression* received_var = Expression::make_var_reference(no, location); - - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); - - Statement* s = Statement::make_tuple_receive_assignment(val_var, - received_var, - receive->channel(), - false, - location); - - if (!this->gogo_->in_global_scope()) - this->gogo_->add_statement(s); - else if (!val_no->is_sink()) - { - if (val_no->is_variable()) - val_no->var_value()->add_preinit_statement(this->gogo_, s); - } - else if (!no->is_sink()) - { - if (no->is_variable()) - no->var_value()->add_preinit_statement(this->gogo_, s); - } - else - { - Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(), - NULL, location); - dummy->var_value()->add_preinit_statement(this->gogo_, s); - } - - return true; -} - -// See if we need to initialize a pair of values from a type guard -// expression. This returns true if we have set up the variables and -// the initialization. - -bool -Parse::init_vars_from_type_guard(const Typed_identifier_list* vars, - Type* type, Expression* expr, - bool is_coloneq, source_location location) -{ - Type_guard_expression* type_guard = expr->type_guard_expression(); - if (type_guard == NULL) - return false; - if (vars->size() != 2) - return false; - - // This is a type guard expression which is being assigned to two - // variables. Declare the variables, and then assign the results of - // the type guard. - bool any_new = false; - Typed_identifier_list::const_iterator p = vars->begin(); - Type* var_type = type; - if (var_type == NULL) - var_type = type_guard->type(); - Named_object* val_no = this->init_var(*p, var_type, NULL, is_coloneq, false, - &any_new); - Expression* val_var = Expression::make_var_reference(val_no, location); - - ++p; - var_type = type; - if (var_type == NULL) - var_type = Type::lookup_bool_type(); - Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false, - &any_new); - Expression* ok_var = Expression::make_var_reference(no, location); - - Expression* texpr = type_guard->expr(); - Type* t = type_guard->type(); - Statement* s = Statement::make_tuple_type_guard_assignment(val_var, ok_var, - texpr, t, - location); - - if (is_coloneq && !any_new) - error_at(location, "variables redeclared but no variable is new"); - - if (!this->gogo_->in_global_scope()) - this->gogo_->add_statement(s); - else if (!val_no->is_sink()) - { - if (val_no->is_variable()) - val_no->var_value()->add_preinit_statement(this->gogo_, s); - } - else if (!no->is_sink()) - { - if (no->is_variable()) - no->var_value()->add_preinit_statement(this->gogo_, s); - } - else - { - Named_object* dummy = this->create_dummy_global(type, NULL, location); - dummy->var_value()->add_preinit_statement(this->gogo_, s); - } - - return true; -} - -// Create a single variable. If IS_COLONEQ is true, we permit -// redeclarations in the same block, and we set *IS_NEW when we find a -// new variable which is not a redeclaration. - -Named_object* -Parse::init_var(const Typed_identifier& tid, Type* type, Expression* init, - bool is_coloneq, bool type_from_init, bool* is_new) -{ - source_location location = tid.location(); - - if (Gogo::is_sink_name(tid.name())) - { - if (!type_from_init && init != NULL) - { - if (!this->gogo_->in_global_scope()) - this->gogo_->add_statement(Statement::make_statement(init)); - else - return this->create_dummy_global(type, init, location); - } - return this->gogo_->add_sink(); - } - - if (is_coloneq) - { - Named_object* no = this->gogo_->lookup_in_block(tid.name()); - if (no != NULL - && (no->is_variable() || no->is_result_variable())) - { - // INIT may be NULL even when IS_COLONEQ is true for cases - // like v, ok := x.(int). - if (!type_from_init && init != NULL) - { - Expression *v = Expression::make_var_reference(no, location); - Statement *s = Statement::make_assignment(v, init, location); - this->gogo_->add_statement(s); - } - return no; - } - } - *is_new = true; - Variable* var = new Variable(type, init, this->gogo_->in_global_scope(), - false, false, location); - Named_object* no = this->gogo_->add_variable(tid.name(), var); - if (!no->is_variable()) - { - // The name is already defined, so we just gave an error. - return this->gogo_->add_sink(); - } - return no; -} - -// Create a dummy global variable to force an initializer to be run in -// the right place. This is used when a sink variable is initialized -// at global scope. - -Named_object* -Parse::create_dummy_global(Type* type, Expression* init, - source_location location) -{ - if (type == NULL && init == NULL) - type = Type::lookup_bool_type(); - Variable* var = new Variable(type, init, true, false, false, location); - static int count; - char buf[30]; - snprintf(buf, sizeof buf, "_.%d", count); - ++count; - return this->gogo_->add_variable(buf, var); -} - -// SimpleVarDecl = identifier ":=" Expression . - -// We've already seen the identifier. - -// FIXME: We also have to implement -// IdentifierList ":=" ExpressionList -// In order to support both "a, b := 1, 0" and "a, b = 1, 0" we accept -// tuple assignments here as well. - -// If P_RANGE_CLAUSE is not NULL, then this will recognize a -// RangeClause. - -// If P_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -void -Parse::simple_var_decl_or_assignment(const std::string& name, - source_location location, - Range_clause* p_range_clause, - Type_switch* p_type_switch) -{ - Typed_identifier_list til; - til.push_back(Typed_identifier(name, NULL, location)); - - // We've seen one identifier. If we see a comma now, this could be - // "a, *p = 1, 2". - if (this->peek_token()->is_op(OPERATOR_COMMA)) - { - gcc_assert(p_type_switch == NULL); - while (true) - { - const Token* token = this->advance_token(); - if (!token->is_identifier()) - break; - - std::string id = token->identifier(); - bool is_id_exported = token->is_identifier_exported(); - source_location id_location = token->location(); - - token = this->advance_token(); - if (!token->is_op(OPERATOR_COMMA)) - { - if (token->is_op(OPERATOR_COLONEQ)) - { - id = this->gogo_->pack_hidden_name(id, is_id_exported); - til.push_back(Typed_identifier(id, NULL, location)); - } - else - this->unget_token(Token::make_identifier_token(id, - is_id_exported, - id_location)); - break; - } - - id = this->gogo_->pack_hidden_name(id, is_id_exported); - til.push_back(Typed_identifier(id, NULL, location)); - } - - // We have a comma separated list of identifiers in TIL. If the - // next token is COLONEQ, then this is a simple var decl, and we - // have the complete list of identifiers. If the next token is - // not COLONEQ, then the only valid parse is a tuple assignment. - // The list of identifiers we have so far is really a list of - // expressions. There are more expressions following. - - if (!this->peek_token()->is_op(OPERATOR_COLONEQ)) - { - Expression_list* exprs = new Expression_list; - for (Typed_identifier_list::const_iterator p = til.begin(); - p != til.end(); - ++p) - exprs->push_back(this->id_to_expression(p->name(), - p->location())); - - Expression_list* more_exprs = this->expression_list(NULL, true); - for (Expression_list::const_iterator p = more_exprs->begin(); - p != more_exprs->end(); - ++p) - exprs->push_back(*p); - delete more_exprs; - - this->tuple_assignment(exprs, p_range_clause); - return; - } - } - - gcc_assert(this->peek_token()->is_op(OPERATOR_COLONEQ)); - const Token* token = this->advance_token(); - - if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE)) - { - this->range_clause_decl(&til, p_range_clause); - return; - } - - Expression_list* init; - if (p_type_switch == NULL) - init = this->expression_list(NULL, false); - else - { - bool is_type_switch = false; - Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, - &is_type_switch); - if (is_type_switch) - { - p_type_switch->found = true; - p_type_switch->name = name; - p_type_switch->location = location; - p_type_switch->expr = expr; - return; - } - - if (!this->peek_token()->is_op(OPERATOR_COMMA)) - { - init = new Expression_list(); - init->push_back(expr); - } - else - { - this->advance_token(); - init = this->expression_list(expr, false); - } - } - - this->init_vars(&til, NULL, init, true, location); -} - -// FunctionDecl = "func" identifier Signature [ Block ] . -// MethodDecl = "func" Receiver identifier Signature [ Block ] . - -// gcc extension: -// FunctionDecl = "func" identifier Signature -// __asm__ "(" string_lit ")" . -// This extension means a function whose real name is the identifier -// inside the asm. - -void -Parse::function_decl() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_FUNC)); - source_location location = this->location(); - const Token* token = this->advance_token(); - - Typed_identifier* rec = NULL; - if (token->is_op(OPERATOR_LPAREN)) - { - rec = this->receiver(); - token = this->peek_token(); - } - - if (!token->is_identifier()) - { - error_at(this->location(), "expected function name"); - return; - } - - std::string name = - this->gogo_->pack_hidden_name(token->identifier(), - token->is_identifier_exported()); - - this->advance_token(); - - Function_type* fntype = this->signature(rec, this->location()); - if (fntype == NULL) - return; - - Named_object* named_object = NULL; - - if (this->peek_token()->is_keyword(KEYWORD_ASM)) - { - if (!this->advance_token()->is_op(OPERATOR_LPAREN)) - { - error_at(this->location(), "expected %<(%>"); - return; - } - token = this->advance_token(); - if (!token->is_string()) - { - error_at(this->location(), "expected string"); - return; - } - std::string asm_name = token->string_value(); - if (!this->advance_token()->is_op(OPERATOR_RPAREN)) - { - error_at(this->location(), "expected %<)%>"); - return; - } - this->advance_token(); - if (!Gogo::is_sink_name(name)) - { - named_object = this->gogo_->declare_function(name, fntype, location); - if (named_object->is_function_declaration()) - named_object->func_declaration_value()->set_asm_name(asm_name); - } - } - - // Check for the easy error of a newline before the opening brace. - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - source_location semi_loc = this->location(); - if (this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(this->location(), - "unexpected semicolon or newline before %<{%>"); - else - this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON, - semi_loc)); - } - - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - { - if (named_object == NULL && !Gogo::is_sink_name(name)) - this->gogo_->declare_function(name, fntype, location); - } - else - { - this->gogo_->start_function(name, fntype, true, location); - source_location end_loc = this->block(); - this->gogo_->finish_function(end_loc); - } -} - -// Receiver = "(" [ identifier ] [ "*" ] BaseTypeName ")" . -// BaseTypeName = identifier . - -Typed_identifier* -Parse::receiver() -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_LPAREN)); - - std::string name; - const Token* token = this->advance_token(); - source_location location = token->location(); - if (!token->is_op(OPERATOR_MULT)) - { - if (!token->is_identifier()) - { - error_at(this->location(), "method has no receiver"); - while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN)) - token = this->advance_token(); - if (!token->is_eof()) - this->advance_token(); - return NULL; - } - name = token->identifier(); - bool is_exported = token->is_identifier_exported(); - token = this->advance_token(); - if (!token->is_op(OPERATOR_DOT) && !token->is_op(OPERATOR_RPAREN)) - { - // An identifier followed by something other than a dot or a - // right parenthesis must be a receiver name followed by a - // type. - name = this->gogo_->pack_hidden_name(name, is_exported); - } - else - { - // This must be a type name. - this->unget_token(Token::make_identifier_token(name, is_exported, - location)); - token = this->peek_token(); - name.clear(); - } - } - - // Here the receiver name is in NAME (it is empty if the receiver is - // unnamed) and TOKEN is the first token in the type. - - bool is_pointer = false; - if (token->is_op(OPERATOR_MULT)) - { - is_pointer = true; - token = this->advance_token(); - } - - if (!token->is_identifier()) - { - error_at(this->location(), "expected receiver name or type"); - int c = token->is_op(OPERATOR_LPAREN) ? 1 : 0; - while (!token->is_eof()) - { - token = this->advance_token(); - if (token->is_op(OPERATOR_LPAREN)) - ++c; - else if (token->is_op(OPERATOR_RPAREN)) - { - if (c == 0) - break; - --c; - } - } - if (!token->is_eof()) - this->advance_token(); - return NULL; - } - - Type* type = this->type_name(true); - - if (is_pointer && !type->is_error_type()) - type = Type::make_pointer_type(type); - - if (this->peek_token()->is_op(OPERATOR_RPAREN)) - this->advance_token(); - else - { - if (this->peek_token()->is_op(OPERATOR_COMMA)) - error_at(this->location(), "method has multiple receivers"); - else - error_at(this->location(), "expected %<)%>"); - while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN)) - token = this->advance_token(); - if (!token->is_eof()) - this->advance_token(); - return NULL; - } - - return new Typed_identifier(name, type, location); -} - -// Operand = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" . -// Literal = BasicLit | CompositeLit | FunctionLit . -// BasicLit = int_lit | float_lit | imaginary_lit | char_lit | string_lit . - -// If MAY_BE_SINK is true, this operand may be "_". - -Expression* -Parse::operand(bool may_be_sink) -{ - const Token* token = this->peek_token(); - Expression* ret; - switch (token->classification()) - { - case Token::TOKEN_IDENTIFIER: - { - source_location location = token->location(); - std::string id = token->identifier(); - bool is_exported = token->is_identifier_exported(); - std::string packed = this->gogo_->pack_hidden_name(id, is_exported); - - Named_object* in_function; - Named_object* named_object = this->gogo_->lookup(packed, &in_function); - - Package* package = NULL; - if (named_object != NULL && named_object->is_package()) - { - if (!this->advance_token()->is_op(OPERATOR_DOT) - || !this->advance_token()->is_identifier()) - { - error_at(location, "unexpected reference to package"); - return Expression::make_error(location); - } - package = named_object->package_value(); - package->set_used(); - id = this->peek_token()->identifier(); - is_exported = this->peek_token()->is_identifier_exported(); - packed = this->gogo_->pack_hidden_name(id, is_exported); - named_object = package->lookup(packed); - location = this->location(); - gcc_assert(in_function == NULL); - } - - this->advance_token(); - - if (named_object != NULL - && named_object->is_type() - && !named_object->type_value()->is_visible()) - { - gcc_assert(package != NULL); - error_at(location, "invalid reference to hidden type %<%s.%s%>", - Gogo::message_name(package->name()).c_str(), - Gogo::message_name(id).c_str()); - return Expression::make_error(location); - } - - - if (named_object == NULL) - { - if (package != NULL) - { - std::string n1 = Gogo::message_name(package->name()); - std::string n2 = Gogo::message_name(id); - if (!is_exported) - error_at(location, - ("invalid reference to unexported identifier " - "%<%s.%s%>"), - n1.c_str(), n2.c_str()); - else - error_at(location, - "reference to undefined identifier %<%s.%s%>", - n1.c_str(), n2.c_str()); - return Expression::make_error(location); - } - - named_object = this->gogo_->add_unknown_name(packed, location); - } - - if (in_function != NULL - && in_function != this->gogo_->current_function() - && (named_object->is_variable() - || named_object->is_result_variable())) - return this->enclosing_var_reference(in_function, named_object, - location); - - switch (named_object->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - return Expression::make_const_reference(named_object, location); - case Named_object::NAMED_OBJECT_TYPE: - return Expression::make_type(named_object->type_value(), location); - case Named_object::NAMED_OBJECT_TYPE_DECLARATION: - { - Type* t = Type::make_forward_declaration(named_object); - return Expression::make_type(t, location); - } - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - return Expression::make_var_reference(named_object, location); - case Named_object::NAMED_OBJECT_SINK: - if (may_be_sink) - return Expression::make_sink(location); - else - { - error_at(location, "cannot use _ as value"); - return Expression::make_error(location); - } - case Named_object::NAMED_OBJECT_FUNC: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - return Expression::make_func_reference(named_object, NULL, - location); - case Named_object::NAMED_OBJECT_UNKNOWN: - return Expression::make_unknown_reference(named_object, location); - default: - gcc_unreachable(); - } - } - gcc_unreachable(); - - case Token::TOKEN_STRING: - ret = Expression::make_string(token->string_value(), token->location()); - this->advance_token(); - return ret; - - case Token::TOKEN_INTEGER: - ret = Expression::make_integer(token->integer_value(), NULL, - token->location()); - this->advance_token(); - return ret; - - case Token::TOKEN_FLOAT: - ret = Expression::make_float(token->float_value(), NULL, - token->location()); - this->advance_token(); - return ret; - - case Token::TOKEN_IMAGINARY: - { - mpfr_t zero; - mpfr_init_set_ui(zero, 0, GMP_RNDN); - ret = Expression::make_complex(&zero, token->imaginary_value(), - NULL, token->location()); - mpfr_clear(zero); - this->advance_token(); - return ret; - } - - case Token::TOKEN_KEYWORD: - switch (token->keyword()) - { - case KEYWORD_FUNC: - return this->function_lit(); - case KEYWORD_CHAN: - case KEYWORD_INTERFACE: - case KEYWORD_MAP: - case KEYWORD_STRUCT: - { - source_location location = token->location(); - return Expression::make_type(this->type(), location); - } - default: - break; - } - break; - - case Token::TOKEN_OPERATOR: - if (token->is_op(OPERATOR_LPAREN)) - { - this->advance_token(); - ret = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "missing %<)%>"); - else - this->advance_token(); - return ret; - } - else if (token->is_op(OPERATOR_LSQUARE)) - { - // Here we call array_type directly, as this is the only - // case where an ellipsis is permitted for an array type. - source_location location = token->location(); - return Expression::make_type(this->array_type(true), location); - } - break; - - default: - break; - } - - error_at(this->location(), "expected operand"); - return Expression::make_error(this->location()); -} - -// Handle a reference to a variable in an enclosing function. We add -// it to a list of such variables. We return a reference to a field -// in a struct which will be passed on the static chain when calling -// the current function. - -Expression* -Parse::enclosing_var_reference(Named_object* in_function, Named_object* var, - source_location location) -{ - gcc_assert(var->is_variable() || var->is_result_variable()); - - Named_object* this_function = this->gogo_->current_function(); - Named_object* closure = this_function->func_value()->closure_var(); - - Enclosing_var ev(var, in_function, this->enclosing_vars_.size()); - std::pair ins = - this->enclosing_vars_.insert(ev); - if (ins.second) - { - // This is a variable we have not seen before. Add a new field - // to the closure type. - this_function->func_value()->add_closure_field(var, location); - } - - Expression* closure_ref = Expression::make_var_reference(closure, - location); - closure_ref = Expression::make_unary(OPERATOR_MULT, closure_ref, location); - - // The closure structure holds pointers to the variables, so we need - // to introduce an indirection. - Expression* e = Expression::make_field_reference(closure_ref, - ins.first->index(), - location); - e = Expression::make_unary(OPERATOR_MULT, e, location); - return e; -} - -// CompositeLit = LiteralType LiteralValue . -// LiteralType = StructType | ArrayType | "[" "..." "]" ElementType | -// SliceType | MapType | TypeName . -// LiteralValue = "{" [ ElementList [ "," ] ] "}" . -// ElementList = Element { "," Element } . -// Element = [ Key ":" ] Value . -// Key = Expression . -// Value = Expression | LiteralValue . - -// We have already seen the type if there is one, and we are now -// looking at the LiteralValue. The case "[" "..." "]" ElementType -// will be seen here as an array type whose length is "nil". The -// DEPTH parameter is non-zero if this is an embedded composite -// literal and the type was omitted. It gives the number of steps up -// to the type which was provided. E.g., in [][]int{{1}} it will be -// 1. In [][][]int{{{1}}} it will be 2. - -Expression* -Parse::composite_lit(Type* type, int depth, source_location location) -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_LCURLY)); - this->advance_token(); - - if (this->peek_token()->is_op(OPERATOR_RCURLY)) - { - this->advance_token(); - return Expression::make_composite_literal(type, depth, false, NULL, - location); - } - - bool has_keys = false; - Expression_list* vals = new Expression_list; - while (true) - { - Expression* val; - bool is_type_omitted = false; - - const Token* token = this->peek_token(); - - if (!token->is_op(OPERATOR_LCURLY)) - val = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - else - { - // This must be a composite literal inside another composite - // literal, with the type omitted for the inner one. - val = this->composite_lit(type, depth + 1, token->location()); - is_type_omitted = true; - } - - token = this->peek_token(); - if (!token->is_op(OPERATOR_COLON)) - { - if (has_keys) - vals->push_back(NULL); - } - else - { - if (is_type_omitted && !val->is_error_expression()) - { - error_at(this->location(), "unexpected %<:%>"); - val = Expression::make_error(this->location()); - } - - this->advance_token(); - - if (!has_keys && !vals->empty()) - { - Expression_list* newvals = new Expression_list; - for (Expression_list::const_iterator p = vals->begin(); - p != vals->end(); - ++p) - { - newvals->push_back(NULL); - newvals->push_back(*p); - } - delete vals; - vals = newvals; - } - has_keys = true; - - if (val->unknown_expression() != NULL) - val->unknown_expression()->set_is_composite_literal_key(); - - vals->push_back(val); - - if (!token->is_op(OPERATOR_LCURLY)) - val = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - else - { - // This must be a composite literal inside another - // composite literal, with the type omitted for the - // inner one. - val = this->composite_lit(type, depth + 1, token->location()); - } - - token = this->peek_token(); - } - - vals->push_back(val); - - if (token->is_op(OPERATOR_COMMA)) - { - if (this->advance_token()->is_op(OPERATOR_RCURLY)) - { - this->advance_token(); - break; - } - } - else if (token->is_op(OPERATOR_RCURLY)) - { - this->advance_token(); - break; - } - else - { - error_at(this->location(), "expected %<,%> or %<}%>"); - - int depth = 0; - while (!token->is_eof() - && (depth > 0 || !token->is_op(OPERATOR_RCURLY))) - { - if (token->is_op(OPERATOR_LCURLY)) - ++depth; - else if (token->is_op(OPERATOR_RCURLY)) - --depth; - token = this->advance_token(); - } - if (token->is_op(OPERATOR_RCURLY)) - this->advance_token(); - - return Expression::make_error(location); - } - } - - return Expression::make_composite_literal(type, depth, has_keys, vals, - location); -} - -// FunctionLit = "func" Signature Block . - -Expression* -Parse::function_lit() -{ - source_location location = this->location(); - gcc_assert(this->peek_token()->is_keyword(KEYWORD_FUNC)); - this->advance_token(); - - Enclosing_vars hold_enclosing_vars; - hold_enclosing_vars.swap(this->enclosing_vars_); - - Function_type* type = this->signature(NULL, location); - if (type == NULL) - type = Type::make_function_type(NULL, NULL, NULL, location); - - // For a function literal, the next token must be a '{'. If we - // don't see that, then we may have a type expression. - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - return Expression::make_type(type, location); - - Bc_stack* hold_break_stack = this->break_stack_; - Bc_stack* hold_continue_stack = this->continue_stack_; - this->break_stack_ = NULL; - this->continue_stack_ = NULL; - - Named_object* no = this->gogo_->start_function("", type, true, location); - - source_location end_loc = this->block(); - - this->gogo_->finish_function(end_loc); - - if (this->break_stack_ != NULL) - delete this->break_stack_; - if (this->continue_stack_ != NULL) - delete this->continue_stack_; - this->break_stack_ = hold_break_stack; - this->continue_stack_ = hold_continue_stack; - - hold_enclosing_vars.swap(this->enclosing_vars_); - - Expression* closure = this->create_closure(no, &hold_enclosing_vars, - location); - - return Expression::make_func_reference(no, closure, location); -} - -// Create a closure for the nested function FUNCTION. This is based -// on ENCLOSING_VARS, which is a list of all variables defined in -// enclosing functions and referenced from FUNCTION. A closure is the -// address of a struct which contains the addresses of all the -// referenced variables. This returns NULL if no closure is required. - -Expression* -Parse::create_closure(Named_object* function, Enclosing_vars* enclosing_vars, - source_location location) -{ - if (enclosing_vars->empty()) - return NULL; - - // Get the variables in order by their field index. - - size_t enclosing_var_count = enclosing_vars->size(); - std::vector ev(enclosing_var_count); - for (Enclosing_vars::const_iterator p = enclosing_vars->begin(); - p != enclosing_vars->end(); - ++p) - ev[p->index()] = *p; - - // Build an initializer for a composite literal of the closure's - // type. - - Named_object* enclosing_function = this->gogo_->current_function(); - Expression_list* initializer = new Expression_list; - for (size_t i = 0; i < enclosing_var_count; ++i) - { - gcc_assert(ev[i].index() == i); - Named_object* var = ev[i].var(); - Expression* ref; - if (ev[i].in_function() == enclosing_function) - ref = Expression::make_var_reference(var, location); - else - ref = this->enclosing_var_reference(ev[i].in_function(), var, - location); - Expression* refaddr = Expression::make_unary(OPERATOR_AND, ref, - location); - initializer->push_back(refaddr); - } - - Named_object* closure_var = function->func_value()->closure_var(); - Struct_type* st = closure_var->var_value()->type()->deref()->struct_type(); - Expression* cv = Expression::make_struct_composite_literal(st, initializer, - location); - return Expression::make_heap_composite(cv, location); -} - -// PrimaryExpr = Operand { Selector | Index | Slice | TypeGuard | Call } . - -// If MAY_BE_SINK is true, this expression may be "_". - -// If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite -// literal. - -// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::primary_expr(bool may_be_sink, bool may_be_composite_lit, - bool* is_type_switch) -{ - source_location start_loc = this->location(); - bool is_parenthesized = this->peek_token()->is_op(OPERATOR_LPAREN); - - Expression* ret = this->operand(may_be_sink); - - // An unknown name followed by a curly brace must be a composite - // literal, and the unknown name must be a type. - if (may_be_composite_lit - && !is_parenthesized - && ret->unknown_expression() != NULL - && this->peek_token()->is_op(OPERATOR_LCURLY)) - { - Named_object* no = ret->unknown_expression()->named_object(); - Type* type = Type::make_forward_declaration(no); - ret = Expression::make_type(type, ret->location()); - } - - // We handle composite literals and type casts here, as it is the - // easiest way to handle types which are in parentheses, as in - // "((uint))(1)". - if (ret->is_type_expression()) - { - if (this->peek_token()->is_op(OPERATOR_LCURLY)) - { - if (is_parenthesized) - error_at(start_loc, - "cannot parenthesize type in composite literal"); - ret = this->composite_lit(ret->type(), 0, ret->location()); - } - else if (this->peek_token()->is_op(OPERATOR_LPAREN)) - { - source_location loc = this->location(); - this->advance_token(); - Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, - NULL); - if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "expected %<)%>"); - else - this->advance_token(); - if (expr->is_error_expression()) - return expr; - ret = Expression::make_cast(ret->type(), expr, loc); - } - } - - while (true) - { - const Token* token = this->peek_token(); - if (token->is_op(OPERATOR_LPAREN)) - ret = this->call(this->verify_not_sink(ret)); - else if (token->is_op(OPERATOR_DOT)) - { - ret = this->selector(this->verify_not_sink(ret), is_type_switch); - if (is_type_switch != NULL && *is_type_switch) - break; - } - else if (token->is_op(OPERATOR_LSQUARE)) - ret = this->index(this->verify_not_sink(ret)); - else - break; - } - - return ret; -} - -// Selector = "." identifier . -// TypeGuard = "." "(" QualifiedIdent ")" . - -// Note that Operand can expand to QualifiedIdent, which contains a -// ".". That is handled directly in operand when it sees a package -// name. - -// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::selector(Expression* left, bool* is_type_switch) -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_DOT)); - source_location location = this->location(); - - const Token* token = this->advance_token(); - if (token->is_identifier()) - { - // This could be a field in a struct, or a method in an - // interface, or a method associated with a type. We can't know - // which until we have seen all the types. - std::string name = - this->gogo_->pack_hidden_name(token->identifier(), - token->is_identifier_exported()); - if (token->identifier() == "_") - { - error_at(this->location(), "invalid use of %<_%>"); - name = this->gogo_->pack_hidden_name("blank", false); - } - this->advance_token(); - return Expression::make_selector(left, name, location); - } - else if (token->is_op(OPERATOR_LPAREN)) - { - this->advance_token(); - Type* type = NULL; - if (!this->peek_token()->is_keyword(KEYWORD_TYPE)) - type = this->type(); - else - { - if (is_type_switch != NULL) - *is_type_switch = true; - else - { - error_at(this->location(), - "use of %<.(type)%> outside type switch"); - type = Type::make_error_type(); - } - this->advance_token(); - } - if (!this->peek_token()->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "missing %<)%>"); - else - this->advance_token(); - if (is_type_switch != NULL && *is_type_switch) - return left; - return Expression::make_type_guard(left, type, location); - } - else - { - error_at(this->location(), "expected identifier or %<(%>"); - return left; - } -} - -// Index = "[" Expression "]" . -// Slice = "[" Expression ":" [ Expression ] "]" . - -Expression* -Parse::index(Expression* expr) -{ - source_location location = this->location(); - gcc_assert(this->peek_token()->is_op(OPERATOR_LSQUARE)); - this->advance_token(); - - Expression* start; - if (!this->peek_token()->is_op(OPERATOR_COLON)) - start = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - else - { - mpz_t zero; - mpz_init_set_ui(zero, 0); - start = Expression::make_integer(&zero, NULL, location); - mpz_clear(zero); - } - - Expression* end = NULL; - if (this->peek_token()->is_op(OPERATOR_COLON)) - { - // We use nil to indicate a missing high expression. - if (this->advance_token()->is_op(OPERATOR_RSQUARE)) - end = Expression::make_nil(this->location()); - else - end = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - } - if (!this->peek_token()->is_op(OPERATOR_RSQUARE)) - error_at(this->location(), "missing %<]%>"); - else - this->advance_token(); - return Expression::make_index(expr, start, end, location); -} - -// Call = "(" [ ArgumentList [ "," ] ] ")" . -// ArgumentList = ExpressionList [ "..." ] . - -Expression* -Parse::call(Expression* func) -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_LPAREN)); - Expression_list* args = NULL; - bool is_varargs = false; - const Token* token = this->advance_token(); - if (!token->is_op(OPERATOR_RPAREN)) - { - args = this->expression_list(NULL, false); - token = this->peek_token(); - if (token->is_op(OPERATOR_ELLIPSIS)) - { - is_varargs = true; - token = this->advance_token(); - } - } - if (token->is_op(OPERATOR_COMMA)) - token = this->advance_token(); - if (!token->is_op(OPERATOR_RPAREN)) - error_at(this->location(), "missing %<)%>"); - else - this->advance_token(); - if (func->is_error_expression()) - return func; - return Expression::make_call(func, args, is_varargs, func->location()); -} - -// Return an expression for a single unqualified identifier. - -Expression* -Parse::id_to_expression(const std::string& name, source_location location) -{ - Named_object* in_function; - Named_object* named_object = this->gogo_->lookup(name, &in_function); - if (named_object == NULL) - named_object = this->gogo_->add_unknown_name(name, location); - - if (in_function != NULL - && in_function != this->gogo_->current_function() - && (named_object->is_variable() || named_object->is_result_variable())) - return this->enclosing_var_reference(in_function, named_object, - location); - - switch (named_object->classification()) - { - case Named_object::NAMED_OBJECT_CONST: - return Expression::make_const_reference(named_object, location); - case Named_object::NAMED_OBJECT_VAR: - case Named_object::NAMED_OBJECT_RESULT_VAR: - return Expression::make_var_reference(named_object, location); - case Named_object::NAMED_OBJECT_SINK: - return Expression::make_sink(location); - case Named_object::NAMED_OBJECT_FUNC: - case Named_object::NAMED_OBJECT_FUNC_DECLARATION: - return Expression::make_func_reference(named_object, NULL, location); - case Named_object::NAMED_OBJECT_UNKNOWN: - return Expression::make_unknown_reference(named_object, location); - default: - error_at(this->location(), "unexpected type of identifier"); - return Expression::make_error(location); - } -} - -// Expression = UnaryExpr { binary_op Expression } . - -// PRECEDENCE is the precedence of the current operator. - -// If MAY_BE_SINK is true, this expression may be "_". - -// If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite -// literal. - -// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::expression(Precedence precedence, bool may_be_sink, - bool may_be_composite_lit, bool* is_type_switch) -{ - Expression* left = this->unary_expr(may_be_sink, may_be_composite_lit, - is_type_switch); - - while (true) - { - if (is_type_switch != NULL && *is_type_switch) - return left; - - const Token* token = this->peek_token(); - if (token->classification() != Token::TOKEN_OPERATOR) - { - // Not a binary_op. - return left; - } - - Precedence right_precedence; - switch (token->op()) - { - case OPERATOR_OROR: - right_precedence = PRECEDENCE_OROR; - break; - case OPERATOR_ANDAND: - right_precedence = PRECEDENCE_ANDAND; - break; - case OPERATOR_EQEQ: - case OPERATOR_NOTEQ: - case OPERATOR_LT: - case OPERATOR_LE: - case OPERATOR_GT: - case OPERATOR_GE: - right_precedence = PRECEDENCE_RELOP; - break; - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_OR: - case OPERATOR_XOR: - right_precedence = PRECEDENCE_ADDOP; - break; - case OPERATOR_MULT: - case OPERATOR_DIV: - case OPERATOR_MOD: - case OPERATOR_LSHIFT: - case OPERATOR_RSHIFT: - case OPERATOR_AND: - case OPERATOR_BITCLEAR: - right_precedence = PRECEDENCE_MULOP; - break; - default: - right_precedence = PRECEDENCE_INVALID; - break; - } - - if (right_precedence == PRECEDENCE_INVALID) - { - // Not a binary_op. - return left; - } - - Operator op = token->op(); - source_location binop_location = token->location(); - - if (precedence >= right_precedence) - { - // We've already seen A * B, and we see + C. We want to - // return so that A * B becomes a group. - return left; - } - - this->advance_token(); - - left = this->verify_not_sink(left); - Expression* right = this->expression(right_precedence, false, - may_be_composite_lit, - NULL); - left = Expression::make_binary(op, left, right, binop_location); - } -} - -bool -Parse::expression_may_start_here() -{ - const Token* token = this->peek_token(); - switch (token->classification()) - { - case Token::TOKEN_INVALID: - case Token::TOKEN_EOF: - return false; - case Token::TOKEN_KEYWORD: - switch (token->keyword()) - { - case KEYWORD_CHAN: - case KEYWORD_FUNC: - case KEYWORD_MAP: - case KEYWORD_STRUCT: - case KEYWORD_INTERFACE: - return true; - default: - return false; - } - case Token::TOKEN_IDENTIFIER: - return true; - case Token::TOKEN_STRING: - return true; - case Token::TOKEN_OPERATOR: - switch (token->op()) - { - case OPERATOR_PLUS: - case OPERATOR_MINUS: - case OPERATOR_NOT: - case OPERATOR_XOR: - case OPERATOR_MULT: - case OPERATOR_CHANOP: - case OPERATOR_AND: - case OPERATOR_LPAREN: - case OPERATOR_LSQUARE: - return true; - default: - return false; - } - case Token::TOKEN_INTEGER: - case Token::TOKEN_FLOAT: - case Token::TOKEN_IMAGINARY: - return true; - default: - gcc_unreachable(); - } -} - -// UnaryExpr = unary_op UnaryExpr | PrimaryExpr . - -// If MAY_BE_SINK is true, this expression may be "_". - -// If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite -// literal. - -// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::unary_expr(bool may_be_sink, bool may_be_composite_lit, - bool* is_type_switch) -{ - const Token* token = this->peek_token(); - if (token->is_op(OPERATOR_PLUS) - || token->is_op(OPERATOR_MINUS) - || token->is_op(OPERATOR_NOT) - || token->is_op(OPERATOR_XOR) - || token->is_op(OPERATOR_CHANOP) - || token->is_op(OPERATOR_MULT) - || token->is_op(OPERATOR_AND)) - { - source_location location = token->location(); - Operator op = token->op(); - this->advance_token(); - - if (op == OPERATOR_CHANOP - && this->peek_token()->is_keyword(KEYWORD_CHAN)) - { - // This is "<- chan" which must be the start of a type. - this->unget_token(Token::make_operator_token(op, location)); - return Expression::make_type(this->type(), location); - } - - Expression* expr = this->unary_expr(false, may_be_composite_lit, NULL); - if (expr->is_error_expression()) - ; - else if (op == OPERATOR_MULT && expr->is_type_expression()) - expr = Expression::make_type(Type::make_pointer_type(expr->type()), - location); - else if (op == OPERATOR_AND && expr->is_composite_literal()) - expr = Expression::make_heap_composite(expr, location); - else if (op != OPERATOR_CHANOP) - expr = Expression::make_unary(op, expr, location); - else - expr = Expression::make_receive(expr, location); - return expr; - } - else - return this->primary_expr(may_be_sink, may_be_composite_lit, - is_type_switch); -} - -// Statement = -// Declaration | LabeledStmt | SimpleStmt | -// GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt | -// FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt | -// DeferStmt . - -// LABEL is the label of this statement if it has one. - -void -Parse::statement(const Label* label) -{ - const Token* token = this->peek_token(); - switch (token->classification()) - { - case Token::TOKEN_KEYWORD: - { - switch (token->keyword()) - { - case KEYWORD_CONST: - case KEYWORD_TYPE: - case KEYWORD_VAR: - this->declaration(); - break; - case KEYWORD_FUNC: - case KEYWORD_MAP: - case KEYWORD_STRUCT: - case KEYWORD_INTERFACE: - this->simple_stat(true, false, NULL, NULL); - break; - case KEYWORD_GO: - case KEYWORD_DEFER: - this->go_or_defer_stat(); - break; - case KEYWORD_RETURN: - this->return_stat(); - break; - case KEYWORD_BREAK: - this->break_stat(); - break; - case KEYWORD_CONTINUE: - this->continue_stat(); - break; - case KEYWORD_GOTO: - this->goto_stat(); - break; - case KEYWORD_IF: - this->if_stat(); - break; - case KEYWORD_SWITCH: - this->switch_stat(label); - break; - case KEYWORD_SELECT: - this->select_stat(label); - break; - case KEYWORD_FOR: - this->for_stat(label); - break; - default: - error_at(this->location(), "expected statement"); - this->advance_token(); - break; - } - } - break; - - case Token::TOKEN_IDENTIFIER: - { - std::string identifier = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - if (this->advance_token()->is_op(OPERATOR_COLON)) - { - this->advance_token(); - this->labeled_stmt(identifier, location); - } - else - { - this->unget_token(Token::make_identifier_token(identifier, - is_exported, - location)); - this->simple_stat(true, false, NULL, NULL); - } - } - break; - - case Token::TOKEN_OPERATOR: - if (token->is_op(OPERATOR_LCURLY)) - { - source_location location = token->location(); - this->gogo_->start_block(location); - source_location end_loc = this->block(); - this->gogo_->add_block(this->gogo_->finish_block(end_loc), - location); - } - else if (!token->is_op(OPERATOR_SEMICOLON)) - this->simple_stat(true, false, NULL, NULL); - break; - - case Token::TOKEN_STRING: - case Token::TOKEN_INTEGER: - case Token::TOKEN_FLOAT: - case Token::TOKEN_IMAGINARY: - this->simple_stat(true, false, NULL, NULL); - break; - - default: - error_at(this->location(), "expected statement"); - this->advance_token(); - break; - } -} - -bool -Parse::statement_may_start_here() -{ - const Token* token = this->peek_token(); - switch (token->classification()) - { - case Token::TOKEN_KEYWORD: - { - switch (token->keyword()) - { - case KEYWORD_CONST: - case KEYWORD_TYPE: - case KEYWORD_VAR: - case KEYWORD_FUNC: - case KEYWORD_MAP: - case KEYWORD_STRUCT: - case KEYWORD_INTERFACE: - case KEYWORD_GO: - case KEYWORD_DEFER: - case KEYWORD_RETURN: - case KEYWORD_BREAK: - case KEYWORD_CONTINUE: - case KEYWORD_GOTO: - case KEYWORD_IF: - case KEYWORD_SWITCH: - case KEYWORD_SELECT: - case KEYWORD_FOR: - return true; - - default: - return false; - } - } - break; - - case Token::TOKEN_IDENTIFIER: - return true; - - case Token::TOKEN_OPERATOR: - if (token->is_op(OPERATOR_LCURLY) - || token->is_op(OPERATOR_SEMICOLON)) - return true; - else - return this->expression_may_start_here(); - - case Token::TOKEN_STRING: - case Token::TOKEN_INTEGER: - case Token::TOKEN_FLOAT: - case Token::TOKEN_IMAGINARY: - return true; - - default: - return false; - } -} - -// LabeledStmt = Label ":" Statement . -// Label = identifier . - -void -Parse::labeled_stmt(const std::string& label_name, source_location location) -{ - Label* label = this->gogo_->add_label_definition(label_name, location); - - if (this->peek_token()->is_op(OPERATOR_RCURLY)) - { - // This is a label at the end of a block. A program is - // permitted to omit a semicolon here. - return; - } - - if (!this->statement_may_start_here()) - { - error_at(location, "missing statement after label"); - this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON, - location)); - return; - } - - this->statement(label); -} - -// SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | -// Assignment | ShortVarDecl . - -// EmptyStmt was handled in Parse::statement. - -// In order to make this work for if and switch statements, if -// RETURN_EXP is true, and we see an ExpressionStat, we return the -// expression rather than adding an expression statement to the -// current block. If we see something other than an ExpressionStat, -// we add the statement and return NULL. - -// If P_RANGE_CLAUSE is not NULL, then this will recognize a -// RangeClause. - -// If P_TYPE_SWITCH is not NULL, this will recognize a type switch -// guard (var := expr.("type") using the literal keyword "type"). - -Expression* -Parse::simple_stat(bool may_be_composite_lit, bool return_exp, - Range_clause* p_range_clause, Type_switch* p_type_switch) -{ - const Token* token = this->peek_token(); - - // An identifier follow by := is a SimpleVarDecl. - if (token->is_identifier()) - { - std::string identifier = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location location = token->location(); - - token = this->advance_token(); - if (token->is_op(OPERATOR_COLONEQ) - || token->is_op(OPERATOR_COMMA)) - { - identifier = this->gogo_->pack_hidden_name(identifier, is_exported); - this->simple_var_decl_or_assignment(identifier, location, - p_range_clause, - (token->is_op(OPERATOR_COLONEQ) - ? p_type_switch - : NULL)); - return NULL; - } - - this->unget_token(Token::make_identifier_token(identifier, is_exported, - location)); - } - - Expression* exp = this->expression(PRECEDENCE_NORMAL, true, - may_be_composite_lit, - (p_type_switch == NULL - ? NULL - : &p_type_switch->found)); - if (p_type_switch != NULL && p_type_switch->found) - { - p_type_switch->name.clear(); - p_type_switch->location = exp->location(); - p_type_switch->expr = this->verify_not_sink(exp); - return NULL; - } - token = this->peek_token(); - if (token->is_op(OPERATOR_CHANOP)) - this->send_stmt(this->verify_not_sink(exp)); - else if (token->is_op(OPERATOR_PLUSPLUS) - || token->is_op(OPERATOR_MINUSMINUS)) - this->inc_dec_stat(this->verify_not_sink(exp)); - else if (token->is_op(OPERATOR_COMMA) - || token->is_op(OPERATOR_EQ)) - this->assignment(exp, p_range_clause); - else if (token->is_op(OPERATOR_PLUSEQ) - || token->is_op(OPERATOR_MINUSEQ) - || token->is_op(OPERATOR_OREQ) - || token->is_op(OPERATOR_XOREQ) - || token->is_op(OPERATOR_MULTEQ) - || token->is_op(OPERATOR_DIVEQ) - || token->is_op(OPERATOR_MODEQ) - || token->is_op(OPERATOR_LSHIFTEQ) - || token->is_op(OPERATOR_RSHIFTEQ) - || token->is_op(OPERATOR_ANDEQ) - || token->is_op(OPERATOR_BITCLEAREQ)) - this->assignment(this->verify_not_sink(exp), p_range_clause); - else if (return_exp) - return this->verify_not_sink(exp); - else - this->expression_stat(this->verify_not_sink(exp)); - - return NULL; -} - -bool -Parse::simple_stat_may_start_here() -{ - return this->expression_may_start_here(); -} - -// Parse { Statement ";" } which is used in a few places. The list of -// statements may end with a right curly brace, in which case the -// semicolon may be omitted. - -void -Parse::statement_list() -{ - while (this->statement_may_start_here()) - { - this->statement(NULL); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - else if (this->peek_token()->is_op(OPERATOR_RCURLY)) - break; - else - { - if (!this->peek_token()->is_eof() || !saw_errors()) - error_at(this->location(), "expected %<;%> or %<}%> or newline"); - if (!this->skip_past_error(OPERATOR_RCURLY)) - return; - } - } -} - -bool -Parse::statement_list_may_start_here() -{ - return this->statement_may_start_here(); -} - -// ExpressionStat = Expression . - -void -Parse::expression_stat(Expression* exp) -{ - exp->discarding_value(); - this->gogo_->add_statement(Statement::make_statement(exp)); -} - -// SendStmt = Channel "<-" Expression . -// Channel = Expression . - -void -Parse::send_stmt(Expression* channel) -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_CHANOP)); - source_location loc = this->location(); - this->advance_token(); - Expression* val = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - Statement* s = Statement::make_send_statement(channel, val, loc); - this->gogo_->add_statement(s); -} - -// IncDecStat = Expression ( "++" | "--" ) . - -void -Parse::inc_dec_stat(Expression* exp) -{ - const Token* token = this->peek_token(); - - // Lvalue maps require special handling. - if (exp->index_expression() != NULL) - exp->index_expression()->set_is_lvalue(); - - if (token->is_op(OPERATOR_PLUSPLUS)) - this->gogo_->add_statement(Statement::make_inc_statement(exp)); - else if (token->is_op(OPERATOR_MINUSMINUS)) - this->gogo_->add_statement(Statement::make_dec_statement(exp)); - else - gcc_unreachable(); - this->advance_token(); -} - -// Assignment = ExpressionList assign_op ExpressionList . - -// EXP is an expression that we have already parsed. - -// If RANGE_CLAUSE is not NULL, then this will recognize a -// RangeClause. - -void -Parse::assignment(Expression* expr, Range_clause* p_range_clause) -{ - Expression_list* vars; - if (!this->peek_token()->is_op(OPERATOR_COMMA)) - { - vars = new Expression_list(); - vars->push_back(expr); - } - else - { - this->advance_token(); - vars = this->expression_list(expr, true); - } - - this->tuple_assignment(vars, p_range_clause); -} - -// An assignment statement. LHS is the list of expressions which -// appear on the left hand side. - -// If RANGE_CLAUSE is not NULL, then this will recognize a -// RangeClause. - -void -Parse::tuple_assignment(Expression_list* lhs, Range_clause* p_range_clause) -{ - const Token* token = this->peek_token(); - if (!token->is_op(OPERATOR_EQ) - && !token->is_op(OPERATOR_PLUSEQ) - && !token->is_op(OPERATOR_MINUSEQ) - && !token->is_op(OPERATOR_OREQ) - && !token->is_op(OPERATOR_XOREQ) - && !token->is_op(OPERATOR_MULTEQ) - && !token->is_op(OPERATOR_DIVEQ) - && !token->is_op(OPERATOR_MODEQ) - && !token->is_op(OPERATOR_LSHIFTEQ) - && !token->is_op(OPERATOR_RSHIFTEQ) - && !token->is_op(OPERATOR_ANDEQ) - && !token->is_op(OPERATOR_BITCLEAREQ)) - { - error_at(this->location(), "expected assignment operator"); - return; - } - Operator op = token->op(); - source_location location = token->location(); - - token = this->advance_token(); - - if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE)) - { - if (op != OPERATOR_EQ) - error_at(this->location(), "range clause requires %<=%>"); - this->range_clause_expr(lhs, p_range_clause); - return; - } - - Expression_list* vals = this->expression_list(NULL, false); - - // We've parsed everything; check for errors. - if (lhs == NULL || vals == NULL) - return; - for (Expression_list::const_iterator pe = lhs->begin(); - pe != lhs->end(); - ++pe) - { - if ((*pe)->is_error_expression()) - return; - if (op != OPERATOR_EQ && (*pe)->is_sink_expression()) - error_at((*pe)->location(), "cannot use _ as value"); - } - for (Expression_list::const_iterator pe = vals->begin(); - pe != vals->end(); - ++pe) - { - if ((*pe)->is_error_expression()) - return; - } - - // Map expressions act differently when they are lvalues. - for (Expression_list::iterator plv = lhs->begin(); - plv != lhs->end(); - ++plv) - if ((*plv)->index_expression() != NULL) - (*plv)->index_expression()->set_is_lvalue(); - - Call_expression* call; - Index_expression* map_index; - Receive_expression* receive; - Type_guard_expression* type_guard; - if (lhs->size() == vals->size()) - { - Statement* s; - if (lhs->size() > 1) - { - if (op != OPERATOR_EQ) - error_at(location, "multiple values only permitted with %<=%>"); - s = Statement::make_tuple_assignment(lhs, vals, location); - } - else - { - if (op == OPERATOR_EQ) - s = Statement::make_assignment(lhs->front(), vals->front(), - location); - else - s = Statement::make_assignment_operation(op, lhs->front(), - vals->front(), location); - delete lhs; - delete vals; - } - this->gogo_->add_statement(s); - } - else if (vals->size() == 1 - && (call = (*vals->begin())->call_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "multiple results only permitted with %<=%>"); - delete vals; - vals = new Expression_list; - for (unsigned int i = 0; i < lhs->size(); ++i) - vals->push_back(Expression::make_call_result(call, i)); - Statement* s = Statement::make_tuple_assignment(lhs, vals, location); - this->gogo_->add_statement(s); - } - else if (lhs->size() == 2 - && vals->size() == 1 - && (map_index = (*vals->begin())->index_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "two values from map requires %<=%>"); - Expression* val = lhs->front(); - Expression* present = lhs->back(); - Statement* s = Statement::make_tuple_map_assignment(val, present, - map_index, location); - this->gogo_->add_statement(s); - } - else if (lhs->size() == 1 - && vals->size() == 2 - && (map_index = lhs->front()->index_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "assigning tuple to map index requires %<=%>"); - Expression* val = vals->front(); - Expression* should_set = vals->back(); - Statement* s = Statement::make_map_assignment(map_index, val, should_set, - location); - this->gogo_->add_statement(s); - } - else if (lhs->size() == 2 - && vals->size() == 1 - && (receive = (*vals->begin())->receive_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "two values from receive requires %<=%>"); - Expression* val = lhs->front(); - Expression* success = lhs->back(); - Expression* channel = receive->channel(); - Statement* s = Statement::make_tuple_receive_assignment(val, success, - channel, - false, - location); - this->gogo_->add_statement(s); - } - else if (lhs->size() == 2 - && vals->size() == 1 - && (type_guard = (*vals->begin())->type_guard_expression()) != NULL) - { - if (op != OPERATOR_EQ) - error_at(location, "two values from type guard requires %<=%>"); - Expression* val = lhs->front(); - Expression* ok = lhs->back(); - Expression* expr = type_guard->expr(); - Type* type = type_guard->type(); - Statement* s = Statement::make_tuple_type_guard_assignment(val, ok, - expr, type, - location); - this->gogo_->add_statement(s); - } - else - { - error_at(location, "number of variables does not match number of values"); - } -} - -// GoStat = "go" Expression . -// DeferStat = "defer" Expression . - -void -Parse::go_or_defer_stat() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_GO) - || this->peek_token()->is_keyword(KEYWORD_DEFER)); - bool is_go = this->peek_token()->is_keyword(KEYWORD_GO); - source_location stat_location = this->location(); - this->advance_token(); - source_location expr_location = this->location(); - Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - Call_expression* call_expr = expr->call_expression(); - if (call_expr == NULL) - { - error_at(expr_location, "expected call expression"); - return; - } - - // Make it easier to simplify go/defer statements by putting every - // statement in its own block. - this->gogo_->start_block(stat_location); - Statement* stat; - if (is_go) - stat = Statement::make_go_statement(call_expr, stat_location); - else - stat = Statement::make_defer_statement(call_expr, stat_location); - this->gogo_->add_statement(stat); - this->gogo_->add_block(this->gogo_->finish_block(stat_location), - stat_location); -} - -// ReturnStat = "return" [ ExpressionList ] . - -void -Parse::return_stat() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_RETURN)); - source_location location = this->location(); - this->advance_token(); - Expression_list* vals = NULL; - if (this->expression_may_start_here()) - vals = this->expression_list(NULL, false); - const Function* function = this->gogo_->current_function()->func_value(); - const Typed_identifier_list* results = function->type()->results(); - this->gogo_->add_statement(Statement::make_return_statement(results, vals, - location)); -} - -// IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" Statement ] . - -void -Parse::if_stat() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_IF)); - source_location location = this->location(); - this->advance_token(); - - this->gogo_->start_block(location); - - Expression* cond = NULL; - if (this->simple_stat_may_start_here()) - cond = this->simple_stat(false, true, NULL, NULL); - if (cond != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - // The SimpleStat is an expression statement. - this->expression_stat(cond); - cond = NULL; - } - if (cond == NULL) - { - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - cond = this->expression(PRECEDENCE_NORMAL, false, false, NULL); - } - - this->gogo_->start_block(this->location()); - source_location end_loc = this->block(); - Block* then_block = this->gogo_->finish_block(end_loc); - - // Check for the easy error of a newline before "else". - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - source_location semi_loc = this->location(); - if (this->advance_token()->is_keyword(KEYWORD_ELSE)) - error_at(this->location(), - "unexpected semicolon or newline before %"); - else - this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON, - semi_loc)); - } - - Block* else_block = NULL; - if (this->peek_token()->is_keyword(KEYWORD_ELSE)) - { - this->advance_token(); - // We create a block to gather the statement. - this->gogo_->start_block(this->location()); - this->statement(NULL); - else_block = this->gogo_->finish_block(this->location()); - } - - this->gogo_->add_statement(Statement::make_if_statement(cond, then_block, - else_block, - location)); - - this->gogo_->add_block(this->gogo_->finish_block(this->location()), - location); -} - -// SwitchStmt = ExprSwitchStmt | TypeSwitchStmt . -// ExprSwitchStmt = "switch" [ [ SimpleStat ] ";" ] [ Expression ] -// "{" { ExprCaseClause } "}" . -// TypeSwitchStmt = "switch" [ [ SimpleStat ] ";" ] TypeSwitchGuard -// "{" { TypeCaseClause } "}" . -// TypeSwitchGuard = [ identifier ":=" ] Expression "." "(" "type" ")" . - -void -Parse::switch_stat(const Label* label) -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_SWITCH)); - source_location location = this->location(); - this->advance_token(); - - this->gogo_->start_block(location); - - Expression* switch_val = NULL; - Type_switch type_switch; - if (this->simple_stat_may_start_here()) - switch_val = this->simple_stat(false, true, NULL, &type_switch); - if (switch_val != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - // The SimpleStat is an expression statement. - this->expression_stat(switch_val); - switch_val = NULL; - } - if (switch_val == NULL && !type_switch.found) - { - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - { - if (this->peek_token()->is_identifier()) - { - const Token* token = this->peek_token(); - std::string identifier = token->identifier(); - bool is_exported = token->is_identifier_exported(); - source_location id_loc = token->location(); - - token = this->advance_token(); - bool is_coloneq = token->is_op(OPERATOR_COLONEQ); - this->unget_token(Token::make_identifier_token(identifier, - is_exported, - id_loc)); - if (is_coloneq) - { - // This must be a TypeSwitchGuard. - switch_val = this->simple_stat(false, true, NULL, - &type_switch); - if (!type_switch.found) - { - if (switch_val == NULL - || !switch_val->is_error_expression()) - { - error_at(id_loc, "expected type switch assignment"); - switch_val = Expression::make_error(id_loc); - } - } - } - } - if (switch_val == NULL && !type_switch.found) - { - switch_val = this->expression(PRECEDENCE_NORMAL, false, false, - &type_switch.found); - if (type_switch.found) - { - type_switch.name.clear(); - type_switch.expr = switch_val; - type_switch.location = switch_val->location(); - } - } - } - } - - if (!this->peek_token()->is_op(OPERATOR_LCURLY)) - { - source_location token_loc = this->location(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(token_loc, "unexpected semicolon or newline before %<{%>"); - else - { - error_at(this->location(), "expected %<{%>"); - this->gogo_->add_block(this->gogo_->finish_block(this->location()), - location); - return; - } - } - this->advance_token(); - - Statement* statement; - if (type_switch.found) - statement = this->type_switch_body(label, type_switch, location); - else - statement = this->expr_switch_body(label, switch_val, location); - - if (statement != NULL) - this->gogo_->add_statement(statement); - - this->gogo_->add_block(this->gogo_->finish_block(this->location()), - location); -} - -// The body of an expression switch. -// "{" { ExprCaseClause } "}" - -Statement* -Parse::expr_switch_body(const Label* label, Expression* switch_val, - source_location location) -{ - Switch_statement* statement = Statement::make_switch_statement(switch_val, - location); - - this->push_break_statement(statement, label); - - Case_clauses* case_clauses = new Case_clauses(); - bool saw_default = false; - while (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - if (this->peek_token()->is_eof()) - { - if (!saw_errors()) - error_at(this->location(), "missing %<}%>"); - return NULL; - } - this->expr_case_clause(case_clauses, &saw_default); - } - this->advance_token(); - - statement->add_clauses(case_clauses); - - this->pop_break_statement(); - - return statement; -} - -// ExprCaseClause = ExprSwitchCase ":" [ StatementList ] . -// FallthroughStat = "fallthrough" . - -void -Parse::expr_case_clause(Case_clauses* clauses, bool* saw_default) -{ - source_location location = this->location(); - - bool is_default = false; - Expression_list* vals = this->expr_switch_case(&is_default); - - if (!this->peek_token()->is_op(OPERATOR_COLON)) - { - if (!saw_errors()) - error_at(this->location(), "expected %<:%>"); - return; - } - else - this->advance_token(); - - Block* statements = NULL; - if (this->statement_list_may_start_here()) - { - this->gogo_->start_block(this->location()); - this->statement_list(); - statements = this->gogo_->finish_block(this->location()); - } - - bool is_fallthrough = false; - if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH)) - { - is_fallthrough = true; - if (this->advance_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - } - - if (is_default) - { - if (*saw_default) - { - error_at(location, "multiple defaults in switch"); - return; - } - *saw_default = true; - } - - if (is_default || vals != NULL) - clauses->add(vals, is_default, statements, is_fallthrough, location); -} - -// ExprSwitchCase = "case" ExpressionList | "default" . - -Expression_list* -Parse::expr_switch_case(bool* is_default) -{ - const Token* token = this->peek_token(); - if (token->is_keyword(KEYWORD_CASE)) - { - this->advance_token(); - return this->expression_list(NULL, false); - } - else if (token->is_keyword(KEYWORD_DEFAULT)) - { - this->advance_token(); - *is_default = true; - return NULL; - } - else - { - if (!saw_errors()) - error_at(this->location(), "expected % or %"); - if (!token->is_op(OPERATOR_RCURLY)) - this->advance_token(); - return NULL; - } -} - -// The body of a type switch. -// "{" { TypeCaseClause } "}" . - -Statement* -Parse::type_switch_body(const Label* label, const Type_switch& type_switch, - source_location location) -{ - Named_object* switch_no = NULL; - if (!type_switch.name.empty()) - { - Variable* switch_var = new Variable(NULL, type_switch.expr, false, false, - false, type_switch.location); - switch_no = this->gogo_->add_variable(type_switch.name, switch_var); - } - - Type_switch_statement* statement = - Statement::make_type_switch_statement(switch_no, - (switch_no == NULL - ? type_switch.expr - : NULL), - location); - - this->push_break_statement(statement, label); - - Type_case_clauses* case_clauses = new Type_case_clauses(); - bool saw_default = false; - while (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - if (this->peek_token()->is_eof()) - { - error_at(this->location(), "missing %<}%>"); - return NULL; - } - this->type_case_clause(switch_no, case_clauses, &saw_default); - } - this->advance_token(); - - statement->add_clauses(case_clauses); - - this->pop_break_statement(); - - return statement; -} - -// TypeCaseClause = TypeSwitchCase ":" [ StatementList ] . - -void -Parse::type_case_clause(Named_object* switch_no, Type_case_clauses* clauses, - bool* saw_default) -{ - source_location location = this->location(); - - std::vector types; - bool is_default = false; - this->type_switch_case(&types, &is_default); - - if (!this->peek_token()->is_op(OPERATOR_COLON)) - error_at(this->location(), "expected %<:%>"); - else - this->advance_token(); - - Block* statements = NULL; - if (this->statement_list_may_start_here()) - { - this->gogo_->start_block(this->location()); - if (switch_no != NULL && types.size() == 1) - { - Type* type = types.front(); - Expression* init = Expression::make_var_reference(switch_no, - location); - init = Expression::make_type_guard(init, type, location); - Variable* v = new Variable(type, init, false, false, false, - location); - v->set_is_type_switch_var(); - this->gogo_->add_variable(switch_no->name(), v); - } - this->statement_list(); - statements = this->gogo_->finish_block(this->location()); - } - - if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH)) - { - error_at(this->location(), - "fallthrough is not permitted in a type switch"); - if (this->advance_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - } - - if (is_default) - { - gcc_assert(types.empty()); - if (*saw_default) - { - error_at(location, "multiple defaults in type switch"); - return; - } - *saw_default = true; - clauses->add(NULL, false, true, statements, location); - } - else if (!types.empty()) - { - for (std::vector::const_iterator p = types.begin(); - p + 1 != types.end(); - ++p) - clauses->add(*p, true, false, NULL, location); - clauses->add(types.back(), false, false, statements, location); - } - else - clauses->add(Type::make_error_type(), false, false, statements, location); -} - -// TypeSwitchCase = "case" type | "default" - -// We accept a comma separated list of types. - -void -Parse::type_switch_case(std::vector* types, bool* is_default) -{ - const Token* token = this->peek_token(); - if (token->is_keyword(KEYWORD_CASE)) - { - this->advance_token(); - while (true) - { - Type* t = this->type(); - if (!t->is_error_type()) - types->push_back(t); - if (!this->peek_token()->is_op(OPERATOR_COMMA)) - break; - this->advance_token(); - } - } - else if (token->is_keyword(KEYWORD_DEFAULT)) - { - this->advance_token(); - *is_default = true; - } - else - { - error_at(this->location(), "expected % or %"); - if (!token->is_op(OPERATOR_RCURLY)) - this->advance_token(); - } -} - -// SelectStat = "select" "{" { CommClause } "}" . - -void -Parse::select_stat(const Label* label) -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_SELECT)); - source_location location = this->location(); - const Token* token = this->advance_token(); - - if (!token->is_op(OPERATOR_LCURLY)) - { - source_location token_loc = token->location(); - if (token->is_op(OPERATOR_SEMICOLON) - && this->advance_token()->is_op(OPERATOR_LCURLY)) - error_at(token_loc, "unexpected semicolon or newline before %<{%>"); - else - { - error_at(this->location(), "expected %<{%>"); - return; - } - } - this->advance_token(); - - Select_statement* statement = Statement::make_select_statement(location); - - this->push_break_statement(statement, label); - - Select_clauses* select_clauses = new Select_clauses(); - bool saw_default = false; - while (!this->peek_token()->is_op(OPERATOR_RCURLY)) - { - if (this->peek_token()->is_eof()) - { - error_at(this->location(), "expected %<}%>"); - return; - } - this->comm_clause(select_clauses, &saw_default); - } - - this->advance_token(); - - statement->add_clauses(select_clauses); - - this->pop_break_statement(); - - this->gogo_->add_statement(statement); -} - -// CommClause = CommCase ":" { Statement ";" } . - -void -Parse::comm_clause(Select_clauses* clauses, bool* saw_default) -{ - source_location location = this->location(); - bool is_send = false; - Expression* channel = NULL; - Expression* val = NULL; - Expression* closed = NULL; - std::string varname; - std::string closedname; - bool is_default = false; - bool got_case = this->comm_case(&is_send, &channel, &val, &closed, - &varname, &closedname, &is_default); - - if (this->peek_token()->is_op(OPERATOR_COLON)) - this->advance_token(); - else - error_at(this->location(), "expected colon"); - - Block* statements = NULL; - Named_object* var = NULL; - Named_object* closedvar = NULL; - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - else if (this->statement_list_may_start_here()) - { - this->gogo_->start_block(this->location()); - - if (!varname.empty()) - { - // FIXME: LOCATION is slightly wrong here. - Variable* v = new Variable(NULL, channel, false, false, false, - location); - v->set_type_from_chan_element(); - var = this->gogo_->add_variable(varname, v); - } - - if (!closedname.empty()) - { - // FIXME: LOCATION is slightly wrong here. - Variable* v = new Variable(Type::lookup_bool_type(), NULL, - false, false, false, location); - closedvar = this->gogo_->add_variable(closedname, v); - } - - this->statement_list(); - statements = this->gogo_->finish_block(this->location()); - } - - if (is_default) - { - if (*saw_default) - { - error_at(location, "multiple defaults in select"); - return; - } - *saw_default = true; - } - - if (got_case) - clauses->add(is_send, channel, val, closed, var, closedvar, is_default, - statements, location); - else if (statements != NULL) - { - // Add the statements to make sure that any names they define - // are traversed. - this->gogo_->add_block(statements, location); - } -} - -// CommCase = "case" ( SendStmt | RecvStmt ) | "default" . - -bool -Parse::comm_case(bool* is_send, Expression** channel, Expression** val, - Expression** closed, std::string* varname, - std::string* closedname, bool* is_default) -{ - const Token* token = this->peek_token(); - if (token->is_keyword(KEYWORD_DEFAULT)) - { - this->advance_token(); - *is_default = true; - } - else if (token->is_keyword(KEYWORD_CASE)) - { - this->advance_token(); - if (!this->send_or_recv_stmt(is_send, channel, val, closed, varname, - closedname)) - return false; - } - else - { - error_at(this->location(), "expected % or %"); - if (!token->is_op(OPERATOR_RCURLY)) - this->advance_token(); - return false; - } - - return true; -} - -// RecvStmt = [ Expression [ "," Expression ] ( "=" | ":=" ) ] RecvExpr . -// RecvExpr = Expression . - -bool -Parse::send_or_recv_stmt(bool* is_send, Expression** channel, Expression** val, - Expression** closed, std::string* varname, - std::string* closedname) -{ - const Token* token = this->peek_token(); - bool saw_comma = false; - bool closed_is_id = false; - if (token->is_identifier()) - { - Gogo* gogo = this->gogo_; - std::string recv_var = token->identifier(); - bool is_rv_exported = token->is_identifier_exported(); - source_location recv_var_loc = token->location(); - token = this->advance_token(); - if (token->is_op(OPERATOR_COLONEQ)) - { - // case rv := <-c: - if (!this->advance_token()->is_op(OPERATOR_CHANOP)) - { - error_at(this->location(), "expected %<<-%>"); - return false; - } - if (recv_var == "_") - { - error_at(recv_var_loc, - "no new variables on left side of %<:=%>"); - recv_var = "blank"; - } - *is_send = false; - *varname = gogo->pack_hidden_name(recv_var, is_rv_exported); - this->advance_token(); - *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - return true; - } - else if (token->is_op(OPERATOR_COMMA)) - { - token = this->advance_token(); - if (token->is_identifier()) - { - std::string recv_closed = token->identifier(); - bool is_rc_exported = token->is_identifier_exported(); - source_location recv_closed_loc = token->location(); - closed_is_id = true; - - token = this->advance_token(); - if (token->is_op(OPERATOR_COLONEQ)) - { - // case rv, rc := <-c: - if (!this->advance_token()->is_op(OPERATOR_CHANOP)) - { - error_at(this->location(), "expected %<<-%>"); - return false; - } - if (recv_var == "_" && recv_closed == "_") - { - error_at(recv_var_loc, - "no new variables on left side of %<:=%>"); - recv_var = "blank"; - } - *is_send = false; - if (recv_var != "_") - *varname = gogo->pack_hidden_name(recv_var, - is_rv_exported); - if (recv_closed != "_") - *closedname = gogo->pack_hidden_name(recv_closed, - is_rc_exported); - this->advance_token(); - *channel = this->expression(PRECEDENCE_NORMAL, false, true, - NULL); - return true; - } - - this->unget_token(Token::make_identifier_token(recv_closed, - is_rc_exported, - recv_closed_loc)); - } - - *val = this->id_to_expression(gogo->pack_hidden_name(recv_var, - is_rv_exported), - recv_var_loc); - saw_comma = true; - } - else - this->unget_token(Token::make_identifier_token(recv_var, - is_rv_exported, - recv_var_loc)); - } - - // If SAW_COMMA is false, then we are looking at the start of the - // send or receive expression. If SAW_COMMA is true, then *VAL is - // set and we just read a comma. - - if (!saw_comma && this->peek_token()->is_op(OPERATOR_CHANOP)) - { - // case <-c: - *is_send = false; - this->advance_token(); - *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - return true; - } - - Expression* e = this->expression(PRECEDENCE_NORMAL, true, true, NULL); - - if (this->peek_token()->is_op(OPERATOR_EQ)) - { - if (!this->advance_token()->is_op(OPERATOR_CHANOP)) - { - error_at(this->location(), "missing %<<-%>"); - return false; - } - *is_send = false; - this->advance_token(); - *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - if (saw_comma) - { - // case v, e = <-c: - // *VAL is already set. - if (!e->is_sink_expression()) - *closed = e; - } - else - { - // case v = <-c: - if (!e->is_sink_expression()) - *val = e; - } - return true; - } - - if (saw_comma) - { - if (closed_is_id) - error_at(this->location(), "expected %<=%> or %<:=%>"); - else - error_at(this->location(), "expected %<=%>"); - return false; - } - - if (this->peek_token()->is_op(OPERATOR_CHANOP)) - { - // case c <- v: - *is_send = true; - *channel = this->verify_not_sink(e); - this->advance_token(); - *val = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - return true; - } - - error_at(this->location(), "expected %<<-%> or %<=%>"); - return false; -} - -// ForStat = "for" [ Condition | ForClause | RangeClause ] Block . -// Condition = Expression . - -void -Parse::for_stat(const Label* label) -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_FOR)); - source_location location = this->location(); - const Token* token = this->advance_token(); - - // Open a block to hold any variables defined in the init statement - // of the for statement. - this->gogo_->start_block(location); - - Block* init = NULL; - Expression* cond = NULL; - Block* post = NULL; - Range_clause range_clause; - - if (!token->is_op(OPERATOR_LCURLY)) - { - if (token->is_keyword(KEYWORD_VAR)) - { - error_at(this->location(), - "var declaration not allowed in for initializer"); - this->var_decl(); - } - - if (token->is_op(OPERATOR_SEMICOLON)) - this->for_clause(&cond, &post); - else - { - // We might be looking at a Condition, an InitStat, or a - // RangeClause. - cond = this->simple_stat(false, true, &range_clause, NULL); - if (!this->peek_token()->is_op(OPERATOR_SEMICOLON)) - { - if (cond == NULL && !range_clause.found) - error_at(this->location(), "parse error in for statement"); - } - else - { - if (range_clause.found) - error_at(this->location(), "parse error after range clause"); - - if (cond != NULL) - { - // COND is actually an expression statement for - // InitStat at the start of a ForClause. - this->expression_stat(cond); - cond = NULL; - } - - this->for_clause(&cond, &post); - } - } - } - - // Build the For_statement and note that it is the current target - // for break and continue statements. - - For_statement* sfor; - For_range_statement* srange; - Statement* s; - if (!range_clause.found) - { - sfor = Statement::make_for_statement(init, cond, post, location); - s = sfor; - srange = NULL; - } - else - { - srange = Statement::make_for_range_statement(range_clause.index, - range_clause.value, - range_clause.range, - location); - s = srange; - sfor = NULL; - } - - this->push_break_statement(s, label); - this->push_continue_statement(s, label); - - // Gather the block of statements in the loop and add them to the - // For_statement. - - this->gogo_->start_block(this->location()); - source_location end_loc = this->block(); - Block* statements = this->gogo_->finish_block(end_loc); - - if (sfor != NULL) - sfor->add_statements(statements); - else - srange->add_statements(statements); - - // This is no longer the break/continue target. - this->pop_break_statement(); - this->pop_continue_statement(); - - // Add the For_statement to the list of statements, and close out - // the block we started to hold any variables defined in the for - // statement. - - this->gogo_->add_statement(s); - - this->gogo_->add_block(this->gogo_->finish_block(this->location()), - location); -} - -// ForClause = [ InitStat ] ";" [ Condition ] ";" [ PostStat ] . -// InitStat = SimpleStat . -// PostStat = SimpleStat . - -// We have already read InitStat at this point. - -void -Parse::for_clause(Expression** cond, Block** post) -{ - gcc_assert(this->peek_token()->is_op(OPERATOR_SEMICOLON)); - this->advance_token(); - if (this->peek_token()->is_op(OPERATOR_SEMICOLON)) - *cond = NULL; - else if (this->peek_token()->is_op(OPERATOR_LCURLY)) - { - error_at(this->location(), - "unexpected semicolon or newline before %<{%>"); - *cond = NULL; - *post = NULL; - return; - } - else - *cond = this->expression(PRECEDENCE_NORMAL, false, true, NULL); - if (!this->peek_token()->is_op(OPERATOR_SEMICOLON)) - error_at(this->location(), "expected semicolon"); - else - this->advance_token(); - - if (this->peek_token()->is_op(OPERATOR_LCURLY)) - *post = NULL; - else - { - this->gogo_->start_block(this->location()); - this->simple_stat(false, false, NULL, NULL); - *post = this->gogo_->finish_block(this->location()); - } -} - -// RangeClause = IdentifierList ( "=" | ":=" ) "range" Expression . - -// This is the := version. It is called with a list of identifiers. - -void -Parse::range_clause_decl(const Typed_identifier_list* til, - Range_clause* p_range_clause) -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_RANGE)); - source_location location = this->location(); - - p_range_clause->found = true; - - gcc_assert(til->size() >= 1); - if (til->size() > 2) - error_at(this->location(), "too many variables for range clause"); - - this->advance_token(); - Expression* expr = this->expression(PRECEDENCE_NORMAL, false, false, NULL); - p_range_clause->range = expr; - - bool any_new = false; - - const Typed_identifier* pti = &til->front(); - Named_object* no = this->init_var(*pti, NULL, expr, true, true, &any_new); - if (any_new && no->is_variable()) - no->var_value()->set_type_from_range_index(); - p_range_clause->index = Expression::make_var_reference(no, location); - - if (til->size() == 1) - p_range_clause->value = NULL; - else - { - pti = &til->back(); - bool is_new = false; - no = this->init_var(*pti, NULL, expr, true, true, &is_new); - if (is_new && no->is_variable()) - no->var_value()->set_type_from_range_value(); - if (is_new) - any_new = true; - p_range_clause->value = Expression::make_var_reference(no, location); - } - - if (!any_new) - error_at(location, "variables redeclared but no variable is new"); -} - -// The = version of RangeClause. This is called with a list of -// expressions. - -void -Parse::range_clause_expr(const Expression_list* vals, - Range_clause* p_range_clause) -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_RANGE)); - - p_range_clause->found = true; - - gcc_assert(vals->size() >= 1); - if (vals->size() > 2) - error_at(this->location(), "too many variables for range clause"); - - this->advance_token(); - p_range_clause->range = this->expression(PRECEDENCE_NORMAL, false, false, - NULL); - - p_range_clause->index = vals->front(); - if (vals->size() == 1) - p_range_clause->value = NULL; - else - p_range_clause->value = vals->back(); -} - -// Push a statement on the break stack. - -void -Parse::push_break_statement(Statement* enclosing, const Label* label) -{ - if (this->break_stack_ == NULL) - this->break_stack_ = new Bc_stack(); - this->break_stack_->push_back(std::make_pair(enclosing, label)); -} - -// Push a statement on the continue stack. - -void -Parse::push_continue_statement(Statement* enclosing, const Label* label) -{ - if (this->continue_stack_ == NULL) - this->continue_stack_ = new Bc_stack(); - this->continue_stack_->push_back(std::make_pair(enclosing, label)); -} - -// Pop the break stack. - -void -Parse::pop_break_statement() -{ - this->break_stack_->pop_back(); -} - -// Pop the continue stack. - -void -Parse::pop_continue_statement() -{ - this->continue_stack_->pop_back(); -} - -// Find a break or continue statement given a label name. - -Statement* -Parse::find_bc_statement(const Bc_stack* bc_stack, const std::string& label) -{ - if (bc_stack == NULL) - return NULL; - for (Bc_stack::const_reverse_iterator p = bc_stack->rbegin(); - p != bc_stack->rend(); - ++p) - if (p->second != NULL && p->second->name() == label) - return p->first; - return NULL; -} - -// BreakStat = "break" [ identifier ] . - -void -Parse::break_stat() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_BREAK)); - source_location location = this->location(); - - const Token* token = this->advance_token(); - Statement* enclosing; - if (!token->is_identifier()) - { - if (this->break_stack_ == NULL || this->break_stack_->empty()) - { - error_at(this->location(), - "break statement not within for or switch or select"); - return; - } - enclosing = this->break_stack_->back().first; - } - else - { - enclosing = this->find_bc_statement(this->break_stack_, - token->identifier()); - if (enclosing == NULL) - { - error_at(token->location(), - ("break label %qs not associated with " - "for or switch or select"), - Gogo::message_name(token->identifier()).c_str()); - this->advance_token(); - return; - } - this->advance_token(); - } - - Unnamed_label* label; - if (enclosing->classification() == Statement::STATEMENT_FOR) - label = enclosing->for_statement()->break_label(); - else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE) - label = enclosing->for_range_statement()->break_label(); - else if (enclosing->classification() == Statement::STATEMENT_SWITCH) - label = enclosing->switch_statement()->break_label(); - else if (enclosing->classification() == Statement::STATEMENT_TYPE_SWITCH) - label = enclosing->type_switch_statement()->break_label(); - else if (enclosing->classification() == Statement::STATEMENT_SELECT) - label = enclosing->select_statement()->break_label(); - else - gcc_unreachable(); - - this->gogo_->add_statement(Statement::make_break_statement(label, - location)); -} - -// ContinueStat = "continue" [ identifier ] . - -void -Parse::continue_stat() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_CONTINUE)); - source_location location = this->location(); - - const Token* token = this->advance_token(); - Statement* enclosing; - if (!token->is_identifier()) - { - if (this->continue_stack_ == NULL || this->continue_stack_->empty()) - { - error_at(this->location(), "continue statement not within for"); - return; - } - enclosing = this->continue_stack_->back().first; - } - else - { - enclosing = this->find_bc_statement(this->continue_stack_, - token->identifier()); - if (enclosing == NULL) - { - error_at(token->location(), - "continue label %qs not associated with for", - Gogo::message_name(token->identifier()).c_str()); - this->advance_token(); - return; - } - this->advance_token(); - } - - Unnamed_label* label; - if (enclosing->classification() == Statement::STATEMENT_FOR) - label = enclosing->for_statement()->continue_label(); - else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE) - label = enclosing->for_range_statement()->continue_label(); - else - gcc_unreachable(); - - this->gogo_->add_statement(Statement::make_continue_statement(label, - location)); -} - -// GotoStat = "goto" identifier . - -void -Parse::goto_stat() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_GOTO)); - source_location location = this->location(); - const Token* token = this->advance_token(); - if (!token->is_identifier()) - error_at(this->location(), "expected label for goto"); - else - { - Label* label = this->gogo_->add_label_reference(token->identifier()); - Statement* s = Statement::make_goto_statement(label, location); - this->gogo_->add_statement(s); - this->advance_token(); - } -} - -// PackageClause = "package" PackageName . - -void -Parse::package_clause() -{ - const Token* token = this->peek_token(); - source_location location = token->location(); - std::string name; - if (!token->is_keyword(KEYWORD_PACKAGE)) - { - error_at(this->location(), "program must start with package clause"); - name = "ERROR"; - } - else - { - token = this->advance_token(); - if (token->is_identifier()) - { - name = token->identifier(); - if (name == "_") - { - error_at(this->location(), "invalid package name _"); - name = "blank"; - } - this->advance_token(); - } - else - { - error_at(this->location(), "package name must be an identifier"); - name = "ERROR"; - } - } - this->gogo_->set_package_name(name, location); -} - -// ImportDecl = "import" Decl . - -void -Parse::import_decl() -{ - gcc_assert(this->peek_token()->is_keyword(KEYWORD_IMPORT)); - this->advance_token(); - this->decl(&Parse::import_spec, NULL); -} - -// ImportSpec = [ "." | PackageName ] PackageFileName . - -void -Parse::import_spec(void*) -{ - const Token* token = this->peek_token(); - source_location location = token->location(); - - std::string local_name; - bool is_local_name_exported = false; - if (token->is_op(OPERATOR_DOT)) - { - local_name = "."; - token = this->advance_token(); - } - else if (token->is_identifier()) - { - local_name = token->identifier(); - is_local_name_exported = token->is_identifier_exported(); - token = this->advance_token(); - } - - if (!token->is_string()) - { - error_at(this->location(), "missing import package name"); - return; - } - - this->gogo_->import_package(token->string_value(), local_name, - is_local_name_exported, location); - - this->advance_token(); -} - -// SourceFile = PackageClause ";" { ImportDecl ";" } -// { TopLevelDecl ";" } . - -void -Parse::program() -{ - this->package_clause(); - - const Token* token = this->peek_token(); - if (token->is_op(OPERATOR_SEMICOLON)) - token = this->advance_token(); - else - error_at(this->location(), - "expected %<;%> or newline after package clause"); - - while (token->is_keyword(KEYWORD_IMPORT)) - { - this->import_decl(); - token = this->peek_token(); - if (token->is_op(OPERATOR_SEMICOLON)) - token = this->advance_token(); - else - error_at(this->location(), - "expected %<;%> or newline after import declaration"); - } - - while (!token->is_eof()) - { - if (this->declaration_may_start_here()) - this->declaration(); - else - { - error_at(this->location(), "expected declaration"); - do - this->advance_token(); - while (!this->peek_token()->is_eof() - && !this->peek_token()->is_op(OPERATOR_SEMICOLON) - && !this->peek_token()->is_op(OPERATOR_RCURLY)); - if (!this->peek_token()->is_eof() - && !this->peek_token()->is_op(OPERATOR_SEMICOLON)) - this->advance_token(); - } - token = this->peek_token(); - if (token->is_op(OPERATOR_SEMICOLON)) - token = this->advance_token(); - else if (!token->is_eof() || !saw_errors()) - { - error_at(this->location(), - "expected %<;%> or newline after top level declaration"); - this->skip_past_error(OPERATOR_INVALID); - } - } -} - -// Reset the current iota value. - -void -Parse::reset_iota() -{ - this->iota_ = 0; -} - -// Return the current iota value. - -int -Parse::iota_value() -{ - return this->iota_; -} - -// Increment the current iota value. - -void -Parse::increment_iota() -{ - ++this->iota_; -} - -// Skip forward to a semicolon or OP. OP will normally be -// OPERATOR_RPAREN or OPERATOR_RCURLY. If we find a semicolon, move -// past it and return. If we find OP, it will be the next token to -// read. Return true if we are OK, false if we found EOF. - -bool -Parse::skip_past_error(Operator op) -{ - const Token* token = this->peek_token(); - while (!token->is_op(op)) - { - if (token->is_eof()) - return false; - if (token->is_op(OPERATOR_SEMICOLON)) - { - this->advance_token(); - return true; - } - token = this->advance_token(); - } - return true; -} - -// Check that an expression is not a sink. - -Expression* -Parse::verify_not_sink(Expression* expr) -{ - if (expr->is_sink_expression()) - { - error_at(expr->location(), "cannot use _ as value"); - expr = Expression::make_error(expr->location()); - } - return expr; -} diff --git a/gcc/go/gofrontend/parse.h.merge-left.r167407 b/gcc/go/gofrontend/parse.h.merge-left.r167407 deleted file mode 100644 index fc2eb12b6d5..00000000000 --- a/gcc/go/gofrontend/parse.h.merge-left.r167407 +++ /dev/null @@ -1,307 +0,0 @@ -// parse.h -- Go frontend parser. -*- C++ -*- - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#ifndef GO_PARSE_H -#define GO_PARSE_H - -class Set_iota_traverse; -class Lex; -class Gogo; -class Named_object; -class Type; -class Typed_identifier; -class Typed_identifier_list; -class Function_type; -class Block; -class Expression; -class Expression_list; -class Struct_field_list; -class Case_clauses; -class Type_case_clauses; -class Select_clauses; -class Statement; -class Label; - -// Parse the program. - -class Parse -{ - public: - Parse(Lex*, Gogo*); - - // Parse a program. - void - program(); - - private: - // Precedence values. - enum Precedence - { - PRECEDENCE_INVALID = -1, - PRECEDENCE_NORMAL = 0, - PRECEDENCE_OROR, - PRECEDENCE_ANDAND, - PRECEDENCE_CHANOP, - PRECEDENCE_RELOP, - PRECEDENCE_ADDOP, - PRECEDENCE_MULOP - }; - - // We use this when parsing the range clause of a for statement. - struct Range_clause - { - // Set to true if we found a range clause. - bool found; - // The index expression. - Expression* index; - // The value expression. - Expression* value; - // The range expression. - Expression* range; - - Range_clause() - : found(false), index(NULL), value(NULL), range(NULL) - { } - }; - - // We use this when parsing the statement at the start of a switch, - // in order to recognize type switches. - struct Type_switch - { - // Set to true if we find a type switch. - bool found; - // The variable name. - std::string name; - // The location of the variable. - source_location location; - // The expression. - Expression* expr; - - Type_switch() - : found(false), name(), location(UNKNOWN_LOCATION), expr(NULL) - { } - }; - - // A variable defined in an enclosing function referenced by the - // current function. - class Enclosing_var - { - public: - Enclosing_var(Named_object* var, Named_object* in_function, - unsigned int index) - : var_(var), in_function_(in_function), index_(index) - { } - - // We put these in a vector, so we need a default constructor. - Enclosing_var() - : var_(NULL), in_function_(NULL), index_(-1U) - { } - - Named_object* - var() const - { return this->var_; } - - Named_object* - in_function() const - { return this->in_function_; } - - unsigned int - index() const - { return this->index_; } - - private: - // The variable which is being referred to. - Named_object* var_; - // The function where the variable is defined. - Named_object* in_function_; - // The index of the field in this function's closure struct for - // this variable. - unsigned int index_; - }; - - // We store Enclosing_var entries in a set, so we need a comparator. - struct Enclosing_var_comparison - { - bool - operator()(const Enclosing_var&, const Enclosing_var&); - }; - - // A set of Enclosing_var entries. - typedef std::set Enclosing_vars; - - // Peek at the current token from the lexer. - const Token* - peek_token(); - - // Consume the current token, return the next one. - const Token* - advance_token(); - - // Push a token back on the input stream. - void - unget_token(const Token&); - - // The location of the current token. - source_location - location(); - - // For break and continue we keep a stack of statements with - // associated labels (if any). The top of the stack is used for a - // break or continue statement with no label. - typedef std::vector > Bc_stack; - - // Parser nonterminals. - void identifier_list(Typed_identifier_list*); - Expression_list* expression_list(Expression*, bool may_be_sink); - bool qualified_ident(std::string*, Named_object**); - Type* type(); - bool type_may_start_here(); - Type* type_name(bool issue_error); - Type* array_type(bool may_use_ellipsis); - Type* map_type(); - Type* struct_type(); - void field_decl(Struct_field_list*); - Type* pointer_type(); - Type* channel_type(); - Function_type* signature(Typed_identifier*, source_location); - Typed_identifier_list* parameters(bool* is_varargs); - Typed_identifier_list* parameter_list(bool* is_varargs); - void parameter_decl(bool, Typed_identifier_list*, bool*, bool*); - Typed_identifier_list* result(); - source_location block(); - Type* interface_type(); - bool method_spec(Typed_identifier_list*); - void declaration(); - bool declaration_may_start_here(); - void decl(void (Parse::*)(void*), void*); - void list(void (Parse::*)(void*), void*, bool); - void const_decl(); - void const_spec(Type**, Expression_list**); - void type_decl(); - void type_spec(void*); - void var_decl(); - void var_spec(void*); - void init_vars(const Typed_identifier_list*, Type*, Expression_list*, - bool is_coloneq, source_location); - bool init_vars_from_call(const Typed_identifier_list*, Type*, Expression*, - bool is_coloneq, source_location); - bool init_vars_from_map(const Typed_identifier_list*, Type*, Expression*, - bool is_coloneq, source_location); - bool init_vars_from_receive(const Typed_identifier_list*, Type*, - Expression*, bool is_coloneq, source_location); - bool init_vars_from_type_guard(const Typed_identifier_list*, Type*, - Expression*, bool is_coloneq, - source_location); - Named_object* init_var(const Typed_identifier&, Type*, Expression*, - bool is_coloneq, bool type_from_init, bool* is_new); - void simple_var_decl_or_assignment(const std::string&, source_location, - Range_clause*, Type_switch*); - void function_decl(); - Typed_identifier* receiver(); - Expression* operand(bool may_be_sink); - Expression* enclosing_var_reference(Named_object*, Named_object*, - source_location); - Expression* composite_lit(Type*, int depth, source_location); - Expression* function_lit(); - Expression* create_closure(Named_object* function, Enclosing_vars*, - source_location); - Expression* primary_expr(bool may_be_sink, bool may_be_composite_lit, - bool* is_type_switch); - Expression* selector(Expression*, bool* is_type_switch); - Expression* index(Expression*); - Expression* call(Expression*); - Expression* expression(Precedence, bool may_be_sink, - bool may_be_composite_lit, bool* is_type_switch); - bool expression_may_start_here(); - Expression* unary_expr(bool may_be_sink, bool may_be_composite_lit, - bool* is_type_switch); - Expression* qualified_expr(Expression*, source_location); - Expression* id_to_expression(const std::string&, source_location); - void statement(const Label*); - bool statement_may_start_here(); - void labeled_stmt(const std::string&, source_location); - Expression* simple_stat(bool, bool, Range_clause*, Type_switch*); - bool simple_stat_may_start_here(); - void statement_list(); - bool statement_list_may_start_here(); - void expression_stat(Expression*); - void inc_dec_stat(Expression*); - void assignment(Expression*, Range_clause*); - void tuple_assignment(Expression_list*, Range_clause*); - void send(); - void go_or_defer_stat(); - void return_stat(); - void if_stat(); - void switch_stat(const Label*); - Statement* expr_switch_body(const Label*, Expression*, source_location); - void expr_case_clause(Case_clauses*); - Expression_list* expr_switch_case(bool*); - Statement* type_switch_body(const Label*, const Type_switch&, - source_location); - void type_case_clause(Named_object*, Type_case_clauses*); - void type_switch_case(std::vector*, bool*); - void select_stat(const Label*); - void comm_clause(Select_clauses*); - bool comm_case(bool*, Expression**, Expression**, std::string*, bool*); - bool send_or_recv_expr(bool*, Expression**, Expression**, std::string*); - void for_stat(const Label*); - void for_clause(Expression**, Block**); - void range_clause_decl(const Typed_identifier_list*, Range_clause*); - void range_clause_expr(const Expression_list*, Range_clause*); - void push_break_statement(Statement*, const Label*); - void push_continue_statement(Statement*, const Label*); - void pop_break_statement(); - void pop_continue_statement(); - Statement* find_bc_statement(const Bc_stack*, const std::string&); - void break_stat(); - void continue_stat(); - void goto_stat(); - void package_clause(); - void import_decl(); - void import_spec(void*); - - void reset_iota(); - int iota_value(); - void increment_iota(); - - // Skip past an error looking for a semicolon or OP. Return true if - // all is well, false if we found EOF. - bool - skip_past_error(Operator op); - - // Verify that an expression is not a sink, and return either the - // expression or an error. - Expression* - verify_not_sink(Expression*); - - // Return the statement associated with a label in a Bc_stack, or - // NULL. - Statement* - find_bc_statement(const Bc_stack*, const std::string&) const; - - // The lexer output we are parsing. - Lex* lex_; - // The current token. - Token token_; - // A token pushed back on the input stream. - Token unget_token_; - // Whether unget_token_ is valid. - bool unget_token_valid_; - // The code we are generating. - Gogo* gogo_; - // A stack of statements for which break may be used. - Bc_stack break_stack_; - // A stack of statements for which continue may be used. - Bc_stack continue_stack_; - // The current iota value. - int iota_; - // References from the local function to variables defined in - // enclosing functions. - Enclosing_vars enclosing_vars_; -}; - - -#endif // !defined(GO_PARSE_H) diff --git a/gcc/go/gofrontend/parse.h.merge-right.r172891 b/gcc/go/gofrontend/parse.h.merge-right.r172891 deleted file mode 100644 index f072fd35932..00000000000 --- a/gcc/go/gofrontend/parse.h.merge-right.r172891 +++ /dev/null @@ -1,309 +0,0 @@ -// parse.h -- Go frontend parser. -*- C++ -*- - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#ifndef GO_PARSE_H -#define GO_PARSE_H - -class Set_iota_traverse; -class Lex; -class Gogo; -class Named_object; -class Type; -class Typed_identifier; -class Typed_identifier_list; -class Function_type; -class Block; -class Expression; -class Expression_list; -class Struct_field_list; -class Case_clauses; -class Type_case_clauses; -class Select_clauses; -class Statement; -class Label; - -// Parse the program. - -class Parse -{ - public: - Parse(Lex*, Gogo*); - - // Parse a program. - void - program(); - - private: - // Precedence values. - enum Precedence - { - PRECEDENCE_INVALID = -1, - PRECEDENCE_NORMAL = 0, - PRECEDENCE_OROR, - PRECEDENCE_ANDAND, - PRECEDENCE_RELOP, - PRECEDENCE_ADDOP, - PRECEDENCE_MULOP - }; - - // We use this when parsing the range clause of a for statement. - struct Range_clause - { - // Set to true if we found a range clause. - bool found; - // The index expression. - Expression* index; - // The value expression. - Expression* value; - // The range expression. - Expression* range; - - Range_clause() - : found(false), index(NULL), value(NULL), range(NULL) - { } - }; - - // We use this when parsing the statement at the start of a switch, - // in order to recognize type switches. - struct Type_switch - { - // Set to true if we find a type switch. - bool found; - // The variable name. - std::string name; - // The location of the variable. - source_location location; - // The expression. - Expression* expr; - - Type_switch() - : found(false), name(), location(UNKNOWN_LOCATION), expr(NULL) - { } - }; - - // A variable defined in an enclosing function referenced by the - // current function. - class Enclosing_var - { - public: - Enclosing_var(Named_object* var, Named_object* in_function, - unsigned int index) - : var_(var), in_function_(in_function), index_(index) - { } - - // We put these in a vector, so we need a default constructor. - Enclosing_var() - : var_(NULL), in_function_(NULL), index_(-1U) - { } - - Named_object* - var() const - { return this->var_; } - - Named_object* - in_function() const - { return this->in_function_; } - - unsigned int - index() const - { return this->index_; } - - private: - // The variable which is being referred to. - Named_object* var_; - // The function where the variable is defined. - Named_object* in_function_; - // The index of the field in this function's closure struct for - // this variable. - unsigned int index_; - }; - - // We store Enclosing_var entries in a set, so we need a comparator. - struct Enclosing_var_comparison - { - bool - operator()(const Enclosing_var&, const Enclosing_var&); - }; - - // A set of Enclosing_var entries. - typedef std::set Enclosing_vars; - - // Peek at the current token from the lexer. - const Token* - peek_token(); - - // Consume the current token, return the next one. - const Token* - advance_token(); - - // Push a token back on the input stream. - void - unget_token(const Token&); - - // The location of the current token. - source_location - location(); - - // For break and continue we keep a stack of statements with - // associated labels (if any). The top of the stack is used for a - // break or continue statement with no label. - typedef std::vector > Bc_stack; - - // Parser nonterminals. - void identifier_list(Typed_identifier_list*); - Expression_list* expression_list(Expression*, bool may_be_sink); - bool qualified_ident(std::string*, Named_object**); - Type* type(); - bool type_may_start_here(); - Type* type_name(bool issue_error); - Type* array_type(bool may_use_ellipsis); - Type* map_type(); - Type* struct_type(); - void field_decl(Struct_field_list*); - Type* pointer_type(); - Type* channel_type(); - Function_type* signature(Typed_identifier*, source_location); - bool parameters(Typed_identifier_list**, bool* is_varargs); - Typed_identifier_list* parameter_list(bool* is_varargs); - void parameter_decl(bool, Typed_identifier_list*, bool*, bool*); - bool result(Typed_identifier_list**); - source_location block(); - Type* interface_type(); - void method_spec(Typed_identifier_list*); - void declaration(); - bool declaration_may_start_here(); - void decl(void (Parse::*)(void*), void*); - void list(void (Parse::*)(void*), void*, bool); - void const_decl(); - void const_spec(Type**, Expression_list**); - void type_decl(); - void type_spec(void*); - void var_decl(); - void var_spec(void*); - void init_vars(const Typed_identifier_list*, Type*, Expression_list*, - bool is_coloneq, source_location); - bool init_vars_from_call(const Typed_identifier_list*, Type*, Expression*, - bool is_coloneq, source_location); - bool init_vars_from_map(const Typed_identifier_list*, Type*, Expression*, - bool is_coloneq, source_location); - bool init_vars_from_receive(const Typed_identifier_list*, Type*, - Expression*, bool is_coloneq, source_location); - bool init_vars_from_type_guard(const Typed_identifier_list*, Type*, - Expression*, bool is_coloneq, - source_location); - Named_object* init_var(const Typed_identifier&, Type*, Expression*, - bool is_coloneq, bool type_from_init, bool* is_new); - Named_object* create_dummy_global(Type*, Expression*, source_location); - void simple_var_decl_or_assignment(const std::string&, source_location, - Range_clause*, Type_switch*); - void function_decl(); - Typed_identifier* receiver(); - Expression* operand(bool may_be_sink); - Expression* enclosing_var_reference(Named_object*, Named_object*, - source_location); - Expression* composite_lit(Type*, int depth, source_location); - Expression* function_lit(); - Expression* create_closure(Named_object* function, Enclosing_vars*, - source_location); - Expression* primary_expr(bool may_be_sink, bool may_be_composite_lit, - bool* is_type_switch); - Expression* selector(Expression*, bool* is_type_switch); - Expression* index(Expression*); - Expression* call(Expression*); - Expression* expression(Precedence, bool may_be_sink, - bool may_be_composite_lit, bool* is_type_switch); - bool expression_may_start_here(); - Expression* unary_expr(bool may_be_sink, bool may_be_composite_lit, - bool* is_type_switch); - Expression* qualified_expr(Expression*, source_location); - Expression* id_to_expression(const std::string&, source_location); - void statement(Label*); - bool statement_may_start_here(); - void labeled_stmt(const std::string&, source_location); - Expression* simple_stat(bool, bool*, Range_clause*, Type_switch*); - bool simple_stat_may_start_here(); - void statement_list(); - bool statement_list_may_start_here(); - void expression_stat(Expression*); - void send_stmt(Expression*); - void inc_dec_stat(Expression*); - void assignment(Expression*, Range_clause*); - void tuple_assignment(Expression_list*, Range_clause*); - void send(); - void go_or_defer_stat(); - void return_stat(); - void if_stat(); - void switch_stat(Label*); - Statement* expr_switch_body(Label*, Expression*, source_location); - void expr_case_clause(Case_clauses*, bool* saw_default); - Expression_list* expr_switch_case(bool*); - Statement* type_switch_body(Label*, const Type_switch&, source_location); - void type_case_clause(Named_object*, Type_case_clauses*, bool* saw_default); - void type_switch_case(std::vector*, bool*); - void select_stat(Label*); - void comm_clause(Select_clauses*, bool* saw_default); - bool comm_case(bool*, Expression**, Expression**, Expression**, - std::string*, std::string*, bool*); - bool send_or_recv_stmt(bool*, Expression**, Expression**, Expression**, - std::string*, std::string*); - void for_stat(Label*); - void for_clause(Expression**, Block**); - void range_clause_decl(const Typed_identifier_list*, Range_clause*); - void range_clause_expr(const Expression_list*, Range_clause*); - void push_break_statement(Statement*, Label*); - void push_continue_statement(Statement*, Label*); - void pop_break_statement(); - void pop_continue_statement(); - Statement* find_bc_statement(const Bc_stack*, const std::string&); - void break_stat(); - void continue_stat(); - void goto_stat(); - void package_clause(); - void import_decl(); - void import_spec(void*); - - void reset_iota(); - int iota_value(); - void increment_iota(); - - // Skip past an error looking for a semicolon or OP. Return true if - // all is well, false if we found EOF. - bool - skip_past_error(Operator op); - - // Verify that an expression is not a sink, and return either the - // expression or an error. - Expression* - verify_not_sink(Expression*); - - // Return the statement associated with a label in a Bc_stack, or - // NULL. - Statement* - find_bc_statement(const Bc_stack*, const std::string&) const; - - // The lexer output we are parsing. - Lex* lex_; - // The current token. - Token token_; - // A token pushed back on the input stream. - Token unget_token_; - // Whether unget_token_ is valid. - bool unget_token_valid_; - // The code we are generating. - Gogo* gogo_; - // A stack of statements for which break may be used. - Bc_stack* break_stack_; - // A stack of statements for which continue may be used. - Bc_stack* continue_stack_; - // The current iota value. - int iota_; - // References from the local function to variables defined in - // enclosing functions. - Enclosing_vars enclosing_vars_; -}; - - -#endif // !defined(GO_PARSE_H) diff --git a/gcc/go/gofrontend/parse.h.working b/gcc/go/gofrontend/parse.h.working deleted file mode 100644 index d164414df7b..00000000000 --- a/gcc/go/gofrontend/parse.h.working +++ /dev/null @@ -1,310 +0,0 @@ -// parse.h -- Go frontend parser. -*- C++ -*- - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#ifndef GO_PARSE_H -#define GO_PARSE_H - -class Set_iota_traverse; -class Lex; -class Gogo; -class Named_object; -class Type; -class Typed_identifier; -class Typed_identifier_list; -class Function_type; -class Block; -class Expression; -class Expression_list; -class Struct_field_list; -class Case_clauses; -class Type_case_clauses; -class Select_clauses; -class Statement; -class Label; - -// Parse the program. - -class Parse -{ - public: - Parse(Lex*, Gogo*); - - // Parse a program. - void - program(); - - private: - // Precedence values. - enum Precedence - { - PRECEDENCE_INVALID = -1, - PRECEDENCE_NORMAL = 0, - PRECEDENCE_OROR, - PRECEDENCE_ANDAND, - PRECEDENCE_RELOP, - PRECEDENCE_ADDOP, - PRECEDENCE_MULOP - }; - - // We use this when parsing the range clause of a for statement. - struct Range_clause - { - // Set to true if we found a range clause. - bool found; - // The index expression. - Expression* index; - // The value expression. - Expression* value; - // The range expression. - Expression* range; - - Range_clause() - : found(false), index(NULL), value(NULL), range(NULL) - { } - }; - - // We use this when parsing the statement at the start of a switch, - // in order to recognize type switches. - struct Type_switch - { - // Set to true if we find a type switch. - bool found; - // The variable name. - std::string name; - // The location of the variable. - source_location location; - // The expression. - Expression* expr; - - Type_switch() - : found(false), name(), location(UNKNOWN_LOCATION), expr(NULL) - { } - }; - - // A variable defined in an enclosing function referenced by the - // current function. - class Enclosing_var - { - public: - Enclosing_var(Named_object* var, Named_object* in_function, - unsigned int index) - : var_(var), in_function_(in_function), index_(index) - { } - - // We put these in a vector, so we need a default constructor. - Enclosing_var() - : var_(NULL), in_function_(NULL), index_(-1U) - { } - - Named_object* - var() const - { return this->var_; } - - Named_object* - in_function() const - { return this->in_function_; } - - unsigned int - index() const - { return this->index_; } - - private: - // The variable which is being referred to. - Named_object* var_; - // The function where the variable is defined. - Named_object* in_function_; - // The index of the field in this function's closure struct for - // this variable. - unsigned int index_; - }; - - // We store Enclosing_var entries in a set, so we need a comparator. - struct Enclosing_var_comparison - { - bool - operator()(const Enclosing_var&, const Enclosing_var&); - }; - - // A set of Enclosing_var entries. - typedef std::set Enclosing_vars; - - // Peek at the current token from the lexer. - const Token* - peek_token(); - - // Consume the current token, return the next one. - const Token* - advance_token(); - - // Push a token back on the input stream. - void - unget_token(const Token&); - - // The location of the current token. - source_location - location(); - - // For break and continue we keep a stack of statements with - // associated labels (if any). The top of the stack is used for a - // break or continue statement with no label. - typedef std::vector > Bc_stack; - - // Parser nonterminals. - void identifier_list(Typed_identifier_list*); - Expression_list* expression_list(Expression*, bool may_be_sink); - bool qualified_ident(std::string*, Named_object**); - Type* type(); - bool type_may_start_here(); - Type* type_name(bool issue_error); - Type* array_type(bool may_use_ellipsis); - Type* map_type(); - Type* struct_type(); - void field_decl(Struct_field_list*); - Type* pointer_type(); - Type* channel_type(); - Function_type* signature(Typed_identifier*, source_location); - bool parameters(Typed_identifier_list**, bool* is_varargs); - Typed_identifier_list* parameter_list(bool* is_varargs); - void parameter_decl(bool, Typed_identifier_list*, bool*, bool*); - bool result(Typed_identifier_list**); - source_location block(); - Type* interface_type(); - void method_spec(Typed_identifier_list*); - void declaration(); - bool declaration_may_start_here(); - void decl(void (Parse::*)(void*), void*); - void list(void (Parse::*)(void*), void*, bool); - void const_decl(); - void const_spec(Type**, Expression_list**); - void type_decl(); - void type_spec(void*); - void var_decl(); - void var_spec(void*); - void init_vars(const Typed_identifier_list*, Type*, Expression_list*, - bool is_coloneq, source_location); - bool init_vars_from_call(const Typed_identifier_list*, Type*, Expression*, - bool is_coloneq, source_location); - bool init_vars_from_map(const Typed_identifier_list*, Type*, Expression*, - bool is_coloneq, source_location); - bool init_vars_from_receive(const Typed_identifier_list*, Type*, - Expression*, bool is_coloneq, source_location); - bool init_vars_from_type_guard(const Typed_identifier_list*, Type*, - Expression*, bool is_coloneq, - source_location); - Named_object* init_var(const Typed_identifier&, Type*, Expression*, - bool is_coloneq, bool type_from_init, bool* is_new); - Named_object* create_dummy_global(Type*, Expression*, source_location); - void simple_var_decl_or_assignment(const std::string&, source_location, - Range_clause*, Type_switch*); - void function_decl(); - Typed_identifier* receiver(); - Expression* operand(bool may_be_sink); - Expression* enclosing_var_reference(Named_object*, Named_object*, - source_location); - Expression* composite_lit(Type*, int depth, source_location); - Expression* function_lit(); - Expression* create_closure(Named_object* function, Enclosing_vars*, - source_location); - Expression* primary_expr(bool may_be_sink, bool may_be_composite_lit, - bool* is_type_switch); - Expression* selector(Expression*, bool* is_type_switch); - Expression* index(Expression*); - Expression* call(Expression*); - Expression* expression(Precedence, bool may_be_sink, - bool may_be_composite_lit, bool* is_type_switch); - bool expression_may_start_here(); - Expression* unary_expr(bool may_be_sink, bool may_be_composite_lit, - bool* is_type_switch); - Expression* qualified_expr(Expression*, source_location); - Expression* id_to_expression(const std::string&, source_location); - void statement(const Label*); - bool statement_may_start_here(); - void labeled_stmt(const std::string&, source_location); - Expression* simple_stat(bool, bool, Range_clause*, Type_switch*); - bool simple_stat_may_start_here(); - void statement_list(); - bool statement_list_may_start_here(); - void expression_stat(Expression*); - void send_stmt(Expression*); - void inc_dec_stat(Expression*); - void assignment(Expression*, Range_clause*); - void tuple_assignment(Expression_list*, Range_clause*); - void send(); - void go_or_defer_stat(); - void return_stat(); - void if_stat(); - void switch_stat(const Label*); - Statement* expr_switch_body(const Label*, Expression*, source_location); - void expr_case_clause(Case_clauses*, bool* saw_default); - Expression_list* expr_switch_case(bool*); - Statement* type_switch_body(const Label*, const Type_switch&, - source_location); - void type_case_clause(Named_object*, Type_case_clauses*, bool* saw_default); - void type_switch_case(std::vector*, bool*); - void select_stat(const Label*); - void comm_clause(Select_clauses*, bool* saw_default); - bool comm_case(bool*, Expression**, Expression**, Expression**, - std::string*, std::string*, bool*); - bool send_or_recv_stmt(bool*, Expression**, Expression**, Expression**, - std::string*, std::string*); - void for_stat(const Label*); - void for_clause(Expression**, Block**); - void range_clause_decl(const Typed_identifier_list*, Range_clause*); - void range_clause_expr(const Expression_list*, Range_clause*); - void push_break_statement(Statement*, const Label*); - void push_continue_statement(Statement*, const Label*); - void pop_break_statement(); - void pop_continue_statement(); - Statement* find_bc_statement(const Bc_stack*, const std::string&); - void break_stat(); - void continue_stat(); - void goto_stat(); - void package_clause(); - void import_decl(); - void import_spec(void*); - - void reset_iota(); - int iota_value(); - void increment_iota(); - - // Skip past an error looking for a semicolon or OP. Return true if - // all is well, false if we found EOF. - bool - skip_past_error(Operator op); - - // Verify that an expression is not a sink, and return either the - // expression or an error. - Expression* - verify_not_sink(Expression*); - - // Return the statement associated with a label in a Bc_stack, or - // NULL. - Statement* - find_bc_statement(const Bc_stack*, const std::string&) const; - - // The lexer output we are parsing. - Lex* lex_; - // The current token. - Token token_; - // A token pushed back on the input stream. - Token unget_token_; - // Whether unget_token_ is valid. - bool unget_token_valid_; - // The code we are generating. - Gogo* gogo_; - // A stack of statements for which break may be used. - Bc_stack* break_stack_; - // A stack of statements for which continue may be used. - Bc_stack* continue_stack_; - // The current iota value. - int iota_; - // References from the local function to variables defined in - // enclosing functions. - Enclosing_vars enclosing_vars_; -}; - - -#endif // !defined(GO_PARSE_H) diff --git a/gcc/go/gofrontend/statements.cc.merge-left.r167407 b/gcc/go/gofrontend/statements.cc.merge-left.r167407 deleted file mode 100644 index 10fe7e41c56..00000000000 --- a/gcc/go/gofrontend/statements.cc.merge-left.r167407 +++ /dev/null @@ -1,5146 +0,0 @@ -// statements.cc -- Go frontend statements. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include - -#ifndef ENABLE_BUILD_WITH_CXX -extern "C" -{ -#endif - -#include "intl.h" -#include "tree.h" -#include "gimple.h" -#include "convert.h" -#include "tree-iterator.h" -#include "tree-flow.h" -#include "real.h" - -#ifndef ENABLE_BUILD_WITH_CXX -} -#endif - -#include "go-c.h" -#include "types.h" -#include "expressions.h" -#include "gogo.h" -#include "statements.h" - -// Class Statement. - -Statement::Statement(Statement_classification classification, - source_location location) - : classification_(classification), location_(location) -{ -} - -Statement::~Statement() -{ -} - -// Traverse the tree. The work of walking the components is handled -// by the subclasses. - -int -Statement::traverse(Block* block, size_t* pindex, Traverse* traverse) -{ - if (this->classification_ == STATEMENT_ERROR) - return TRAVERSE_CONTINUE; - - unsigned int traverse_mask = traverse->traverse_mask(); - - if ((traverse_mask & Traverse::traverse_statements) != 0) - { - int t = traverse->statement(block, pindex, this); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - return TRAVERSE_CONTINUE; - } - - // No point in checking traverse_mask here--a statement may contain - // other blocks or statements, and if we got here we always want to - // walk them. - return this->do_traverse(traverse); -} - -// Traverse the contents of a statement. - -int -Statement::traverse_contents(Traverse* traverse) -{ - return this->do_traverse(traverse); -} - -// Traverse assignments. - -bool -Statement::traverse_assignments(Traverse_assignments* tassign) -{ - if (this->classification_ == STATEMENT_ERROR) - return false; - return this->do_traverse_assignments(tassign); -} - -// Traverse an expression in a statement. This is a helper function -// for child classes. - -int -Statement::traverse_expression(Traverse* traverse, Expression** expr) -{ - if ((traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) == 0) - return TRAVERSE_CONTINUE; - return Expression::traverse(expr, traverse); -} - -// Traverse an expression list in a statement. This is a helper -// function for child classes. - -int -Statement::traverse_expression_list(Traverse* traverse, - Expression_list* expr_list) -{ - if (expr_list == NULL) - return TRAVERSE_CONTINUE; - if ((traverse->traverse_mask() & Traverse::traverse_expressions) == 0) - return TRAVERSE_CONTINUE; - return expr_list->traverse(traverse); -} - -// Traverse a type in a statement. This is a helper function for -// child classes. - -int -Statement::traverse_type(Traverse* traverse, Type* type) -{ - if ((traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) == 0) - return TRAVERSE_CONTINUE; - return Type::traverse(type, traverse); -} - -// Set type information for unnamed constants. This is really done by -// the child class. - -void -Statement::determine_types() -{ - this->do_determine_types(); -} - -// If this is a thunk statement, return it. - -Thunk_statement* -Statement::thunk_statement() -{ - Thunk_statement* ret = this->convert(); - if (ret == NULL) - ret = this->convert(); - return ret; -} - -// Get a tree for a Statement. This is really done by the child -// class. - -tree -Statement::get_tree(Translate_context* context) -{ - if (this->classification_ == STATEMENT_ERROR) - return error_mark_node; - - return this->do_get_tree(context); -} - -// Build tree nodes and set locations. - -tree -Statement::build_stmt_1(int tree_code_value, tree node) -{ - tree ret = build1(static_cast(tree_code_value), - void_type_node, node); - SET_EXPR_LOCATION(ret, this->location_); - return ret; -} - -// Note that this statement is erroneous. This is called by children -// when they discover an error. - -void -Statement::set_is_error() -{ - this->classification_ = STATEMENT_ERROR; -} - -// For children to call to report an error conveniently. - -void -Statement::report_error(const char* msg) -{ - error_at(this->location_, "%s", msg); - this->set_is_error(); -} - -// An error statement, used to avoid crashing after we report an -// error. - -class Error_statement : public Statement -{ - public: - Error_statement(source_location location) - : Statement(STATEMENT_ERROR, location) - { } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } -}; - -// Make an error statement. - -Statement* -Statement::make_error_statement(source_location location) -{ - return new Error_statement(location); -} - -// Class Variable_declaration_statement. - -Variable_declaration_statement::Variable_declaration_statement( - Named_object* var) - : Statement(STATEMENT_VARIABLE_DECLARATION, var->var_value()->location()), - var_(var) -{ -} - -// We don't actually traverse the variable here; it was traversed -// while traversing the Block. - -int -Variable_declaration_statement::do_traverse(Traverse*) -{ - return TRAVERSE_CONTINUE; -} - -// Traverse the assignments in a variable declaration. Note that this -// traversal is different from the usual traversal. - -bool -Variable_declaration_statement::do_traverse_assignments( - Traverse_assignments* tassign) -{ - tassign->initialize_variable(this->var_); - return true; -} - -// Return the tree for a variable declaration. - -tree -Variable_declaration_statement::do_get_tree(Translate_context* context) -{ - tree val = this->var_->get_tree(context->gogo(), context->function()); - if (val == error_mark_node || TREE_TYPE(val) == error_mark_node) - return error_mark_node; - Variable* variable = this->var_->var_value(); - - tree init = variable->get_init_tree(context->gogo(), context->function()); - if (init == error_mark_node) - return error_mark_node; - - // If this variable lives on the heap, we need to allocate it now. - if (!variable->is_in_heap()) - { - DECL_INITIAL(val) = init; - return this->build_stmt_1(DECL_EXPR, val); - } - else - { - gcc_assert(TREE_CODE(val) == INDIRECT_REF); - tree decl = TREE_OPERAND(val, 0); - gcc_assert(TREE_CODE(decl) == VAR_DECL); - tree type = TREE_TYPE(decl); - gcc_assert(POINTER_TYPE_P(type)); - tree size = TYPE_SIZE_UNIT(TREE_TYPE(type)); - tree space = context->gogo()->allocate_memory(variable->type(), size, - this->location()); - space = fold_convert(TREE_TYPE(decl), space); - DECL_INITIAL(decl) = space; - return build2(COMPOUND_EXPR, void_type_node, - this->build_stmt_1(DECL_EXPR, decl), - build2(MODIFY_EXPR, void_type_node, val, init)); - } -} - -// Make a variable declaration. - -Statement* -Statement::make_variable_declaration(Named_object* var) -{ - return new Variable_declaration_statement(var); -} - -// Class Temporary_statement. - -// Return the type of the temporary variable. - -Type* -Temporary_statement::type() const -{ - return this->type_ != NULL ? this->type_ : this->init_->type(); -} - -// Traversal. - -int -Temporary_statement::do_traverse(Traverse* traverse) -{ - if (this->init_ == NULL) - return TRAVERSE_CONTINUE; - else - return this->traverse_expression(traverse, &this->init_); -} - -// Traverse assignments. - -bool -Temporary_statement::do_traverse_assignments(Traverse_assignments* tassign) -{ - if (this->init_ == NULL) - return false; - tassign->value(&this->init_, true, true); - return true; -} - -// Determine types. - -void -Temporary_statement::do_determine_types() -{ - if (this->init_ != NULL) - { - if (this->type_ == NULL) - this->init_->determine_type_no_context(); - else - { - Type_context context(this->type_, false); - this->init_->determine_type(&context); - } - } - - if (this->type_ == NULL) - this->type_ = this->init_->type(); - - if (this->type_->is_abstract()) - this->type_ = this->type_->make_non_abstract_type(); -} - -// Check types. - -void -Temporary_statement::do_check_types(Gogo*) -{ - if (this->type_ != NULL && this->init_ != NULL) - gcc_assert(Type::are_assignable(this->type_, this->init_->type(), NULL)); -} - -// Return a tree. - -tree -Temporary_statement::do_get_tree(Translate_context* context) -{ - gcc_assert(this->decl_ == NULL_TREE); - tree type_tree = this->type()->get_tree(context->gogo()); - if (type_tree == error_mark_node) - { - this->decl_ = error_mark_node; - return error_mark_node; - } - // We can only use create_tmp_var if the type is not addressable. - if (!TREE_ADDRESSABLE(type_tree)) - { - this->decl_ = create_tmp_var(type_tree, "GOTMP"); - DECL_SOURCE_LOCATION(this->decl_) = this->location(); - } - else - { - gcc_assert(context->function() != NULL && context->block() != NULL); - tree decl = build_decl(this->location(), VAR_DECL, - create_tmp_var_name("GOTMP"), - type_tree); - DECL_ARTIFICIAL(decl) = 1; - DECL_IGNORED_P(decl) = 1; - TREE_USED(decl) = 1; - gcc_assert(current_function_decl != NULL_TREE); - DECL_CONTEXT(decl) = current_function_decl; - - // We have to add this variable to the block so that it winds up - // in a BIND_EXPR. - tree block_tree = context->block_tree(); - gcc_assert(block_tree != NULL_TREE); - DECL_CHAIN(decl) = BLOCK_VARS(block_tree); - BLOCK_VARS(block_tree) = decl; - - this->decl_ = decl; - } - if (this->init_ != NULL) - DECL_INITIAL(this->decl_) = - Expression::convert_for_assignment(context, this->type(), - this->init_->type(), - this->init_->get_tree(context), - this->location()); - if (this->is_address_taken_) - TREE_ADDRESSABLE(this->decl_) = 1; - return this->build_stmt_1(DECL_EXPR, this->decl_); -} - -// Make and initialize a temporary variable in BLOCK. - -Temporary_statement* -Statement::make_temporary(Type* type, Expression* init, - source_location location) -{ - return new Temporary_statement(type, init, location); -} - -// An assignment statement. - -class Assignment_statement : public Statement -{ - public: - Assignment_statement(Expression* lhs, Expression* rhs, - source_location location) - : Statement(STATEMENT_ASSIGNMENT, location), - lhs_(lhs), rhs_(rhs) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - tree - do_get_tree(Translate_context*); - - private: - // Left hand side--the lvalue. - Expression* lhs_; - // Right hand side--the rvalue. - Expression* rhs_; -}; - -// Traversal. - -int -Assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->lhs_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->rhs_); -} - -bool -Assignment_statement::do_traverse_assignments(Traverse_assignments* tassign) -{ - tassign->assignment(&this->lhs_, &this->rhs_); - return true; -} - -// Set types for the assignment. - -void -Assignment_statement::do_determine_types() -{ - this->lhs_->determine_type_no_context(); - Type_context context(this->lhs_->type(), false); - this->rhs_->determine_type(&context); -} - -// Check types for an assignment. - -void -Assignment_statement::do_check_types(Gogo*) -{ - // The left hand side must be either addressable, a map index - // expression, or the blank identifier. - if (!this->lhs_->is_addressable() - && this->lhs_->map_index_expression() == NULL - && !this->lhs_->is_sink_expression()) - { - if (!this->lhs_->type()->is_error_type()) - this->report_error(_("invalid left hand side of assignment")); - return; - } - - Type* lhs_type = this->lhs_->type(); - Type* rhs_type = this->rhs_->type(); - std::string reason; - if (!Type::are_assignable(lhs_type, rhs_type, &reason)) - { - if (reason.empty()) - error_at(this->location(), "incompatible types in assignment"); - else - error_at(this->location(), "incompatible types in assignment (%s)", - reason.c_str()); - this->set_is_error(); - } - - if (lhs_type->is_error_type() - || rhs_type->is_error_type() - || lhs_type->is_undefined() - || rhs_type->is_undefined()) - { - // Make sure we get the error for an undefined type. - lhs_type->base(); - rhs_type->base(); - this->set_is_error(); - } -} - -// Build a tree for an assignment statement. - -tree -Assignment_statement::do_get_tree(Translate_context* context) -{ - tree rhs_tree = this->rhs_->get_tree(context); - - if (this->lhs_->is_sink_expression()) - return rhs_tree; - - tree lhs_tree = this->lhs_->get_tree(context); - - if (lhs_tree == error_mark_node || rhs_tree == error_mark_node) - return error_mark_node; - - rhs_tree = Expression::convert_for_assignment(context, this->lhs_->type(), - this->rhs_->type(), rhs_tree, - this->location()); - if (rhs_tree == error_mark_node) - return error_mark_node; - - return fold_build2_loc(this->location(), MODIFY_EXPR, void_type_node, - lhs_tree, rhs_tree); -} - -// Make an assignment statement. - -Statement* -Statement::make_assignment(Expression* lhs, Expression* rhs, - source_location location) -{ - return new Assignment_statement(lhs, rhs, location); -} - -// The Move_ordered_evals class is used to find any subexpressions of -// an expression that have an evaluation order dependency. It creates -// temporary variables to hold them. - -class Move_ordered_evals : public Traverse -{ - public: - Move_ordered_evals(Block* block) - : Traverse(traverse_expressions), - block_(block) - { } - - protected: - int - expression(Expression**); - - private: - // The block where new temporary variables should be added. - Block* block_; -}; - -int -Move_ordered_evals::expression(Expression** pexpr) -{ - // We have to look at subexpressions first. - if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if ((*pexpr)->must_eval_in_order()) - { - source_location loc = (*pexpr)->location(); - Temporary_statement* temp = Statement::make_temporary(NULL, *pexpr, loc); - this->block_->add_statement(temp); - *pexpr = Expression::make_temporary_reference(temp, loc); - } - return TRAVERSE_SKIP_COMPONENTS; -} - -// An assignment operation statement. - -class Assignment_operation_statement : public Statement -{ - public: - Assignment_operation_statement(Operator op, Expression* lhs, Expression* rhs, - source_location location) - : Statement(STATEMENT_ASSIGNMENT_OPERATION, location), - op_(op), lhs_(lhs), rhs_(rhs) - { } - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // The operator (OPERATOR_PLUSEQ, etc.). - Operator op_; - // Left hand side. - Expression* lhs_; - // Right hand side. - Expression* rhs_; -}; - -// Traversal. - -int -Assignment_operation_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->lhs_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->rhs_); -} - -// Lower an assignment operation statement to a regular assignment -// statement. - -Statement* -Assignment_operation_statement::do_lower(Gogo*, Block* enclosing) -{ - source_location loc = this->location(); - - // We have to evaluate the left hand side expression only once. We - // do this by moving out any expression with side effects. - Block* b = new Block(enclosing, loc); - Move_ordered_evals moe(b); - this->lhs_->traverse_subexpressions(&moe); - - Expression* lval = this->lhs_->copy(); - - Operator op; - switch (this->op_) - { - case OPERATOR_PLUSEQ: - op = OPERATOR_PLUS; - break; - case OPERATOR_MINUSEQ: - op = OPERATOR_MINUS; - break; - case OPERATOR_OREQ: - op = OPERATOR_OR; - break; - case OPERATOR_XOREQ: - op = OPERATOR_XOR; - break; - case OPERATOR_MULTEQ: - op = OPERATOR_MULT; - break; - case OPERATOR_DIVEQ: - op = OPERATOR_DIV; - break; - case OPERATOR_MODEQ: - op = OPERATOR_MOD; - break; - case OPERATOR_LSHIFTEQ: - op = OPERATOR_LSHIFT; - break; - case OPERATOR_RSHIFTEQ: - op = OPERATOR_RSHIFT; - break; - case OPERATOR_ANDEQ: - op = OPERATOR_AND; - break; - case OPERATOR_BITCLEAREQ: - op = OPERATOR_BITCLEAR; - break; - default: - gcc_unreachable(); - } - - Expression* binop = Expression::make_binary(op, lval, this->rhs_, loc); - Statement* s = Statement::make_assignment(this->lhs_, binop, loc); - if (b->statements()->empty()) - { - delete b; - return s; - } - else - { - b->add_statement(s); - return Statement::make_block_statement(b, loc); - } -} - -// Make an assignment operation statement. - -Statement* -Statement::make_assignment_operation(Operator op, Expression* lhs, - Expression* rhs, source_location location) -{ - return new Assignment_operation_statement(op, lhs, rhs, location); -} - -// A tuple assignment statement. This differs from an assignment -// statement in that the right-hand-side expressions are evaluated in -// parallel. - -class Tuple_assignment_statement : public Statement -{ - public: - Tuple_assignment_statement(Expression_list* lhs, Expression_list* rhs, - source_location location) - : Statement(STATEMENT_TUPLE_ASSIGNMENT, location), - lhs_(lhs), rhs_(rhs) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // Left hand side--a list of lvalues. - Expression_list* lhs_; - // Right hand side--a list of rvalues. - Expression_list* rhs_; -}; - -// Traversal. - -int -Tuple_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression_list(traverse, this->lhs_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression_list(traverse, this->rhs_); -} - -// Lower a tuple assignment. We use temporary variables to split it -// up into a set of single assignments. - -Statement* -Tuple_assignment_statement::do_lower(Gogo*, Block* enclosing) -{ - source_location loc = this->location(); - - Block* b = new Block(enclosing, loc); - - // First move out any subexpressions on the left hand side. The - // right hand side will be evaluated in the required order anyhow. - Move_ordered_evals moe(b); - for (Expression_list::const_iterator plhs = this->lhs_->begin(); - plhs != this->lhs_->end(); - ++plhs) - (*plhs)->traverse_subexpressions(&moe); - - std::vector temps; - temps.reserve(this->lhs_->size()); - - Expression_list::const_iterator prhs = this->rhs_->begin(); - for (Expression_list::const_iterator plhs = this->lhs_->begin(); - plhs != this->lhs_->end(); - ++plhs, ++prhs) - { - gcc_assert(prhs != this->rhs_->end()); - - if ((*plhs)->is_sink_expression()) - { - b->add_statement(Statement::make_statement(*prhs)); - continue; - } - - Temporary_statement* temp = Statement::make_temporary((*plhs)->type(), - *prhs, loc); - b->add_statement(temp); - temps.push_back(temp); - - } - gcc_assert(prhs == this->rhs_->end()); - - prhs = this->rhs_->begin(); - std::vector::const_iterator ptemp = temps.begin(); - for (Expression_list::const_iterator plhs = this->lhs_->begin(); - plhs != this->lhs_->end(); - ++plhs, ++prhs) - { - if ((*plhs)->is_sink_expression()) - continue; - - Expression* ref = Expression::make_temporary_reference(*ptemp, loc); - Statement* s = Statement::make_assignment(*plhs, ref, loc); - b->add_statement(s); - ++ptemp; - } - gcc_assert(ptemp == temps.end()); - - return Statement::make_block_statement(b, loc); -} - -// Make a tuple assignment statement. - -Statement* -Statement::make_tuple_assignment(Expression_list* lhs, Expression_list* rhs, - source_location location) -{ - return new Tuple_assignment_statement(lhs, rhs, location); -} - -// A tuple assignment from a map index expression. -// v, ok = m[k] - -class Tuple_map_assignment_statement : public Statement -{ -public: - Tuple_map_assignment_statement(Expression* val, Expression* present, - Expression* map_index, - source_location location) - : Statement(STATEMENT_TUPLE_MAP_ASSIGNMENT, location), - val_(val), present_(present), map_index_(map_index) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // Lvalue which receives the value from the map. - Expression* val_; - // Lvalue which receives whether the key value was present. - Expression* present_; - // The map index expression. - Expression* map_index_; -}; - -// Traversal. - -int -Tuple_map_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT - || this->traverse_expression(traverse, &this->present_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->map_index_); -} - -// Lower a tuple map assignment. - -Statement* -Tuple_map_assignment_statement::do_lower(Gogo*, Block* enclosing) -{ - source_location loc = this->location(); - - Map_index_expression* map_index = this->map_index_->map_index_expression(); - if (map_index == NULL) - { - this->report_error(_("expected map index on right hand side")); - return Statement::make_error_statement(loc); - } - Map_type* map_type = map_index->get_map_type(); - - Block* b = new Block(enclosing, loc); - - // Move out any subexpressions to make sure that functions are - // called in the required order. - Move_ordered_evals moe(b); - this->val_->traverse_subexpressions(&moe); - this->present_->traverse_subexpressions(&moe); - - // Copy the key value into a temporary so that we can take its - // address without pushing the value onto the heap. - - // var key_temp KEY_TYPE = MAP_INDEX - Temporary_statement* key_temp = - Statement::make_temporary(map_type->key_type(), map_index->index(), loc); - b->add_statement(key_temp); - - // var val_temp VAL_TYPE - Temporary_statement* val_temp = - Statement::make_temporary(map_type->val_type(), NULL, loc); - b->add_statement(val_temp); - - // var present_temp bool - Temporary_statement* present_temp = - Statement::make_temporary(Type::lookup_bool_type(), NULL, loc); - b->add_statement(present_temp); - - // func mapaccess2(hmap map[k]v, key *k, val *v) bool - source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("hmap", map_type, bloc)); - Type* pkey_type = Type::make_pointer_type(map_type->key_type()); - param_types->push_back(Typed_identifier("key", pkey_type, bloc)); - Type* pval_type = Type::make_pointer_type(map_type->val_type()); - param_types->push_back(Typed_identifier("val", pval_type, bloc)); - - Typed_identifier_list* ret_types = new Typed_identifier_list(); - ret_types->push_back(Typed_identifier("", Type::make_boolean_type(), bloc)); - - Function_type* fntype = Type::make_function_type(NULL, param_types, - ret_types, bloc); - Named_object* mapaccess2 = - Named_object::make_function_declaration("mapaccess2", NULL, fntype, bloc); - mapaccess2->func_declaration_value()->set_asm_name("runtime.mapaccess2"); - - // present_temp = mapaccess2(MAP, &key_temp, &val_temp) - Expression* func = Expression::make_func_reference(mapaccess2, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(map_index->map()); - Expression* ref = Expression::make_temporary_reference(key_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - ref = Expression::make_temporary_reference(val_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - Expression* call = Expression::make_call(func, params, false, loc); - - ref = Expression::make_temporary_reference(present_temp, loc); - Statement* s = Statement::make_assignment(ref, call, loc); - b->add_statement(s); - - // val = val_temp - ref = Expression::make_temporary_reference(val_temp, loc); - s = Statement::make_assignment(this->val_, ref, loc); - b->add_statement(s); - - // present = present_temp - ref = Expression::make_temporary_reference(present_temp, loc); - s = Statement::make_assignment(this->present_, ref, loc); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Make a map assignment statement which returns a pair of values. - -Statement* -Statement::make_tuple_map_assignment(Expression* val, Expression* present, - Expression* map_index, - source_location location) -{ - return new Tuple_map_assignment_statement(val, present, map_index, location); -} - -// Assign a pair of entries to a map. -// m[k] = v, p - -class Map_assignment_statement : public Statement -{ - public: - Map_assignment_statement(Expression* map_index, - Expression* val, Expression* should_set, - source_location location) - : Statement(STATEMENT_MAP_ASSIGNMENT, location), - map_index_(map_index), val_(val), should_set_(should_set) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // A reference to the map index which should be set or deleted. - Expression* map_index_; - // The value to add to the map. - Expression* val_; - // Whether or not to add the value. - Expression* should_set_; -}; - -// Traverse a map assignment. - -int -Map_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->map_index_) == TRAVERSE_EXIT - || this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->should_set_); -} - -// Lower a map assignment to a function call. - -Statement* -Map_assignment_statement::do_lower(Gogo*, Block* enclosing) -{ - source_location loc = this->location(); - - Map_index_expression* map_index = this->map_index_->map_index_expression(); - if (map_index == NULL) - { - this->report_error(_("expected map index on left hand side")); - return Statement::make_error_statement(loc); - } - Map_type* map_type = map_index->get_map_type(); - - Block* b = new Block(enclosing, loc); - - // Evaluate the map first to get order of evaluation right. - // map_temp := m // we are evaluating m[k] = v, p - Temporary_statement* map_temp = Statement::make_temporary(map_type, - map_index->map(), - loc); - b->add_statement(map_temp); - - // var key_temp MAP_KEY_TYPE = k - Temporary_statement* key_temp = - Statement::make_temporary(map_type->key_type(), map_index->index(), loc); - b->add_statement(key_temp); - - // var val_temp MAP_VAL_TYPE = v - Temporary_statement* val_temp = - Statement::make_temporary(map_type->val_type(), this->val_, loc); - b->add_statement(val_temp); - - // func mapassign2(hmap map[k]v, key *k, val *v, p) - source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("hmap", map_type, bloc)); - Type* pkey_type = Type::make_pointer_type(map_type->key_type()); - param_types->push_back(Typed_identifier("key", pkey_type, bloc)); - Type* pval_type = Type::make_pointer_type(map_type->val_type()); - param_types->push_back(Typed_identifier("val", pval_type, bloc)); - param_types->push_back(Typed_identifier("p", Type::lookup_bool_type(), bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, - NULL, bloc); - Named_object* mapassign2 = - Named_object::make_function_declaration("mapassign2", NULL, fntype, bloc); - mapassign2->func_declaration_value()->set_asm_name("runtime.mapassign2"); - - // mapassign2(map_temp, &key_temp, &val_temp, p) - Expression* func = Expression::make_func_reference(mapassign2, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(Expression::make_temporary_reference(map_temp, loc)); - Expression* ref = Expression::make_temporary_reference(key_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - ref = Expression::make_temporary_reference(val_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - params->push_back(this->should_set_); - Expression* call = Expression::make_call(func, params, false, loc); - Statement* s = Statement::make_statement(call); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Make a statement which assigns a pair of entries to a map. - -Statement* -Statement::make_map_assignment(Expression* map_index, - Expression* val, Expression* should_set, - source_location location) -{ - return new Map_assignment_statement(map_index, val, should_set, location); -} - -// A tuple assignment from a receive statement. - -class Tuple_receive_assignment_statement : public Statement -{ - public: - Tuple_receive_assignment_statement(Expression* val, Expression* success, - Expression* channel, - source_location location) - : Statement(STATEMENT_TUPLE_RECEIVE_ASSIGNMENT, location), - val_(val), success_(success), channel_(channel) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // Lvalue which receives the value from the channel. - Expression* val_; - // Lvalue which receives whether the read succeeded or failed. - Expression* success_; - // The channel on which we receive the value. - Expression* channel_; -}; - -// Traversal. - -int -Tuple_receive_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT - || this->traverse_expression(traverse, &this->success_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->channel_); -} - -// Lower to a function call. - -Statement* -Tuple_receive_assignment_statement::do_lower(Gogo*, Block* enclosing) -{ - source_location loc = this->location(); - - Channel_type* channel_type = this->channel_->type()->channel_type(); - if (channel_type == NULL) - { - this->report_error(_("expected channel")); - return Statement::make_error_statement(loc); - } - if (!channel_type->may_receive()) - { - this->report_error(_("invalid receive on send-only channel")); - return Statement::make_error_statement(loc); - } - - Block* b = new Block(enclosing, loc); - - // Make sure that any subexpressions on the left hand side are - // evaluated in the right order. - Move_ordered_evals moe(b); - this->val_->traverse_subexpressions(&moe); - this->success_->traverse_subexpressions(&moe); - - // var val_temp ELEMENT_TYPE - Temporary_statement* val_temp = - Statement::make_temporary(channel_type->element_type(), NULL, loc); - b->add_statement(val_temp); - - // var success_temp bool - Temporary_statement* success_temp = - Statement::make_temporary(Type::lookup_bool_type(), NULL, loc); - b->add_statement(success_temp); - - // func chanrecv2(c chan T, val *T) bool - source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("c", channel_type, bloc)); - Type* pelement_type = Type::make_pointer_type(channel_type->element_type()); - param_types->push_back(Typed_identifier("val", pelement_type, bloc)); - - Typed_identifier_list* ret_types = new Typed_identifier_list(); - ret_types->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc)); - - Function_type* fntype = Type::make_function_type(NULL, param_types, - ret_types, bloc); - Named_object* chanrecv2 = - Named_object::make_function_declaration("chanrecv2", NULL, fntype, bloc); - chanrecv2->func_declaration_value()->set_asm_name("runtime.chanrecv2"); - - // success_temp = chanrecv2(channel, &val_temp) - Expression* func = Expression::make_func_reference(chanrecv2, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(this->channel_); - Expression* ref = Expression::make_temporary_reference(val_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - Expression* call = Expression::make_call(func, params, false, loc); - ref = Expression::make_temporary_reference(success_temp, loc); - Statement* s = Statement::make_assignment(ref, call, loc); - b->add_statement(s); - - // val = val_temp - ref = Expression::make_temporary_reference(val_temp, loc); - s = Statement::make_assignment(this->val_, ref, loc); - b->add_statement(s); - - // success = success_temp - ref = Expression::make_temporary_reference(success_temp, loc); - s = Statement::make_assignment(this->success_, ref, loc); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Make a nonblocking receive statement. - -Statement* -Statement::make_tuple_receive_assignment(Expression* val, Expression* success, - Expression* channel, - source_location location) -{ - return new Tuple_receive_assignment_statement(val, success, channel, - location); -} - -// An assignment to a pair of values from a type guard. This is a -// conditional type guard. v, ok = i.(type). - -class Tuple_type_guard_assignment_statement : public Statement -{ - public: - Tuple_type_guard_assignment_statement(Expression* val, Expression* ok, - Expression* expr, Type* type, - source_location location) - : Statement(STATEMENT_TUPLE_TYPE_GUARD_ASSIGNMENT, location), - val_(val), ok_(ok), expr_(expr), type_(type) - { } - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - Call_expression* - lower_to_empty_interface(const char*); - - Call_expression* - lower_to_type(const char*); - - void - lower_to_object_type(Block*, const char*); - - // The variable which recieves the converted value. - Expression* val_; - // The variable which receives the indication of success. - Expression* ok_; - // The expression being converted. - Expression* expr_; - // The type to which the expression is being converted. - Type* type_; -}; - -// Traverse a type guard tuple assignment. - -int -Tuple_type_guard_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT - || this->traverse_expression(traverse, &this->ok_) == TRAVERSE_EXIT - || this->traverse_type(traverse, this->type_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->expr_); -} - -// Lower to a function call. - -Statement* -Tuple_type_guard_assignment_statement::do_lower(Gogo*, Block* enclosing) -{ - source_location loc = this->location(); - - Type* expr_type = this->expr_->type(); - if (expr_type->interface_type() == NULL) - { - this->report_error(_("type assertion only valid for interface types")); - return Statement::make_error_statement(loc); - } - - Block* b = new Block(enclosing, loc); - - // Make sure that any subexpressions on the left hand side are - // evaluated in the right order. - Move_ordered_evals moe(b); - this->val_->traverse_subexpressions(&moe); - this->ok_->traverse_subexpressions(&moe); - - bool expr_is_empty = expr_type->interface_type()->is_empty(); - Call_expression* call; - if (this->type_->interface_type() != NULL) - { - if (this->type_->interface_type()->is_empty()) - call = this->lower_to_empty_interface(expr_is_empty - ? "ifaceE2E2" - : "ifaceI2E2"); - else - call = this->lower_to_type(expr_is_empty ? "ifaceE2I2" : "ifaceI2I2"); - } - else if (this->type_->points_to() != NULL) - call = this->lower_to_type(expr_is_empty ? "ifaceE2T2P" : "ifaceI2T2P"); - else - { - this->lower_to_object_type(b, expr_is_empty ? "ifaceE2T2" : "ifaceI2T2"); - call = NULL; - } - - if (call != NULL) - { - Expression* res = Expression::make_call_result(call, 0); - Statement* s = Statement::make_assignment(this->val_, res, loc); - b->add_statement(s); - - res = Expression::make_call_result(call, 1); - s = Statement::make_assignment(this->ok_, res, loc); - b->add_statement(s); - } - - return Statement::make_block_statement(b, loc); -} - -// Lower a conversion to an empty interface type. - -Call_expression* -Tuple_type_guard_assignment_statement::lower_to_empty_interface( - const char *fnname) -{ - source_location loc = this->location(); - - // func FNNAME(interface) (empty, bool) - source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("i", this->expr_->type(), bloc)); - Typed_identifier_list* ret_types = new Typed_identifier_list(); - ret_types->push_back(Typed_identifier("ret", this->type_, bloc)); - ret_types->push_back(Typed_identifier("ok", Type::lookup_bool_type(), bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, - ret_types, bloc); - Named_object* fn = - Named_object::make_function_declaration(fnname, NULL, fntype, bloc); - std::string asm_name = "runtime."; - asm_name += fnname; - fn->func_declaration_value()->set_asm_name(asm_name); - - // val, ok = FNNAME(expr) - Expression* func = Expression::make_func_reference(fn, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(this->expr_); - return Expression::make_call(func, params, false, loc); -} - -// Lower a conversion to a non-empty interface type or a pointer type. - -Call_expression* -Tuple_type_guard_assignment_statement::lower_to_type(const char* fnname) -{ - source_location loc = this->location(); - - // func FNNAME(*descriptor, interface) (interface, bool) - source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("inter", - Type::make_type_descriptor_ptr_type(), - bloc)); - param_types->push_back(Typed_identifier("i", this->expr_->type(), bloc)); - Typed_identifier_list* ret_types = new Typed_identifier_list(); - ret_types->push_back(Typed_identifier("ret", this->type_, bloc)); - ret_types->push_back(Typed_identifier("ok", Type::lookup_bool_type(), bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, - ret_types, bloc); - Named_object* fn = - Named_object::make_function_declaration(fnname, NULL, fntype, bloc); - std::string asm_name = "runtime."; - asm_name += fnname; - fn->func_declaration_value()->set_asm_name(asm_name); - - // val, ok = FNNAME(type_descriptor, expr) - Expression* func = Expression::make_func_reference(fn, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(Expression::make_type_descriptor(this->type_, loc)); - params->push_back(this->expr_); - return Expression::make_call(func, params, false, loc); -} - -// Lower a conversion to a non-interface non-pointer type. - -void -Tuple_type_guard_assignment_statement::lower_to_object_type(Block* b, - const char *fnname) -{ - source_location loc = this->location(); - - // var val_temp TYPE - Temporary_statement* val_temp = Statement::make_temporary(this->type_, - NULL, loc); - b->add_statement(val_temp); - - // func FNNAME(*descriptor, interface, *T) bool - source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("inter", - Type::make_type_descriptor_ptr_type(), - bloc)); - param_types->push_back(Typed_identifier("i", this->expr_->type(), bloc)); - Type* ptype = Type::make_pointer_type(this->type_); - param_types->push_back(Typed_identifier("v", ptype, bloc)); - Typed_identifier_list* ret_types = new Typed_identifier_list(); - ret_types->push_back(Typed_identifier("ok", Type::lookup_bool_type(), bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, - ret_types, bloc); - Named_object* fn = - Named_object::make_function_declaration(fnname, NULL, fntype, bloc); - std::string asm_name = "runtime."; - asm_name += fnname; - fn->func_declaration_value()->set_asm_name(asm_name); - - // ok = FNNAME(type_descriptor, expr, &val_temp) - Expression* func = Expression::make_func_reference(fn, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(Expression::make_type_descriptor(this->type_, loc)); - params->push_back(this->expr_); - Expression* ref = Expression::make_temporary_reference(val_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - Expression* call = Expression::make_call(func, params, false, loc); - Statement* s = Statement::make_assignment(this->ok_, call, loc); - b->add_statement(s); - - // val = val_temp - ref = Expression::make_temporary_reference(val_temp, loc); - s = Statement::make_assignment(this->val_, ref, loc); - b->add_statement(s); -} - -// Make an assignment from a type guard to a pair of variables. - -Statement* -Statement::make_tuple_type_guard_assignment(Expression* val, Expression* ok, - Expression* expr, Type* type, - source_location location) -{ - return new Tuple_type_guard_assignment_statement(val, ok, expr, type, - location); -} - -// An expression statement. - -class Expression_statement : public Statement -{ - public: - Expression_statement(Expression* expr) - : Statement(STATEMENT_EXPRESSION, expr->location()), - expr_(expr) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return this->traverse_expression(traverse, &this->expr_); } - - void - do_determine_types() - { this->expr_->determine_type_no_context(); } - - bool - do_may_fall_through() const; - - tree - do_get_tree(Translate_context* context) - { return this->expr_->get_tree(context); } - - private: - Expression* expr_; -}; - -// An expression statement may fall through unless it is a call to a -// function which does not return. - -bool -Expression_statement::do_may_fall_through() const -{ - const Call_expression* call = this->expr_->call_expression(); - if (call != NULL) - { - const Expression* fn = call->fn(); - const Func_expression* fe = fn->func_expression(); - if (fe != NULL) - { - const Named_object* no = fe->named_object(); - - Function_type* fntype; - if (no->is_function()) - fntype = no->func_value()->type(); - else if (no->is_function_declaration()) - fntype = no->func_declaration_value()->type(); - else - fntype = NULL; - - // The builtin function panic does not return. - if (fntype != NULL && fntype->is_builtin() && no->name() == "panic") - return false; - } - } - return true; -} - -// Make an expression statement from an Expression. - -Statement* -Statement::make_statement(Expression* expr) -{ - return new Expression_statement(expr); -} - -// A block statement--a list of statements which may include variable -// definitions. - -class Block_statement : public Statement -{ - public: - Block_statement(Block* block, source_location location) - : Statement(STATEMENT_BLOCK, location), - block_(block) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return this->block_->traverse(traverse); } - - void - do_determine_types() - { this->block_->determine_types(); } - - bool - do_may_fall_through() const - { return this->block_->may_fall_through(); } - - tree - do_get_tree(Translate_context* context) - { return this->block_->get_tree(context); } - - private: - Block* block_; -}; - -// Make a block statement. - -Statement* -Statement::make_block_statement(Block* block, source_location location) -{ - return new Block_statement(block, location); -} - -// An increment or decrement statement. - -class Inc_dec_statement : public Statement -{ - public: - Inc_dec_statement(bool is_inc, Expression* expr) - : Statement(STATEMENT_INCDEC, expr->location()), - expr_(expr), is_inc_(is_inc) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return this->traverse_expression(traverse, &this->expr_); } - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // The l-value to increment or decrement. - Expression* expr_; - // Whether to increment or decrement. - bool is_inc_; -}; - -// Lower to += or -=. - -Statement* -Inc_dec_statement::do_lower(Gogo*, Block*) -{ - source_location loc = this->location(); - - mpz_t oval; - mpz_init_set_ui(oval, 1UL); - Expression* oexpr = Expression::make_integer(&oval, NULL, loc); - mpz_clear(oval); - - Operator op = this->is_inc_ ? OPERATOR_PLUSEQ : OPERATOR_MINUSEQ; - return Statement::make_assignment_operation(op, this->expr_, oexpr, loc); -} - -// Make an increment statement. - -Statement* -Statement::make_inc_statement(Expression* expr) -{ - return new Inc_dec_statement(true, expr); -} - -// Make a decrement statement. - -Statement* -Statement::make_dec_statement(Expression* expr) -{ - return new Inc_dec_statement(false, expr); -} - -// Class Thunk_statement. This is the base class for go and defer -// statements. - -const char* const Thunk_statement::thunk_field_fn = "fn"; - -const char* const Thunk_statement::thunk_field_receiver = "receiver"; - -// Constructor. - -Thunk_statement::Thunk_statement(Statement_classification classification, - Call_expression* call, - source_location location) - : Statement(classification, location), - call_(call), struct_type_(NULL) -{ -} - -// Return whether this is a simple statement which does not require a -// thunk. - -bool -Thunk_statement::is_simple(Function_type* fntype) const -{ - // We need a thunk to call a method, or to pass a variable number of - // arguments. - if (fntype->is_method() || fntype->is_varargs()) - return false; - - // A defer statement requires a thunk to set up for whether the - // function can call recover. - if (this->classification() == STATEMENT_DEFER) - return false; - - // We can only permit a single parameter of pointer type. - const Typed_identifier_list* parameters = fntype->parameters(); - if (parameters != NULL - && (parameters->size() > 1 - || (parameters->size() == 1 - && parameters->begin()->type()->points_to() == NULL))) - return false; - - // If the function returns multiple values, or returns a type other - // than integer, floating point, or pointer, then it may get a - // hidden first parameter, in which case we need the more - // complicated approach. This is true even though we are going to - // ignore the return value. - const Typed_identifier_list* results = fntype->results(); - if (results != NULL - && (results->size() > 1 - || (results->size() == 1 - && !results->begin()->type()->is_basic_type() - && results->begin()->type()->points_to() == NULL))) - return false; - - // If this calls something which is not a simple function, then we - // need a thunk. - Expression* fn = this->call_->call_expression()->fn(); - if (fn->bound_method_expression() != NULL - || fn->interface_field_reference_expression() != NULL) - return false; - - return true; -} - -// Traverse a thunk statement. - -int -Thunk_statement::do_traverse(Traverse* traverse) -{ - return this->traverse_expression(traverse, &this->call_); -} - -// We implement traverse_assignment for a thunk statement because it -// effectively copies the function call. - -bool -Thunk_statement::do_traverse_assignments(Traverse_assignments* tassign) -{ - Expression* fn = this->call_->call_expression()->fn(); - Expression* fn2 = fn; - tassign->value(&fn2, true, false); - return true; -} - -// Determine types in a thunk statement. - -void -Thunk_statement::do_determine_types() -{ - this->call_->determine_type_no_context(); - - // Now that we know the types of the call, build the struct used to - // pass parameters. - Function_type* fntype = - this->call_->call_expression()->get_function_type(); - if (fntype != NULL && !this->is_simple(fntype)) - this->struct_type_ = this->build_struct(fntype); -} - -// Check types in a thunk statement. - -void -Thunk_statement::do_check_types(Gogo*) -{ - Call_expression* ce = this->call_->call_expression(); - Function_type* fntype = ce->get_function_type(); - if (fntype != NULL && fntype->is_method()) - { - Expression* fn = ce->fn(); - if (fn->bound_method_expression() == NULL - && fn->interface_field_reference_expression() == NULL) - this->report_error(_("no object for method call")); - } -} - -// The Traverse class used to find and simplify thunk statements. - -class Simplify_thunk_traverse : public Traverse -{ - public: - Simplify_thunk_traverse(Gogo* gogo) - : Traverse(traverse_blocks), - gogo_(gogo) - { } - - int - block(Block*); - - private: - Gogo* gogo_; -}; - -int -Simplify_thunk_traverse::block(Block* b) -{ - // The parser ensures that thunk statements always appear at the end - // of a block. - if (b->statements()->size() < 1) - return TRAVERSE_CONTINUE; - Thunk_statement* stat = b->statements()->back()->thunk_statement(); - if (stat == NULL) - return TRAVERSE_CONTINUE; - if (stat->simplify_statement(this->gogo_, b)) - return TRAVERSE_SKIP_COMPONENTS; - return TRAVERSE_CONTINUE; -} - -// Simplify all thunk statements. - -void -Gogo::simplify_thunk_statements() -{ - Simplify_thunk_traverse thunk_traverse(this); - this->traverse(&thunk_traverse); -} - -// Simplify complex thunk statements into simple ones. A complicated -// thunk statement is one which takes anything other than zero -// parameters or a single pointer parameter. We rewrite it into code -// which allocates a struct, stores the parameter values into the -// struct, and does a simple go or defer statement which passes the -// struct to a thunk. The thunk does the real call. - -bool -Thunk_statement::simplify_statement(Gogo* gogo, Block* block) -{ - if (this->classification() == STATEMENT_ERROR) - return false; - if (this->call_->is_error_expression()) - return false; - - Call_expression* ce = this->call_->call_expression(); - Function_type* fntype = ce->get_function_type(); - if (fntype == NULL || this->is_simple(fntype)) - return false; - - Expression* fn = ce->fn(); - Bound_method_expression* bound_method = fn->bound_method_expression(); - Interface_field_reference_expression* interface_method = - fn->interface_field_reference_expression(); - const bool is_method = bound_method != NULL || interface_method != NULL; - - source_location location = this->location(); - - std::string thunk_name = Gogo::thunk_name(); - - // Build the thunk. - this->build_thunk(gogo, thunk_name, fntype); - - // Generate code to call the thunk. - - // Get the values to store into the struct which is the single - // argument to the thunk. - - Expression_list* vals = new Expression_list(); - if (fntype->is_builtin()) - ; - else if (!is_method) - vals->push_back(fn); - else if (interface_method != NULL) - vals->push_back(interface_method->expr()); - else if (bound_method != NULL) - { - vals->push_back(bound_method->method()); - Expression* first_arg = bound_method->first_argument(); - - // We always pass a pointer when calling a method. - if (first_arg->type()->points_to() == NULL) - first_arg = Expression::make_unary(OPERATOR_AND, first_arg, location); - - // If we are calling a method which was inherited from an - // embedded struct, and the method did not get a stub, then the - // first type may be wrong. - Type* fatype = bound_method->first_argument_type(); - if (fatype != NULL) - { - if (fatype->points_to() == NULL) - fatype = Type::make_pointer_type(fatype); - Type* unsafe = Type::make_pointer_type(Type::make_void_type()); - first_arg = Expression::make_cast(unsafe, first_arg, location); - first_arg = Expression::make_cast(fatype, first_arg, location); - } - - vals->push_back(first_arg); - } - else - gcc_unreachable(); - - if (ce->args() != NULL) - { - for (Expression_list::const_iterator p = ce->args()->begin(); - p != ce->args()->end(); - ++p) - vals->push_back(*p); - } - - // Build the struct. - Expression* constructor = - Expression::make_struct_composite_literal(this->struct_type_, vals, - location); - - // Allocate the initialized struct on the heap. - constructor = Expression::make_heap_composite(constructor, location); - - // Look up the thunk. - Named_object* named_thunk = gogo->lookup(thunk_name, NULL); - gcc_assert(named_thunk != NULL && named_thunk->is_function()); - - // Build the call. - Expression* func = Expression::make_func_reference(named_thunk, NULL, - location); - Expression_list* params = new Expression_list(); - params->push_back(constructor); - Call_expression* call = Expression::make_call(func, params, false, location); - - // Build the simple go or defer statement. - Statement* s; - if (this->classification() == STATEMENT_GO) - s = Statement::make_go_statement(call, location); - else if (this->classification() == STATEMENT_DEFER) - s = Statement::make_defer_statement(call, location); - else - gcc_unreachable(); - - // The current block should end with the go statement. - gcc_assert(block->statements()->size() >= 1); - gcc_assert(block->statements()->back() == this); - block->replace_statement(block->statements()->size() - 1, s); - - // We already ran the determine_types pass, so we need to run it now - // for the new statement. - s->determine_types(); - - // Sanity check. - gogo->check_types_in_block(block); - - // Return true to tell the block not to keep looking at statements. - return true; -} - -// Set the name to use for thunk parameter N. - -void -Thunk_statement::thunk_field_param(int n, char* buf, size_t buflen) -{ - snprintf(buf, buflen, "a%d", n); -} - -// Build a new struct type to hold the parameters for a complicated -// thunk statement. FNTYPE is the type of the function call. - -Struct_type* -Thunk_statement::build_struct(Function_type* fntype) -{ - source_location location = this->location(); - - Struct_field_list* fields = new Struct_field_list(); - - Call_expression* ce = this->call_->call_expression(); - Expression* fn = ce->fn(); - - Interface_field_reference_expression* interface_method = - fn->interface_field_reference_expression(); - if (interface_method != NULL) - { - // If this thunk statement calls a method on an interface, we - // pass the interface object to the thunk. - Typed_identifier tid(Thunk_statement::thunk_field_fn, - interface_method->expr()->type(), - location); - fields->push_back(Struct_field(tid)); - } - else if (!fntype->is_builtin()) - { - // The function to call. - Typed_identifier tid(Go_statement::thunk_field_fn, fntype, location); - fields->push_back(Struct_field(tid)); - } - else if (ce->is_recover_call()) - { - // The predeclared recover function has no argument. However, - // we add an argument when building recover thunks. Handle that - // here. - fields->push_back(Struct_field(Typed_identifier("can_recover", - Type::make_boolean_type(), - location))); - } - - if (fn->bound_method_expression() != NULL) - { - gcc_assert(fntype->is_method()); - Type* rtype = fntype->receiver()->type(); - // We always pass the receiver as a pointer. - if (rtype->points_to() == NULL) - rtype = Type::make_pointer_type(rtype); - Typed_identifier tid(Thunk_statement::thunk_field_receiver, rtype, - location); - fields->push_back(Struct_field(tid)); - } - - const Expression_list* args = ce->args(); - if (args != NULL) - { - int i = 0; - for (Expression_list::const_iterator p = args->begin(); - p != args->end(); - ++p, ++i) - { - char buf[50]; - this->thunk_field_param(i, buf, sizeof buf); - fields->push_back(Struct_field(Typed_identifier(buf, (*p)->type(), - location))); - } - } - - return Type::make_struct_type(fields, location); -} - -// Build the thunk we are going to call. This is a brand new, albeit -// artificial, function. - -void -Thunk_statement::build_thunk(Gogo* gogo, const std::string& thunk_name, - Function_type* fntype) -{ - source_location location = this->location(); - - Call_expression* ce = this->call_->call_expression(); - - bool may_call_recover = false; - if (this->classification() == STATEMENT_DEFER) - { - Func_expression* fn = ce->fn()->func_expression(); - if (fn == NULL) - may_call_recover = true; - else - { - const Named_object* no = fn->named_object(); - if (!no->is_function()) - may_call_recover = true; - else - may_call_recover = no->func_value()->calls_recover(); - } - } - - // Build the type of the thunk. The thunk takes a single parameter, - // which is a pointer to the special structure we build. - const char* const parameter_name = "__go_thunk_parameter"; - Typed_identifier_list* thunk_parameters = new Typed_identifier_list(); - Type* pointer_to_struct_type = Type::make_pointer_type(this->struct_type_); - thunk_parameters->push_back(Typed_identifier(parameter_name, - pointer_to_struct_type, - location)); - - Typed_identifier_list* thunk_results = NULL; - if (may_call_recover) - { - // When deferring a function which may call recover, add a - // return value, to disable tail call optimizations which will - // break the way we check whether recover is permitted. - thunk_results = new Typed_identifier_list(); - thunk_results->push_back(Typed_identifier("", Type::make_boolean_type(), - location)); - } - - Function_type* thunk_type = Type::make_function_type(NULL, thunk_parameters, - thunk_results, - location); - - // Start building the thunk. - Named_object* function = gogo->start_function(thunk_name, thunk_type, true, - location); - - // For a defer statement, start with a call to - // __go_set_defer_retaddr. */ - Label* retaddr_label = NULL; - if (may_call_recover) - { - retaddr_label = gogo->add_label_reference("retaddr"); - Expression* arg = Expression::make_label_addr(retaddr_label, location); - Expression_list* args = new Expression_list(); - args->push_back(arg); - - static Named_object* set_defer_retaddr; - if (set_defer_retaddr == NULL) - { - const source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - Type *voidptr_type = Type::make_pointer_type(Type::make_void_type()); - param_types->push_back(Typed_identifier("r", voidptr_type, bloc)); - - Typed_identifier_list* result_types = new Typed_identifier_list(); - result_types->push_back(Typed_identifier("", - Type::make_boolean_type(), - bloc)); - - Function_type* t = Type::make_function_type(NULL, param_types, - result_types, bloc); - set_defer_retaddr = - Named_object::make_function_declaration("__go_set_defer_retaddr", - NULL, t, bloc); - const char* n = "__go_set_defer_retaddr"; - set_defer_retaddr->func_declaration_value()->set_asm_name(n); - } - - Expression* fn = Expression::make_func_reference(set_defer_retaddr, - NULL, location); - Expression* call = Expression::make_call(fn, args, false, location); - - // This is a hack to prevent the middle-end from deleting the - // label. - gogo->start_block(location); - gogo->add_statement(Statement::make_goto_statement(retaddr_label, - location)); - Block* then_block = gogo->finish_block(location); - then_block->determine_types(); - - Statement* s = Statement::make_if_statement(call, then_block, NULL, - location); - s->determine_types(); - gogo->add_statement(s); - } - - // Get a reference to the parameter. - Named_object* named_parameter = gogo->lookup(parameter_name, NULL); - gcc_assert(named_parameter != NULL && named_parameter->is_variable()); - - // Build the call. Note that the field names are the same as the - // ones used in build_struct. - Expression* thunk_parameter = Expression::make_var_reference(named_parameter, - location); - thunk_parameter = Expression::make_unary(OPERATOR_MULT, thunk_parameter, - location); - - Bound_method_expression* bound_method = ce->fn()->bound_method_expression(); - Interface_field_reference_expression* interface_method = - ce->fn()->interface_field_reference_expression(); - - Expression* func_to_call; - unsigned int next_index; - if (!fntype->is_builtin()) - { - func_to_call = Expression::make_field_reference(thunk_parameter, - 0, location); - next_index = 1; - } - else - { - gcc_assert(bound_method == NULL && interface_method == NULL); - func_to_call = ce->fn(); - next_index = 0; - } - - if (bound_method != NULL) - { - Expression* r = Expression::make_field_reference(thunk_parameter, 1, - location); - // The main program passes in a function pointer from the - // interface expression, so here we can make a bound method in - // all cases. - func_to_call = Expression::make_bound_method(r, func_to_call, - location); - next_index = 2; - } - else if (interface_method != NULL) - { - // The main program passes the interface object. - const std::string& name(interface_method->name()); - func_to_call = Expression::make_interface_field_reference(func_to_call, - name, - location); - } - - Expression_list* call_params = new Expression_list(); - const Struct_field_list* fields = this->struct_type_->fields(); - Struct_field_list::const_iterator p = fields->begin(); - for (unsigned int i = 0; i < next_index; ++i) - ++p; - for (; p != fields->end(); ++p, ++next_index) - { - Expression* thunk_param = Expression::make_var_reference(named_parameter, - location); - thunk_param = Expression::make_unary(OPERATOR_MULT, thunk_param, - location); - Expression* param = Expression::make_field_reference(thunk_param, - next_index, - location); - call_params->push_back(param); - } - - Expression* call = Expression::make_call(func_to_call, call_params, false, - location); - // We need to lower in case this is a builtin function. - call = call->lower(gogo, function, -1); - if (may_call_recover) - { - Call_expression* ce = call->call_expression(); - if (ce != NULL) - ce->set_is_deferred(); - } - - Statement* call_statement = Statement::make_statement(call); - - // We already ran the determine_types pass, so we need to run it - // just for this statement now. - call_statement->determine_types(); - - gogo->add_statement(call_statement); - - // If this is a defer statement, the label comes immediately after - // the call. - if (may_call_recover) - { - gogo->add_label_definition("retaddr", location); - - Expression_list* vals = new Expression_list(); - vals->push_back(Expression::make_boolean(false, location)); - const Typed_identifier_list* results = - function->func_value()->type()->results(); - gogo->add_statement(Statement::make_return_statement(results, vals, - location)); - } - - // That is all the thunk has to do. - gogo->finish_function(location); -} - -// Get the function and argument trees. - -void -Thunk_statement::get_fn_and_arg(Translate_context* context, tree* pfn, - tree* parg) -{ - if (this->call_->is_error_expression()) - { - *pfn = error_mark_node; - *parg = error_mark_node; - return; - } - - Call_expression* ce = this->call_->call_expression(); - - Expression* fn = ce->fn(); - *pfn = fn->get_tree(context); - - const Expression_list* args = ce->args(); - if (args == NULL || args->empty()) - *parg = null_pointer_node; - else - { - gcc_assert(args->size() == 1); - *parg = args->front()->get_tree(context); - } -} - -// Class Go_statement. - -tree -Go_statement::do_get_tree(Translate_context* context) -{ - tree fn_tree; - tree arg_tree; - this->get_fn_and_arg(context, &fn_tree, &arg_tree); - - static tree go_fndecl; - - tree fn_arg_type = NULL_TREE; - if (go_fndecl == NULL_TREE) - { - // Only build FN_ARG_TYPE if we need it. - tree subargtypes = tree_cons(NULL_TREE, ptr_type_node, void_list_node); - tree subfntype = build_function_type(ptr_type_node, subargtypes); - fn_arg_type = build_pointer_type(subfntype); - } - - return Gogo::call_builtin(&go_fndecl, - this->location(), - "__go_go", - 2, - void_type_node, - fn_arg_type, - fn_tree, - ptr_type_node, - arg_tree); -} - -// Make a go statement. - -Statement* -Statement::make_go_statement(Call_expression* call, source_location location) -{ - return new Go_statement(call, location); -} - -// Class Defer_statement. - -tree -Defer_statement::do_get_tree(Translate_context* context) -{ - source_location loc = this->location(); - - tree fn_tree; - tree arg_tree; - this->get_fn_and_arg(context, &fn_tree, &arg_tree); - if (fn_tree == error_mark_node || arg_tree == error_mark_node) - return error_mark_node; - - static tree defer_fndecl; - - tree fn_arg_type = NULL_TREE; - if (defer_fndecl == NULL_TREE) - { - // Only build FN_ARG_TYPE if we need it. - tree subargtypes = tree_cons(NULL_TREE, ptr_type_node, void_list_node); - tree subfntype = build_function_type(ptr_type_node, subargtypes); - fn_arg_type = build_pointer_type(subfntype); - } - - tree defer_stack = context->function()->func_value()->defer_stack(loc); - - return Gogo::call_builtin(&defer_fndecl, - loc, - "__go_defer", - 3, - void_type_node, - ptr_type_node, - defer_stack, - fn_arg_type, - fn_tree, - ptr_type_node, - arg_tree); -} - -// Make a defer statement. - -Statement* -Statement::make_defer_statement(Call_expression* call, - source_location location) -{ - return new Defer_statement(call, location); -} - -// Class Return_statement. - -// Traverse assignments. We treat each return value as a top level -// RHS in an expression. - -bool -Return_statement::do_traverse_assignments(Traverse_assignments* tassign) -{ - Expression_list* vals = this->vals_; - if (vals != NULL) - { - for (Expression_list::iterator p = vals->begin(); - p != vals->end(); - ++p) - tassign->value(&*p, true, true); - } - return true; -} - -// Lower a return statement. If we are returning a function call -// which returns multiple values which match the current function, -// split up the call's results. If the function has named result -// variables, and the return statement lists explicit values, then -// implement it by assigning the values to the result variables and -// changing the statement to not list any values. This lets -// panic/recover work correctly. - -Statement* -Return_statement::do_lower(Gogo*, Block* enclosing) -{ - if (this->vals_ == NULL) - return this; - - const Typed_identifier_list* results = this->results_; - if (results == NULL || results->empty()) - return this; - - // If the current function has multiple return values, and we are - // returning a single call expression, split up the call expression. - size_t results_count = results->size(); - if (results_count > 1 - && this->vals_->size() == 1 - && this->vals_->front()->call_expression() != NULL) - { - Call_expression* call = this->vals_->front()->call_expression(); - size_t count = results->size(); - Expression_list* vals = new Expression_list; - for (size_t i = 0; i < count; ++i) - vals->push_back(Expression::make_call_result(call, i)); - delete this->vals_; - this->vals_ = vals; - } - - if (results->front().name().empty()) - return this; - - if (results_count != this->vals_->size()) - { - // Presumably an error which will be reported in check_types. - return this; - } - - // Assign to named return values and then return them. - - source_location loc = this->location(); - const Block* top = enclosing; - while (top->enclosing() != NULL) - top = top->enclosing(); - - const Bindings *bindings = top->bindings(); - Block* b = new Block(enclosing, loc); - - Expression_list* lhs = new Expression_list(); - Expression_list* rhs = new Expression_list(); - - Expression_list::const_iterator pe = this->vals_->begin(); - int i = 1; - for (Typed_identifier_list::const_iterator pr = results->begin(); - pr != results->end(); - ++pr, ++pe, ++i) - { - Named_object* rv = bindings->lookup_local(pr->name()); - if (rv == NULL || !rv->is_result_variable()) - { - // Presumably an error. - delete b; - delete lhs; - delete rhs; - return this; - } - - Expression* e = *pe; - - // Check types now so that we give a good error message. The - // result type is known. We determine the expression type - // early. - - Type *rvtype = rv->result_var_value()->type(); - Type_context type_context(rvtype, false); - e->determine_type(&type_context); - - std::string reason; - if (Type::are_assignable(rvtype, e->type(), &reason)) - { - Expression* ve = Expression::make_var_reference(rv, e->location()); - lhs->push_back(ve); - rhs->push_back(e); - } - else - { - if (reason.empty()) - error_at(e->location(), "incompatible type for return value %d", i); - else - error_at(e->location(), - "incompatible type for return value %d (%s)", - i, reason.c_str()); - } - } - gcc_assert(lhs->size() == rhs->size()); - - if (lhs->empty()) - ; - else if (lhs->size() == 1) - { - b->add_statement(Statement::make_assignment(lhs->front(), rhs->front(), - loc)); - delete lhs; - delete rhs; - } - else - b->add_statement(Statement::make_tuple_assignment(lhs, rhs, loc)); - - b->add_statement(Statement::make_return_statement(this->results_, NULL, - loc)); - - return Statement::make_block_statement(b, loc); -} - -// Determine types. - -void -Return_statement::do_determine_types() -{ - if (this->vals_ == NULL) - return; - const Typed_identifier_list* results = this->results_; - - Typed_identifier_list::const_iterator pt; - if (results != NULL) - pt = results->begin(); - for (Expression_list::iterator pe = this->vals_->begin(); - pe != this->vals_->end(); - ++pe) - { - if (results == NULL || pt == results->end()) - (*pe)->determine_type_no_context(); - else - { - Type_context context(pt->type(), false); - (*pe)->determine_type(&context); - ++pt; - } - } -} - -// Check types. - -void -Return_statement::do_check_types(Gogo*) -{ - if (this->vals_ == NULL) - return; - - const Typed_identifier_list* results = this->results_; - if (results == NULL) - { - this->report_error(_("return with value in function " - "with no return type")); - return; - } - - int i = 1; - Typed_identifier_list::const_iterator pt = results->begin(); - for (Expression_list::const_iterator pe = this->vals_->begin(); - pe != this->vals_->end(); - ++pe, ++pt, ++i) - { - if (pt == results->end()) - { - this->report_error(_("too many values in return statement")); - return; - } - std::string reason; - if (!Type::are_assignable(pt->type(), (*pe)->type(), &reason)) - { - if (reason.empty()) - error_at(this->location(), - "incompatible type for return value %d", - i); - else - error_at(this->location(), - "incompatible type for return value %d (%s)", - i, reason.c_str()); - this->set_is_error(); - } - else if (pt->type()->is_error_type() - || (*pe)->type()->is_error_type() - || pt->type()->is_undefined() - || (*pe)->type()->is_undefined()) - { - // Make sure we get the error for an undefined type. - pt->type()->base(); - (*pe)->type()->base(); - this->set_is_error(); - } - } - - if (pt != results->end()) - this->report_error(_("not enough values in return statement")); -} - -// Build a RETURN_EXPR tree. - -tree -Return_statement::do_get_tree(Translate_context* context) -{ - Function* function = context->function()->func_value(); - tree fndecl = function->get_decl(); - - const Typed_identifier_list* results = this->results_; - - if (this->vals_ == NULL) - { - tree stmt_list = NULL_TREE; - tree retval = function->return_value(context->gogo(), - context->function(), - this->location(), - &stmt_list); - tree set; - if (retval == NULL_TREE) - set = NULL_TREE; - else - set = fold_build2_loc(this->location(), MODIFY_EXPR, void_type_node, - DECL_RESULT(fndecl), retval); - append_to_statement_list(this->build_stmt_1(RETURN_EXPR, set), - &stmt_list); - return stmt_list; - } - else if (this->vals_->size() == 1) - { - gcc_assert(!VOID_TYPE_P(TREE_TYPE(TREE_TYPE(fndecl)))); - tree val = (*this->vals_->begin())->get_tree(context); - if (val == error_mark_node) - return error_mark_node; - gcc_assert(results != NULL && results->size() == 1); - val = Expression::convert_for_assignment(context, - results->begin()->type(), - (*this->vals_->begin())->type(), - val, this->location()); - tree set = build2(MODIFY_EXPR, void_type_node, - DECL_RESULT(fndecl), val); - SET_EXPR_LOCATION(set, this->location()); - return this->build_stmt_1(RETURN_EXPR, set); - } - else - { - gcc_assert(!VOID_TYPE_P(TREE_TYPE(TREE_TYPE(fndecl)))); - tree stmt_list = NULL_TREE; - tree rettype = TREE_TYPE(DECL_RESULT(fndecl)); - tree retvar = create_tmp_var(rettype, "RESULT"); - gcc_assert(results != NULL && results->size() == this->vals_->size()); - Expression_list::const_iterator pv = this->vals_->begin(); - Typed_identifier_list::const_iterator pr = results->begin(); - for (tree field = TYPE_FIELDS(rettype); - field != NULL_TREE; - ++pv, ++pr, field = DECL_CHAIN(field)) - { - gcc_assert(pv != this->vals_->end()); - tree val = (*pv)->get_tree(context); - if (val == error_mark_node) - return error_mark_node; - val = Expression::convert_for_assignment(context, pr->type(), - (*pv)->type(), val, - this->location()); - tree set = build2(MODIFY_EXPR, void_type_node, - build3(COMPONENT_REF, TREE_TYPE(field), - retvar, field, NULL_TREE), - val); - SET_EXPR_LOCATION(set, this->location()); - append_to_statement_list(set, &stmt_list); - } - tree set = build2(MODIFY_EXPR, void_type_node, DECL_RESULT(fndecl), - retvar); - append_to_statement_list(this->build_stmt_1(RETURN_EXPR, set), - &stmt_list); - return stmt_list; - } -} - -// Make a return statement. - -Statement* -Statement::make_return_statement(const Typed_identifier_list* results, - Expression_list* vals, - source_location location) -{ - return new Return_statement(results, vals, location); -} - -// A break or continue statement. - -class Bc_statement : public Statement -{ - public: - Bc_statement(bool is_break, Unnamed_label* label, source_location location) - : Statement(STATEMENT_BREAK_OR_CONTINUE, location), - label_(label), is_break_(is_break) - { } - - bool - is_break() const - { return this->is_break_; } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - bool - do_may_fall_through() const - { return false; } - - tree - do_get_tree(Translate_context*) - { return this->label_->get_goto(this->location()); } - - private: - // The label that this branches to. - Unnamed_label* label_; - // True if this is "break", false if it is "continue". - bool is_break_; -}; - -// Make a break statement. - -Statement* -Statement::make_break_statement(Unnamed_label* label, source_location location) -{ - return new Bc_statement(true, label, location); -} - -// Make a continue statement. - -Statement* -Statement::make_continue_statement(Unnamed_label* label, - source_location location) -{ - return new Bc_statement(false, label, location); -} - -// A goto statement. - -class Goto_statement : public Statement -{ - public: - Goto_statement(Label* label, source_location location) - : Statement(STATEMENT_GOTO, location), - label_(label) - { } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - void - do_check_types(Gogo*); - - bool - do_may_fall_through() const - { return false; } - - tree - do_get_tree(Translate_context*); - - private: - Label* label_; -}; - -// Check types for a label. There aren't any types per se, but we use -// this to give an error if the label was never defined. - -void -Goto_statement::do_check_types(Gogo*) -{ - if (!this->label_->is_defined()) - { - error_at(this->location(), "reference to undefined label %qs", - Gogo::message_name(this->label_->name()).c_str()); - this->set_is_error(); - } -} - -// Return the tree for the goto statement. - -tree -Goto_statement::do_get_tree(Translate_context*) -{ - return this->build_stmt_1(GOTO_EXPR, this->label_->get_decl()); -} - -// Make a goto statement. - -Statement* -Statement::make_goto_statement(Label* label, source_location location) -{ - return new Goto_statement(label, location); -} - -// A goto statement to an unnamed label. - -class Goto_unnamed_statement : public Statement -{ - public: - Goto_unnamed_statement(Unnamed_label* label, source_location location) - : Statement(STATEMENT_GOTO_UNNAMED, location), - label_(label) - { } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - bool - do_may_fall_through() const - { return false; } - - tree - do_get_tree(Translate_context*) - { return this->label_->get_goto(this->location()); } - - private: - Unnamed_label* label_; -}; - -// Make a goto statement to an unnamed label. - -Statement* -Statement::make_goto_unnamed_statement(Unnamed_label* label, - source_location location) -{ - return new Goto_unnamed_statement(label, location); -} - -// Class Label_statement. - -// Traversal. - -int -Label_statement::do_traverse(Traverse*) -{ - return TRAVERSE_CONTINUE; -} - -// Return a tree defining this label. - -tree -Label_statement::do_get_tree(Translate_context*) -{ - return this->build_stmt_1(LABEL_EXPR, this->label_->get_decl()); -} - -// Make a label statement. - -Statement* -Statement::make_label_statement(Label* label, source_location location) -{ - return new Label_statement(label, location); -} - -// An unnamed label statement. - -class Unnamed_label_statement : public Statement -{ - public: - Unnamed_label_statement(Unnamed_label* label) - : Statement(STATEMENT_UNNAMED_LABEL, label->location()), - label_(label) - { } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - tree - do_get_tree(Translate_context*) - { return this->label_->get_definition(); } - - private: - // The label. - Unnamed_label* label_; -}; - -// Make an unnamed label statement. - -Statement* -Statement::make_unnamed_label_statement(Unnamed_label* label) -{ - return new Unnamed_label_statement(label); -} - -// An if statement. - -class If_statement : public Statement -{ - public: - If_statement(Expression* cond, Block* then_block, Block* else_block, - source_location location) - : Statement(STATEMENT_IF, location), - cond_(cond), then_block_(then_block), else_block_(else_block) - { } - - protected: - int - do_traverse(Traverse*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - bool - do_may_fall_through() const; - - tree - do_get_tree(Translate_context*); - - private: - Expression* cond_; - Block* then_block_; - Block* else_block_; -}; - -// Traversal. - -int -If_statement::do_traverse(Traverse* traverse) -{ - if (this->cond_ != NULL) - { - if (this->traverse_expression(traverse, &this->cond_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->then_block_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->else_block_ != NULL) - { - if (this->else_block_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -void -If_statement::do_determine_types() -{ - if (this->cond_ != NULL) - { - Type_context context(Type::lookup_bool_type(), false); - this->cond_->determine_type(&context); - } - this->then_block_->determine_types(); - if (this->else_block_ != NULL) - this->else_block_->determine_types(); -} - -// Check types. - -void -If_statement::do_check_types(Gogo*) -{ - if (this->cond_ != NULL) - { - Type* type = this->cond_->type(); - if (type->is_error_type()) - this->set_is_error(); - else if (!type->is_boolean_type()) - this->report_error(_("expected boolean expression")); - } -} - -// Whether the overall statement may fall through. - -bool -If_statement::do_may_fall_through() const -{ - return (this->else_block_ == NULL - || this->then_block_->may_fall_through() - || this->else_block_->may_fall_through()); -} - -// Get tree. - -tree -If_statement::do_get_tree(Translate_context* context) -{ - gcc_assert(this->cond_ == NULL || this->cond_->type()->is_boolean_type()); - tree ret = build3(COND_EXPR, void_type_node, - (this->cond_ == NULL - ? boolean_true_node - : this->cond_->get_tree(context)), - this->then_block_->get_tree(context), - (this->else_block_ == NULL - ? NULL_TREE - : this->else_block_->get_tree(context))); - SET_EXPR_LOCATION(ret, this->location()); - return ret; -} - -// Make an if statement. - -Statement* -Statement::make_if_statement(Expression* cond, Block* then_block, - Block* else_block, source_location location) -{ - return new If_statement(cond, then_block, else_block, location); -} - -// Class Case_clauses::Case_clause. - -// Traversal. - -int -Case_clauses::Case_clause::traverse(Traverse* traverse) -{ - if (this->cases_ != NULL - && (traverse->traverse_mask() & Traverse::traverse_expressions) != 0) - { - if (this->cases_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->statements_ != NULL) - { - if (this->statements_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Check whether all the case expressions are integer constants. - -bool -Case_clauses::Case_clause::is_constant() const -{ - if (this->cases_ != NULL) - { - for (Expression_list::const_iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - if (!(*p)->is_constant() || (*p)->type()->integer_type() == NULL) - return false; - } - return true; -} - -// Lower a case clause for a nonconstant switch. VAL_TEMP is the -// value we are switching on; it may be NULL. If START_LABEL is not -// NULL, it goes at the start of the statements, after the condition -// test. We branch to FINISH_LABEL at the end of the statements. - -void -Case_clauses::Case_clause::lower(Block* b, Temporary_statement* val_temp, - Unnamed_label* start_label, - Unnamed_label* finish_label) const -{ - source_location loc = this->location_; - Unnamed_label* next_case_label; - if (this->cases_ == NULL || this->cases_->empty()) - { - gcc_assert(this->is_default_); - next_case_label = NULL; - } - else - { - Expression* cond = NULL; - - for (Expression_list::const_iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - { - Expression* this_cond; - if (val_temp == NULL) - this_cond = *p; - else - { - Expression* ref = Expression::make_temporary_reference(val_temp, - loc); - this_cond = Expression::make_binary(OPERATOR_EQEQ, ref, *p, loc); - } - - if (cond == NULL) - cond = this_cond; - else - cond = Expression::make_binary(OPERATOR_OROR, cond, this_cond, loc); - } - - Block* then_block = new Block(b, loc); - next_case_label = new Unnamed_label(UNKNOWN_LOCATION); - Statement* s = Statement::make_goto_unnamed_statement(next_case_label, - loc); - then_block->add_statement(s); - - // if !COND { goto NEXT_CASE_LABEL } - cond = Expression::make_unary(OPERATOR_NOT, cond, loc); - s = Statement::make_if_statement(cond, then_block, NULL, loc); - b->add_statement(s); - } - - if (start_label != NULL) - b->add_statement(Statement::make_unnamed_label_statement(start_label)); - - if (this->statements_ != NULL) - b->add_statement(Statement::make_block_statement(this->statements_, loc)); - - Statement* s = Statement::make_goto_unnamed_statement(finish_label, loc); - b->add_statement(s); - - if (next_case_label != NULL) - b->add_statement(Statement::make_unnamed_label_statement(next_case_label)); -} - -// Determine types. - -void -Case_clauses::Case_clause::determine_types(Type* type) -{ - if (this->cases_ != NULL) - { - Type_context case_context(type, false); - for (Expression_list::iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - (*p)->determine_type(&case_context); - } - if (this->statements_ != NULL) - this->statements_->determine_types(); -} - -// Check types. Returns false if there was an error. - -bool -Case_clauses::Case_clause::check_types(Type* type) -{ - if (this->cases_ != NULL) - { - for (Expression_list::iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - { - if (!Type::are_assignable(type, (*p)->type(), NULL) - && !Type::are_assignable((*p)->type(), type, NULL)) - { - error_at((*p)->location(), - "type mismatch between switch value and case clause"); - return false; - } - } - } - return true; -} - -// Return true if this clause may fall through to the following -// statements. Note that this is not the same as whether the case -// uses the "fallthrough" keyword. - -bool -Case_clauses::Case_clause::may_fall_through() const -{ - if (this->statements_ == NULL) - return true; - return this->statements_->may_fall_through(); -} - -// Build up the body of a SWITCH_EXPR. - -void -Case_clauses::Case_clause::get_constant_tree(Translate_context* context, - Unnamed_label* break_label, - Case_constants* case_constants, - tree* stmt_list) const -{ - if (this->cases_ != NULL) - { - for (Expression_list::const_iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - { - Type* itype; - mpz_t ival; - mpz_init(ival); - if (!(*p)->integer_constant_value(true, ival, &itype)) - gcc_unreachable(); - gcc_assert(itype != NULL); - tree type_tree = itype->get_tree(context->gogo()); - tree val = Expression::integer_constant_tree(ival, type_tree); - mpz_clear(ival); - - if (val != error_mark_node) - { - gcc_assert(TREE_CODE(val) == INTEGER_CST); - - std::pair ins = - case_constants->insert(val); - if (!ins.second) - { - // Value was already present. - warning_at(this->location_, 0, - "duplicate case value will never match"); - continue; - } - - tree label = create_artificial_label(this->location_); - append_to_statement_list(build3(CASE_LABEL_EXPR, void_type_node, - val, NULL_TREE, label), - stmt_list); - } - } - } - - if (this->is_default_) - { - tree label = create_artificial_label(this->location_); - append_to_statement_list(build3(CASE_LABEL_EXPR, void_type_node, - NULL_TREE, NULL_TREE, label), - stmt_list); - } - - if (this->statements_ != NULL) - { - tree block_tree = this->statements_->get_tree(context); - if (block_tree != error_mark_node) - append_to_statement_list(block_tree, stmt_list); - } - - if (!this->is_fallthrough_) - append_to_statement_list(break_label->get_goto(this->location_), stmt_list); -} - -// Class Case_clauses. - -// Traversal. - -int -Case_clauses::traverse(Traverse* traverse) -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Check whether all the case expressions are constant. - -bool -Case_clauses::is_constant() const -{ - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - if (!p->is_constant()) - return false; - return true; -} - -// Lower case clauses for a nonconstant switch. - -void -Case_clauses::lower(Block* b, Temporary_statement* val_temp, - Unnamed_label* break_label) const -{ - // The default case. - const Case_clause* default_case = NULL; - - // The label for the fallthrough of the previous case. - Unnamed_label* last_fallthrough_label = NULL; - - // The label for the start of the default case. This is used if the - // case before the default case falls through. - Unnamed_label* default_start_label = NULL; - - // The label for the end of the default case. This normally winds - // up as BREAK_LABEL, but it will be different if the default case - // falls through. - Unnamed_label* default_finish_label = NULL; - - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - // The label to use for the start of the statements for this - // case. This is NULL unless the previous case falls through. - Unnamed_label* start_label = last_fallthrough_label; - - // The label to jump to after the end of the statements for this - // case. - Unnamed_label* finish_label = break_label; - - last_fallthrough_label = NULL; - if (p->is_fallthrough() && p + 1 != this->clauses_.end()) - { - finish_label = new Unnamed_label(p->location()); - last_fallthrough_label = finish_label; - } - - if (!p->is_default()) - p->lower(b, val_temp, start_label, finish_label); - else - { - // We have to move the default case to the end, so that we - // only use it if all the other tests fail. - default_case = &*p; - default_start_label = start_label; - default_finish_label = finish_label; - } - } - - if (default_case != NULL) - default_case->lower(b, val_temp, default_start_label, - default_finish_label); - -} - -// Determine types. - -void -Case_clauses::determine_types(Type* type) -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - p->determine_types(type); -} - -// Check types. Returns false if there was an error. - -bool -Case_clauses::check_types(Type* type) -{ - bool ret = true; - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (!p->check_types(type)) - ret = false; - } - return ret; -} - -// Return true if these clauses may fall through to the statements -// following the switch statement. - -bool -Case_clauses::may_fall_through() const -{ - bool found_default = false; - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->may_fall_through() && !p->is_fallthrough()) - return true; - if (p->is_default()) - found_default = true; - } - return !found_default; -} - -// Return a tree when all case expressions are constants. - -tree -Case_clauses::get_constant_tree(Translate_context* context, - Unnamed_label* break_label) const -{ - Case_constants case_constants; - tree stmt_list = NULL_TREE; - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - p->get_constant_tree(context, break_label, &case_constants, - &stmt_list); - return stmt_list; -} - -// A constant switch statement. A Switch_statement is lowered to this -// when all the cases are constants. - -class Constant_switch_statement : public Statement -{ - public: - Constant_switch_statement(Expression* val, Case_clauses* clauses, - Unnamed_label* break_label, - source_location location) - : Statement(STATEMENT_CONSTANT_SWITCH, location), - val_(val), clauses_(clauses), break_label_(break_label) - { } - - protected: - int - do_traverse(Traverse*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - bool - do_may_fall_through() const; - - tree - do_get_tree(Translate_context*); - - private: - // The value to switch on. - Expression* val_; - // The case clauses. - Case_clauses* clauses_; - // The break label, if needed. - Unnamed_label* break_label_; -}; - -// Traversal. - -int -Constant_switch_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->clauses_->traverse(traverse); -} - -// Determine types. - -void -Constant_switch_statement::do_determine_types() -{ - this->val_->determine_type_no_context(); - this->clauses_->determine_types(this->val_->type()); -} - -// Check types. - -void -Constant_switch_statement::do_check_types(Gogo*) -{ - if (!this->clauses_->check_types(this->val_->type())) - this->set_is_error(); -} - -// Return whether this switch may fall through. - -bool -Constant_switch_statement::do_may_fall_through() const -{ - if (this->clauses_ == NULL) - return true; - - // If we have a break label, then some case needed it. That implies - // that the switch statement as a whole can fall through. - if (this->break_label_ != NULL) - return true; - - return this->clauses_->may_fall_through(); -} - -// Convert to GENERIC. - -tree -Constant_switch_statement::do_get_tree(Translate_context* context) -{ - tree switch_val_tree = this->val_->get_tree(context); - - Unnamed_label* break_label = this->break_label_; - if (break_label == NULL) - break_label = new Unnamed_label(this->location()); - - tree stmt_list = NULL_TREE; - tree s = build3(SWITCH_EXPR, void_type_node, switch_val_tree, - this->clauses_->get_constant_tree(context, break_label), - NULL_TREE); - SET_EXPR_LOCATION(s, this->location()); - append_to_statement_list(s, &stmt_list); - - append_to_statement_list(break_label->get_definition(), &stmt_list); - - return stmt_list; -} - -// Class Switch_statement. - -// Traversal. - -int -Switch_statement::do_traverse(Traverse* traverse) -{ - if (this->val_ != NULL) - { - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return this->clauses_->traverse(traverse); -} - -// Lower a Switch_statement to a Constant_switch_statement or a series -// of if statements. - -Statement* -Switch_statement::do_lower(Gogo*, Block* enclosing) -{ - source_location loc = this->location(); - - if (this->val_ != NULL - && (this->val_->is_error_expression() - || this->val_->type()->is_error_type())) - return Statement::make_error_statement(loc); - - if (this->val_ != NULL - && this->val_->type()->integer_type() != NULL - && !this->clauses_->empty() - && this->clauses_->is_constant()) - return new Constant_switch_statement(this->val_, this->clauses_, - this->break_label_, loc); - - Block* b = new Block(enclosing, loc); - - if (this->clauses_->empty()) - { - Expression* val = this->val_; - if (val == NULL) - val = Expression::make_boolean(true, loc); - return Statement::make_statement(val); - } - - Temporary_statement* val_temp; - if (this->val_ == NULL) - val_temp = NULL; - else - { - // var val_temp VAL_TYPE = VAL - val_temp = Statement::make_temporary(NULL, this->val_, loc); - b->add_statement(val_temp); - } - - this->clauses_->lower(b, val_temp, this->break_label()); - - Statement* s = Statement::make_unnamed_label_statement(this->break_label_); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Return the break label for this switch statement, creating it if -// necessary. - -Unnamed_label* -Switch_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Make a switch statement. - -Switch_statement* -Statement::make_switch_statement(Expression* val, source_location location) -{ - return new Switch_statement(val, location); -} - -// Class Type_case_clauses::Type_case_clause. - -// Traversal. - -int -Type_case_clauses::Type_case_clause::traverse(Traverse* traverse) -{ - if (!this->is_default_ - && ((traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) != 0) - && Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->statements_ != NULL) - return this->statements_->traverse(traverse); - return TRAVERSE_CONTINUE; -} - -// Lower one clause in a type switch. Add statements to the block B. -// The type descriptor we are switching on is in DESCRIPTOR_TEMP. -// BREAK_LABEL is the label at the end of the type switch. -// *STMTS_LABEL, if not NULL, is a label to put at the start of the -// statements. - -void -Type_case_clauses::Type_case_clause::lower(Block* b, - Temporary_statement* descriptor_temp, - Unnamed_label* break_label, - Unnamed_label** stmts_label) const -{ - source_location loc = this->location_; - - Unnamed_label* next_case_label = NULL; - if (!this->is_default_) - { - Type* type = this->type_; - - Expression* cond; - // The language permits case nil, which is of course a constant - // rather than a type. It will appear here as an invalid - // forwarding type. - if (type->is_nil_constant_as_type()) - { - Expression* ref = - Expression::make_temporary_reference(descriptor_temp, loc); - cond = Expression::make_binary(OPERATOR_EQEQ, ref, - Expression::make_nil(loc), - loc); - } - else - { - Expression* func; - if (type->interface_type() == NULL) - { - // func ifacetypeeq(*descriptor, *descriptor) bool - static Named_object* ifacetypeeq; - if (ifacetypeeq == NULL) - { - const source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = - new Typed_identifier_list(); - Type* descriptor_type = Type::make_type_descriptor_ptr_type(); - param_types->push_back(Typed_identifier("a", descriptor_type, - bloc)); - param_types->push_back(Typed_identifier("b", descriptor_type, - bloc)); - Typed_identifier_list* ret_types = - new Typed_identifier_list(); - Type* bool_type = Type::lookup_bool_type(); - ret_types->push_back(Typed_identifier("", bool_type, bloc)); - Function_type* fntype = Type::make_function_type(NULL, - param_types, - ret_types, - bloc); - ifacetypeeq = - Named_object::make_function_declaration("ifacetypeeq", NULL, - fntype, bloc); - const char* n = "runtime.ifacetypeeq"; - ifacetypeeq->func_declaration_value()->set_asm_name(n); - } - - // ifacetypeeq(descriptor_temp, DESCRIPTOR) - func = Expression::make_func_reference(ifacetypeeq, NULL, loc); - } - else - { - // func ifaceI2Tp(*descriptor, *descriptor) bool - static Named_object* ifaceI2Tp; - if (ifaceI2Tp == NULL) - { - const source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = - new Typed_identifier_list(); - Type* descriptor_type = Type::make_type_descriptor_ptr_type(); - param_types->push_back(Typed_identifier("a", descriptor_type, - bloc)); - param_types->push_back(Typed_identifier("b", descriptor_type, - bloc)); - Typed_identifier_list* ret_types = - new Typed_identifier_list(); - Type* bool_type = Type::lookup_bool_type(); - ret_types->push_back(Typed_identifier("", bool_type, bloc)); - Function_type* fntype = Type::make_function_type(NULL, - param_types, - ret_types, - bloc); - ifaceI2Tp = - Named_object::make_function_declaration("ifaceI2Tp", NULL, - fntype, bloc); - const char* n = "runtime.ifaceI2Tp"; - ifaceI2Tp->func_declaration_value()->set_asm_name(n); - } - - // ifaceI2Tp(descriptor_temp, DESCRIPTOR) - func = Expression::make_func_reference(ifaceI2Tp, NULL, loc); - } - Expression_list* params = new Expression_list(); - params->push_back(Expression::make_type_descriptor(type, loc)); - Expression* ref = - Expression::make_temporary_reference(descriptor_temp, loc); - params->push_back(ref); - cond = Expression::make_call(func, params, false, loc); - } - - Unnamed_label* dest; - if (!this->is_fallthrough_) - { - // if !COND { goto NEXT_CASE_LABEL } - next_case_label = new Unnamed_label(UNKNOWN_LOCATION); - dest = next_case_label; - cond = Expression::make_unary(OPERATOR_NOT, cond, loc); - } - else - { - // if COND { goto STMTS_LABEL } - gcc_assert(stmts_label != NULL); - if (*stmts_label == NULL) - *stmts_label = new Unnamed_label(UNKNOWN_LOCATION); - dest = *stmts_label; - } - Block* then_block = new Block(b, loc); - Statement* s = Statement::make_goto_unnamed_statement(dest, loc); - then_block->add_statement(s); - s = Statement::make_if_statement(cond, then_block, NULL, loc); - b->add_statement(s); - } - - if (this->statements_ != NULL - || (!this->is_fallthrough_ - && stmts_label != NULL - && *stmts_label != NULL)) - { - gcc_assert(!this->is_fallthrough_); - if (stmts_label != NULL && *stmts_label != NULL) - { - gcc_assert(!this->is_default_); - if (this->statements_ != NULL) - (*stmts_label)->set_location(this->statements_->start_location()); - Statement* s = Statement::make_unnamed_label_statement(*stmts_label); - b->add_statement(s); - *stmts_label = NULL; - } - if (this->statements_ != NULL) - b->add_statement(Statement::make_block_statement(this->statements_, - loc)); - } - - if (this->is_fallthrough_) - gcc_assert(next_case_label == NULL); - else - { - source_location gloc = (this->statements_ == NULL - ? loc - : this->statements_->end_location()); - b->add_statement(Statement::make_goto_unnamed_statement(break_label, - gloc)); - if (next_case_label != NULL) - { - Statement* s = - Statement::make_unnamed_label_statement(next_case_label); - b->add_statement(s); - } - } -} - -// Class Type_case_clauses. - -// Traversal. - -int -Type_case_clauses::traverse(Traverse* traverse) -{ - for (Type_clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Check for duplicate types. - -void -Type_case_clauses::check_duplicates() const -{ - typedef Unordered_set_hash(const Type*, Type_hash_identical, - Type_identical) Types_seen; - Types_seen types_seen; - for (Type_clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - Type* t = p->type(); - if (t == NULL) - continue; - if (t->is_nil_constant_as_type()) - t = Type::make_nil_type(); - std::pair ins = types_seen.insert(t); - if (!ins.second) - error_at(p->location(), "duplicate type in switch"); - } -} - -// Lower the clauses in a type switch. Add statements to the block B. -// The type descriptor we are switching on is in DESCRIPTOR_TEMP. -// BREAK_LABEL is the label at the end of the type switch. - -void -Type_case_clauses::lower(Block* b, Temporary_statement* descriptor_temp, - Unnamed_label* break_label) const -{ - const Type_case_clause* default_case = NULL; - - Unnamed_label* stmts_label = NULL; - for (Type_clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (!p->is_default()) - p->lower(b, descriptor_temp, break_label, &stmts_label); - else - { - // We are generating a series of tests, which means that we - // need to move the default case to the end. - default_case = &*p; - } - } - gcc_assert(stmts_label == NULL); - - if (default_case != NULL) - default_case->lower(b, descriptor_temp, break_label, NULL); -} - -// Class Type_switch_statement. - -// Traversal. - -int -Type_switch_statement::do_traverse(Traverse* traverse) -{ - if (this->var_ == NULL) - { - if (this->traverse_expression(traverse, &this->expr_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->clauses_ != NULL) - return this->clauses_->traverse(traverse); - return TRAVERSE_CONTINUE; -} - -// Lower a type switch statement to a series of if statements. The gc -// compiler is able to generate a table in some cases. However, that -// does not work for us because we may have type descriptors in -// different shared libraries, so we can't compare them with simple -// equality testing. - -Statement* -Type_switch_statement::do_lower(Gogo*, Block* enclosing) -{ - const source_location loc = this->location(); - - if (this->clauses_ != NULL) - this->clauses_->check_duplicates(); - - Block* b = new Block(enclosing, loc); - - Type* val_type = (this->var_ != NULL - ? this->var_->var_value()->type() - : this->expr_->type()); - - // var descriptor_temp DESCRIPTOR_TYPE - Type* descriptor_type = Type::make_type_descriptor_ptr_type(); - Temporary_statement* descriptor_temp = - Statement::make_temporary(descriptor_type, NULL, loc); - b->add_statement(descriptor_temp); - - if (val_type->interface_type() == NULL) - { - // Doing a type switch on a non-interface type. Should we issue - // a warning for this case? - // descriptor_temp = DESCRIPTOR - Expression* lhs = Expression::make_temporary_reference(descriptor_temp, - loc); - Expression* rhs = Expression::make_type_descriptor(val_type, loc); - Statement* s = Statement::make_assignment(lhs, rhs, loc); - b->add_statement(s); - } - else - { - const source_location bloc = BUILTINS_LOCATION; - - // func {efacetype,ifacetype}(*interface) *descriptor - // FIXME: This should be inlined. - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("i", val_type, bloc)); - Typed_identifier_list* ret_types = new Typed_identifier_list(); - ret_types->push_back(Typed_identifier("", descriptor_type, bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, - ret_types, bloc); - bool is_empty = val_type->interface_type()->is_empty(); - const char* fnname = is_empty ? "efacetype" : "ifacetype"; - Named_object* fn = - Named_object::make_function_declaration(fnname, NULL, fntype, bloc); - const char* asm_name = (is_empty - ? "runtime.efacetype" - : "runtime.ifacetype"); - fn->func_declaration_value()->set_asm_name(asm_name); - - // descriptor_temp = ifacetype(val_temp) - Expression* func = Expression::make_func_reference(fn, NULL, loc); - Expression_list* params = new Expression_list(); - Expression* ref; - if (this->var_ == NULL) - ref = this->expr_; - else - ref = Expression::make_var_reference(this->var_, loc); - params->push_back(ref); - Expression* call = Expression::make_call(func, params, false, loc); - Expression* lhs = Expression::make_temporary_reference(descriptor_temp, - loc); - Statement* s = Statement::make_assignment(lhs, call, loc); - b->add_statement(s); - } - - if (this->clauses_ != NULL) - this->clauses_->lower(b, descriptor_temp, this->break_label()); - - Statement* s = Statement::make_unnamed_label_statement(this->break_label_); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Return the break label for this type switch statement, creating it -// if necessary. - -Unnamed_label* -Type_switch_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Make a type switch statement. - -Type_switch_statement* -Statement::make_type_switch_statement(Named_object* var, Expression* expr, - source_location location) -{ - return new Type_switch_statement(var, expr, location); -} - -// Class Select_clauses::Select_clause. - -// Traversal. - -int -Select_clauses::Select_clause::traverse(Traverse* traverse) -{ - if (!this->is_lowered_ - && (traverse->traverse_mask() & Traverse::traverse_expressions) != 0) - { - if (this->channel_ != NULL) - { - if (Expression::traverse(&this->channel_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->val_ != NULL) - { - if (Expression::traverse(&this->val_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - if (this->statements_ != NULL) - { - if (this->statements_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lowering. Here we pull out the channel and the send values, to -// enforce the order of evaluation. We also add explicit send and -// receive statements to the clauses. - -void -Select_clauses::Select_clause::lower(Block* b) -{ - if (this->is_default_) - { - gcc_assert(this->channel_ == NULL && this->val_ == NULL); - this->is_lowered_ = true; - return; - } - - source_location loc = this->location_; - - // Evaluate the channel before the select statement. - Temporary_statement* channel_temp = Statement::make_temporary(NULL, - this->channel_, - loc); - b->add_statement(channel_temp); - this->channel_ = Expression::make_temporary_reference(channel_temp, loc); - - // If this is a send clause, evaluate the value to send before the - // select statement. - Temporary_statement* val_temp = NULL; - if (this->is_send_) - { - val_temp = Statement::make_temporary(NULL, this->val_, loc); - b->add_statement(val_temp); - } - - // Add the send or receive before the rest of the statements if any. - Block *init = new Block(b, loc); - Expression* ref = Expression::make_temporary_reference(channel_temp, loc); - if (this->is_send_) - { - Expression* ref2 = Expression::make_temporary_reference(val_temp, loc); - Send_expression* send = Expression::make_send(ref, ref2, loc); - send->discarding_value(); - send->set_for_select(); - init->add_statement(Statement::make_statement(send)); - } - else - { - Receive_expression* recv = Expression::make_receive(ref, loc); - recv->set_for_select(); - if (this->val_ != NULL) - { - gcc_assert(this->var_ == NULL); - init->add_statement(Statement::make_assignment(this->val_, recv, - loc)); - } - else if (this->var_ != NULL) - { - this->var_->var_value()->set_init(recv); - this->var_->var_value()->clear_type_from_chan_element(); - } - else - { - recv->discarding_value(); - init->add_statement(Statement::make_statement(recv)); - } - } - - if (this->statements_ != NULL) - init->add_statement(Statement::make_block_statement(this->statements_, - loc)); - - this->statements_ = init; - - // Now all references should be handled through the statements, not - // through here. - this->is_lowered_ = true; - this->val_ = NULL; - this->var_ = NULL; -} - -// Determine types. - -void -Select_clauses::Select_clause::determine_types() -{ - gcc_assert(this->is_lowered_); - if (this->statements_ != NULL) - this->statements_->determine_types(); -} - -// Whether this clause may fall through to the statement which follows -// the overall select statement. - -bool -Select_clauses::Select_clause::may_fall_through() const -{ - if (this->statements_ == NULL) - return true; - return this->statements_->may_fall_through(); -} - -// Return a tree for the statements to execute. - -tree -Select_clauses::Select_clause::get_statements_tree(Translate_context* context) -{ - if (this->statements_ == NULL) - return NULL_TREE; - return this->statements_->get_tree(context); -} - -// Class Select_clauses. - -// Traversal. - -int -Select_clauses::traverse(Traverse* traverse) -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lowering. Here we pull out the channel and the send values, to -// enforce the order of evaluation. We also add explicit send and -// receive statements to the clauses. - -void -Select_clauses::lower(Block* b) -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - p->lower(b); -} - -// Determine types. - -void -Select_clauses::determine_types() -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - p->determine_types(); -} - -// Return whether these select clauses fall through to the statement -// following the overall select statement. - -bool -Select_clauses::may_fall_through() const -{ - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - if (p->may_fall_through()) - return true; - return false; -} - -// Return a tree. We build a call to -// size_t __go_select(size_t count, _Bool has_default, -// channel* channels, _Bool* is_send) -// -// There are COUNT entries in the CHANNELS and IS_SEND arrays. The -// value in the IS_SEND array is true for send, false for receive. -// __go_select returns an integer from 0 to COUNT, inclusive. A -// return of 0 means that the default case should be run; this only -// happens if HAS_DEFAULT is non-zero. Otherwise the number indicates -// the case to run. - -// FIXME: This doesn't handle channels which send interface types -// where the receiver has a static type which matches that interface. - -tree -Select_clauses::get_tree(Translate_context* context, - Unnamed_label *break_label, - source_location location) -{ - size_t count = this->clauses_.size(); - VEC(constructor_elt, gc)* chan_init = VEC_alloc(constructor_elt, gc, count); - VEC(constructor_elt, gc)* is_send_init = VEC_alloc(constructor_elt, gc, - count); - Select_clause* default_clause = NULL; - tree final_stmt_list = NULL_TREE; - tree channel_type_tree = NULL_TREE; - - size_t i = 0; - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->is_default()) - { - default_clause = &*p; - --count; - continue; - } - - tree channel_tree = p->channel()->get_tree(context); - if (channel_tree == error_mark_node) - return error_mark_node; - channel_type_tree = TREE_TYPE(channel_tree); - - constructor_elt* elt = VEC_quick_push(constructor_elt, chan_init, NULL); - elt->index = build_int_cstu(sizetype, i); - elt->value = channel_tree; - - elt = VEC_quick_push(constructor_elt, is_send_init, NULL); - elt->index = build_int_cstu(sizetype, i); - elt->value = p->is_send() ? boolean_true_node : boolean_false_node; - - ++i; - } - gcc_assert(i == count); - - if (i == 0 && default_clause != NULL) - { - // There is only a default clause. - gcc_assert(final_stmt_list == NULL_TREE); - tree stmt_list = NULL_TREE; - append_to_statement_list(default_clause->get_statements_tree(context), - &stmt_list); - append_to_statement_list(break_label->get_definition(), &stmt_list); - return stmt_list; - } - - tree pointer_chan_type_tree = (channel_type_tree == NULL_TREE - ? ptr_type_node - : build_pointer_type(channel_type_tree)); - tree chans_arg; - tree pointer_boolean_type_tree = build_pointer_type(boolean_type_node); - tree is_sends_arg; - - if (i == 0) - { - chans_arg = fold_convert_loc(location, pointer_chan_type_tree, - null_pointer_node); - is_sends_arg = fold_convert_loc(location, pointer_boolean_type_tree, - null_pointer_node); - } - else - { - tree index_type_tree = build_index_type(size_int(count - 1)); - tree chan_array_type_tree = build_array_type(channel_type_tree, - index_type_tree); - tree chan_constructor = build_constructor(chan_array_type_tree, - chan_init); - tree chan_var = create_tmp_var(chan_array_type_tree, "CHAN"); - DECL_IGNORED_P(chan_var) = 0; - DECL_INITIAL(chan_var) = chan_constructor; - DECL_SOURCE_LOCATION(chan_var) = location; - TREE_ADDRESSABLE(chan_var) = 1; - tree decl_expr = build1(DECL_EXPR, void_type_node, chan_var); - SET_EXPR_LOCATION(decl_expr, location); - append_to_statement_list(decl_expr, &final_stmt_list); - - tree is_send_array_type_tree = build_array_type(boolean_type_node, - index_type_tree); - tree is_send_constructor = build_constructor(is_send_array_type_tree, - is_send_init); - tree is_send_var = create_tmp_var(is_send_array_type_tree, "ISSEND"); - DECL_IGNORED_P(is_send_var) = 0; - DECL_INITIAL(is_send_var) = is_send_constructor; - DECL_SOURCE_LOCATION(is_send_var) = location; - TREE_ADDRESSABLE(is_send_var) = 1; - decl_expr = build1(DECL_EXPR, void_type_node, is_send_var); - SET_EXPR_LOCATION(decl_expr, location); - append_to_statement_list(decl_expr, &final_stmt_list); - - chans_arg = fold_convert_loc(location, pointer_chan_type_tree, - build_fold_addr_expr_loc(location, - chan_var)); - is_sends_arg = fold_convert_loc(location, pointer_boolean_type_tree, - build_fold_addr_expr_loc(location, - is_send_var)); - } - - static tree select_fndecl; - tree call = Gogo::call_builtin(&select_fndecl, - location, - "__go_select", - 4, - sizetype, - sizetype, - size_int(count), - boolean_type_node, - (default_clause == NULL - ? boolean_false_node - : boolean_true_node), - pointer_chan_type_tree, - chans_arg, - pointer_boolean_type_tree, - is_sends_arg); - - tree stmt_list = NULL_TREE; - - if (default_clause != NULL) - this->add_clause_tree(context, 0, default_clause, break_label, &stmt_list); - - i = 1; - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (!p->is_default()) - { - this->add_clause_tree(context, i, &*p, break_label, &stmt_list); - ++i; - } - } - - append_to_statement_list(break_label->get_definition(), &stmt_list); - - tree switch_stmt = build3(SWITCH_EXPR, sizetype, call, stmt_list, NULL_TREE); - SET_EXPR_LOCATION(switch_stmt, location); - append_to_statement_list(switch_stmt, &final_stmt_list); - - return final_stmt_list; -} - -// Add the tree for CLAUSE to STMT_LIST. - -void -Select_clauses::add_clause_tree(Translate_context* context, int case_index, - Select_clause* clause, - Unnamed_label* bottom_label, tree* stmt_list) -{ - tree label = create_artificial_label(clause->location()); - append_to_statement_list(build3(CASE_LABEL_EXPR, void_type_node, - build_int_cst(sizetype, case_index), - NULL_TREE, label), - stmt_list); - append_to_statement_list(clause->get_statements_tree(context), stmt_list); - tree g = bottom_label->get_goto(clause->statements() == NULL - ? clause->location() - : clause->statements()->end_location()); - append_to_statement_list(g, stmt_list); -} - -// Class Select_statement. - -// Return the break label for this switch statement, creating it if -// necessary. - -Unnamed_label* -Select_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Lower a select statement. This will still return a select -// statement, but it will be modified to implement the order of -// evaluation rules, and to include the send and receive statements as -// explicit statements in the clauses. - -Statement* -Select_statement::do_lower(Gogo*, Block* enclosing) -{ - if (this->is_lowered_) - return this; - Block* b = new Block(enclosing, this->location()); - this->clauses_->lower(b); - this->is_lowered_ = true; - b->add_statement(this); - return Statement::make_block_statement(b, this->location()); -} - -// Return the tree for a select statement. - -tree -Select_statement::do_get_tree(Translate_context* context) -{ - return this->clauses_->get_tree(context, this->break_label(), - this->location()); -} - -// Make a select statement. - -Select_statement* -Statement::make_select_statement(source_location location) -{ - return new Select_statement(location); -} - -// Class For_statement. - -// Traversal. - -int -For_statement::do_traverse(Traverse* traverse) -{ - if (this->init_ != NULL) - { - if (this->init_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->cond_ != NULL) - { - if (this->traverse_expression(traverse, &this->cond_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->post_ != NULL) - { - if (this->post_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return this->statements_->traverse(traverse); -} - -// Lower a For_statement into if statements and gotos. Getting rid of -// complex statements make it easier to handle garbage collection. - -Statement* -For_statement::do_lower(Gogo*, Block* enclosing) -{ - Statement* s; - source_location loc = this->location(); - - Block* b = new Block(enclosing, this->location()); - if (this->init_ != NULL) - { - s = Statement::make_block_statement(this->init_, - this->init_->start_location()); - b->add_statement(s); - } - - Unnamed_label* entry = NULL; - if (this->cond_ != NULL) - { - entry = new Unnamed_label(this->location()); - b->add_statement(Statement::make_goto_unnamed_statement(entry, loc)); - } - - Unnamed_label* top = new Unnamed_label(this->location()); - b->add_statement(Statement::make_unnamed_label_statement(top)); - - s = Statement::make_block_statement(this->statements_, - this->statements_->start_location()); - b->add_statement(s); - - source_location end_loc = this->statements_->end_location(); - - Unnamed_label* cont = this->continue_label_; - if (cont != NULL) - b->add_statement(Statement::make_unnamed_label_statement(cont)); - - if (this->post_ != NULL) - { - s = Statement::make_block_statement(this->post_, - this->post_->start_location()); - b->add_statement(s); - end_loc = this->post_->end_location(); - } - - if (this->cond_ == NULL) - b->add_statement(Statement::make_goto_unnamed_statement(top, end_loc)); - else - { - b->add_statement(Statement::make_unnamed_label_statement(entry)); - - source_location cond_loc = this->cond_->location(); - Block* then_block = new Block(b, cond_loc); - s = Statement::make_goto_unnamed_statement(top, cond_loc); - then_block->add_statement(s); - - s = Statement::make_if_statement(this->cond_, then_block, NULL, cond_loc); - b->add_statement(s); - } - - Unnamed_label* brk = this->break_label_; - if (brk != NULL) - b->add_statement(Statement::make_unnamed_label_statement(brk)); - - b->set_end_location(end_loc); - - return Statement::make_block_statement(b, loc); -} - -// Return the break label, creating it if necessary. - -Unnamed_label* -For_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Return the continue LABEL_EXPR. - -Unnamed_label* -For_statement::continue_label() -{ - if (this->continue_label_ == NULL) - this->continue_label_ = new Unnamed_label(this->location()); - return this->continue_label_; -} - -// Set the break and continue labels a for statement. This is used -// when lowering a for range statement. - -void -For_statement::set_break_continue_labels(Unnamed_label* break_label, - Unnamed_label* continue_label) -{ - gcc_assert(this->break_label_ == NULL && this->continue_label_ == NULL); - this->break_label_ = break_label; - this->continue_label_ = continue_label; -} - -// Make a for statement. - -For_statement* -Statement::make_for_statement(Block* init, Expression* cond, Block* post, - source_location location) -{ - return new For_statement(init, cond, post, location); -} - -// Class For_range_statement. - -// Traversal. - -int -For_range_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->index_var_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->value_var_ != NULL) - { - if (this->traverse_expression(traverse, &this->value_var_) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->traverse_expression(traverse, &this->range_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->statements_->traverse(traverse); -} - -// Lower a for range statement. For simplicity we lower this into a -// for statement, which will then be lowered in turn to goto -// statements. - -Statement* -For_range_statement::do_lower(Gogo* gogo, Block* enclosing) -{ - Type* range_type = this->range_->type(); - if (range_type->points_to() != NULL - && range_type->points_to()->array_type() != NULL - && !range_type->points_to()->is_open_array_type()) - range_type = range_type->points_to(); - - Type* index_type; - Type* value_type = NULL; - if (range_type->array_type() != NULL) - { - index_type = Type::lookup_integer_type("int"); - value_type = range_type->array_type()->element_type(); - } - else if (range_type->is_string_type()) - { - index_type = Type::lookup_integer_type("int"); - value_type = index_type; - } - else if (range_type->map_type() != NULL) - { - index_type = range_type->map_type()->key_type(); - value_type = range_type->map_type()->val_type(); - } - else if (range_type->channel_type() != NULL) - { - index_type = range_type->channel_type()->element_type(); - if (this->value_var_ != NULL) - { - if (!this->value_var_->type()->is_error_type()) - this->report_error(_("too many variables for range clause " - "with channel")); - return Statement::make_error_statement(this->location()); - } - } - else - { - this->report_error(_("range clause must have " - "array, slice, setring, map, or channel type")); - return Statement::make_error_statement(this->location()); - } - - source_location loc = this->location(); - Block* temp_block = new Block(enclosing, loc); - - Named_object* range_object = NULL; - Temporary_statement* range_temp = NULL; - Var_expression* ve = this->range_->var_expression(); - if (ve != NULL) - range_object = ve->named_object(); - else - { - range_temp = Statement::make_temporary(NULL, this->range_, loc); - temp_block->add_statement(range_temp); - } - - Temporary_statement* index_temp = Statement::make_temporary(index_type, - NULL, loc); - temp_block->add_statement(index_temp); - - Temporary_statement* value_temp = NULL; - if (this->value_var_ != NULL) - { - value_temp = Statement::make_temporary(value_type, NULL, loc); - temp_block->add_statement(value_temp); - } - - Block* body = new Block(temp_block, loc); - - Block* init; - Expression* cond; - Block* iter_init; - Block* post; - - // Arrange to do a loop appropriate for the type. We will produce - // for INIT ; COND ; POST { - // ITER_INIT - // INDEX = INDEX_TEMP - // VALUE = VALUE_TEMP // If there is a value - // original statements - // } - - if (range_type->array_type() != NULL) - this->lower_range_array(gogo, temp_block, body, range_object, range_temp, - index_temp, value_temp, &init, &cond, &iter_init, - &post); - else if (range_type->is_string_type()) - this->lower_range_string(gogo, temp_block, body, range_object, range_temp, - index_temp, value_temp, &init, &cond, &iter_init, - &post); - else if (range_type->map_type() != NULL) - this->lower_range_map(gogo, temp_block, body, range_object, range_temp, - index_temp, value_temp, &init, &cond, &iter_init, - &post); - else if (range_type->channel_type() != NULL) - this->lower_range_channel(gogo, temp_block, body, range_object, range_temp, - index_temp, value_temp, &init, &cond, &iter_init, - &post); - else - gcc_unreachable(); - - if (iter_init != NULL) - body->add_statement(Statement::make_block_statement(iter_init, loc)); - - Statement* assign; - Expression* index_ref = Expression::make_temporary_reference(index_temp, loc); - if (this->value_var_ == NULL) - { - assign = Statement::make_assignment(this->index_var_, index_ref, loc); - } - else - { - Expression_list* lhs = new Expression_list(); - lhs->push_back(this->index_var_); - lhs->push_back(this->value_var_); - - Expression_list* rhs = new Expression_list(); - rhs->push_back(index_ref); - rhs->push_back(Expression::make_temporary_reference(value_temp, loc)); - - assign = Statement::make_tuple_assignment(lhs, rhs, loc); - } - body->add_statement(assign); - - body->add_statement(Statement::make_block_statement(this->statements_, loc)); - - body->set_end_location(this->statements_->end_location()); - - For_statement* loop = Statement::make_for_statement(init, cond, post, - this->location()); - loop->add_statements(body); - loop->set_break_continue_labels(this->break_label_, this->continue_label_); - - temp_block->add_statement(loop); - - return Statement::make_block_statement(temp_block, loc); -} - -// Return a reference to the range, which may be in RANGE_OBJECT or in -// RANGE_TEMP. - -Expression* -For_range_statement::make_range_ref(Named_object* range_object, - Temporary_statement* range_temp, - source_location loc) -{ - if (range_object != NULL) - return Expression::make_var_reference(range_object, loc); - else - return Expression::make_temporary_reference(range_temp, loc); -} - -// Return a call to the predeclared function FUNCNAME passing a -// reference to the temporary variable ARG. - -Expression* -For_range_statement::call_builtin(Gogo* gogo, const char* funcname, - Expression* arg, - source_location loc) -{ - Named_object* no = gogo->lookup_global(funcname); - gcc_assert(no != NULL && no->is_function_declaration()); - Expression* func = Expression::make_func_reference(no, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(arg); - return Expression::make_call(func, params, false, loc); -} - -// Lower a for range over an array or slice. - -void -For_range_statement::lower_range_array(Gogo* gogo, - Block* enclosing, - Block* body_block, - Named_object* range_object, - Temporary_statement* range_temp, - Temporary_statement* index_temp, - Temporary_statement* value_temp, - Block** pinit, - Expression** pcond, - Block** piter_init, - Block** ppost) -{ - source_location loc = this->location(); - - // The loop we generate: - // len_temp := len(range) - // for index_temp = 0; index_temp < len_temp; index_temp++ { - // value_temp = range[index_temp] - // index = index_temp - // value = value_temp - // original body - // } - - // Set *PINIT to - // var len_temp int - // len_temp = len(range) - // index_temp = 0 - - Block* init = new Block(enclosing, loc); - - Expression* ref = this->make_range_ref(range_object, range_temp, loc); - Expression* len_call = this->call_builtin(gogo, "len", ref, loc); - Temporary_statement* len_temp = Statement::make_temporary(index_temp->type(), - len_call, loc); - init->add_statement(len_temp); - - mpz_t zval; - mpz_init_set_ui(zval, 0UL); - Expression* zexpr = Expression::make_integer(&zval, NULL, loc); - mpz_clear(zval); - - ref = Expression::make_temporary_reference(index_temp, loc); - Statement* s = Statement::make_assignment(ref, zexpr, loc); - init->add_statement(s); - - *pinit = init; - - // Set *PCOND to - // index_temp < len_temp - - ref = Expression::make_temporary_reference(index_temp, loc); - Expression* ref2 = Expression::make_temporary_reference(len_temp, loc); - Expression* lt = Expression::make_binary(OPERATOR_LT, ref, ref2, loc); - - *pcond = lt; - - // Set *PITER_INIT to - // value_temp = range[index_temp] - - Block* iter_init = NULL; - if (value_temp != NULL) - { - iter_init = new Block(body_block, loc); - - ref = this->make_range_ref(range_object, range_temp, loc); - Expression* ref2 = Expression::make_temporary_reference(index_temp, loc); - Expression* index = Expression::make_index(ref, ref2, NULL, loc); - - ref = Expression::make_temporary_reference(value_temp, loc); - s = Statement::make_assignment(ref, index, loc); - - iter_init->add_statement(s); - } - *piter_init = iter_init; - - // Set *PPOST to - // index_temp++ - - Block* post = new Block(enclosing, loc); - ref = Expression::make_temporary_reference(index_temp, loc); - s = Statement::make_inc_statement(ref); - post->add_statement(s); - *ppost = post; -} - -// Lower a for range over a string. - -void -For_range_statement::lower_range_string(Gogo* gogo, - Block* enclosing, - Block* body_block, - Named_object* range_object, - Temporary_statement* range_temp, - Temporary_statement* index_temp, - Temporary_statement* value_temp, - Block** pinit, - Expression** pcond, - Block** piter_init, - Block** ppost) -{ - source_location loc = this->location(); - - // The loop we generate: - // var next_index_temp int - // for index_temp = 0; ; index_temp = next_index_temp { - // next_index_temp, value_temp = stringiter2(range, index_temp) - // if next_index_temp == 0 { - // break - // } - // index = index_temp - // value = value_temp - // original body - // } - - // Set *PINIT to - // var next_index_temp int - // index_temp = 0 - - Block* init = new Block(enclosing, loc); - - Temporary_statement* next_index_temp = - Statement::make_temporary(index_temp->type(), NULL, loc); - init->add_statement(next_index_temp); - - mpz_t zval; - mpz_init_set_ui(zval, 0UL); - Expression* zexpr = Expression::make_integer(&zval, NULL, loc); - - Expression* ref = Expression::make_temporary_reference(index_temp, loc); - Statement* s = Statement::make_assignment(ref, zexpr, loc); - - init->add_statement(s); - *pinit = init; - - // The loop has no condition. - - *pcond = NULL; - - // Set *PITER_INIT to - // next_index_temp = runtime.stringiter(range, index_temp) - // or - // next_index_temp, value_temp = runtime.stringiter2(range, index_temp) - // followed by - // if next_index_temp == 0 { - // break - // } - - Block* iter_init = new Block(body_block, loc); - - Named_object* no; - if (value_temp == NULL) - { - static Named_object* stringiter; - if (stringiter == NULL) - { - source_location bloc = BUILTINS_LOCATION; - Type* int_type = gogo->lookup_global("int")->type_value(); - - Typed_identifier_list* params = new Typed_identifier_list(); - params->push_back(Typed_identifier("s", Type::make_string_type(), - bloc)); - params->push_back(Typed_identifier("k", int_type, bloc)); - - Typed_identifier_list* results = new Typed_identifier_list(); - results->push_back(Typed_identifier("", int_type, bloc)); - - Function_type* fntype = Type::make_function_type(NULL, params, - results, bloc); - stringiter = Named_object::make_function_declaration("stringiter", - NULL, fntype, - bloc); - const char* n = "runtime.stringiter"; - stringiter->func_declaration_value()->set_asm_name(n); - } - no = stringiter; - } - else - { - static Named_object* stringiter2; - if (stringiter2 == NULL) - { - source_location bloc = BUILTINS_LOCATION; - Type* int_type = gogo->lookup_global("int")->type_value(); - - Typed_identifier_list* params = new Typed_identifier_list(); - params->push_back(Typed_identifier("s", Type::make_string_type(), - bloc)); - params->push_back(Typed_identifier("k", int_type, bloc)); - - Typed_identifier_list* results = new Typed_identifier_list(); - results->push_back(Typed_identifier("", int_type, bloc)); - results->push_back(Typed_identifier("", int_type, bloc)); - - Function_type* fntype = Type::make_function_type(NULL, params, - results, bloc); - stringiter2 = Named_object::make_function_declaration("stringiter", - NULL, fntype, - bloc); - const char* n = "runtime.stringiter2"; - stringiter2->func_declaration_value()->set_asm_name(n); - } - no = stringiter2; - } - - Expression* func = Expression::make_func_reference(no, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(this->make_range_ref(range_object, range_temp, loc)); - params->push_back(Expression::make_temporary_reference(index_temp, loc)); - Call_expression* call = Expression::make_call(func, params, false, loc); - - if (value_temp == NULL) - { - ref = Expression::make_temporary_reference(next_index_temp, loc); - s = Statement::make_assignment(ref, call, loc); - } - else - { - Expression_list* lhs = new Expression_list(); - lhs->push_back(Expression::make_temporary_reference(next_index_temp, - loc)); - lhs->push_back(Expression::make_temporary_reference(value_temp, loc)); - - Expression_list* rhs = new Expression_list(); - rhs->push_back(Expression::make_call_result(call, 0)); - rhs->push_back(Expression::make_call_result(call, 1)); - - s = Statement::make_tuple_assignment(lhs, rhs, loc); - } - iter_init->add_statement(s); - - ref = Expression::make_temporary_reference(next_index_temp, loc); - zexpr = Expression::make_integer(&zval, NULL, loc); - mpz_clear(zval); - Expression* equals = Expression::make_binary(OPERATOR_EQEQ, ref, zexpr, loc); - - Block* then_block = new Block(iter_init, loc); - s = Statement::make_break_statement(this->break_label(), loc); - then_block->add_statement(s); - - s = Statement::make_if_statement(equals, then_block, NULL, loc); - iter_init->add_statement(s); - - *piter_init = iter_init; - - // Set *PPOST to - // index_temp = next_index_temp - - Block* post = new Block(enclosing, loc); - - Expression* lhs = Expression::make_temporary_reference(index_temp, loc); - Expression* rhs = Expression::make_temporary_reference(next_index_temp, loc); - s = Statement::make_assignment(lhs, rhs, loc); - - post->add_statement(s); - *ppost = post; -} - -// Lower a for range over a map. - -void -For_range_statement::lower_range_map(Gogo* gogo, - Block* enclosing, - Block* body_block, - Named_object* range_object, - Temporary_statement* range_temp, - Temporary_statement* index_temp, - Temporary_statement* value_temp, - Block** pinit, - Expression** pcond, - Block** piter_init, - Block** ppost) -{ - source_location loc = this->location(); - - // The runtime uses a struct to handle ranges over a map. The - // struct is four pointers long. The first pointer is NULL when we - // have completed the iteration. - - // The loop we generate: - // var hiter map_iteration_struct - // for mapiterinit(range, &hiter); hiter[0] != nil; mapiternext(&hiter) { - // mapiter2(hiter, &index_temp, &value_temp) - // index = index_temp - // value = value_temp - // original body - // } - - // Set *PINIT to - // var hiter map_iteration_struct - // runtime.mapiterinit(range, &hiter) - - Block* init = new Block(enclosing, loc); - - const unsigned long map_iteration_size = 4; - - mpz_t ival; - mpz_init_set_ui(ival, map_iteration_size); - Expression* iexpr = Expression::make_integer(&ival, NULL, loc); - mpz_clear(ival); - - Type* byte_type = gogo->lookup_global("byte")->type_value(); - Type* ptr_type = Type::make_pointer_type(byte_type); - - Type* map_iteration_type = Type::make_array_type(ptr_type, iexpr); - Type* map_iteration_ptr = Type::make_pointer_type(map_iteration_type); - - Temporary_statement* hiter = Statement::make_temporary(map_iteration_type, - NULL, loc); - init->add_statement(hiter); - - source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("map", this->range_->type(), bloc)); - param_types->push_back(Typed_identifier("it", map_iteration_ptr, bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, NULL, - bloc); - - Named_object* mapiterinit = - Named_object::make_function_declaration("mapiterinit", NULL, fntype, bloc); - const char* n = "runtime.mapiterinit"; - mapiterinit->func_declaration_value()->set_asm_name(n); - - Expression* func = Expression::make_func_reference(mapiterinit, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(this->make_range_ref(range_object, range_temp, loc)); - Expression* ref = Expression::make_temporary_reference(hiter, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - Expression* call = Expression::make_call(func, params, false, loc); - init->add_statement(Statement::make_statement(call)); - - *pinit = init; - - // Set *PCOND to - // hiter[0] != nil - - ref = Expression::make_temporary_reference(hiter, loc); - - mpz_t zval; - mpz_init_set_ui(zval, 0UL); - Expression* zexpr = Expression::make_integer(&zval, NULL, loc); - mpz_clear(zval); - - Expression* index = Expression::make_index(ref, zexpr, NULL, loc); - - Expression* ne = Expression::make_binary(OPERATOR_NOTEQ, index, - Expression::make_nil(loc), - loc); - - *pcond = ne; - - // Set *PITER_INIT to - // mapiter1(hiter, &index_temp) - // or - // mapiter2(hiter, &index_temp, &value_temp) - - Block* iter_init = new Block(body_block, loc); - - param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("hiter", map_iteration_ptr, bloc)); - Type* pkey_type = Type::make_pointer_type(index_temp->type()); - param_types->push_back(Typed_identifier("key", pkey_type, bloc)); - if (value_temp != NULL) - { - Type* pval_type = Type::make_pointer_type(value_temp->type()); - param_types->push_back(Typed_identifier("val", pval_type, bloc)); - } - fntype = Type::make_function_type(NULL, param_types, NULL, bloc); - n = value_temp == NULL ? "mapiter1" : "mapiter2"; - Named_object* mapiter = Named_object::make_function_declaration(n, NULL, - fntype, bloc); - n = value_temp == NULL ? "runtime.mapiter1" : "runtime.mapiter2"; - mapiter->func_declaration_value()->set_asm_name(n); - - func = Expression::make_func_reference(mapiter, NULL, loc); - params = new Expression_list(); - ref = Expression::make_temporary_reference(hiter, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - ref = Expression::make_temporary_reference(index_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - if (value_temp != NULL) - { - ref = Expression::make_temporary_reference(value_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - } - call = Expression::make_call(func, params, false, loc); - iter_init->add_statement(Statement::make_statement(call)); - - *piter_init = iter_init; - - // Set *PPOST to - // mapiternext(&hiter) - - Block* post = new Block(enclosing, loc); - - static Named_object* mapiternext; - if (mapiternext == NULL) - { - param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("it", map_iteration_ptr, bloc)); - fntype = Type::make_function_type(NULL, param_types, NULL, bloc); - mapiternext = Named_object::make_function_declaration("mapiternext", - NULL, fntype, - bloc); - const char* n = "runtime.mapiternext"; - mapiternext->func_declaration_value()->set_asm_name(n); - } - - func = Expression::make_func_reference(mapiternext, NULL, loc); - params = new Expression_list(); - ref = Expression::make_temporary_reference(hiter, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - call = Expression::make_call(func, params, false, loc); - post->add_statement(Statement::make_statement(call)); - - *ppost = post; -} - -// Lower a for range over a channel. - -void -For_range_statement::lower_range_channel(Gogo* gogo, - Block*, - Block* body_block, - Named_object* range_object, - Temporary_statement* range_temp, - Temporary_statement* index_temp, - Temporary_statement* value_temp, - Block** pinit, - Expression** pcond, - Block** piter_init, - Block** ppost) -{ - gcc_assert(value_temp == NULL); - - source_location loc = this->location(); - - // The loop we generate: - // for { - // index_temp = <-range - // if closed(range) { - // break - // } - // index = index_temp - // value = value_temp - // original body - // } - - // We have no initialization code, no condition, and no post code. - - *pinit = NULL; - *pcond = NULL; - *ppost = NULL; - - // Set *PITER_INIT to - // index_temp = <-range - // if closed(range) { - // break - // } - - Block* iter_init = new Block(body_block, loc); - - Expression* ref = this->make_range_ref(range_object, range_temp, loc); - Expression* cond = this->call_builtin(gogo, "closed", ref, loc); - - ref = this->make_range_ref(range_object, range_temp, loc); - Expression* recv = Expression::make_receive(ref, loc); - ref = Expression::make_temporary_reference(index_temp, loc); - Statement* s = Statement::make_assignment(ref, recv, loc); - iter_init->add_statement(s); - - Block* then_block = new Block(iter_init, loc); - s = Statement::make_break_statement(this->break_label(), loc); - then_block->add_statement(s); - - s = Statement::make_if_statement(cond, then_block, NULL, loc); - iter_init->add_statement(s); - - *piter_init = iter_init; -} - -// Return the break LABEL_EXPR. - -Unnamed_label* -For_range_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Return the continue LABEL_EXPR. - -Unnamed_label* -For_range_statement::continue_label() -{ - if (this->continue_label_ == NULL) - this->continue_label_ = new Unnamed_label(this->location()); - return this->continue_label_; -} - -// Make a for statement with a range clause. - -For_range_statement* -Statement::make_for_range_statement(Expression* index_var, - Expression* value_var, - Expression* range, - source_location location) -{ - return new For_range_statement(index_var, value_var, range, location); -} diff --git a/gcc/go/gofrontend/statements.cc.merge-right.r172891 b/gcc/go/gofrontend/statements.cc.merge-right.r172891 deleted file mode 100644 index 7e422fc94b7..00000000000 --- a/gcc/go/gofrontend/statements.cc.merge-right.r172891 +++ /dev/null @@ -1,5073 +0,0 @@ -// statements.cc -- Go frontend statements. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include - -#include "go-c.h" -#include "types.h" -#include "expressions.h" -#include "gogo.h" -#include "runtime.h" -#include "backend.h" -#include "statements.h" - -// Class Statement. - -Statement::Statement(Statement_classification classification, - source_location location) - : classification_(classification), location_(location) -{ -} - -Statement::~Statement() -{ -} - -// Traverse the tree. The work of walking the components is handled -// by the subclasses. - -int -Statement::traverse(Block* block, size_t* pindex, Traverse* traverse) -{ - if (this->classification_ == STATEMENT_ERROR) - return TRAVERSE_CONTINUE; - - unsigned int traverse_mask = traverse->traverse_mask(); - - if ((traverse_mask & Traverse::traverse_statements) != 0) - { - int t = traverse->statement(block, pindex, this); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - return TRAVERSE_CONTINUE; - } - - // No point in checking traverse_mask here--a statement may contain - // other blocks or statements, and if we got here we always want to - // walk them. - return this->do_traverse(traverse); -} - -// Traverse the contents of a statement. - -int -Statement::traverse_contents(Traverse* traverse) -{ - return this->do_traverse(traverse); -} - -// Traverse assignments. - -bool -Statement::traverse_assignments(Traverse_assignments* tassign) -{ - if (this->classification_ == STATEMENT_ERROR) - return false; - return this->do_traverse_assignments(tassign); -} - -// Traverse an expression in a statement. This is a helper function -// for child classes. - -int -Statement::traverse_expression(Traverse* traverse, Expression** expr) -{ - if ((traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) == 0) - return TRAVERSE_CONTINUE; - return Expression::traverse(expr, traverse); -} - -// Traverse an expression list in a statement. This is a helper -// function for child classes. - -int -Statement::traverse_expression_list(Traverse* traverse, - Expression_list* expr_list) -{ - if (expr_list == NULL) - return TRAVERSE_CONTINUE; - if ((traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) == 0) - return TRAVERSE_CONTINUE; - return expr_list->traverse(traverse); -} - -// Traverse a type in a statement. This is a helper function for -// child classes. - -int -Statement::traverse_type(Traverse* traverse, Type* type) -{ - if ((traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) == 0) - return TRAVERSE_CONTINUE; - return Type::traverse(type, traverse); -} - -// Set type information for unnamed constants. This is really done by -// the child class. - -void -Statement::determine_types() -{ - this->do_determine_types(); -} - -// If this is a thunk statement, return it. - -Thunk_statement* -Statement::thunk_statement() -{ - Thunk_statement* ret = this->convert(); - if (ret == NULL) - ret = this->convert(); - return ret; -} - -// Convert a Statement to the backend representation. This is really -// done by the child class. - -Bstatement* -Statement::get_backend(Translate_context* context) -{ - if (this->classification_ == STATEMENT_ERROR) - return context->backend()->error_statement(); - return this->do_get_backend(context); -} - -// Note that this statement is erroneous. This is called by children -// when they discover an error. - -void -Statement::set_is_error() -{ - this->classification_ = STATEMENT_ERROR; -} - -// For children to call to report an error conveniently. - -void -Statement::report_error(const char* msg) -{ - error_at(this->location_, "%s", msg); - this->set_is_error(); -} - -// An error statement, used to avoid crashing after we report an -// error. - -class Error_statement : public Statement -{ - public: - Error_statement(source_location location) - : Statement(STATEMENT_ERROR, location) - { } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - Bstatement* - do_get_backend(Translate_context*) - { go_unreachable(); } -}; - -// Make an error statement. - -Statement* -Statement::make_error_statement(source_location location) -{ - return new Error_statement(location); -} - -// Class Variable_declaration_statement. - -Variable_declaration_statement::Variable_declaration_statement( - Named_object* var) - : Statement(STATEMENT_VARIABLE_DECLARATION, var->var_value()->location()), - var_(var) -{ -} - -// We don't actually traverse the variable here; it was traversed -// while traversing the Block. - -int -Variable_declaration_statement::do_traverse(Traverse*) -{ - return TRAVERSE_CONTINUE; -} - -// Traverse the assignments in a variable declaration. Note that this -// traversal is different from the usual traversal. - -bool -Variable_declaration_statement::do_traverse_assignments( - Traverse_assignments* tassign) -{ - tassign->initialize_variable(this->var_); - return true; -} - -// Convert a variable declaration to the backend representation. - -Bstatement* -Variable_declaration_statement::do_get_backend(Translate_context* context) -{ - Variable* var = this->var_->var_value(); - Bvariable* bvar = this->var_->get_backend_variable(context->gogo(), - context->function()); - tree init = var->get_init_tree(context->gogo(), context->function()); - Bexpression* binit = init == NULL ? NULL : tree_to_expr(init); - - if (!var->is_in_heap()) - { - go_assert(binit != NULL); - return context->backend()->init_statement(bvar, binit); - } - - // Something takes the address of this variable, so the value is - // stored in the heap. Initialize it to newly allocated memory - // space, and assign the initial value to the new space. - source_location loc = this->location(); - Named_object* newfn = context->gogo()->lookup_global("new"); - go_assert(newfn != NULL && newfn->is_function_declaration()); - Expression* func = Expression::make_func_reference(newfn, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(Expression::make_type(var->type(), loc)); - Expression* call = Expression::make_call(func, params, false, loc); - context->gogo()->lower_expression(context->function(), &call); - Temporary_statement* temp = Statement::make_temporary(NULL, call, loc); - Bstatement* btemp = temp->get_backend(context); - - Bstatement* set = NULL; - if (binit != NULL) - { - Expression* e = Expression::make_temporary_reference(temp, loc); - e = Expression::make_unary(OPERATOR_MULT, e, loc); - Bexpression* be = tree_to_expr(e->get_tree(context)); - set = context->backend()->assignment_statement(be, binit, loc); - } - - Expression* ref = Expression::make_temporary_reference(temp, loc); - Bexpression* bref = tree_to_expr(ref->get_tree(context)); - Bstatement* sinit = context->backend()->init_statement(bvar, bref); - - std::vector stats; - stats.reserve(3); - stats.push_back(btemp); - if (set != NULL) - stats.push_back(set); - stats.push_back(sinit); - return context->backend()->statement_list(stats); -} - -// Make a variable declaration. - -Statement* -Statement::make_variable_declaration(Named_object* var) -{ - return new Variable_declaration_statement(var); -} - -// Class Temporary_statement. - -// Return the type of the temporary variable. - -Type* -Temporary_statement::type() const -{ - return this->type_ != NULL ? this->type_ : this->init_->type(); -} - -// Traversal. - -int -Temporary_statement::do_traverse(Traverse* traverse) -{ - if (this->type_ != NULL - && this->traverse_type(traverse, this->type_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->init_ == NULL) - return TRAVERSE_CONTINUE; - else - return this->traverse_expression(traverse, &this->init_); -} - -// Traverse assignments. - -bool -Temporary_statement::do_traverse_assignments(Traverse_assignments* tassign) -{ - if (this->init_ == NULL) - return false; - tassign->value(&this->init_, true, true); - return true; -} - -// Determine types. - -void -Temporary_statement::do_determine_types() -{ - if (this->type_ != NULL && this->type_->is_abstract()) - this->type_ = this->type_->make_non_abstract_type(); - - if (this->init_ != NULL) - { - if (this->type_ == NULL) - this->init_->determine_type_no_context(); - else - { - Type_context context(this->type_, false); - this->init_->determine_type(&context); - } - } - - if (this->type_ == NULL) - { - this->type_ = this->init_->type(); - go_assert(!this->type_->is_abstract()); - } -} - -// Check types. - -void -Temporary_statement::do_check_types(Gogo*) -{ - if (this->type_ != NULL && this->init_ != NULL) - { - std::string reason; - if (!Type::are_assignable(this->type_, this->init_->type(), &reason)) - { - if (reason.empty()) - error_at(this->location(), "incompatible types in assignment"); - else - error_at(this->location(), "incompatible types in assignment (%s)", - reason.c_str()); - this->set_is_error(); - } - } -} - -// Convert to backend representation. - -Bstatement* -Temporary_statement::do_get_backend(Translate_context* context) -{ - go_assert(this->bvariable_ == NULL); - - // FIXME: Permitting FUNCTION to be NULL here is a temporary measure - // until we have a better representation of the init function. - Named_object* function = context->function(); - Bfunction* bfunction; - if (function == NULL) - bfunction = NULL; - else - bfunction = tree_to_function(function->func_value()->get_decl()); - - Btype* btype = tree_to_type(this->type()->get_tree(context->gogo())); - - Bexpression* binit; - if (this->init_ == NULL) - binit = NULL; - else if (this->type_ == NULL) - binit = tree_to_expr(this->init_->get_tree(context)); - else - { - Expression* init = Expression::make_cast(this->type_, this->init_, - this->location()); - context->gogo()->lower_expression(context->function(), &init); - binit = tree_to_expr(init->get_tree(context)); - } - - Bstatement* statement; - this->bvariable_ = - context->backend()->temporary_variable(bfunction, context->bblock(), - btype, binit, - this->is_address_taken_, - this->location(), &statement); - return statement; -} - -// Return the backend variable. - -Bvariable* -Temporary_statement::get_backend_variable(Translate_context* context) const -{ - if (this->bvariable_ == NULL) - { - go_assert(saw_errors()); - return context->backend()->error_variable(); - } - return this->bvariable_; -} - -// Make and initialize a temporary variable in BLOCK. - -Temporary_statement* -Statement::make_temporary(Type* type, Expression* init, - source_location location) -{ - return new Temporary_statement(type, init, location); -} - -// An assignment statement. - -class Assignment_statement : public Statement -{ - public: - Assignment_statement(Expression* lhs, Expression* rhs, - source_location location) - : Statement(STATEMENT_ASSIGNMENT, location), - lhs_(lhs), rhs_(rhs) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - Bstatement* - do_get_backend(Translate_context*); - - private: - // Left hand side--the lvalue. - Expression* lhs_; - // Right hand side--the rvalue. - Expression* rhs_; -}; - -// Traversal. - -int -Assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->lhs_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->rhs_); -} - -bool -Assignment_statement::do_traverse_assignments(Traverse_assignments* tassign) -{ - tassign->assignment(&this->lhs_, &this->rhs_); - return true; -} - -// Set types for the assignment. - -void -Assignment_statement::do_determine_types() -{ - this->lhs_->determine_type_no_context(); - Type_context context(this->lhs_->type(), false); - this->rhs_->determine_type(&context); -} - -// Check types for an assignment. - -void -Assignment_statement::do_check_types(Gogo*) -{ - // The left hand side must be either addressable, a map index - // expression, or the blank identifier. - if (!this->lhs_->is_addressable() - && this->lhs_->map_index_expression() == NULL - && !this->lhs_->is_sink_expression()) - { - if (!this->lhs_->type()->is_error()) - this->report_error(_("invalid left hand side of assignment")); - return; - } - - Type* lhs_type = this->lhs_->type(); - Type* rhs_type = this->rhs_->type(); - std::string reason; - if (!Type::are_assignable(lhs_type, rhs_type, &reason)) - { - if (reason.empty()) - error_at(this->location(), "incompatible types in assignment"); - else - error_at(this->location(), "incompatible types in assignment (%s)", - reason.c_str()); - this->set_is_error(); - } - - if (lhs_type->is_error() || rhs_type->is_error()) - this->set_is_error(); -} - -// Convert an assignment statement to the backend representation. - -Bstatement* -Assignment_statement::do_get_backend(Translate_context* context) -{ - tree rhs_tree = this->rhs_->get_tree(context); - if (this->lhs_->is_sink_expression()) - return context->backend()->expression_statement(tree_to_expr(rhs_tree)); - tree lhs_tree = this->lhs_->get_tree(context); - rhs_tree = Expression::convert_for_assignment(context, this->lhs_->type(), - this->rhs_->type(), rhs_tree, - this->location()); - return context->backend()->assignment_statement(tree_to_expr(lhs_tree), - tree_to_expr(rhs_tree), - this->location()); -} - -// Make an assignment statement. - -Statement* -Statement::make_assignment(Expression* lhs, Expression* rhs, - source_location location) -{ - return new Assignment_statement(lhs, rhs, location); -} - -// The Move_ordered_evals class is used to find any subexpressions of -// an expression that have an evaluation order dependency. It creates -// temporary variables to hold them. - -class Move_ordered_evals : public Traverse -{ - public: - Move_ordered_evals(Block* block) - : Traverse(traverse_expressions), - block_(block) - { } - - protected: - int - expression(Expression**); - - private: - // The block where new temporary variables should be added. - Block* block_; -}; - -int -Move_ordered_evals::expression(Expression** pexpr) -{ - // We have to look at subexpressions first. - if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if ((*pexpr)->must_eval_in_order()) - { - source_location loc = (*pexpr)->location(); - Temporary_statement* temp = Statement::make_temporary(NULL, *pexpr, loc); - this->block_->add_statement(temp); - *pexpr = Expression::make_temporary_reference(temp, loc); - } - return TRAVERSE_SKIP_COMPONENTS; -} - -// An assignment operation statement. - -class Assignment_operation_statement : public Statement -{ - public: - Assignment_operation_statement(Operator op, Expression* lhs, Expression* rhs, - source_location location) - : Statement(STATEMENT_ASSIGNMENT_OPERATION, location), - op_(op), lhs_(lhs), rhs_(rhs) - { } - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*) - { go_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - Bstatement* - do_get_backend(Translate_context*) - { go_unreachable(); } - - private: - // The operator (OPERATOR_PLUSEQ, etc.). - Operator op_; - // Left hand side. - Expression* lhs_; - // Right hand side. - Expression* rhs_; -}; - -// Traversal. - -int -Assignment_operation_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->lhs_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->rhs_); -} - -// Lower an assignment operation statement to a regular assignment -// statement. - -Statement* -Assignment_operation_statement::do_lower(Gogo*, Named_object*, - Block* enclosing) -{ - source_location loc = this->location(); - - // We have to evaluate the left hand side expression only once. We - // do this by moving out any expression with side effects. - Block* b = new Block(enclosing, loc); - Move_ordered_evals moe(b); - this->lhs_->traverse_subexpressions(&moe); - - Expression* lval = this->lhs_->copy(); - - Operator op; - switch (this->op_) - { - case OPERATOR_PLUSEQ: - op = OPERATOR_PLUS; - break; - case OPERATOR_MINUSEQ: - op = OPERATOR_MINUS; - break; - case OPERATOR_OREQ: - op = OPERATOR_OR; - break; - case OPERATOR_XOREQ: - op = OPERATOR_XOR; - break; - case OPERATOR_MULTEQ: - op = OPERATOR_MULT; - break; - case OPERATOR_DIVEQ: - op = OPERATOR_DIV; - break; - case OPERATOR_MODEQ: - op = OPERATOR_MOD; - break; - case OPERATOR_LSHIFTEQ: - op = OPERATOR_LSHIFT; - break; - case OPERATOR_RSHIFTEQ: - op = OPERATOR_RSHIFT; - break; - case OPERATOR_ANDEQ: - op = OPERATOR_AND; - break; - case OPERATOR_BITCLEAREQ: - op = OPERATOR_BITCLEAR; - break; - default: - go_unreachable(); - } - - Expression* binop = Expression::make_binary(op, lval, this->rhs_, loc); - Statement* s = Statement::make_assignment(this->lhs_, binop, loc); - if (b->statements()->empty()) - { - delete b; - return s; - } - else - { - b->add_statement(s); - return Statement::make_block_statement(b, loc); - } -} - -// Make an assignment operation statement. - -Statement* -Statement::make_assignment_operation(Operator op, Expression* lhs, - Expression* rhs, source_location location) -{ - return new Assignment_operation_statement(op, lhs, rhs, location); -} - -// A tuple assignment statement. This differs from an assignment -// statement in that the right-hand-side expressions are evaluated in -// parallel. - -class Tuple_assignment_statement : public Statement -{ - public: - Tuple_assignment_statement(Expression_list* lhs, Expression_list* rhs, - source_location location) - : Statement(STATEMENT_TUPLE_ASSIGNMENT, location), - lhs_(lhs), rhs_(rhs) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*) - { go_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - Bstatement* - do_get_backend(Translate_context*) - { go_unreachable(); } - - private: - // Left hand side--a list of lvalues. - Expression_list* lhs_; - // Right hand side--a list of rvalues. - Expression_list* rhs_; -}; - -// Traversal. - -int -Tuple_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression_list(traverse, this->lhs_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression_list(traverse, this->rhs_); -} - -// Lower a tuple assignment. We use temporary variables to split it -// up into a set of single assignments. - -Statement* -Tuple_assignment_statement::do_lower(Gogo*, Named_object*, Block* enclosing) -{ - source_location loc = this->location(); - - Block* b = new Block(enclosing, loc); - - // First move out any subexpressions on the left hand side. The - // right hand side will be evaluated in the required order anyhow. - Move_ordered_evals moe(b); - for (Expression_list::const_iterator plhs = this->lhs_->begin(); - plhs != this->lhs_->end(); - ++plhs) - (*plhs)->traverse_subexpressions(&moe); - - std::vector temps; - temps.reserve(this->lhs_->size()); - - Expression_list::const_iterator prhs = this->rhs_->begin(); - for (Expression_list::const_iterator plhs = this->lhs_->begin(); - plhs != this->lhs_->end(); - ++plhs, ++prhs) - { - go_assert(prhs != this->rhs_->end()); - - if ((*plhs)->is_error_expression() - || (*plhs)->type()->is_error() - || (*prhs)->is_error_expression() - || (*prhs)->type()->is_error()) - continue; - - if ((*plhs)->is_sink_expression()) - { - b->add_statement(Statement::make_statement(*prhs)); - continue; - } - - Temporary_statement* temp = Statement::make_temporary((*plhs)->type(), - *prhs, loc); - b->add_statement(temp); - temps.push_back(temp); - - } - go_assert(prhs == this->rhs_->end()); - - prhs = this->rhs_->begin(); - std::vector::const_iterator ptemp = temps.begin(); - for (Expression_list::const_iterator plhs = this->lhs_->begin(); - plhs != this->lhs_->end(); - ++plhs, ++prhs) - { - if ((*plhs)->is_error_expression() - || (*plhs)->type()->is_error() - || (*prhs)->is_error_expression() - || (*prhs)->type()->is_error()) - continue; - - if ((*plhs)->is_sink_expression()) - continue; - - Expression* ref = Expression::make_temporary_reference(*ptemp, loc); - Statement* s = Statement::make_assignment(*plhs, ref, loc); - b->add_statement(s); - ++ptemp; - } - go_assert(ptemp == temps.end()); - - return Statement::make_block_statement(b, loc); -} - -// Make a tuple assignment statement. - -Statement* -Statement::make_tuple_assignment(Expression_list* lhs, Expression_list* rhs, - source_location location) -{ - return new Tuple_assignment_statement(lhs, rhs, location); -} - -// A tuple assignment from a map index expression. -// v, ok = m[k] - -class Tuple_map_assignment_statement : public Statement -{ -public: - Tuple_map_assignment_statement(Expression* val, Expression* present, - Expression* map_index, - source_location location) - : Statement(STATEMENT_TUPLE_MAP_ASSIGNMENT, location), - val_(val), present_(present), map_index_(map_index) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*) - { go_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - Bstatement* - do_get_backend(Translate_context*) - { go_unreachable(); } - - private: - // Lvalue which receives the value from the map. - Expression* val_; - // Lvalue which receives whether the key value was present. - Expression* present_; - // The map index expression. - Expression* map_index_; -}; - -// Traversal. - -int -Tuple_map_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT - || this->traverse_expression(traverse, &this->present_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->map_index_); -} - -// Lower a tuple map assignment. - -Statement* -Tuple_map_assignment_statement::do_lower(Gogo*, Named_object*, - Block* enclosing) -{ - source_location loc = this->location(); - - Map_index_expression* map_index = this->map_index_->map_index_expression(); - if (map_index == NULL) - { - this->report_error(_("expected map index on right hand side")); - return Statement::make_error_statement(loc); - } - Map_type* map_type = map_index->get_map_type(); - if (map_type == NULL) - return Statement::make_error_statement(loc); - - Block* b = new Block(enclosing, loc); - - // Move out any subexpressions to make sure that functions are - // called in the required order. - Move_ordered_evals moe(b); - this->val_->traverse_subexpressions(&moe); - this->present_->traverse_subexpressions(&moe); - - // Copy the key value into a temporary so that we can take its - // address without pushing the value onto the heap. - - // var key_temp KEY_TYPE = MAP_INDEX - Temporary_statement* key_temp = - Statement::make_temporary(map_type->key_type(), map_index->index(), loc); - b->add_statement(key_temp); - - // var val_temp VAL_TYPE - Temporary_statement* val_temp = - Statement::make_temporary(map_type->val_type(), NULL, loc); - b->add_statement(val_temp); - - // var present_temp bool - Temporary_statement* present_temp = - Statement::make_temporary(Type::lookup_bool_type(), NULL, loc); - b->add_statement(present_temp); - - // present_temp = mapaccess2(MAP, &key_temp, &val_temp) - Expression* ref = Expression::make_temporary_reference(key_temp, loc); - Expression* a1 = Expression::make_unary(OPERATOR_AND, ref, loc); - ref = Expression::make_temporary_reference(val_temp, loc); - Expression* a2 = Expression::make_unary(OPERATOR_AND, ref, loc); - Expression* call = Runtime::make_call(Runtime::MAPACCESS2, loc, 3, - map_index->map(), a1, a2); - - ref = Expression::make_temporary_reference(present_temp, loc); - Statement* s = Statement::make_assignment(ref, call, loc); - b->add_statement(s); - - // val = val_temp - ref = Expression::make_temporary_reference(val_temp, loc); - s = Statement::make_assignment(this->val_, ref, loc); - b->add_statement(s); - - // present = present_temp - ref = Expression::make_temporary_reference(present_temp, loc); - s = Statement::make_assignment(this->present_, ref, loc); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Make a map assignment statement which returns a pair of values. - -Statement* -Statement::make_tuple_map_assignment(Expression* val, Expression* present, - Expression* map_index, - source_location location) -{ - return new Tuple_map_assignment_statement(val, present, map_index, location); -} - -// Assign a pair of entries to a map. -// m[k] = v, p - -class Map_assignment_statement : public Statement -{ - public: - Map_assignment_statement(Expression* map_index, - Expression* val, Expression* should_set, - source_location location) - : Statement(STATEMENT_MAP_ASSIGNMENT, location), - map_index_(map_index), val_(val), should_set_(should_set) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*) - { go_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - Bstatement* - do_get_backend(Translate_context*) - { go_unreachable(); } - - private: - // A reference to the map index which should be set or deleted. - Expression* map_index_; - // The value to add to the map. - Expression* val_; - // Whether or not to add the value. - Expression* should_set_; -}; - -// Traverse a map assignment. - -int -Map_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->map_index_) == TRAVERSE_EXIT - || this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->should_set_); -} - -// Lower a map assignment to a function call. - -Statement* -Map_assignment_statement::do_lower(Gogo*, Named_object*, Block* enclosing) -{ - source_location loc = this->location(); - - Map_index_expression* map_index = this->map_index_->map_index_expression(); - if (map_index == NULL) - { - this->report_error(_("expected map index on left hand side")); - return Statement::make_error_statement(loc); - } - Map_type* map_type = map_index->get_map_type(); - if (map_type == NULL) - return Statement::make_error_statement(loc); - - Block* b = new Block(enclosing, loc); - - // Evaluate the map first to get order of evaluation right. - // map_temp := m // we are evaluating m[k] = v, p - Temporary_statement* map_temp = Statement::make_temporary(map_type, - map_index->map(), - loc); - b->add_statement(map_temp); - - // var key_temp MAP_KEY_TYPE = k - Temporary_statement* key_temp = - Statement::make_temporary(map_type->key_type(), map_index->index(), loc); - b->add_statement(key_temp); - - // var val_temp MAP_VAL_TYPE = v - Temporary_statement* val_temp = - Statement::make_temporary(map_type->val_type(), this->val_, loc); - b->add_statement(val_temp); - - // var insert_temp bool = p - Temporary_statement* insert_temp = - Statement::make_temporary(Type::lookup_bool_type(), this->should_set_, - loc); - b->add_statement(insert_temp); - - // mapassign2(map_temp, &key_temp, &val_temp, p) - Expression* p1 = Expression::make_temporary_reference(map_temp, loc); - Expression* ref = Expression::make_temporary_reference(key_temp, loc); - Expression* p2 = Expression::make_unary(OPERATOR_AND, ref, loc); - ref = Expression::make_temporary_reference(val_temp, loc); - Expression* p3 = Expression::make_unary(OPERATOR_AND, ref, loc); - Expression* p4 = Expression::make_temporary_reference(insert_temp, loc); - Expression* call = Runtime::make_call(Runtime::MAPASSIGN2, loc, 4, - p1, p2, p3, p4); - Statement* s = Statement::make_statement(call); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Make a statement which assigns a pair of entries to a map. - -Statement* -Statement::make_map_assignment(Expression* map_index, - Expression* val, Expression* should_set, - source_location location) -{ - return new Map_assignment_statement(map_index, val, should_set, location); -} - -// A tuple assignment from a receive statement. - -class Tuple_receive_assignment_statement : public Statement -{ - public: - Tuple_receive_assignment_statement(Expression* val, Expression* closed, - Expression* channel, bool for_select, - source_location location) - : Statement(STATEMENT_TUPLE_RECEIVE_ASSIGNMENT, location), - val_(val), closed_(closed), channel_(channel), for_select_(for_select) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*) - { go_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - Bstatement* - do_get_backend(Translate_context*) - { go_unreachable(); } - - private: - // Lvalue which receives the value from the channel. - Expression* val_; - // Lvalue which receives whether the channel is closed. - Expression* closed_; - // The channel on which we receive the value. - Expression* channel_; - // Whether this is for a select statement. - bool for_select_; -}; - -// Traversal. - -int -Tuple_receive_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT - || this->traverse_expression(traverse, &this->closed_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->channel_); -} - -// Lower to a function call. - -Statement* -Tuple_receive_assignment_statement::do_lower(Gogo*, Named_object*, - Block* enclosing) -{ - source_location loc = this->location(); - - Channel_type* channel_type = this->channel_->type()->channel_type(); - if (channel_type == NULL) - { - this->report_error(_("expected channel")); - return Statement::make_error_statement(loc); - } - if (!channel_type->may_receive()) - { - this->report_error(_("invalid receive on send-only channel")); - return Statement::make_error_statement(loc); - } - - Block* b = new Block(enclosing, loc); - - // Make sure that any subexpressions on the left hand side are - // evaluated in the right order. - Move_ordered_evals moe(b); - this->val_->traverse_subexpressions(&moe); - this->closed_->traverse_subexpressions(&moe); - - // var val_temp ELEMENT_TYPE - Temporary_statement* val_temp = - Statement::make_temporary(channel_type->element_type(), NULL, loc); - b->add_statement(val_temp); - - // var closed_temp bool - Temporary_statement* closed_temp = - Statement::make_temporary(Type::lookup_bool_type(), NULL, loc); - b->add_statement(closed_temp); - - // closed_temp = chanrecv[23](channel, &val_temp) - Expression* ref = Expression::make_temporary_reference(val_temp, loc); - Expression* p2 = Expression::make_unary(OPERATOR_AND, ref, loc); - Expression* call = Runtime::make_call((this->for_select_ - ? Runtime::CHANRECV3 - : Runtime::CHANRECV2), - loc, 2, this->channel_, p2); - ref = Expression::make_temporary_reference(closed_temp, loc); - Statement* s = Statement::make_assignment(ref, call, loc); - b->add_statement(s); - - // val = val_temp - ref = Expression::make_temporary_reference(val_temp, loc); - s = Statement::make_assignment(this->val_, ref, loc); - b->add_statement(s); - - // closed = closed_temp - ref = Expression::make_temporary_reference(closed_temp, loc); - s = Statement::make_assignment(this->closed_, ref, loc); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Make a nonblocking receive statement. - -Statement* -Statement::make_tuple_receive_assignment(Expression* val, Expression* closed, - Expression* channel, - bool for_select, - source_location location) -{ - return new Tuple_receive_assignment_statement(val, closed, channel, - for_select, location); -} - -// An assignment to a pair of values from a type guard. This is a -// conditional type guard. v, ok = i.(type). - -class Tuple_type_guard_assignment_statement : public Statement -{ - public: - Tuple_type_guard_assignment_statement(Expression* val, Expression* ok, - Expression* expr, Type* type, - source_location location) - : Statement(STATEMENT_TUPLE_TYPE_GUARD_ASSIGNMENT, location), - val_(val), ok_(ok), expr_(expr), type_(type) - { } - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*) - { go_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - Bstatement* - do_get_backend(Translate_context*) - { go_unreachable(); } - - private: - Call_expression* - lower_to_type(Runtime::Function); - - void - lower_to_object_type(Block*, Runtime::Function); - - // The variable which recieves the converted value. - Expression* val_; - // The variable which receives the indication of success. - Expression* ok_; - // The expression being converted. - Expression* expr_; - // The type to which the expression is being converted. - Type* type_; -}; - -// Traverse a type guard tuple assignment. - -int -Tuple_type_guard_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT - || this->traverse_expression(traverse, &this->ok_) == TRAVERSE_EXIT - || this->traverse_type(traverse, this->type_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->expr_); -} - -// Lower to a function call. - -Statement* -Tuple_type_guard_assignment_statement::do_lower(Gogo*, Named_object*, - Block* enclosing) -{ - source_location loc = this->location(); - - Type* expr_type = this->expr_->type(); - if (expr_type->interface_type() == NULL) - { - if (!expr_type->is_error() && !this->type_->is_error()) - this->report_error(_("type assertion only valid for interface types")); - return Statement::make_error_statement(loc); - } - - Block* b = new Block(enclosing, loc); - - // Make sure that any subexpressions on the left hand side are - // evaluated in the right order. - Move_ordered_evals moe(b); - this->val_->traverse_subexpressions(&moe); - this->ok_->traverse_subexpressions(&moe); - - bool expr_is_empty = expr_type->interface_type()->is_empty(); - Call_expression* call; - if (this->type_->interface_type() != NULL) - { - if (this->type_->interface_type()->is_empty()) - call = Runtime::make_call((expr_is_empty - ? Runtime::IFACEE2E2 - : Runtime::IFACEI2E2), - loc, 1, this->expr_); - else - call = this->lower_to_type(expr_is_empty - ? Runtime::IFACEE2I2 - : Runtime::IFACEI2I2); - } - else if (this->type_->points_to() != NULL) - call = this->lower_to_type(expr_is_empty - ? Runtime::IFACEE2T2P - : Runtime::IFACEI2T2P); - else - { - this->lower_to_object_type(b, - (expr_is_empty - ? Runtime::IFACEE2T2 - : Runtime::IFACEI2T2)); - call = NULL; - } - - if (call != NULL) - { - Expression* res = Expression::make_call_result(call, 0); - res = Expression::make_unsafe_cast(this->type_, res, loc); - Statement* s = Statement::make_assignment(this->val_, res, loc); - b->add_statement(s); - - res = Expression::make_call_result(call, 1); - s = Statement::make_assignment(this->ok_, res, loc); - b->add_statement(s); - } - - return Statement::make_block_statement(b, loc); -} - -// Lower a conversion to a non-empty interface type or a pointer type. - -Call_expression* -Tuple_type_guard_assignment_statement::lower_to_type(Runtime::Function code) -{ - source_location loc = this->location(); - return Runtime::make_call(code, loc, 2, - Expression::make_type_descriptor(this->type_, loc), - this->expr_); -} - -// Lower a conversion to a non-interface non-pointer type. - -void -Tuple_type_guard_assignment_statement::lower_to_object_type( - Block* b, - Runtime::Function code) -{ - source_location loc = this->location(); - - // var val_temp TYPE - Temporary_statement* val_temp = Statement::make_temporary(this->type_, - NULL, loc); - b->add_statement(val_temp); - - // ok = CODE(type_descriptor, expr, &val_temp) - Expression* p1 = Expression::make_type_descriptor(this->type_, loc); - Expression* ref = Expression::make_temporary_reference(val_temp, loc); - Expression* p3 = Expression::make_unary(OPERATOR_AND, ref, loc); - Expression* call = Runtime::make_call(code, loc, 3, p1, this->expr_, p3); - Statement* s = Statement::make_assignment(this->ok_, call, loc); - b->add_statement(s); - - // val = val_temp - ref = Expression::make_temporary_reference(val_temp, loc); - s = Statement::make_assignment(this->val_, ref, loc); - b->add_statement(s); -} - -// Make an assignment from a type guard to a pair of variables. - -Statement* -Statement::make_tuple_type_guard_assignment(Expression* val, Expression* ok, - Expression* expr, Type* type, - source_location location) -{ - return new Tuple_type_guard_assignment_statement(val, ok, expr, type, - location); -} - -// An expression statement. - -class Expression_statement : public Statement -{ - public: - Expression_statement(Expression* expr) - : Statement(STATEMENT_EXPRESSION, expr->location()), - expr_(expr) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return this->traverse_expression(traverse, &this->expr_); } - - void - do_determine_types() - { this->expr_->determine_type_no_context(); } - - bool - do_may_fall_through() const; - - Bstatement* - do_get_backend(Translate_context* context); - - private: - Expression* expr_; -}; - -// An expression statement may fall through unless it is a call to a -// function which does not return. - -bool -Expression_statement::do_may_fall_through() const -{ - const Call_expression* call = this->expr_->call_expression(); - if (call != NULL) - { - const Expression* fn = call->fn(); - const Func_expression* fe = fn->func_expression(); - if (fe != NULL) - { - const Named_object* no = fe->named_object(); - - Function_type* fntype; - if (no->is_function()) - fntype = no->func_value()->type(); - else if (no->is_function_declaration()) - fntype = no->func_declaration_value()->type(); - else - fntype = NULL; - - // The builtin function panic does not return. - if (fntype != NULL && fntype->is_builtin() && no->name() == "panic") - return false; - } - } - return true; -} - -// Convert to backend representation. - -Bstatement* -Expression_statement::do_get_backend(Translate_context* context) -{ - tree expr_tree = this->expr_->get_tree(context); - return context->backend()->expression_statement(tree_to_expr(expr_tree)); -} - -// Make an expression statement from an Expression. - -Statement* -Statement::make_statement(Expression* expr) -{ - return new Expression_statement(expr); -} - -// A block statement--a list of statements which may include variable -// definitions. - -class Block_statement : public Statement -{ - public: - Block_statement(Block* block, source_location location) - : Statement(STATEMENT_BLOCK, location), - block_(block) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return this->block_->traverse(traverse); } - - void - do_determine_types() - { this->block_->determine_types(); } - - bool - do_may_fall_through() const - { return this->block_->may_fall_through(); } - - Bstatement* - do_get_backend(Translate_context* context); - - private: - Block* block_; -}; - -// Convert a block to the backend representation of a statement. - -Bstatement* -Block_statement::do_get_backend(Translate_context* context) -{ - Bblock* bblock = this->block_->get_backend(context); - return context->backend()->block_statement(bblock); -} - -// Make a block statement. - -Statement* -Statement::make_block_statement(Block* block, source_location location) -{ - return new Block_statement(block, location); -} - -// An increment or decrement statement. - -class Inc_dec_statement : public Statement -{ - public: - Inc_dec_statement(bool is_inc, Expression* expr) - : Statement(STATEMENT_INCDEC, expr->location()), - expr_(expr), is_inc_(is_inc) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return this->traverse_expression(traverse, &this->expr_); } - - bool - do_traverse_assignments(Traverse_assignments*) - { go_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - Bstatement* - do_get_backend(Translate_context*) - { go_unreachable(); } - - private: - // The l-value to increment or decrement. - Expression* expr_; - // Whether to increment or decrement. - bool is_inc_; -}; - -// Lower to += or -=. - -Statement* -Inc_dec_statement::do_lower(Gogo*, Named_object*, Block*) -{ - source_location loc = this->location(); - - mpz_t oval; - mpz_init_set_ui(oval, 1UL); - Expression* oexpr = Expression::make_integer(&oval, NULL, loc); - mpz_clear(oval); - - Operator op = this->is_inc_ ? OPERATOR_PLUSEQ : OPERATOR_MINUSEQ; - return Statement::make_assignment_operation(op, this->expr_, oexpr, loc); -} - -// Make an increment statement. - -Statement* -Statement::make_inc_statement(Expression* expr) -{ - return new Inc_dec_statement(true, expr); -} - -// Make a decrement statement. - -Statement* -Statement::make_dec_statement(Expression* expr) -{ - return new Inc_dec_statement(false, expr); -} - -// Class Thunk_statement. This is the base class for go and defer -// statements. - -const char* const Thunk_statement::thunk_field_fn = "fn"; - -const char* const Thunk_statement::thunk_field_receiver = "receiver"; - -// Constructor. - -Thunk_statement::Thunk_statement(Statement_classification classification, - Call_expression* call, - source_location location) - : Statement(classification, location), - call_(call), struct_type_(NULL) -{ -} - -// Return whether this is a simple statement which does not require a -// thunk. - -bool -Thunk_statement::is_simple(Function_type* fntype) const -{ - // We need a thunk to call a method, or to pass a variable number of - // arguments. - if (fntype->is_method() || fntype->is_varargs()) - return false; - - // A defer statement requires a thunk to set up for whether the - // function can call recover. - if (this->classification() == STATEMENT_DEFER) - return false; - - // We can only permit a single parameter of pointer type. - const Typed_identifier_list* parameters = fntype->parameters(); - if (parameters != NULL - && (parameters->size() > 1 - || (parameters->size() == 1 - && parameters->begin()->type()->points_to() == NULL))) - return false; - - // If the function returns multiple values, or returns a type other - // than integer, floating point, or pointer, then it may get a - // hidden first parameter, in which case we need the more - // complicated approach. This is true even though we are going to - // ignore the return value. - const Typed_identifier_list* results = fntype->results(); - if (results != NULL - && (results->size() > 1 - || (results->size() == 1 - && !results->begin()->type()->is_basic_type() - && results->begin()->type()->points_to() == NULL))) - return false; - - // If this calls something which is not a simple function, then we - // need a thunk. - Expression* fn = this->call_->call_expression()->fn(); - if (fn->bound_method_expression() != NULL - || fn->interface_field_reference_expression() != NULL) - return false; - - return true; -} - -// Traverse a thunk statement. - -int -Thunk_statement::do_traverse(Traverse* traverse) -{ - return this->traverse_expression(traverse, &this->call_); -} - -// We implement traverse_assignment for a thunk statement because it -// effectively copies the function call. - -bool -Thunk_statement::do_traverse_assignments(Traverse_assignments* tassign) -{ - Expression* fn = this->call_->call_expression()->fn(); - Expression* fn2 = fn; - tassign->value(&fn2, true, false); - return true; -} - -// Determine types in a thunk statement. - -void -Thunk_statement::do_determine_types() -{ - this->call_->determine_type_no_context(); - - // Now that we know the types of the call, build the struct used to - // pass parameters. - Call_expression* ce = this->call_->call_expression(); - if (ce == NULL) - return; - Function_type* fntype = ce->get_function_type(); - if (fntype != NULL && !this->is_simple(fntype)) - this->struct_type_ = this->build_struct(fntype); -} - -// Check types in a thunk statement. - -void -Thunk_statement::do_check_types(Gogo*) -{ - Call_expression* ce = this->call_->call_expression(); - if (ce == NULL) - { - if (!this->call_->is_error_expression()) - this->report_error("expected call expression"); - return; - } - Function_type* fntype = ce->get_function_type(); - if (fntype != NULL && fntype->is_method()) - { - Expression* fn = ce->fn(); - if (fn->bound_method_expression() == NULL - && fn->interface_field_reference_expression() == NULL) - this->report_error(_("no object for method call")); - } -} - -// The Traverse class used to find and simplify thunk statements. - -class Simplify_thunk_traverse : public Traverse -{ - public: - Simplify_thunk_traverse(Gogo* gogo) - : Traverse(traverse_functions | traverse_blocks), - gogo_(gogo), function_(NULL) - { } - - int - function(Named_object*); - - int - block(Block*); - - private: - // General IR. - Gogo* gogo_; - // The function we are traversing. - Named_object* function_; -}; - -// Keep track of the current function while looking for thunks. - -int -Simplify_thunk_traverse::function(Named_object* no) -{ - go_assert(this->function_ == NULL); - this->function_ = no; - int t = no->func_value()->traverse(this); - this->function_ = NULL; - if (t == TRAVERSE_EXIT) - return t; - return TRAVERSE_SKIP_COMPONENTS; -} - -// Look for thunks in a block. - -int -Simplify_thunk_traverse::block(Block* b) -{ - // The parser ensures that thunk statements always appear at the end - // of a block. - if (b->statements()->size() < 1) - return TRAVERSE_CONTINUE; - Thunk_statement* stat = b->statements()->back()->thunk_statement(); - if (stat == NULL) - return TRAVERSE_CONTINUE; - if (stat->simplify_statement(this->gogo_, this->function_, b)) - return TRAVERSE_SKIP_COMPONENTS; - return TRAVERSE_CONTINUE; -} - -// Simplify all thunk statements. - -void -Gogo::simplify_thunk_statements() -{ - Simplify_thunk_traverse thunk_traverse(this); - this->traverse(&thunk_traverse); -} - -// Simplify complex thunk statements into simple ones. A complicated -// thunk statement is one which takes anything other than zero -// parameters or a single pointer parameter. We rewrite it into code -// which allocates a struct, stores the parameter values into the -// struct, and does a simple go or defer statement which passes the -// struct to a thunk. The thunk does the real call. - -bool -Thunk_statement::simplify_statement(Gogo* gogo, Named_object* function, - Block* block) -{ - if (this->classification() == STATEMENT_ERROR) - return false; - if (this->call_->is_error_expression()) - return false; - - if (this->classification() == STATEMENT_DEFER) - { - // Make sure that the defer stack exists for the function. We - // will use when converting this statement to the backend - // representation, but we want it to exist when we start - // converting the function. - function->func_value()->defer_stack(this->location()); - } - - Call_expression* ce = this->call_->call_expression(); - Function_type* fntype = ce->get_function_type(); - if (fntype == NULL) - { - go_assert(saw_errors()); - this->set_is_error(); - return false; - } - if (this->is_simple(fntype)) - return false; - - Expression* fn = ce->fn(); - Bound_method_expression* bound_method = fn->bound_method_expression(); - Interface_field_reference_expression* interface_method = - fn->interface_field_reference_expression(); - const bool is_method = bound_method != NULL || interface_method != NULL; - - source_location location = this->location(); - - std::string thunk_name = Gogo::thunk_name(); - - // Build the thunk. - this->build_thunk(gogo, thunk_name, fntype); - - // Generate code to call the thunk. - - // Get the values to store into the struct which is the single - // argument to the thunk. - - Expression_list* vals = new Expression_list(); - if (fntype->is_builtin()) - ; - else if (!is_method) - vals->push_back(fn); - else if (interface_method != NULL) - vals->push_back(interface_method->expr()); - else if (bound_method != NULL) - { - vals->push_back(bound_method->method()); - Expression* first_arg = bound_method->first_argument(); - - // We always pass a pointer when calling a method. - if (first_arg->type()->points_to() == NULL) - first_arg = Expression::make_unary(OPERATOR_AND, first_arg, location); - - // If we are calling a method which was inherited from an - // embedded struct, and the method did not get a stub, then the - // first type may be wrong. - Type* fatype = bound_method->first_argument_type(); - if (fatype != NULL) - { - if (fatype->points_to() == NULL) - fatype = Type::make_pointer_type(fatype); - Type* unsafe = Type::make_pointer_type(Type::make_void_type()); - first_arg = Expression::make_cast(unsafe, first_arg, location); - first_arg = Expression::make_cast(fatype, first_arg, location); - } - - vals->push_back(first_arg); - } - else - go_unreachable(); - - if (ce->args() != NULL) - { - for (Expression_list::const_iterator p = ce->args()->begin(); - p != ce->args()->end(); - ++p) - vals->push_back(*p); - } - - // Build the struct. - Expression* constructor = - Expression::make_struct_composite_literal(this->struct_type_, vals, - location); - - // Allocate the initialized struct on the heap. - constructor = Expression::make_heap_composite(constructor, location); - - // Look up the thunk. - Named_object* named_thunk = gogo->lookup(thunk_name, NULL); - go_assert(named_thunk != NULL && named_thunk->is_function()); - - // Build the call. - Expression* func = Expression::make_func_reference(named_thunk, NULL, - location); - Expression_list* params = new Expression_list(); - params->push_back(constructor); - Call_expression* call = Expression::make_call(func, params, false, location); - - // Build the simple go or defer statement. - Statement* s; - if (this->classification() == STATEMENT_GO) - s = Statement::make_go_statement(call, location); - else if (this->classification() == STATEMENT_DEFER) - s = Statement::make_defer_statement(call, location); - else - go_unreachable(); - - // The current block should end with the go statement. - go_assert(block->statements()->size() >= 1); - go_assert(block->statements()->back() == this); - block->replace_statement(block->statements()->size() - 1, s); - - // We already ran the determine_types pass, so we need to run it now - // for the new statement. - s->determine_types(); - - // Sanity check. - gogo->check_types_in_block(block); - - // Return true to tell the block not to keep looking at statements. - return true; -} - -// Set the name to use for thunk parameter N. - -void -Thunk_statement::thunk_field_param(int n, char* buf, size_t buflen) -{ - snprintf(buf, buflen, "a%d", n); -} - -// Build a new struct type to hold the parameters for a complicated -// thunk statement. FNTYPE is the type of the function call. - -Struct_type* -Thunk_statement::build_struct(Function_type* fntype) -{ - source_location location = this->location(); - - Struct_field_list* fields = new Struct_field_list(); - - Call_expression* ce = this->call_->call_expression(); - Expression* fn = ce->fn(); - - Interface_field_reference_expression* interface_method = - fn->interface_field_reference_expression(); - if (interface_method != NULL) - { - // If this thunk statement calls a method on an interface, we - // pass the interface object to the thunk. - Typed_identifier tid(Thunk_statement::thunk_field_fn, - interface_method->expr()->type(), - location); - fields->push_back(Struct_field(tid)); - } - else if (!fntype->is_builtin()) - { - // The function to call. - Typed_identifier tid(Go_statement::thunk_field_fn, fntype, location); - fields->push_back(Struct_field(tid)); - } - else if (ce->is_recover_call()) - { - // The predeclared recover function has no argument. However, - // we add an argument when building recover thunks. Handle that - // here. - fields->push_back(Struct_field(Typed_identifier("can_recover", - Type::lookup_bool_type(), - location))); - } - - if (fn->bound_method_expression() != NULL) - { - go_assert(fntype->is_method()); - Type* rtype = fntype->receiver()->type(); - // We always pass the receiver as a pointer. - if (rtype->points_to() == NULL) - rtype = Type::make_pointer_type(rtype); - Typed_identifier tid(Thunk_statement::thunk_field_receiver, rtype, - location); - fields->push_back(Struct_field(tid)); - } - - const Expression_list* args = ce->args(); - if (args != NULL) - { - int i = 0; - for (Expression_list::const_iterator p = args->begin(); - p != args->end(); - ++p, ++i) - { - char buf[50]; - this->thunk_field_param(i, buf, sizeof buf); - fields->push_back(Struct_field(Typed_identifier(buf, (*p)->type(), - location))); - } - } - - return Type::make_struct_type(fields, location); -} - -// Build the thunk we are going to call. This is a brand new, albeit -// artificial, function. - -void -Thunk_statement::build_thunk(Gogo* gogo, const std::string& thunk_name, - Function_type* fntype) -{ - source_location location = this->location(); - - Call_expression* ce = this->call_->call_expression(); - - bool may_call_recover = false; - if (this->classification() == STATEMENT_DEFER) - { - Func_expression* fn = ce->fn()->func_expression(); - if (fn == NULL) - may_call_recover = true; - else - { - const Named_object* no = fn->named_object(); - if (!no->is_function()) - may_call_recover = true; - else - may_call_recover = no->func_value()->calls_recover(); - } - } - - // Build the type of the thunk. The thunk takes a single parameter, - // which is a pointer to the special structure we build. - const char* const parameter_name = "__go_thunk_parameter"; - Typed_identifier_list* thunk_parameters = new Typed_identifier_list(); - Type* pointer_to_struct_type = Type::make_pointer_type(this->struct_type_); - thunk_parameters->push_back(Typed_identifier(parameter_name, - pointer_to_struct_type, - location)); - - Typed_identifier_list* thunk_results = NULL; - if (may_call_recover) - { - // When deferring a function which may call recover, add a - // return value, to disable tail call optimizations which will - // break the way we check whether recover is permitted. - thunk_results = new Typed_identifier_list(); - thunk_results->push_back(Typed_identifier("", Type::lookup_bool_type(), - location)); - } - - Function_type* thunk_type = Type::make_function_type(NULL, thunk_parameters, - thunk_results, - location); - - // Start building the thunk. - Named_object* function = gogo->start_function(thunk_name, thunk_type, true, - location); - - // For a defer statement, start with a call to - // __go_set_defer_retaddr. */ - Label* retaddr_label = NULL; - if (may_call_recover) - { - retaddr_label = gogo->add_label_reference("retaddr"); - Expression* arg = Expression::make_label_addr(retaddr_label, location); - Expression* call = Runtime::make_call(Runtime::SET_DEFER_RETADDR, - location, 1, arg); - - // This is a hack to prevent the middle-end from deleting the - // label. - gogo->start_block(location); - gogo->add_statement(Statement::make_goto_statement(retaddr_label, - location)); - Block* then_block = gogo->finish_block(location); - then_block->determine_types(); - - Statement* s = Statement::make_if_statement(call, then_block, NULL, - location); - s->determine_types(); - gogo->add_statement(s); - } - - // Get a reference to the parameter. - Named_object* named_parameter = gogo->lookup(parameter_name, NULL); - go_assert(named_parameter != NULL && named_parameter->is_variable()); - - // Build the call. Note that the field names are the same as the - // ones used in build_struct. - Expression* thunk_parameter = Expression::make_var_reference(named_parameter, - location); - thunk_parameter = Expression::make_unary(OPERATOR_MULT, thunk_parameter, - location); - - Bound_method_expression* bound_method = ce->fn()->bound_method_expression(); - Interface_field_reference_expression* interface_method = - ce->fn()->interface_field_reference_expression(); - - Expression* func_to_call; - unsigned int next_index; - if (!fntype->is_builtin()) - { - func_to_call = Expression::make_field_reference(thunk_parameter, - 0, location); - next_index = 1; - } - else - { - go_assert(bound_method == NULL && interface_method == NULL); - func_to_call = ce->fn(); - next_index = 0; - } - - if (bound_method != NULL) - { - Expression* r = Expression::make_field_reference(thunk_parameter, 1, - location); - // The main program passes in a function pointer from the - // interface expression, so here we can make a bound method in - // all cases. - func_to_call = Expression::make_bound_method(r, func_to_call, - location); - next_index = 2; - } - else if (interface_method != NULL) - { - // The main program passes the interface object. - const std::string& name(interface_method->name()); - func_to_call = Expression::make_interface_field_reference(func_to_call, - name, - location); - } - - Expression_list* call_params = new Expression_list(); - const Struct_field_list* fields = this->struct_type_->fields(); - Struct_field_list::const_iterator p = fields->begin(); - for (unsigned int i = 0; i < next_index; ++i) - ++p; - bool is_recover_call = ce->is_recover_call(); - Expression* recover_arg = NULL; - for (; p != fields->end(); ++p, ++next_index) - { - Expression* thunk_param = Expression::make_var_reference(named_parameter, - location); - thunk_param = Expression::make_unary(OPERATOR_MULT, thunk_param, - location); - Expression* param = Expression::make_field_reference(thunk_param, - next_index, - location); - if (!is_recover_call) - call_params->push_back(param); - else - { - go_assert(call_params->empty()); - recover_arg = param; - } - } - - if (call_params->empty()) - { - delete call_params; - call_params = NULL; - } - - Expression* call = Expression::make_call(func_to_call, call_params, false, - location); - // We need to lower in case this is a builtin function. - call = call->lower(gogo, function, -1); - Call_expression* call_ce = call->call_expression(); - if (call_ce != NULL && may_call_recover) - call_ce->set_is_deferred(); - - Statement* call_statement = Statement::make_statement(call); - - // We already ran the determine_types pass, so we need to run it - // just for this statement now. - call_statement->determine_types(); - - // Sanity check. - call->check_types(gogo); - - if (call_ce != NULL && recover_arg != NULL) - call_ce->set_recover_arg(recover_arg); - - gogo->add_statement(call_statement); - - // If this is a defer statement, the label comes immediately after - // the call. - if (may_call_recover) - { - gogo->add_label_definition("retaddr", location); - - Expression_list* vals = new Expression_list(); - vals->push_back(Expression::make_boolean(false, location)); - gogo->add_statement(Statement::make_return_statement(vals, location)); - } - - // That is all the thunk has to do. - gogo->finish_function(location); -} - -// Get the function and argument expressions. - -bool -Thunk_statement::get_fn_and_arg(Expression** pfn, Expression** parg) -{ - if (this->call_->is_error_expression()) - return false; - - Call_expression* ce = this->call_->call_expression(); - - *pfn = ce->fn(); - - const Expression_list* args = ce->args(); - if (args == NULL || args->empty()) - *parg = Expression::make_nil(this->location()); - else - { - go_assert(args->size() == 1); - *parg = args->front(); - } - - return true; -} - -// Class Go_statement. - -Bstatement* -Go_statement::do_get_backend(Translate_context* context) -{ - Expression* fn; - Expression* arg; - if (!this->get_fn_and_arg(&fn, &arg)) - return context->backend()->error_statement(); - - Expression* call = Runtime::make_call(Runtime::GO, this->location(), 2, - fn, arg); - tree call_tree = call->get_tree(context); - Bexpression* call_bexpr = tree_to_expr(call_tree); - return context->backend()->expression_statement(call_bexpr); -} - -// Make a go statement. - -Statement* -Statement::make_go_statement(Call_expression* call, source_location location) -{ - return new Go_statement(call, location); -} - -// Class Defer_statement. - -Bstatement* -Defer_statement::do_get_backend(Translate_context* context) -{ - Expression* fn; - Expression* arg; - if (!this->get_fn_and_arg(&fn, &arg)) - return context->backend()->error_statement(); - - source_location loc = this->location(); - Expression* ds = context->function()->func_value()->defer_stack(loc); - - Expression* call = Runtime::make_call(Runtime::DEFER, loc, 3, - ds, fn, arg); - tree call_tree = call->get_tree(context); - Bexpression* call_bexpr = tree_to_expr(call_tree); - return context->backend()->expression_statement(call_bexpr); -} - -// Make a defer statement. - -Statement* -Statement::make_defer_statement(Call_expression* call, - source_location location) -{ - return new Defer_statement(call, location); -} - -// Class Return_statement. - -// Traverse assignments. We treat each return value as a top level -// RHS in an expression. - -bool -Return_statement::do_traverse_assignments(Traverse_assignments* tassign) -{ - Expression_list* vals = this->vals_; - if (vals != NULL) - { - for (Expression_list::iterator p = vals->begin(); - p != vals->end(); - ++p) - tassign->value(&*p, true, true); - } - return true; -} - -// Lower a return statement. If we are returning a function call -// which returns multiple values which match the current function, -// split up the call's results. If the function has named result -// variables, and the return statement lists explicit values, then -// implement it by assigning the values to the result variables and -// changing the statement to not list any values. This lets -// panic/recover work correctly. - -Statement* -Return_statement::do_lower(Gogo*, Named_object* function, Block* enclosing) -{ - if (this->is_lowered_) - return this; - - Expression_list* vals = this->vals_; - this->vals_ = NULL; - this->is_lowered_ = true; - - source_location loc = this->location(); - - size_t vals_count = vals == NULL ? 0 : vals->size(); - Function::Results* results = function->func_value()->result_variables(); - size_t results_count = results == NULL ? 0 : results->size(); - - if (vals_count == 0) - { - if (results_count > 0 && !function->func_value()->results_are_named()) - { - this->report_error(_("not enough arguments to return")); - return this; - } - return this; - } - - if (results_count == 0) - { - this->report_error(_("return with value in function " - "with no return type")); - return this; - } - - // If the current function has multiple return values, and we are - // returning a single call expression, split up the call expression. - if (results_count > 1 - && vals->size() == 1 - && vals->front()->call_expression() != NULL) - { - Call_expression* call = vals->front()->call_expression(); - delete vals; - vals = new Expression_list; - for (size_t i = 0; i < results_count; ++i) - vals->push_back(Expression::make_call_result(call, i)); - vals_count = results_count; - } - - if (vals_count < results_count) - { - this->report_error(_("not enough arguments to return")); - return this; - } - - if (vals_count > results_count) - { - this->report_error(_("too many values in return statement")); - return this; - } - - Block* b = new Block(enclosing, loc); - - Expression_list* lhs = new Expression_list(); - Expression_list* rhs = new Expression_list(); - - Expression_list::const_iterator pe = vals->begin(); - int i = 1; - for (Function::Results::const_iterator pr = results->begin(); - pr != results->end(); - ++pr, ++pe, ++i) - { - Named_object* rv = *pr; - Expression* e = *pe; - - // Check types now so that we give a good error message. The - // result type is known. We determine the expression type - // early. - - Type *rvtype = rv->result_var_value()->type(); - Type_context type_context(rvtype, false); - e->determine_type(&type_context); - - std::string reason; - if (Type::are_assignable(rvtype, e->type(), &reason)) - { - Expression* ve = Expression::make_var_reference(rv, e->location()); - lhs->push_back(ve); - rhs->push_back(e); - } - else - { - if (reason.empty()) - error_at(e->location(), "incompatible type for return value %d", i); - else - error_at(e->location(), - "incompatible type for return value %d (%s)", - i, reason.c_str()); - } - } - go_assert(lhs->size() == rhs->size()); - - if (lhs->empty()) - ; - else if (lhs->size() == 1) - { - b->add_statement(Statement::make_assignment(lhs->front(), rhs->front(), - loc)); - delete lhs; - delete rhs; - } - else - b->add_statement(Statement::make_tuple_assignment(lhs, rhs, loc)); - - b->add_statement(this); - - delete vals; - - return Statement::make_block_statement(b, loc); -} - -// Convert a return statement to the backend representation. - -Bstatement* -Return_statement::do_get_backend(Translate_context* context) -{ - source_location loc = this->location(); - - Function* function = context->function()->func_value(); - tree fndecl = function->get_decl(); - - Function::Results* results = function->result_variables(); - std::vector retvals; - if (results != NULL && !results->empty()) - { - retvals.reserve(results->size()); - for (Function::Results::const_iterator p = results->begin(); - p != results->end(); - p++) - { - Expression* vr = Expression::make_var_reference(*p, loc); - retvals.push_back(tree_to_expr(vr->get_tree(context))); - } - } - - return context->backend()->return_statement(tree_to_function(fndecl), - retvals, loc); -} - -// Make a return statement. - -Statement* -Statement::make_return_statement(Expression_list* vals, - source_location location) -{ - return new Return_statement(vals, location); -} - -// A break or continue statement. - -class Bc_statement : public Statement -{ - public: - Bc_statement(bool is_break, Unnamed_label* label, source_location location) - : Statement(STATEMENT_BREAK_OR_CONTINUE, location), - label_(label), is_break_(is_break) - { } - - bool - is_break() const - { return this->is_break_; } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - bool - do_may_fall_through() const - { return false; } - - Bstatement* - do_get_backend(Translate_context* context) - { return this->label_->get_goto(context, this->location()); } - - private: - // The label that this branches to. - Unnamed_label* label_; - // True if this is "break", false if it is "continue". - bool is_break_; -}; - -// Make a break statement. - -Statement* -Statement::make_break_statement(Unnamed_label* label, source_location location) -{ - return new Bc_statement(true, label, location); -} - -// Make a continue statement. - -Statement* -Statement::make_continue_statement(Unnamed_label* label, - source_location location) -{ - return new Bc_statement(false, label, location); -} - -// A goto statement. - -class Goto_statement : public Statement -{ - public: - Goto_statement(Label* label, source_location location) - : Statement(STATEMENT_GOTO, location), - label_(label) - { } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - void - do_check_types(Gogo*); - - bool - do_may_fall_through() const - { return false; } - - Bstatement* - do_get_backend(Translate_context*); - - private: - Label* label_; -}; - -// Check types for a label. There aren't any types per se, but we use -// this to give an error if the label was never defined. - -void -Goto_statement::do_check_types(Gogo*) -{ - if (!this->label_->is_defined()) - { - error_at(this->location(), "reference to undefined label %qs", - Gogo::message_name(this->label_->name()).c_str()); - this->set_is_error(); - } -} - -// Convert the goto statement to the backend representation. - -Bstatement* -Goto_statement::do_get_backend(Translate_context* context) -{ - Blabel* blabel = this->label_->get_backend_label(context); - return context->backend()->goto_statement(blabel, this->location()); -} - -// Make a goto statement. - -Statement* -Statement::make_goto_statement(Label* label, source_location location) -{ - return new Goto_statement(label, location); -} - -// A goto statement to an unnamed label. - -class Goto_unnamed_statement : public Statement -{ - public: - Goto_unnamed_statement(Unnamed_label* label, source_location location) - : Statement(STATEMENT_GOTO_UNNAMED, location), - label_(label) - { } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - bool - do_may_fall_through() const - { return false; } - - Bstatement* - do_get_backend(Translate_context* context) - { return this->label_->get_goto(context, this->location()); } - - private: - Unnamed_label* label_; -}; - -// Make a goto statement to an unnamed label. - -Statement* -Statement::make_goto_unnamed_statement(Unnamed_label* label, - source_location location) -{ - return new Goto_unnamed_statement(label, location); -} - -// Class Label_statement. - -// Traversal. - -int -Label_statement::do_traverse(Traverse*) -{ - return TRAVERSE_CONTINUE; -} - -// Return the backend representation of the statement defining this -// label. - -Bstatement* -Label_statement::do_get_backend(Translate_context* context) -{ - Blabel* blabel = this->label_->get_backend_label(context); - return context->backend()->label_definition_statement(blabel); -} - -// Make a label statement. - -Statement* -Statement::make_label_statement(Label* label, source_location location) -{ - return new Label_statement(label, location); -} - -// An unnamed label statement. - -class Unnamed_label_statement : public Statement -{ - public: - Unnamed_label_statement(Unnamed_label* label) - : Statement(STATEMENT_UNNAMED_LABEL, label->location()), - label_(label) - { } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - Bstatement* - do_get_backend(Translate_context* context) - { return this->label_->get_definition(context); } - - private: - // The label. - Unnamed_label* label_; -}; - -// Make an unnamed label statement. - -Statement* -Statement::make_unnamed_label_statement(Unnamed_label* label) -{ - return new Unnamed_label_statement(label); -} - -// An if statement. - -class If_statement : public Statement -{ - public: - If_statement(Expression* cond, Block* then_block, Block* else_block, - source_location location) - : Statement(STATEMENT_IF, location), - cond_(cond), then_block_(then_block), else_block_(else_block) - { } - - protected: - int - do_traverse(Traverse*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - bool - do_may_fall_through() const; - - Bstatement* - do_get_backend(Translate_context*); - - private: - Expression* cond_; - Block* then_block_; - Block* else_block_; -}; - -// Traversal. - -int -If_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->cond_) == TRAVERSE_EXIT - || this->then_block_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->else_block_ != NULL) - { - if (this->else_block_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -void -If_statement::do_determine_types() -{ - Type_context context(Type::lookup_bool_type(), false); - this->cond_->determine_type(&context); - this->then_block_->determine_types(); - if (this->else_block_ != NULL) - this->else_block_->determine_types(); -} - -// Check types. - -void -If_statement::do_check_types(Gogo*) -{ - Type* type = this->cond_->type(); - if (type->is_error()) - this->set_is_error(); - else if (!type->is_boolean_type()) - this->report_error(_("expected boolean expression")); -} - -// Whether the overall statement may fall through. - -bool -If_statement::do_may_fall_through() const -{ - return (this->else_block_ == NULL - || this->then_block_->may_fall_through() - || this->else_block_->may_fall_through()); -} - -// Get the backend representation. - -Bstatement* -If_statement::do_get_backend(Translate_context* context) -{ - go_assert(this->cond_->type()->is_boolean_type() - || this->cond_->type()->is_error()); - tree cond_tree = this->cond_->get_tree(context); - Bexpression* cond_expr = tree_to_expr(cond_tree); - Bblock* then_block = this->then_block_->get_backend(context); - Bblock* else_block = (this->else_block_ == NULL - ? NULL - : this->else_block_->get_backend(context)); - return context->backend()->if_statement(cond_expr, then_block, - else_block, this->location()); -} - -// Make an if statement. - -Statement* -Statement::make_if_statement(Expression* cond, Block* then_block, - Block* else_block, source_location location) -{ - return new If_statement(cond, then_block, else_block, location); -} - -// Class Case_clauses::Hash_integer_value. - -class Case_clauses::Hash_integer_value -{ - public: - size_t - operator()(Expression*) const; -}; - -size_t -Case_clauses::Hash_integer_value::operator()(Expression* pe) const -{ - Type* itype; - mpz_t ival; - mpz_init(ival); - if (!pe->integer_constant_value(true, ival, &itype)) - go_unreachable(); - size_t ret = mpz_get_ui(ival); - mpz_clear(ival); - return ret; -} - -// Class Case_clauses::Eq_integer_value. - -class Case_clauses::Eq_integer_value -{ - public: - bool - operator()(Expression*, Expression*) const; -}; - -bool -Case_clauses::Eq_integer_value::operator()(Expression* a, Expression* b) const -{ - Type* atype; - Type* btype; - mpz_t aval; - mpz_t bval; - mpz_init(aval); - mpz_init(bval); - if (!a->integer_constant_value(true, aval, &atype) - || !b->integer_constant_value(true, bval, &btype)) - go_unreachable(); - bool ret = mpz_cmp(aval, bval) == 0; - mpz_clear(aval); - mpz_clear(bval); - return ret; -} - -// Class Case_clauses::Case_clause. - -// Traversal. - -int -Case_clauses::Case_clause::traverse(Traverse* traverse) -{ - if (this->cases_ != NULL - && (traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) != 0) - { - if (this->cases_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->statements_ != NULL) - { - if (this->statements_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Check whether all the case expressions are integer constants. - -bool -Case_clauses::Case_clause::is_constant() const -{ - if (this->cases_ != NULL) - { - for (Expression_list::const_iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - if (!(*p)->is_constant() || (*p)->type()->integer_type() == NULL) - return false; - } - return true; -} - -// Lower a case clause for a nonconstant switch. VAL_TEMP is the -// value we are switching on; it may be NULL. If START_LABEL is not -// NULL, it goes at the start of the statements, after the condition -// test. We branch to FINISH_LABEL at the end of the statements. - -void -Case_clauses::Case_clause::lower(Block* b, Temporary_statement* val_temp, - Unnamed_label* start_label, - Unnamed_label* finish_label) const -{ - source_location loc = this->location_; - Unnamed_label* next_case_label; - if (this->cases_ == NULL || this->cases_->empty()) - { - go_assert(this->is_default_); - next_case_label = NULL; - } - else - { - Expression* cond = NULL; - - for (Expression_list::const_iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - { - Expression* this_cond; - if (val_temp == NULL) - this_cond = *p; - else - { - Expression* ref = Expression::make_temporary_reference(val_temp, - loc); - this_cond = Expression::make_binary(OPERATOR_EQEQ, ref, *p, loc); - } - - if (cond == NULL) - cond = this_cond; - else - cond = Expression::make_binary(OPERATOR_OROR, cond, this_cond, loc); - } - - Block* then_block = new Block(b, loc); - next_case_label = new Unnamed_label(UNKNOWN_LOCATION); - Statement* s = Statement::make_goto_unnamed_statement(next_case_label, - loc); - then_block->add_statement(s); - - // if !COND { goto NEXT_CASE_LABEL } - cond = Expression::make_unary(OPERATOR_NOT, cond, loc); - s = Statement::make_if_statement(cond, then_block, NULL, loc); - b->add_statement(s); - } - - if (start_label != NULL) - b->add_statement(Statement::make_unnamed_label_statement(start_label)); - - if (this->statements_ != NULL) - b->add_statement(Statement::make_block_statement(this->statements_, loc)); - - Statement* s = Statement::make_goto_unnamed_statement(finish_label, loc); - b->add_statement(s); - - if (next_case_label != NULL) - b->add_statement(Statement::make_unnamed_label_statement(next_case_label)); -} - -// Determine types. - -void -Case_clauses::Case_clause::determine_types(Type* type) -{ - if (this->cases_ != NULL) - { - Type_context case_context(type, false); - for (Expression_list::iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - (*p)->determine_type(&case_context); - } - if (this->statements_ != NULL) - this->statements_->determine_types(); -} - -// Check types. Returns false if there was an error. - -bool -Case_clauses::Case_clause::check_types(Type* type) -{ - if (this->cases_ != NULL) - { - for (Expression_list::iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - { - if (!Type::are_assignable(type, (*p)->type(), NULL) - && !Type::are_assignable((*p)->type(), type, NULL)) - { - error_at((*p)->location(), - "type mismatch between switch value and case clause"); - return false; - } - } - } - return true; -} - -// Return true if this clause may fall through to the following -// statements. Note that this is not the same as whether the case -// uses the "fallthrough" keyword. - -bool -Case_clauses::Case_clause::may_fall_through() const -{ - if (this->statements_ == NULL) - return true; - return this->statements_->may_fall_through(); -} - -// Convert the case values and statements to the backend -// representation. BREAK_LABEL is the label which break statements -// should branch to. CASE_CONSTANTS is used to detect duplicate -// constants. *CASES should be passed as an empty vector; the values -// for this case will be added to it. If this is the default case, -// *CASES will remain empty. This returns the statement to execute if -// one of these cases is selected. - -Bstatement* -Case_clauses::Case_clause::get_backend(Translate_context* context, - Unnamed_label* break_label, - Case_constants* case_constants, - std::vector* cases) const -{ - if (this->cases_ != NULL) - { - go_assert(!this->is_default_); - for (Expression_list::const_iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - { - Expression* e = *p; - if (e->classification() != Expression::EXPRESSION_INTEGER) - { - Type* itype; - mpz_t ival; - mpz_init(ival); - if (!(*p)->integer_constant_value(true, ival, &itype)) - { - // Something went wrong. This can happen with a - // negative constant and an unsigned switch value. - go_assert(saw_errors()); - continue; - } - go_assert(itype != NULL); - e = Expression::make_integer(&ival, itype, e->location()); - mpz_clear(ival); - } - - std::pair ins = - case_constants->insert(e); - if (!ins.second) - { - // Value was already present. - error_at(this->location_, "duplicate case in switch"); - continue; - } - - tree case_tree = e->get_tree(context); - Bexpression* case_expr = tree_to_expr(case_tree); - cases->push_back(case_expr); - } - } - - Bstatement* statements; - if (this->statements_ == NULL) - statements = NULL; - else - { - Bblock* bblock = this->statements_->get_backend(context); - statements = context->backend()->block_statement(bblock); - } - - Bstatement* break_stat; - if (this->is_fallthrough_) - break_stat = NULL; - else - break_stat = break_label->get_goto(context, this->location_); - - if (statements == NULL) - return break_stat; - else if (break_stat == NULL) - return statements; - else - return context->backend()->compound_statement(statements, break_stat); -} - -// Class Case_clauses. - -// Traversal. - -int -Case_clauses::traverse(Traverse* traverse) -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Check whether all the case expressions are constant. - -bool -Case_clauses::is_constant() const -{ - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - if (!p->is_constant()) - return false; - return true; -} - -// Lower case clauses for a nonconstant switch. - -void -Case_clauses::lower(Block* b, Temporary_statement* val_temp, - Unnamed_label* break_label) const -{ - // The default case. - const Case_clause* default_case = NULL; - - // The label for the fallthrough of the previous case. - Unnamed_label* last_fallthrough_label = NULL; - - // The label for the start of the default case. This is used if the - // case before the default case falls through. - Unnamed_label* default_start_label = NULL; - - // The label for the end of the default case. This normally winds - // up as BREAK_LABEL, but it will be different if the default case - // falls through. - Unnamed_label* default_finish_label = NULL; - - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - // The label to use for the start of the statements for this - // case. This is NULL unless the previous case falls through. - Unnamed_label* start_label = last_fallthrough_label; - - // The label to jump to after the end of the statements for this - // case. - Unnamed_label* finish_label = break_label; - - last_fallthrough_label = NULL; - if (p->is_fallthrough() && p + 1 != this->clauses_.end()) - { - finish_label = new Unnamed_label(p->location()); - last_fallthrough_label = finish_label; - } - - if (!p->is_default()) - p->lower(b, val_temp, start_label, finish_label); - else - { - // We have to move the default case to the end, so that we - // only use it if all the other tests fail. - default_case = &*p; - default_start_label = start_label; - default_finish_label = finish_label; - } - } - - if (default_case != NULL) - default_case->lower(b, val_temp, default_start_label, - default_finish_label); - -} - -// Determine types. - -void -Case_clauses::determine_types(Type* type) -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - p->determine_types(type); -} - -// Check types. Returns false if there was an error. - -bool -Case_clauses::check_types(Type* type) -{ - bool ret = true; - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (!p->check_types(type)) - ret = false; - } - return ret; -} - -// Return true if these clauses may fall through to the statements -// following the switch statement. - -bool -Case_clauses::may_fall_through() const -{ - bool found_default = false; - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->may_fall_through() && !p->is_fallthrough()) - return true; - if (p->is_default()) - found_default = true; - } - return !found_default; -} - -// Convert the cases to the backend representation. This sets -// *ALL_CASES and *ALL_STATEMENTS. - -void -Case_clauses::get_backend(Translate_context* context, - Unnamed_label* break_label, - std::vector >* all_cases, - std::vector* all_statements) const -{ - Case_constants case_constants; - - size_t c = this->clauses_.size(); - all_cases->resize(c); - all_statements->resize(c); - - size_t i = 0; - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p, ++i) - { - std::vector cases; - Bstatement* stat = p->get_backend(context, break_label, &case_constants, - &cases); - (*all_cases)[i].swap(cases); - (*all_statements)[i] = stat; - } -} - -// A constant switch statement. A Switch_statement is lowered to this -// when all the cases are constants. - -class Constant_switch_statement : public Statement -{ - public: - Constant_switch_statement(Expression* val, Case_clauses* clauses, - Unnamed_label* break_label, - source_location location) - : Statement(STATEMENT_CONSTANT_SWITCH, location), - val_(val), clauses_(clauses), break_label_(break_label) - { } - - protected: - int - do_traverse(Traverse*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - bool - do_may_fall_through() const; - - Bstatement* - do_get_backend(Translate_context*); - - private: - // The value to switch on. - Expression* val_; - // The case clauses. - Case_clauses* clauses_; - // The break label, if needed. - Unnamed_label* break_label_; -}; - -// Traversal. - -int -Constant_switch_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->clauses_->traverse(traverse); -} - -// Determine types. - -void -Constant_switch_statement::do_determine_types() -{ - this->val_->determine_type_no_context(); - this->clauses_->determine_types(this->val_->type()); -} - -// Check types. - -void -Constant_switch_statement::do_check_types(Gogo*) -{ - if (!this->clauses_->check_types(this->val_->type())) - this->set_is_error(); -} - -// Return whether this switch may fall through. - -bool -Constant_switch_statement::do_may_fall_through() const -{ - if (this->clauses_ == NULL) - return true; - - // If we have a break label, then some case needed it. That implies - // that the switch statement as a whole can fall through. - if (this->break_label_ != NULL) - return true; - - return this->clauses_->may_fall_through(); -} - -// Convert to GENERIC. - -Bstatement* -Constant_switch_statement::do_get_backend(Translate_context* context) -{ - tree switch_val_tree = this->val_->get_tree(context); - Bexpression* switch_val_expr = tree_to_expr(switch_val_tree); - - Unnamed_label* break_label = this->break_label_; - if (break_label == NULL) - break_label = new Unnamed_label(this->location()); - - std::vector > all_cases; - std::vector all_statements; - this->clauses_->get_backend(context, break_label, &all_cases, - &all_statements); - - Bstatement* switch_statement; - switch_statement = context->backend()->switch_statement(switch_val_expr, - all_cases, - all_statements, - this->location()); - Bstatement* ldef = break_label->get_definition(context); - return context->backend()->compound_statement(switch_statement, ldef); -} - -// Class Switch_statement. - -// Traversal. - -int -Switch_statement::do_traverse(Traverse* traverse) -{ - if (this->val_ != NULL) - { - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return this->clauses_->traverse(traverse); -} - -// Lower a Switch_statement to a Constant_switch_statement or a series -// of if statements. - -Statement* -Switch_statement::do_lower(Gogo*, Named_object*, Block* enclosing) -{ - source_location loc = this->location(); - - if (this->val_ != NULL - && (this->val_->is_error_expression() - || this->val_->type()->is_error())) - return Statement::make_error_statement(loc); - - if (this->val_ != NULL - && this->val_->type()->integer_type() != NULL - && !this->clauses_->empty() - && this->clauses_->is_constant()) - return new Constant_switch_statement(this->val_, this->clauses_, - this->break_label_, loc); - - Block* b = new Block(enclosing, loc); - - if (this->clauses_->empty()) - { - Expression* val = this->val_; - if (val == NULL) - val = Expression::make_boolean(true, loc); - return Statement::make_statement(val); - } - - Temporary_statement* val_temp; - if (this->val_ == NULL) - val_temp = NULL; - else - { - // var val_temp VAL_TYPE = VAL - val_temp = Statement::make_temporary(NULL, this->val_, loc); - b->add_statement(val_temp); - } - - this->clauses_->lower(b, val_temp, this->break_label()); - - Statement* s = Statement::make_unnamed_label_statement(this->break_label_); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Return the break label for this switch statement, creating it if -// necessary. - -Unnamed_label* -Switch_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Make a switch statement. - -Switch_statement* -Statement::make_switch_statement(Expression* val, source_location location) -{ - return new Switch_statement(val, location); -} - -// Class Type_case_clauses::Type_case_clause. - -// Traversal. - -int -Type_case_clauses::Type_case_clause::traverse(Traverse* traverse) -{ - if (!this->is_default_ - && ((traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) != 0) - && Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->statements_ != NULL) - return this->statements_->traverse(traverse); - return TRAVERSE_CONTINUE; -} - -// Lower one clause in a type switch. Add statements to the block B. -// The type descriptor we are switching on is in DESCRIPTOR_TEMP. -// BREAK_LABEL is the label at the end of the type switch. -// *STMTS_LABEL, if not NULL, is a label to put at the start of the -// statements. - -void -Type_case_clauses::Type_case_clause::lower(Block* b, - Temporary_statement* descriptor_temp, - Unnamed_label* break_label, - Unnamed_label** stmts_label) const -{ - source_location loc = this->location_; - - Unnamed_label* next_case_label = NULL; - if (!this->is_default_) - { - Type* type = this->type_; - - Expression* ref = Expression::make_temporary_reference(descriptor_temp, - loc); - - Expression* cond; - // The language permits case nil, which is of course a constant - // rather than a type. It will appear here as an invalid - // forwarding type. - if (type->is_nil_constant_as_type()) - cond = Expression::make_binary(OPERATOR_EQEQ, ref, - Expression::make_nil(loc), - loc); - else - cond = Runtime::make_call((type->interface_type() == NULL - ? Runtime::IFACETYPEEQ - : Runtime::IFACEI2TP), - loc, 2, - Expression::make_type_descriptor(type, loc), - ref); - - Unnamed_label* dest; - if (!this->is_fallthrough_) - { - // if !COND { goto NEXT_CASE_LABEL } - next_case_label = new Unnamed_label(UNKNOWN_LOCATION); - dest = next_case_label; - cond = Expression::make_unary(OPERATOR_NOT, cond, loc); - } - else - { - // if COND { goto STMTS_LABEL } - go_assert(stmts_label != NULL); - if (*stmts_label == NULL) - *stmts_label = new Unnamed_label(UNKNOWN_LOCATION); - dest = *stmts_label; - } - Block* then_block = new Block(b, loc); - Statement* s = Statement::make_goto_unnamed_statement(dest, loc); - then_block->add_statement(s); - s = Statement::make_if_statement(cond, then_block, NULL, loc); - b->add_statement(s); - } - - if (this->statements_ != NULL - || (!this->is_fallthrough_ - && stmts_label != NULL - && *stmts_label != NULL)) - { - go_assert(!this->is_fallthrough_); - if (stmts_label != NULL && *stmts_label != NULL) - { - go_assert(!this->is_default_); - if (this->statements_ != NULL) - (*stmts_label)->set_location(this->statements_->start_location()); - Statement* s = Statement::make_unnamed_label_statement(*stmts_label); - b->add_statement(s); - *stmts_label = NULL; - } - if (this->statements_ != NULL) - b->add_statement(Statement::make_block_statement(this->statements_, - loc)); - } - - if (this->is_fallthrough_) - go_assert(next_case_label == NULL); - else - { - source_location gloc = (this->statements_ == NULL - ? loc - : this->statements_->end_location()); - b->add_statement(Statement::make_goto_unnamed_statement(break_label, - gloc)); - if (next_case_label != NULL) - { - Statement* s = - Statement::make_unnamed_label_statement(next_case_label); - b->add_statement(s); - } - } -} - -// Class Type_case_clauses. - -// Traversal. - -int -Type_case_clauses::traverse(Traverse* traverse) -{ - for (Type_clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Check for duplicate types. - -void -Type_case_clauses::check_duplicates() const -{ - typedef Unordered_set_hash(const Type*, Type_hash_identical, - Type_identical) Types_seen; - Types_seen types_seen; - for (Type_clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - Type* t = p->type(); - if (t == NULL) - continue; - if (t->is_nil_constant_as_type()) - t = Type::make_nil_type(); - std::pair ins = types_seen.insert(t); - if (!ins.second) - error_at(p->location(), "duplicate type in switch"); - } -} - -// Lower the clauses in a type switch. Add statements to the block B. -// The type descriptor we are switching on is in DESCRIPTOR_TEMP. -// BREAK_LABEL is the label at the end of the type switch. - -void -Type_case_clauses::lower(Block* b, Temporary_statement* descriptor_temp, - Unnamed_label* break_label) const -{ - const Type_case_clause* default_case = NULL; - - Unnamed_label* stmts_label = NULL; - for (Type_clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (!p->is_default()) - p->lower(b, descriptor_temp, break_label, &stmts_label); - else - { - // We are generating a series of tests, which means that we - // need to move the default case to the end. - default_case = &*p; - } - } - go_assert(stmts_label == NULL); - - if (default_case != NULL) - default_case->lower(b, descriptor_temp, break_label, NULL); -} - -// Class Type_switch_statement. - -// Traversal. - -int -Type_switch_statement::do_traverse(Traverse* traverse) -{ - if (this->var_ == NULL) - { - if (this->traverse_expression(traverse, &this->expr_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->clauses_ != NULL) - return this->clauses_->traverse(traverse); - return TRAVERSE_CONTINUE; -} - -// Lower a type switch statement to a series of if statements. The gc -// compiler is able to generate a table in some cases. However, that -// does not work for us because we may have type descriptors in -// different shared libraries, so we can't compare them with simple -// equality testing. - -Statement* -Type_switch_statement::do_lower(Gogo*, Named_object*, Block* enclosing) -{ - const source_location loc = this->location(); - - if (this->clauses_ != NULL) - this->clauses_->check_duplicates(); - - Block* b = new Block(enclosing, loc); - - Type* val_type = (this->var_ != NULL - ? this->var_->var_value()->type() - : this->expr_->type()); - - // var descriptor_temp DESCRIPTOR_TYPE - Type* descriptor_type = Type::make_type_descriptor_ptr_type(); - Temporary_statement* descriptor_temp = - Statement::make_temporary(descriptor_type, NULL, loc); - b->add_statement(descriptor_temp); - - if (val_type->interface_type() == NULL) - { - // Doing a type switch on a non-interface type. Should we issue - // a warning for this case? - Expression* lhs = Expression::make_temporary_reference(descriptor_temp, - loc); - Expression* rhs; - if (val_type->is_nil_type()) - rhs = Expression::make_nil(loc); - else - { - if (val_type->is_abstract()) - val_type = val_type->make_non_abstract_type(); - rhs = Expression::make_type_descriptor(val_type, loc); - } - Statement* s = Statement::make_assignment(lhs, rhs, loc); - b->add_statement(s); - } - else - { - // descriptor_temp = ifacetype(val_temp) - // FIXME: This should be inlined. - bool is_empty = val_type->interface_type()->is_empty(); - Expression* ref; - if (this->var_ == NULL) - ref = this->expr_; - else - ref = Expression::make_var_reference(this->var_, loc); - Expression* call = Runtime::make_call((is_empty - ? Runtime::EFACETYPE - : Runtime::IFACETYPE), - loc, 1, ref); - Expression* lhs = Expression::make_temporary_reference(descriptor_temp, - loc); - Statement* s = Statement::make_assignment(lhs, call, loc); - b->add_statement(s); - } - - if (this->clauses_ != NULL) - this->clauses_->lower(b, descriptor_temp, this->break_label()); - - Statement* s = Statement::make_unnamed_label_statement(this->break_label_); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Return the break label for this type switch statement, creating it -// if necessary. - -Unnamed_label* -Type_switch_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Make a type switch statement. - -Type_switch_statement* -Statement::make_type_switch_statement(Named_object* var, Expression* expr, - source_location location) -{ - return new Type_switch_statement(var, expr, location); -} - -// Class Send_statement. - -// Traversal. - -int -Send_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->channel_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->val_); -} - -// Determine types. - -void -Send_statement::do_determine_types() -{ - this->channel_->determine_type_no_context(); - Type* type = this->channel_->type(); - Type_context context; - if (type->channel_type() != NULL) - context.type = type->channel_type()->element_type(); - this->val_->determine_type(&context); -} - -// Check types. - -void -Send_statement::do_check_types(Gogo*) -{ - Type* type = this->channel_->type(); - if (type->is_error()) - { - this->set_is_error(); - return; - } - Channel_type* channel_type = type->channel_type(); - if (channel_type == NULL) - { - error_at(this->location(), "left operand of %<<-%> must be channel"); - this->set_is_error(); - return; - } - Type* element_type = channel_type->element_type(); - if (!Type::are_assignable(element_type, this->val_->type(), NULL)) - { - this->report_error(_("incompatible types in send")); - return; - } - if (!channel_type->may_send()) - { - this->report_error(_("invalid send on receive-only channel")); - return; - } -} - -// Convert a send statement to the backend representation. - -Bstatement* -Send_statement::do_get_backend(Translate_context* context) -{ - source_location loc = this->location(); - - Channel_type* channel_type = this->channel_->type()->channel_type(); - Type* element_type = channel_type->element_type(); - Expression* val = Expression::make_cast(element_type, this->val_, loc); - - bool is_small; - bool can_take_address; - switch (element_type->base()->classification()) - { - case Type::TYPE_BOOLEAN: - case Type::TYPE_INTEGER: - case Type::TYPE_FUNCTION: - case Type::TYPE_POINTER: - case Type::TYPE_MAP: - case Type::TYPE_CHANNEL: - is_small = true; - can_take_address = false; - break; - - case Type::TYPE_FLOAT: - case Type::TYPE_COMPLEX: - case Type::TYPE_STRING: - case Type::TYPE_INTERFACE: - is_small = false; - can_take_address = false; - break; - - case Type::TYPE_STRUCT: - is_small = false; - can_take_address = true; - break; - - case Type::TYPE_ARRAY: - is_small = false; - can_take_address = !element_type->is_open_array_type(); - break; - - default: - case Type::TYPE_ERROR: - case Type::TYPE_VOID: - case Type::TYPE_SINK: - case Type::TYPE_NIL: - case Type::TYPE_NAMED: - case Type::TYPE_FORWARD: - go_assert(saw_errors()); - return context->backend()->error_statement(); - } - - // Only try to take the address of a variable. We have already - // moved variables to the heap, so this should not cause that to - // happen unnecessarily. - if (can_take_address - && val->var_expression() == NULL - && val->temporary_reference_expression() == NULL) - can_take_address = false; - - Runtime::Function code; - Bstatement* btemp = NULL; - Expression* call; - if (is_small) - { - // Type is small enough to handle as uint64. - code = Runtime::SEND_SMALL; - val = Expression::make_unsafe_cast(Type::lookup_integer_type("uint64"), - val, loc); - } - else if (can_take_address) - { - // Must pass address of value. The function doesn't change the - // value, so just take its address directly. - code = Runtime::SEND_BIG; - val = Expression::make_unary(OPERATOR_AND, val, loc); - } - else - { - // Must pass address of value, but the value is small enough - // that it might be in registers. Copy value into temporary - // variable to take address. - code = Runtime::SEND_BIG; - Temporary_statement* temp = Statement::make_temporary(element_type, - val, loc); - Expression* ref = Expression::make_temporary_reference(temp, loc); - val = Expression::make_unary(OPERATOR_AND, ref, loc); - btemp = temp->get_backend(context); - } - - call = Runtime::make_call(code, loc, 3, this->channel_, val, - Expression::make_boolean(this->for_select_, loc)); - - context->gogo()->lower_expression(context->function(), &call); - Bexpression* bcall = tree_to_expr(call->get_tree(context)); - Bstatement* s = context->backend()->expression_statement(bcall); - - if (btemp == NULL) - return s; - else - return context->backend()->compound_statement(btemp, s); -} - -// Make a send statement. - -Send_statement* -Statement::make_send_statement(Expression* channel, Expression* val, - source_location location) -{ - return new Send_statement(channel, val, location); -} - -// Class Select_clauses::Select_clause. - -// Traversal. - -int -Select_clauses::Select_clause::traverse(Traverse* traverse) -{ - if (!this->is_lowered_ - && (traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) != 0) - { - if (this->channel_ != NULL) - { - if (Expression::traverse(&this->channel_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->val_ != NULL) - { - if (Expression::traverse(&this->val_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->closed_ != NULL) - { - if (Expression::traverse(&this->closed_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - if (this->statements_ != NULL) - { - if (this->statements_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lowering. Here we pull out the channel and the send values, to -// enforce the order of evaluation. We also add explicit send and -// receive statements to the clauses. - -void -Select_clauses::Select_clause::lower(Gogo* gogo, Named_object* function, - Block* b) -{ - if (this->is_default_) - { - go_assert(this->channel_ == NULL && this->val_ == NULL); - this->is_lowered_ = true; - return; - } - - source_location loc = this->location_; - - // Evaluate the channel before the select statement. - Temporary_statement* channel_temp = Statement::make_temporary(NULL, - this->channel_, - loc); - b->add_statement(channel_temp); - this->channel_ = Expression::make_temporary_reference(channel_temp, loc); - - // If this is a send clause, evaluate the value to send before the - // select statement. - Temporary_statement* val_temp = NULL; - if (this->is_send_ && !this->val_->is_constant()) - { - val_temp = Statement::make_temporary(NULL, this->val_, loc); - b->add_statement(val_temp); - } - - // Add the send or receive before the rest of the statements if any. - Block *init = new Block(b, loc); - Expression* ref = Expression::make_temporary_reference(channel_temp, loc); - if (this->is_send_) - { - Expression* ref2; - if (val_temp == NULL) - ref2 = this->val_; - else - ref2 = Expression::make_temporary_reference(val_temp, loc); - Send_statement* send = Statement::make_send_statement(ref, ref2, loc); - send->set_for_select(); - init->add_statement(send); - } - else if (this->closed_ != NULL && !this->closed_->is_sink_expression()) - { - go_assert(this->var_ == NULL && this->closedvar_ == NULL); - if (this->val_ == NULL) - this->val_ = Expression::make_sink(loc); - Statement* s = Statement::make_tuple_receive_assignment(this->val_, - this->closed_, - ref, true, loc); - init->add_statement(s); - } - else if (this->closedvar_ != NULL) - { - go_assert(this->val_ == NULL); - Expression* val; - if (this->var_ == NULL) - val = Expression::make_sink(loc); - else - val = Expression::make_var_reference(this->var_, loc); - Expression* closed = Expression::make_var_reference(this->closedvar_, - loc); - Statement* s = Statement::make_tuple_receive_assignment(val, closed, ref, - true, loc); - // We have to put S in STATEMENTS_, because that is where the - // variables are declared. - go_assert(this->statements_ != NULL); - this->statements_->add_statement_at_front(s); - // We have to lower STATEMENTS_ again, to lower the tuple - // receive assignment we just added. - gogo->lower_block(function, this->statements_); - } - else - { - Receive_expression* recv = Expression::make_receive(ref, loc); - recv->set_for_select(); - if (this->val_ != NULL) - { - go_assert(this->var_ == NULL); - init->add_statement(Statement::make_assignment(this->val_, recv, - loc)); - } - else if (this->var_ != NULL) - { - this->var_->var_value()->set_init(recv); - this->var_->var_value()->clear_type_from_chan_element(); - } - else - { - init->add_statement(Statement::make_statement(recv)); - } - } - - // Lower any statements we just created. - gogo->lower_block(function, init); - - if (this->statements_ != NULL) - init->add_statement(Statement::make_block_statement(this->statements_, - loc)); - - this->statements_ = init; - - // Now all references should be handled through the statements, not - // through here. - this->is_lowered_ = true; - this->val_ = NULL; - this->var_ = NULL; -} - -// Determine types. - -void -Select_clauses::Select_clause::determine_types() -{ - go_assert(this->is_lowered_); - if (this->statements_ != NULL) - this->statements_->determine_types(); -} - -// Whether this clause may fall through to the statement which follows -// the overall select statement. - -bool -Select_clauses::Select_clause::may_fall_through() const -{ - if (this->statements_ == NULL) - return true; - return this->statements_->may_fall_through(); -} - -// Return the backend representation for the statements to execute. - -Bstatement* -Select_clauses::Select_clause::get_statements_backend( - Translate_context* context) -{ - if (this->statements_ == NULL) - return NULL; - Bblock* bblock = this->statements_->get_backend(context); - return context->backend()->block_statement(bblock); -} - -// Class Select_clauses. - -// Traversal. - -int -Select_clauses::traverse(Traverse* traverse) -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lowering. Here we pull out the channel and the send values, to -// enforce the order of evaluation. We also add explicit send and -// receive statements to the clauses. - -void -Select_clauses::lower(Gogo* gogo, Named_object* function, Block* b) -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - p->lower(gogo, function, b); -} - -// Determine types. - -void -Select_clauses::determine_types() -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - p->determine_types(); -} - -// Return whether these select clauses fall through to the statement -// following the overall select statement. - -bool -Select_clauses::may_fall_through() const -{ - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - if (p->may_fall_through()) - return true; - return false; -} - -// Convert to the backend representation. We build a call to -// size_t __go_select(size_t count, _Bool has_default, -// channel* channels, _Bool* is_send) -// -// There are COUNT entries in the CHANNELS and IS_SEND arrays. The -// value in the IS_SEND array is true for send, false for receive. -// __go_select returns an integer from 0 to COUNT, inclusive. A -// return of 0 means that the default case should be run; this only -// happens if HAS_DEFAULT is non-zero. Otherwise the number indicates -// the case to run. - -// FIXME: This doesn't handle channels which send interface types -// where the receiver has a static type which matches that interface. - -Bstatement* -Select_clauses::get_backend(Translate_context* context, - Unnamed_label *break_label, - source_location location) -{ - size_t count = this->clauses_.size(); - - Expression_list* chan_init = new Expression_list(); - chan_init->reserve(count); - - Expression_list* is_send_init = new Expression_list(); - is_send_init->reserve(count); - - Select_clause *default_clause = NULL; - - Type* runtime_chanptr_type = Runtime::chanptr_type(); - Type* runtime_chan_type = runtime_chanptr_type->points_to(); - - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->is_default()) - { - default_clause = &*p; - --count; - continue; - } - - if (p->channel()->type()->channel_type() == NULL) - { - // We should have given an error in the send or receive - // statement we created via lowering. - go_assert(saw_errors()); - return context->backend()->error_statement(); - } - - Expression* c = p->channel(); - c = Expression::make_unsafe_cast(runtime_chan_type, c, p->location()); - chan_init->push_back(c); - - is_send_init->push_back(Expression::make_boolean(p->is_send(), - p->location())); - } - - if (chan_init->empty()) - { - go_assert(count == 0); - Bstatement* s; - Bstatement* ldef = break_label->get_definition(context); - if (default_clause != NULL) - { - // There is a default clause and no cases. Just execute the - // default clause. - s = default_clause->get_statements_backend(context); - } - else - { - // There isn't even a default clause. In this case select - // pauses forever. Call the runtime function with nils. - mpz_t zval; - mpz_init_set_ui(zval, 0); - Expression* zero = Expression::make_integer(&zval, NULL, location); - mpz_clear(zval); - Expression* default_arg = Expression::make_boolean(false, location); - Expression* nil1 = Expression::make_nil(location); - Expression* nil2 = nil1->copy(); - Expression* call = Runtime::make_call(Runtime::SELECT, location, 4, - zero, default_arg, nil1, nil2); - context->gogo()->lower_expression(context->function(), &call); - Bexpression* bcall = tree_to_expr(call->get_tree(context)); - s = context->backend()->expression_statement(bcall); - } - if (s == NULL) - return ldef; - return context->backend()->compound_statement(s, ldef); - } - go_assert(count > 0); - - std::vector statements; - - mpz_t ival; - mpz_init_set_ui(ival, count); - Expression* ecount = Expression::make_integer(&ival, NULL, location); - mpz_clear(ival); - - Type* chan_array_type = Type::make_array_type(runtime_chan_type, ecount); - Expression* chans = Expression::make_composite_literal(chan_array_type, 0, - false, chan_init, - location); - context->gogo()->lower_expression(context->function(), &chans); - Temporary_statement* chan_temp = Statement::make_temporary(chan_array_type, - chans, - location); - statements.push_back(chan_temp->get_backend(context)); - - Type* is_send_array_type = Type::make_array_type(Type::lookup_bool_type(), - ecount->copy()); - Expression* is_sends = Expression::make_composite_literal(is_send_array_type, - 0, false, - is_send_init, - location); - context->gogo()->lower_expression(context->function(), &is_sends); - Temporary_statement* is_send_temp = - Statement::make_temporary(is_send_array_type, is_sends, location); - statements.push_back(is_send_temp->get_backend(context)); - - mpz_init_set_ui(ival, 0); - Expression* zero = Expression::make_integer(&ival, NULL, location); - mpz_clear(ival); - - Expression* ref = Expression::make_temporary_reference(chan_temp, location); - Expression* chan_arg = Expression::make_array_index(ref, zero, NULL, - location); - chan_arg = Expression::make_unary(OPERATOR_AND, chan_arg, location); - chan_arg = Expression::make_unsafe_cast(runtime_chanptr_type, chan_arg, - location); - - ref = Expression::make_temporary_reference(is_send_temp, location); - Expression* is_send_arg = Expression::make_array_index(ref, zero->copy(), - NULL, location); - is_send_arg = Expression::make_unary(OPERATOR_AND, is_send_arg, location); - - Expression* default_arg = Expression::make_boolean(default_clause != NULL, - location); - Expression* call = Runtime::make_call(Runtime::SELECT, location, 4, - ecount->copy(), default_arg, - chan_arg, is_send_arg); - context->gogo()->lower_expression(context->function(), &call); - Bexpression* bcall = tree_to_expr(call->get_tree(context)); - - std::vector > cases; - std::vector clauses; - - cases.resize(count + (default_clause != NULL ? 1 : 0)); - clauses.resize(count + (default_clause != NULL ? 1 : 0)); - - int index = 0; - - if (default_clause != NULL) - { - this->add_clause_backend(context, location, index, 0, default_clause, - break_label, &cases, &clauses); - ++index; - } - - int i = 1; - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (!p->is_default()) - { - this->add_clause_backend(context, location, index, i, &*p, - break_label, &cases, &clauses); - ++i; - ++index; - } - } - - Bstatement* switch_stmt = context->backend()->switch_statement(bcall, - cases, - clauses, - location); - statements.push_back(switch_stmt); - - Bstatement* ldef = break_label->get_definition(context); - statements.push_back(ldef); - - return context->backend()->statement_list(statements); -} - -// Add CLAUSE to CASES/CLAUSES at INDEX. - -void -Select_clauses::add_clause_backend( - Translate_context* context, - source_location location, - int index, - int case_value, - Select_clause* clause, - Unnamed_label* bottom_label, - std::vector > *cases, - std::vector* clauses) -{ - mpz_t ival; - mpz_init_set_ui(ival, case_value); - Expression* e = Expression::make_integer(&ival, NULL, location); - mpz_clear(ival); - (*cases)[index].push_back(tree_to_expr(e->get_tree(context))); - - Bstatement* s = clause->get_statements_backend(context); - - source_location gloc = (clause->statements() == NULL - ? clause->location() - : clause->statements()->end_location()); - Bstatement* g = bottom_label->get_goto(context, gloc); - - if (s == NULL) - (*clauses)[index] = g; - else - (*clauses)[index] = context->backend()->compound_statement(s, g); -} - -// Class Select_statement. - -// Return the break label for this switch statement, creating it if -// necessary. - -Unnamed_label* -Select_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Lower a select statement. This will still return a select -// statement, but it will be modified to implement the order of -// evaluation rules, and to include the send and receive statements as -// explicit statements in the clauses. - -Statement* -Select_statement::do_lower(Gogo* gogo, Named_object* function, - Block* enclosing) -{ - if (this->is_lowered_) - return this; - Block* b = new Block(enclosing, this->location()); - this->clauses_->lower(gogo, function, b); - this->is_lowered_ = true; - b->add_statement(this); - return Statement::make_block_statement(b, this->location()); -} - -// Return the backend representation for a select statement. - -Bstatement* -Select_statement::do_get_backend(Translate_context* context) -{ - return this->clauses_->get_backend(context, this->break_label(), - this->location()); -} - -// Make a select statement. - -Select_statement* -Statement::make_select_statement(source_location location) -{ - return new Select_statement(location); -} - -// Class For_statement. - -// Traversal. - -int -For_statement::do_traverse(Traverse* traverse) -{ - if (this->init_ != NULL) - { - if (this->init_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->cond_ != NULL) - { - if (this->traverse_expression(traverse, &this->cond_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->post_ != NULL) - { - if (this->post_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return this->statements_->traverse(traverse); -} - -// Lower a For_statement into if statements and gotos. Getting rid of -// complex statements make it easier to handle garbage collection. - -Statement* -For_statement::do_lower(Gogo*, Named_object*, Block* enclosing) -{ - Statement* s; - source_location loc = this->location(); - - Block* b = new Block(enclosing, this->location()); - if (this->init_ != NULL) - { - s = Statement::make_block_statement(this->init_, - this->init_->start_location()); - b->add_statement(s); - } - - Unnamed_label* entry = NULL; - if (this->cond_ != NULL) - { - entry = new Unnamed_label(this->location()); - b->add_statement(Statement::make_goto_unnamed_statement(entry, loc)); - } - - Unnamed_label* top = new Unnamed_label(this->location()); - b->add_statement(Statement::make_unnamed_label_statement(top)); - - s = Statement::make_block_statement(this->statements_, - this->statements_->start_location()); - b->add_statement(s); - - source_location end_loc = this->statements_->end_location(); - - Unnamed_label* cont = this->continue_label_; - if (cont != NULL) - b->add_statement(Statement::make_unnamed_label_statement(cont)); - - if (this->post_ != NULL) - { - s = Statement::make_block_statement(this->post_, - this->post_->start_location()); - b->add_statement(s); - end_loc = this->post_->end_location(); - } - - if (this->cond_ == NULL) - b->add_statement(Statement::make_goto_unnamed_statement(top, end_loc)); - else - { - b->add_statement(Statement::make_unnamed_label_statement(entry)); - - source_location cond_loc = this->cond_->location(); - Block* then_block = new Block(b, cond_loc); - s = Statement::make_goto_unnamed_statement(top, cond_loc); - then_block->add_statement(s); - - s = Statement::make_if_statement(this->cond_, then_block, NULL, cond_loc); - b->add_statement(s); - } - - Unnamed_label* brk = this->break_label_; - if (brk != NULL) - b->add_statement(Statement::make_unnamed_label_statement(brk)); - - b->set_end_location(end_loc); - - return Statement::make_block_statement(b, loc); -} - -// Return the break label, creating it if necessary. - -Unnamed_label* -For_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Return the continue LABEL_EXPR. - -Unnamed_label* -For_statement::continue_label() -{ - if (this->continue_label_ == NULL) - this->continue_label_ = new Unnamed_label(this->location()); - return this->continue_label_; -} - -// Set the break and continue labels a for statement. This is used -// when lowering a for range statement. - -void -For_statement::set_break_continue_labels(Unnamed_label* break_label, - Unnamed_label* continue_label) -{ - go_assert(this->break_label_ == NULL && this->continue_label_ == NULL); - this->break_label_ = break_label; - this->continue_label_ = continue_label; -} - -// Make a for statement. - -For_statement* -Statement::make_for_statement(Block* init, Expression* cond, Block* post, - source_location location) -{ - return new For_statement(init, cond, post, location); -} - -// Class For_range_statement. - -// Traversal. - -int -For_range_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->index_var_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->value_var_ != NULL) - { - if (this->traverse_expression(traverse, &this->value_var_) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->traverse_expression(traverse, &this->range_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->statements_->traverse(traverse); -} - -// Lower a for range statement. For simplicity we lower this into a -// for statement, which will then be lowered in turn to goto -// statements. - -Statement* -For_range_statement::do_lower(Gogo* gogo, Named_object*, Block* enclosing) -{ - Type* range_type = this->range_->type(); - if (range_type->points_to() != NULL - && range_type->points_to()->array_type() != NULL - && !range_type->points_to()->is_open_array_type()) - range_type = range_type->points_to(); - - Type* index_type; - Type* value_type = NULL; - if (range_type->array_type() != NULL) - { - index_type = Type::lookup_integer_type("int"); - value_type = range_type->array_type()->element_type(); - } - else if (range_type->is_string_type()) - { - index_type = Type::lookup_integer_type("int"); - value_type = index_type; - } - else if (range_type->map_type() != NULL) - { - index_type = range_type->map_type()->key_type(); - value_type = range_type->map_type()->val_type(); - } - else if (range_type->channel_type() != NULL) - { - index_type = range_type->channel_type()->element_type(); - if (this->value_var_ != NULL) - { - if (!this->value_var_->type()->is_error()) - this->report_error(_("too many variables for range clause " - "with channel")); - return Statement::make_error_statement(this->location()); - } - } - else - { - this->report_error(_("range clause must have " - "array, slice, setring, map, or channel type")); - return Statement::make_error_statement(this->location()); - } - - source_location loc = this->location(); - Block* temp_block = new Block(enclosing, loc); - - Named_object* range_object = NULL; - Temporary_statement* range_temp = NULL; - Var_expression* ve = this->range_->var_expression(); - if (ve != NULL) - range_object = ve->named_object(); - else - { - range_temp = Statement::make_temporary(NULL, this->range_, loc); - temp_block->add_statement(range_temp); - } - - Temporary_statement* index_temp = Statement::make_temporary(index_type, - NULL, loc); - temp_block->add_statement(index_temp); - - Temporary_statement* value_temp = NULL; - if (this->value_var_ != NULL) - { - value_temp = Statement::make_temporary(value_type, NULL, loc); - temp_block->add_statement(value_temp); - } - - Block* body = new Block(temp_block, loc); - - Block* init; - Expression* cond; - Block* iter_init; - Block* post; - - // Arrange to do a loop appropriate for the type. We will produce - // for INIT ; COND ; POST { - // ITER_INIT - // INDEX = INDEX_TEMP - // VALUE = VALUE_TEMP // If there is a value - // original statements - // } - - if (range_type->array_type() != NULL) - this->lower_range_array(gogo, temp_block, body, range_object, range_temp, - index_temp, value_temp, &init, &cond, &iter_init, - &post); - else if (range_type->is_string_type()) - this->lower_range_string(gogo, temp_block, body, range_object, range_temp, - index_temp, value_temp, &init, &cond, &iter_init, - &post); - else if (range_type->map_type() != NULL) - this->lower_range_map(gogo, temp_block, body, range_object, range_temp, - index_temp, value_temp, &init, &cond, &iter_init, - &post); - else if (range_type->channel_type() != NULL) - this->lower_range_channel(gogo, temp_block, body, range_object, range_temp, - index_temp, value_temp, &init, &cond, &iter_init, - &post); - else - go_unreachable(); - - if (iter_init != NULL) - body->add_statement(Statement::make_block_statement(iter_init, loc)); - - Statement* assign; - Expression* index_ref = Expression::make_temporary_reference(index_temp, loc); - if (this->value_var_ == NULL) - { - assign = Statement::make_assignment(this->index_var_, index_ref, loc); - } - else - { - Expression_list* lhs = new Expression_list(); - lhs->push_back(this->index_var_); - lhs->push_back(this->value_var_); - - Expression_list* rhs = new Expression_list(); - rhs->push_back(index_ref); - rhs->push_back(Expression::make_temporary_reference(value_temp, loc)); - - assign = Statement::make_tuple_assignment(lhs, rhs, loc); - } - body->add_statement(assign); - - body->add_statement(Statement::make_block_statement(this->statements_, loc)); - - body->set_end_location(this->statements_->end_location()); - - For_statement* loop = Statement::make_for_statement(init, cond, post, - this->location()); - loop->add_statements(body); - loop->set_break_continue_labels(this->break_label_, this->continue_label_); - - temp_block->add_statement(loop); - - return Statement::make_block_statement(temp_block, loc); -} - -// Return a reference to the range, which may be in RANGE_OBJECT or in -// RANGE_TEMP. - -Expression* -For_range_statement::make_range_ref(Named_object* range_object, - Temporary_statement* range_temp, - source_location loc) -{ - if (range_object != NULL) - return Expression::make_var_reference(range_object, loc); - else - return Expression::make_temporary_reference(range_temp, loc); -} - -// Return a call to the predeclared function FUNCNAME passing a -// reference to the temporary variable ARG. - -Expression* -For_range_statement::call_builtin(Gogo* gogo, const char* funcname, - Expression* arg, - source_location loc) -{ - Named_object* no = gogo->lookup_global(funcname); - go_assert(no != NULL && no->is_function_declaration()); - Expression* func = Expression::make_func_reference(no, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(arg); - return Expression::make_call(func, params, false, loc); -} - -// Lower a for range over an array or slice. - -void -For_range_statement::lower_range_array(Gogo* gogo, - Block* enclosing, - Block* body_block, - Named_object* range_object, - Temporary_statement* range_temp, - Temporary_statement* index_temp, - Temporary_statement* value_temp, - Block** pinit, - Expression** pcond, - Block** piter_init, - Block** ppost) -{ - source_location loc = this->location(); - - // The loop we generate: - // len_temp := len(range) - // for index_temp = 0; index_temp < len_temp; index_temp++ { - // value_temp = range[index_temp] - // index = index_temp - // value = value_temp - // original body - // } - - // Set *PINIT to - // var len_temp int - // len_temp = len(range) - // index_temp = 0 - - Block* init = new Block(enclosing, loc); - - Expression* ref = this->make_range_ref(range_object, range_temp, loc); - Expression* len_call = this->call_builtin(gogo, "len", ref, loc); - Temporary_statement* len_temp = Statement::make_temporary(index_temp->type(), - len_call, loc); - init->add_statement(len_temp); - - mpz_t zval; - mpz_init_set_ui(zval, 0UL); - Expression* zexpr = Expression::make_integer(&zval, NULL, loc); - mpz_clear(zval); - - ref = Expression::make_temporary_reference(index_temp, loc); - Statement* s = Statement::make_assignment(ref, zexpr, loc); - init->add_statement(s); - - *pinit = init; - - // Set *PCOND to - // index_temp < len_temp - - ref = Expression::make_temporary_reference(index_temp, loc); - Expression* ref2 = Expression::make_temporary_reference(len_temp, loc); - Expression* lt = Expression::make_binary(OPERATOR_LT, ref, ref2, loc); - - *pcond = lt; - - // Set *PITER_INIT to - // value_temp = range[index_temp] - - Block* iter_init = NULL; - if (value_temp != NULL) - { - iter_init = new Block(body_block, loc); - - ref = this->make_range_ref(range_object, range_temp, loc); - Expression* ref2 = Expression::make_temporary_reference(index_temp, loc); - Expression* index = Expression::make_index(ref, ref2, NULL, loc); - - ref = Expression::make_temporary_reference(value_temp, loc); - s = Statement::make_assignment(ref, index, loc); - - iter_init->add_statement(s); - } - *piter_init = iter_init; - - // Set *PPOST to - // index_temp++ - - Block* post = new Block(enclosing, loc); - ref = Expression::make_temporary_reference(index_temp, loc); - s = Statement::make_inc_statement(ref); - post->add_statement(s); - *ppost = post; -} - -// Lower a for range over a string. - -void -For_range_statement::lower_range_string(Gogo*, - Block* enclosing, - Block* body_block, - Named_object* range_object, - Temporary_statement* range_temp, - Temporary_statement* index_temp, - Temporary_statement* value_temp, - Block** pinit, - Expression** pcond, - Block** piter_init, - Block** ppost) -{ - source_location loc = this->location(); - - // The loop we generate: - // var next_index_temp int - // for index_temp = 0; ; index_temp = next_index_temp { - // next_index_temp, value_temp = stringiter2(range, index_temp) - // if next_index_temp == 0 { - // break - // } - // index = index_temp - // value = value_temp - // original body - // } - - // Set *PINIT to - // var next_index_temp int - // index_temp = 0 - - Block* init = new Block(enclosing, loc); - - Temporary_statement* next_index_temp = - Statement::make_temporary(index_temp->type(), NULL, loc); - init->add_statement(next_index_temp); - - mpz_t zval; - mpz_init_set_ui(zval, 0UL); - Expression* zexpr = Expression::make_integer(&zval, NULL, loc); - - Expression* ref = Expression::make_temporary_reference(index_temp, loc); - Statement* s = Statement::make_assignment(ref, zexpr, loc); - - init->add_statement(s); - *pinit = init; - - // The loop has no condition. - - *pcond = NULL; - - // Set *PITER_INIT to - // next_index_temp = runtime.stringiter(range, index_temp) - // or - // next_index_temp, value_temp = runtime.stringiter2(range, index_temp) - // followed by - // if next_index_temp == 0 { - // break - // } - - Block* iter_init = new Block(body_block, loc); - - Expression* p1 = this->make_range_ref(range_object, range_temp, loc); - Expression* p2 = Expression::make_temporary_reference(index_temp, loc); - Call_expression* call = Runtime::make_call((value_temp == NULL - ? Runtime::STRINGITER - : Runtime::STRINGITER2), - loc, 2, p1, p2); - - if (value_temp == NULL) - { - ref = Expression::make_temporary_reference(next_index_temp, loc); - s = Statement::make_assignment(ref, call, loc); - } - else - { - Expression_list* lhs = new Expression_list(); - lhs->push_back(Expression::make_temporary_reference(next_index_temp, - loc)); - lhs->push_back(Expression::make_temporary_reference(value_temp, loc)); - - Expression_list* rhs = new Expression_list(); - rhs->push_back(Expression::make_call_result(call, 0)); - rhs->push_back(Expression::make_call_result(call, 1)); - - s = Statement::make_tuple_assignment(lhs, rhs, loc); - } - iter_init->add_statement(s); - - ref = Expression::make_temporary_reference(next_index_temp, loc); - zexpr = Expression::make_integer(&zval, NULL, loc); - mpz_clear(zval); - Expression* equals = Expression::make_binary(OPERATOR_EQEQ, ref, zexpr, loc); - - Block* then_block = new Block(iter_init, loc); - s = Statement::make_break_statement(this->break_label(), loc); - then_block->add_statement(s); - - s = Statement::make_if_statement(equals, then_block, NULL, loc); - iter_init->add_statement(s); - - *piter_init = iter_init; - - // Set *PPOST to - // index_temp = next_index_temp - - Block* post = new Block(enclosing, loc); - - Expression* lhs = Expression::make_temporary_reference(index_temp, loc); - Expression* rhs = Expression::make_temporary_reference(next_index_temp, loc); - s = Statement::make_assignment(lhs, rhs, loc); - - post->add_statement(s); - *ppost = post; -} - -// Lower a for range over a map. - -void -For_range_statement::lower_range_map(Gogo*, - Block* enclosing, - Block* body_block, - Named_object* range_object, - Temporary_statement* range_temp, - Temporary_statement* index_temp, - Temporary_statement* value_temp, - Block** pinit, - Expression** pcond, - Block** piter_init, - Block** ppost) -{ - source_location loc = this->location(); - - // The runtime uses a struct to handle ranges over a map. The - // struct is four pointers long. The first pointer is NULL when we - // have completed the iteration. - - // The loop we generate: - // var hiter map_iteration_struct - // for mapiterinit(range, &hiter); hiter[0] != nil; mapiternext(&hiter) { - // mapiter2(hiter, &index_temp, &value_temp) - // index = index_temp - // value = value_temp - // original body - // } - - // Set *PINIT to - // var hiter map_iteration_struct - // runtime.mapiterinit(range, &hiter) - - Block* init = new Block(enclosing, loc); - - Type* map_iteration_type = Runtime::map_iteration_type(); - Temporary_statement* hiter = Statement::make_temporary(map_iteration_type, - NULL, loc); - init->add_statement(hiter); - - Expression* p1 = this->make_range_ref(range_object, range_temp, loc); - Expression* ref = Expression::make_temporary_reference(hiter, loc); - Expression* p2 = Expression::make_unary(OPERATOR_AND, ref, loc); - Expression* call = Runtime::make_call(Runtime::MAPITERINIT, loc, 2, p1, p2); - init->add_statement(Statement::make_statement(call)); - - *pinit = init; - - // Set *PCOND to - // hiter[0] != nil - - ref = Expression::make_temporary_reference(hiter, loc); - - mpz_t zval; - mpz_init_set_ui(zval, 0UL); - Expression* zexpr = Expression::make_integer(&zval, NULL, loc); - mpz_clear(zval); - - Expression* index = Expression::make_index(ref, zexpr, NULL, loc); - - Expression* ne = Expression::make_binary(OPERATOR_NOTEQ, index, - Expression::make_nil(loc), - loc); - - *pcond = ne; - - // Set *PITER_INIT to - // mapiter1(hiter, &index_temp) - // or - // mapiter2(hiter, &index_temp, &value_temp) - - Block* iter_init = new Block(body_block, loc); - - ref = Expression::make_temporary_reference(hiter, loc); - p1 = Expression::make_unary(OPERATOR_AND, ref, loc); - ref = Expression::make_temporary_reference(index_temp, loc); - p2 = Expression::make_unary(OPERATOR_AND, ref, loc); - if (value_temp == NULL) - call = Runtime::make_call(Runtime::MAPITER1, loc, 2, p1, p2); - else - { - ref = Expression::make_temporary_reference(value_temp, loc); - Expression* p3 = Expression::make_unary(OPERATOR_AND, ref, loc); - call = Runtime::make_call(Runtime::MAPITER2, loc, 3, p1, p2, p3); - } - iter_init->add_statement(Statement::make_statement(call)); - - *piter_init = iter_init; - - // Set *PPOST to - // mapiternext(&hiter) - - Block* post = new Block(enclosing, loc); - - ref = Expression::make_temporary_reference(hiter, loc); - p1 = Expression::make_unary(OPERATOR_AND, ref, loc); - call = Runtime::make_call(Runtime::MAPITERNEXT, loc, 1, p1); - post->add_statement(Statement::make_statement(call)); - - *ppost = post; -} - -// Lower a for range over a channel. - -void -For_range_statement::lower_range_channel(Gogo*, - Block*, - Block* body_block, - Named_object* range_object, - Temporary_statement* range_temp, - Temporary_statement* index_temp, - Temporary_statement* value_temp, - Block** pinit, - Expression** pcond, - Block** piter_init, - Block** ppost) -{ - go_assert(value_temp == NULL); - - source_location loc = this->location(); - - // The loop we generate: - // for { - // index_temp, ok_temp = <-range - // if !ok_temp { - // break - // } - // index = index_temp - // original body - // } - - // We have no initialization code, no condition, and no post code. - - *pinit = NULL; - *pcond = NULL; - *ppost = NULL; - - // Set *PITER_INIT to - // index_temp, ok_temp = <-range - // if !ok_temp { - // break - // } - - Block* iter_init = new Block(body_block, loc); - - Temporary_statement* ok_temp = - Statement::make_temporary(Type::lookup_bool_type(), NULL, loc); - iter_init->add_statement(ok_temp); - - Expression* cref = this->make_range_ref(range_object, range_temp, loc); - Expression* iref = Expression::make_temporary_reference(index_temp, loc); - Expression* oref = Expression::make_temporary_reference(ok_temp, loc); - Statement* s = Statement::make_tuple_receive_assignment(iref, oref, cref, - false, loc); - iter_init->add_statement(s); - - Block* then_block = new Block(iter_init, loc); - s = Statement::make_break_statement(this->break_label(), loc); - then_block->add_statement(s); - - oref = Expression::make_temporary_reference(ok_temp, loc); - Expression* cond = Expression::make_unary(OPERATOR_NOT, oref, loc); - s = Statement::make_if_statement(cond, then_block, NULL, loc); - iter_init->add_statement(s); - - *piter_init = iter_init; -} - -// Return the break LABEL_EXPR. - -Unnamed_label* -For_range_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Return the continue LABEL_EXPR. - -Unnamed_label* -For_range_statement::continue_label() -{ - if (this->continue_label_ == NULL) - this->continue_label_ = new Unnamed_label(this->location()); - return this->continue_label_; -} - -// Make a for statement with a range clause. - -For_range_statement* -Statement::make_for_range_statement(Expression* index_var, - Expression* value_var, - Expression* range, - source_location location) -{ - return new For_range_statement(index_var, value_var, range, location); -} diff --git a/gcc/go/gofrontend/statements.cc.working b/gcc/go/gofrontend/statements.cc.working deleted file mode 100644 index d24d98f4f88..00000000000 --- a/gcc/go/gofrontend/statements.cc.working +++ /dev/null @@ -1,5396 +0,0 @@ -// statements.cc -- Go frontend statements. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include - -#ifndef ENABLE_BUILD_WITH_CXX -extern "C" -{ -#endif - -#include "intl.h" -#include "tree.h" -#include "gimple.h" -#include "convert.h" -#include "tree-iterator.h" -#include "tree-flow.h" -#include "real.h" - -#ifndef ENABLE_BUILD_WITH_CXX -} -#endif - -#include "go-c.h" -#include "types.h" -#include "expressions.h" -#include "gogo.h" -#include "statements.h" - -// Class Statement. - -Statement::Statement(Statement_classification classification, - source_location location) - : classification_(classification), location_(location) -{ -} - -Statement::~Statement() -{ -} - -// Traverse the tree. The work of walking the components is handled -// by the subclasses. - -int -Statement::traverse(Block* block, size_t* pindex, Traverse* traverse) -{ - if (this->classification_ == STATEMENT_ERROR) - return TRAVERSE_CONTINUE; - - unsigned int traverse_mask = traverse->traverse_mask(); - - if ((traverse_mask & Traverse::traverse_statements) != 0) - { - int t = traverse->statement(block, pindex, this); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - return TRAVERSE_CONTINUE; - } - - // No point in checking traverse_mask here--a statement may contain - // other blocks or statements, and if we got here we always want to - // walk them. - return this->do_traverse(traverse); -} - -// Traverse the contents of a statement. - -int -Statement::traverse_contents(Traverse* traverse) -{ - return this->do_traverse(traverse); -} - -// Traverse assignments. - -bool -Statement::traverse_assignments(Traverse_assignments* tassign) -{ - if (this->classification_ == STATEMENT_ERROR) - return false; - return this->do_traverse_assignments(tassign); -} - -// Traverse an expression in a statement. This is a helper function -// for child classes. - -int -Statement::traverse_expression(Traverse* traverse, Expression** expr) -{ - if ((traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) == 0) - return TRAVERSE_CONTINUE; - return Expression::traverse(expr, traverse); -} - -// Traverse an expression list in a statement. This is a helper -// function for child classes. - -int -Statement::traverse_expression_list(Traverse* traverse, - Expression_list* expr_list) -{ - if (expr_list == NULL) - return TRAVERSE_CONTINUE; - if ((traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) == 0) - return TRAVERSE_CONTINUE; - return expr_list->traverse(traverse); -} - -// Traverse a type in a statement. This is a helper function for -// child classes. - -int -Statement::traverse_type(Traverse* traverse, Type* type) -{ - if ((traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) == 0) - return TRAVERSE_CONTINUE; - return Type::traverse(type, traverse); -} - -// Set type information for unnamed constants. This is really done by -// the child class. - -void -Statement::determine_types() -{ - this->do_determine_types(); -} - -// If this is a thunk statement, return it. - -Thunk_statement* -Statement::thunk_statement() -{ - Thunk_statement* ret = this->convert(); - if (ret == NULL) - ret = this->convert(); - return ret; -} - -// Get a tree for a Statement. This is really done by the child -// class. - -tree -Statement::get_tree(Translate_context* context) -{ - if (this->classification_ == STATEMENT_ERROR) - return error_mark_node; - - return this->do_get_tree(context); -} - -// Build tree nodes and set locations. - -tree -Statement::build_stmt_1(int tree_code_value, tree node) -{ - tree ret = build1(static_cast(tree_code_value), - void_type_node, node); - SET_EXPR_LOCATION(ret, this->location_); - return ret; -} - -// Note that this statement is erroneous. This is called by children -// when they discover an error. - -void -Statement::set_is_error() -{ - this->classification_ = STATEMENT_ERROR; -} - -// For children to call to report an error conveniently. - -void -Statement::report_error(const char* msg) -{ - error_at(this->location_, "%s", msg); - this->set_is_error(); -} - -// An error statement, used to avoid crashing after we report an -// error. - -class Error_statement : public Statement -{ - public: - Error_statement(source_location location) - : Statement(STATEMENT_ERROR, location) - { } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } -}; - -// Make an error statement. - -Statement* -Statement::make_error_statement(source_location location) -{ - return new Error_statement(location); -} - -// Class Variable_declaration_statement. - -Variable_declaration_statement::Variable_declaration_statement( - Named_object* var) - : Statement(STATEMENT_VARIABLE_DECLARATION, var->var_value()->location()), - var_(var) -{ -} - -// We don't actually traverse the variable here; it was traversed -// while traversing the Block. - -int -Variable_declaration_statement::do_traverse(Traverse*) -{ - return TRAVERSE_CONTINUE; -} - -// Traverse the assignments in a variable declaration. Note that this -// traversal is different from the usual traversal. - -bool -Variable_declaration_statement::do_traverse_assignments( - Traverse_assignments* tassign) -{ - tassign->initialize_variable(this->var_); - return true; -} - -// Return the tree for a variable declaration. - -tree -Variable_declaration_statement::do_get_tree(Translate_context* context) -{ - tree val = this->var_->get_tree(context->gogo(), context->function()); - if (val == error_mark_node || TREE_TYPE(val) == error_mark_node) - return error_mark_node; - Variable* variable = this->var_->var_value(); - - tree init = variable->get_init_tree(context->gogo(), context->function()); - if (init == error_mark_node) - return error_mark_node; - - // If this variable lives on the heap, we need to allocate it now. - if (!variable->is_in_heap()) - { - DECL_INITIAL(val) = init; - return this->build_stmt_1(DECL_EXPR, val); - } - else - { - gcc_assert(TREE_CODE(val) == INDIRECT_REF); - tree decl = TREE_OPERAND(val, 0); - gcc_assert(TREE_CODE(decl) == VAR_DECL); - tree type = TREE_TYPE(decl); - gcc_assert(POINTER_TYPE_P(type)); - tree size = TYPE_SIZE_UNIT(TREE_TYPE(type)); - tree space = context->gogo()->allocate_memory(variable->type(), size, - this->location()); - space = fold_convert(TREE_TYPE(decl), space); - DECL_INITIAL(decl) = space; - return build2(COMPOUND_EXPR, void_type_node, - this->build_stmt_1(DECL_EXPR, decl), - build2(MODIFY_EXPR, void_type_node, val, init)); - } -} - -// Make a variable declaration. - -Statement* -Statement::make_variable_declaration(Named_object* var) -{ - return new Variable_declaration_statement(var); -} - -// Class Temporary_statement. - -// Return the type of the temporary variable. - -Type* -Temporary_statement::type() const -{ - return this->type_ != NULL ? this->type_ : this->init_->type(); -} - -// Return the tree for the temporary variable. - -tree -Temporary_statement::get_decl() const -{ - if (this->decl_ == NULL) - { - gcc_assert(saw_errors()); - return error_mark_node; - } - return this->decl_; -} - -// Traversal. - -int -Temporary_statement::do_traverse(Traverse* traverse) -{ - if (this->type_ != NULL - && this->traverse_type(traverse, this->type_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->init_ == NULL) - return TRAVERSE_CONTINUE; - else - return this->traverse_expression(traverse, &this->init_); -} - -// Traverse assignments. - -bool -Temporary_statement::do_traverse_assignments(Traverse_assignments* tassign) -{ - if (this->init_ == NULL) - return false; - tassign->value(&this->init_, true, true); - return true; -} - -// Determine types. - -void -Temporary_statement::do_determine_types() -{ - if (this->type_ != NULL && this->type_->is_abstract()) - this->type_ = this->type_->make_non_abstract_type(); - - if (this->init_ != NULL) - { - if (this->type_ == NULL) - this->init_->determine_type_no_context(); - else - { - Type_context context(this->type_, false); - this->init_->determine_type(&context); - } - } - - if (this->type_ == NULL) - { - this->type_ = this->init_->type(); - gcc_assert(!this->type_->is_abstract()); - } -} - -// Check types. - -void -Temporary_statement::do_check_types(Gogo*) -{ - if (this->type_ != NULL && this->init_ != NULL) - { - std::string reason; - if (!Type::are_assignable(this->type_, this->init_->type(), &reason)) - { - if (reason.empty()) - error_at(this->location(), "incompatible types in assignment"); - else - error_at(this->location(), "incompatible types in assignment (%s)", - reason.c_str()); - this->set_is_error(); - } - } -} - -// Return a tree. - -tree -Temporary_statement::do_get_tree(Translate_context* context) -{ - gcc_assert(this->decl_ == NULL_TREE); - tree type_tree = this->type()->get_tree(context->gogo()); - tree init_tree = (this->init_ == NULL - ? NULL_TREE - : this->init_->get_tree(context)); - if (type_tree == error_mark_node || init_tree == error_mark_node) - { - this->decl_ = error_mark_node; - return error_mark_node; - } - // We can only use create_tmp_var if the type is not addressable. - if (!TREE_ADDRESSABLE(type_tree)) - { - this->decl_ = create_tmp_var(type_tree, "GOTMP"); - DECL_SOURCE_LOCATION(this->decl_) = this->location(); - } - else - { - gcc_assert(context->function() != NULL && context->block() != NULL); - tree decl = build_decl(this->location(), VAR_DECL, - create_tmp_var_name("GOTMP"), - type_tree); - DECL_ARTIFICIAL(decl) = 1; - DECL_IGNORED_P(decl) = 1; - TREE_USED(decl) = 1; - gcc_assert(current_function_decl != NULL_TREE); - DECL_CONTEXT(decl) = current_function_decl; - - // We have to add this variable to the block so that it winds up - // in a BIND_EXPR. - tree block_tree = context->block_tree(); - gcc_assert(block_tree != NULL_TREE); - DECL_CHAIN(decl) = BLOCK_VARS(block_tree); - BLOCK_VARS(block_tree) = decl; - - this->decl_ = decl; - } - if (init_tree != NULL_TREE) - DECL_INITIAL(this->decl_) = - Expression::convert_for_assignment(context, this->type(), - this->init_->type(), init_tree, - this->location()); - if (this->is_address_taken_) - TREE_ADDRESSABLE(this->decl_) = 1; - return this->build_stmt_1(DECL_EXPR, this->decl_); -} - -// Make and initialize a temporary variable in BLOCK. - -Temporary_statement* -Statement::make_temporary(Type* type, Expression* init, - source_location location) -{ - return new Temporary_statement(type, init, location); -} - -// An assignment statement. - -class Assignment_statement : public Statement -{ - public: - Assignment_statement(Expression* lhs, Expression* rhs, - source_location location) - : Statement(STATEMENT_ASSIGNMENT, location), - lhs_(lhs), rhs_(rhs) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - tree - do_get_tree(Translate_context*); - - private: - // Left hand side--the lvalue. - Expression* lhs_; - // Right hand side--the rvalue. - Expression* rhs_; -}; - -// Traversal. - -int -Assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->lhs_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->rhs_); -} - -bool -Assignment_statement::do_traverse_assignments(Traverse_assignments* tassign) -{ - tassign->assignment(&this->lhs_, &this->rhs_); - return true; -} - -// Set types for the assignment. - -void -Assignment_statement::do_determine_types() -{ - this->lhs_->determine_type_no_context(); - Type_context context(this->lhs_->type(), false); - this->rhs_->determine_type(&context); -} - -// Check types for an assignment. - -void -Assignment_statement::do_check_types(Gogo*) -{ - // The left hand side must be either addressable, a map index - // expression, or the blank identifier. - if (!this->lhs_->is_addressable() - && this->lhs_->map_index_expression() == NULL - && !this->lhs_->is_sink_expression()) - { - if (!this->lhs_->type()->is_error_type()) - this->report_error(_("invalid left hand side of assignment")); - return; - } - - Type* lhs_type = this->lhs_->type(); - Type* rhs_type = this->rhs_->type(); - std::string reason; - if (!Type::are_assignable(lhs_type, rhs_type, &reason)) - { - if (reason.empty()) - error_at(this->location(), "incompatible types in assignment"); - else - error_at(this->location(), "incompatible types in assignment (%s)", - reason.c_str()); - this->set_is_error(); - } - - if (lhs_type->is_error_type() - || rhs_type->is_error_type() - || lhs_type->is_undefined() - || rhs_type->is_undefined()) - { - // Make sure we get the error for an undefined type. - lhs_type->base(); - rhs_type->base(); - this->set_is_error(); - } -} - -// Build a tree for an assignment statement. - -tree -Assignment_statement::do_get_tree(Translate_context* context) -{ - tree rhs_tree = this->rhs_->get_tree(context); - - if (this->lhs_->is_sink_expression()) - return rhs_tree; - - tree lhs_tree = this->lhs_->get_tree(context); - - if (lhs_tree == error_mark_node || rhs_tree == error_mark_node) - return error_mark_node; - - rhs_tree = Expression::convert_for_assignment(context, this->lhs_->type(), - this->rhs_->type(), rhs_tree, - this->location()); - if (rhs_tree == error_mark_node) - return error_mark_node; - - return fold_build2_loc(this->location(), MODIFY_EXPR, void_type_node, - lhs_tree, rhs_tree); -} - -// Make an assignment statement. - -Statement* -Statement::make_assignment(Expression* lhs, Expression* rhs, - source_location location) -{ - return new Assignment_statement(lhs, rhs, location); -} - -// The Move_ordered_evals class is used to find any subexpressions of -// an expression that have an evaluation order dependency. It creates -// temporary variables to hold them. - -class Move_ordered_evals : public Traverse -{ - public: - Move_ordered_evals(Block* block) - : Traverse(traverse_expressions), - block_(block) - { } - - protected: - int - expression(Expression**); - - private: - // The block where new temporary variables should be added. - Block* block_; -}; - -int -Move_ordered_evals::expression(Expression** pexpr) -{ - // We have to look at subexpressions first. - if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if ((*pexpr)->must_eval_in_order()) - { - source_location loc = (*pexpr)->location(); - Temporary_statement* temp = Statement::make_temporary(NULL, *pexpr, loc); - this->block_->add_statement(temp); - *pexpr = Expression::make_temporary_reference(temp, loc); - } - return TRAVERSE_SKIP_COMPONENTS; -} - -// An assignment operation statement. - -class Assignment_operation_statement : public Statement -{ - public: - Assignment_operation_statement(Operator op, Expression* lhs, Expression* rhs, - source_location location) - : Statement(STATEMENT_ASSIGNMENT_OPERATION, location), - op_(op), lhs_(lhs), rhs_(rhs) - { } - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // The operator (OPERATOR_PLUSEQ, etc.). - Operator op_; - // Left hand side. - Expression* lhs_; - // Right hand side. - Expression* rhs_; -}; - -// Traversal. - -int -Assignment_operation_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->lhs_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->rhs_); -} - -// Lower an assignment operation statement to a regular assignment -// statement. - -Statement* -Assignment_operation_statement::do_lower(Gogo*, Named_object*, - Block* enclosing) -{ - source_location loc = this->location(); - - // We have to evaluate the left hand side expression only once. We - // do this by moving out any expression with side effects. - Block* b = new Block(enclosing, loc); - Move_ordered_evals moe(b); - this->lhs_->traverse_subexpressions(&moe); - - Expression* lval = this->lhs_->copy(); - - Operator op; - switch (this->op_) - { - case OPERATOR_PLUSEQ: - op = OPERATOR_PLUS; - break; - case OPERATOR_MINUSEQ: - op = OPERATOR_MINUS; - break; - case OPERATOR_OREQ: - op = OPERATOR_OR; - break; - case OPERATOR_XOREQ: - op = OPERATOR_XOR; - break; - case OPERATOR_MULTEQ: - op = OPERATOR_MULT; - break; - case OPERATOR_DIVEQ: - op = OPERATOR_DIV; - break; - case OPERATOR_MODEQ: - op = OPERATOR_MOD; - break; - case OPERATOR_LSHIFTEQ: - op = OPERATOR_LSHIFT; - break; - case OPERATOR_RSHIFTEQ: - op = OPERATOR_RSHIFT; - break; - case OPERATOR_ANDEQ: - op = OPERATOR_AND; - break; - case OPERATOR_BITCLEAREQ: - op = OPERATOR_BITCLEAR; - break; - default: - gcc_unreachable(); - } - - Expression* binop = Expression::make_binary(op, lval, this->rhs_, loc); - Statement* s = Statement::make_assignment(this->lhs_, binop, loc); - if (b->statements()->empty()) - { - delete b; - return s; - } - else - { - b->add_statement(s); - return Statement::make_block_statement(b, loc); - } -} - -// Make an assignment operation statement. - -Statement* -Statement::make_assignment_operation(Operator op, Expression* lhs, - Expression* rhs, source_location location) -{ - return new Assignment_operation_statement(op, lhs, rhs, location); -} - -// A tuple assignment statement. This differs from an assignment -// statement in that the right-hand-side expressions are evaluated in -// parallel. - -class Tuple_assignment_statement : public Statement -{ - public: - Tuple_assignment_statement(Expression_list* lhs, Expression_list* rhs, - source_location location) - : Statement(STATEMENT_TUPLE_ASSIGNMENT, location), - lhs_(lhs), rhs_(rhs) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // Left hand side--a list of lvalues. - Expression_list* lhs_; - // Right hand side--a list of rvalues. - Expression_list* rhs_; -}; - -// Traversal. - -int -Tuple_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression_list(traverse, this->lhs_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression_list(traverse, this->rhs_); -} - -// Lower a tuple assignment. We use temporary variables to split it -// up into a set of single assignments. - -Statement* -Tuple_assignment_statement::do_lower(Gogo*, Named_object*, Block* enclosing) -{ - source_location loc = this->location(); - - Block* b = new Block(enclosing, loc); - - // First move out any subexpressions on the left hand side. The - // right hand side will be evaluated in the required order anyhow. - Move_ordered_evals moe(b); - for (Expression_list::const_iterator plhs = this->lhs_->begin(); - plhs != this->lhs_->end(); - ++plhs) - (*plhs)->traverse_subexpressions(&moe); - - std::vector temps; - temps.reserve(this->lhs_->size()); - - Expression_list::const_iterator prhs = this->rhs_->begin(); - for (Expression_list::const_iterator plhs = this->lhs_->begin(); - plhs != this->lhs_->end(); - ++plhs, ++prhs) - { - gcc_assert(prhs != this->rhs_->end()); - - if ((*plhs)->is_error_expression() - || (*plhs)->type()->is_error_type() - || (*prhs)->is_error_expression() - || (*prhs)->type()->is_error_type()) - continue; - - if ((*plhs)->is_sink_expression()) - { - b->add_statement(Statement::make_statement(*prhs)); - continue; - } - - Temporary_statement* temp = Statement::make_temporary((*plhs)->type(), - *prhs, loc); - b->add_statement(temp); - temps.push_back(temp); - - } - gcc_assert(prhs == this->rhs_->end()); - - prhs = this->rhs_->begin(); - std::vector::const_iterator ptemp = temps.begin(); - for (Expression_list::const_iterator plhs = this->lhs_->begin(); - plhs != this->lhs_->end(); - ++plhs, ++prhs) - { - if ((*plhs)->is_error_expression() - || (*plhs)->type()->is_error_type() - || (*prhs)->is_error_expression() - || (*prhs)->type()->is_error_type()) - continue; - - if ((*plhs)->is_sink_expression()) - continue; - - Expression* ref = Expression::make_temporary_reference(*ptemp, loc); - Statement* s = Statement::make_assignment(*plhs, ref, loc); - b->add_statement(s); - ++ptemp; - } - gcc_assert(ptemp == temps.end()); - - return Statement::make_block_statement(b, loc); -} - -// Make a tuple assignment statement. - -Statement* -Statement::make_tuple_assignment(Expression_list* lhs, Expression_list* rhs, - source_location location) -{ - return new Tuple_assignment_statement(lhs, rhs, location); -} - -// A tuple assignment from a map index expression. -// v, ok = m[k] - -class Tuple_map_assignment_statement : public Statement -{ -public: - Tuple_map_assignment_statement(Expression* val, Expression* present, - Expression* map_index, - source_location location) - : Statement(STATEMENT_TUPLE_MAP_ASSIGNMENT, location), - val_(val), present_(present), map_index_(map_index) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // Lvalue which receives the value from the map. - Expression* val_; - // Lvalue which receives whether the key value was present. - Expression* present_; - // The map index expression. - Expression* map_index_; -}; - -// Traversal. - -int -Tuple_map_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT - || this->traverse_expression(traverse, &this->present_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->map_index_); -} - -// Lower a tuple map assignment. - -Statement* -Tuple_map_assignment_statement::do_lower(Gogo*, Named_object*, - Block* enclosing) -{ - source_location loc = this->location(); - - Map_index_expression* map_index = this->map_index_->map_index_expression(); - if (map_index == NULL) - { - this->report_error(_("expected map index on right hand side")); - return Statement::make_error_statement(loc); - } - Map_type* map_type = map_index->get_map_type(); - if (map_type == NULL) - return Statement::make_error_statement(loc); - - Block* b = new Block(enclosing, loc); - - // Move out any subexpressions to make sure that functions are - // called in the required order. - Move_ordered_evals moe(b); - this->val_->traverse_subexpressions(&moe); - this->present_->traverse_subexpressions(&moe); - - // Copy the key value into a temporary so that we can take its - // address without pushing the value onto the heap. - - // var key_temp KEY_TYPE = MAP_INDEX - Temporary_statement* key_temp = - Statement::make_temporary(map_type->key_type(), map_index->index(), loc); - b->add_statement(key_temp); - - // var val_temp VAL_TYPE - Temporary_statement* val_temp = - Statement::make_temporary(map_type->val_type(), NULL, loc); - b->add_statement(val_temp); - - // var present_temp bool - Temporary_statement* present_temp = - Statement::make_temporary(Type::lookup_bool_type(), NULL, loc); - b->add_statement(present_temp); - - // func mapaccess2(hmap map[k]v, key *k, val *v) bool - source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("hmap", map_type, bloc)); - Type* pkey_type = Type::make_pointer_type(map_type->key_type()); - param_types->push_back(Typed_identifier("key", pkey_type, bloc)); - Type* pval_type = Type::make_pointer_type(map_type->val_type()); - param_types->push_back(Typed_identifier("val", pval_type, bloc)); - - Typed_identifier_list* ret_types = new Typed_identifier_list(); - ret_types->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc)); - - Function_type* fntype = Type::make_function_type(NULL, param_types, - ret_types, bloc); - Named_object* mapaccess2 = - Named_object::make_function_declaration("mapaccess2", NULL, fntype, bloc); - mapaccess2->func_declaration_value()->set_asm_name("runtime.mapaccess2"); - - // present_temp = mapaccess2(MAP, &key_temp, &val_temp) - Expression* func = Expression::make_func_reference(mapaccess2, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(map_index->map()); - Expression* ref = Expression::make_temporary_reference(key_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - ref = Expression::make_temporary_reference(val_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - Expression* call = Expression::make_call(func, params, false, loc); - - ref = Expression::make_temporary_reference(present_temp, loc); - Statement* s = Statement::make_assignment(ref, call, loc); - b->add_statement(s); - - // val = val_temp - ref = Expression::make_temporary_reference(val_temp, loc); - s = Statement::make_assignment(this->val_, ref, loc); - b->add_statement(s); - - // present = present_temp - ref = Expression::make_temporary_reference(present_temp, loc); - s = Statement::make_assignment(this->present_, ref, loc); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Make a map assignment statement which returns a pair of values. - -Statement* -Statement::make_tuple_map_assignment(Expression* val, Expression* present, - Expression* map_index, - source_location location) -{ - return new Tuple_map_assignment_statement(val, present, map_index, location); -} - -// Assign a pair of entries to a map. -// m[k] = v, p - -class Map_assignment_statement : public Statement -{ - public: - Map_assignment_statement(Expression* map_index, - Expression* val, Expression* should_set, - source_location location) - : Statement(STATEMENT_MAP_ASSIGNMENT, location), - map_index_(map_index), val_(val), should_set_(should_set) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // A reference to the map index which should be set or deleted. - Expression* map_index_; - // The value to add to the map. - Expression* val_; - // Whether or not to add the value. - Expression* should_set_; -}; - -// Traverse a map assignment. - -int -Map_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->map_index_) == TRAVERSE_EXIT - || this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->should_set_); -} - -// Lower a map assignment to a function call. - -Statement* -Map_assignment_statement::do_lower(Gogo*, Named_object*, Block* enclosing) -{ - source_location loc = this->location(); - - Map_index_expression* map_index = this->map_index_->map_index_expression(); - if (map_index == NULL) - { - this->report_error(_("expected map index on left hand side")); - return Statement::make_error_statement(loc); - } - Map_type* map_type = map_index->get_map_type(); - if (map_type == NULL) - return Statement::make_error_statement(loc); - - Block* b = new Block(enclosing, loc); - - // Evaluate the map first to get order of evaluation right. - // map_temp := m // we are evaluating m[k] = v, p - Temporary_statement* map_temp = Statement::make_temporary(map_type, - map_index->map(), - loc); - b->add_statement(map_temp); - - // var key_temp MAP_KEY_TYPE = k - Temporary_statement* key_temp = - Statement::make_temporary(map_type->key_type(), map_index->index(), loc); - b->add_statement(key_temp); - - // var val_temp MAP_VAL_TYPE = v - Temporary_statement* val_temp = - Statement::make_temporary(map_type->val_type(), this->val_, loc); - b->add_statement(val_temp); - - // func mapassign2(hmap map[k]v, key *k, val *v, p) - source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("hmap", map_type, bloc)); - Type* pkey_type = Type::make_pointer_type(map_type->key_type()); - param_types->push_back(Typed_identifier("key", pkey_type, bloc)); - Type* pval_type = Type::make_pointer_type(map_type->val_type()); - param_types->push_back(Typed_identifier("val", pval_type, bloc)); - param_types->push_back(Typed_identifier("p", Type::lookup_bool_type(), bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, - NULL, bloc); - Named_object* mapassign2 = - Named_object::make_function_declaration("mapassign2", NULL, fntype, bloc); - mapassign2->func_declaration_value()->set_asm_name("runtime.mapassign2"); - - // mapassign2(map_temp, &key_temp, &val_temp, p) - Expression* func = Expression::make_func_reference(mapassign2, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(Expression::make_temporary_reference(map_temp, loc)); - Expression* ref = Expression::make_temporary_reference(key_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - ref = Expression::make_temporary_reference(val_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - params->push_back(this->should_set_); - Expression* call = Expression::make_call(func, params, false, loc); - Statement* s = Statement::make_statement(call); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Make a statement which assigns a pair of entries to a map. - -Statement* -Statement::make_map_assignment(Expression* map_index, - Expression* val, Expression* should_set, - source_location location) -{ - return new Map_assignment_statement(map_index, val, should_set, location); -} - -// A tuple assignment from a receive statement. - -class Tuple_receive_assignment_statement : public Statement -{ - public: - Tuple_receive_assignment_statement(Expression* val, Expression* closed, - Expression* channel, bool for_select, - source_location location) - : Statement(STATEMENT_TUPLE_RECEIVE_ASSIGNMENT, location), - val_(val), closed_(closed), channel_(channel), for_select_(for_select) - { } - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // Lvalue which receives the value from the channel. - Expression* val_; - // Lvalue which receives whether the channel is closed. - Expression* closed_; - // The channel on which we receive the value. - Expression* channel_; - // Whether this is for a select statement. - bool for_select_; -}; - -// Traversal. - -int -Tuple_receive_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT - || this->traverse_expression(traverse, &this->closed_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->channel_); -} - -// Lower to a function call. - -Statement* -Tuple_receive_assignment_statement::do_lower(Gogo*, Named_object*, - Block* enclosing) -{ - source_location loc = this->location(); - - Channel_type* channel_type = this->channel_->type()->channel_type(); - if (channel_type == NULL) - { - this->report_error(_("expected channel")); - return Statement::make_error_statement(loc); - } - if (!channel_type->may_receive()) - { - this->report_error(_("invalid receive on send-only channel")); - return Statement::make_error_statement(loc); - } - - Block* b = new Block(enclosing, loc); - - // Make sure that any subexpressions on the left hand side are - // evaluated in the right order. - Move_ordered_evals moe(b); - this->val_->traverse_subexpressions(&moe); - this->closed_->traverse_subexpressions(&moe); - - // var val_temp ELEMENT_TYPE - Temporary_statement* val_temp = - Statement::make_temporary(channel_type->element_type(), NULL, loc); - b->add_statement(val_temp); - - // var closed_temp bool - Temporary_statement* closed_temp = - Statement::make_temporary(Type::lookup_bool_type(), NULL, loc); - b->add_statement(closed_temp); - - // func chanrecv2(c chan T, val *T) bool - // func chanrecv3(c chan T, val *T) bool (if for_select) - source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("c", channel_type, bloc)); - Type* pelement_type = Type::make_pointer_type(channel_type->element_type()); - param_types->push_back(Typed_identifier("val", pelement_type, bloc)); - - Typed_identifier_list* ret_types = new Typed_identifier_list(); - ret_types->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc)); - - Function_type* fntype = Type::make_function_type(NULL, param_types, - ret_types, bloc); - Named_object* chanrecv; - if (!this->for_select_) - { - chanrecv = Named_object::make_function_declaration("chanrecv2", NULL, - fntype, bloc); - chanrecv->func_declaration_value()->set_asm_name("runtime.chanrecv2"); - } - else - { - chanrecv = Named_object::make_function_declaration("chanrecv3", NULL, - fntype, bloc); - chanrecv->func_declaration_value()->set_asm_name("runtime.chanrecv3"); - } - - // closed_temp = chanrecv[23](channel, &val_temp) - Expression* func = Expression::make_func_reference(chanrecv, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(this->channel_); - Expression* ref = Expression::make_temporary_reference(val_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - Expression* call = Expression::make_call(func, params, false, loc); - ref = Expression::make_temporary_reference(closed_temp, loc); - Statement* s = Statement::make_assignment(ref, call, loc); - b->add_statement(s); - - // val = val_temp - ref = Expression::make_temporary_reference(val_temp, loc); - s = Statement::make_assignment(this->val_, ref, loc); - b->add_statement(s); - - // closed = closed_temp - ref = Expression::make_temporary_reference(closed_temp, loc); - s = Statement::make_assignment(this->closed_, ref, loc); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Make a nonblocking receive statement. - -Statement* -Statement::make_tuple_receive_assignment(Expression* val, Expression* closed, - Expression* channel, - bool for_select, - source_location location) -{ - return new Tuple_receive_assignment_statement(val, closed, channel, - for_select, location); -} - -// An assignment to a pair of values from a type guard. This is a -// conditional type guard. v, ok = i.(type). - -class Tuple_type_guard_assignment_statement : public Statement -{ - public: - Tuple_type_guard_assignment_statement(Expression* val, Expression* ok, - Expression* expr, Type* type, - source_location location) - : Statement(STATEMENT_TUPLE_TYPE_GUARD_ASSIGNMENT, location), - val_(val), ok_(ok), expr_(expr), type_(type) - { } - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - Call_expression* - lower_to_empty_interface(const char*); - - Call_expression* - lower_to_type(const char*); - - void - lower_to_object_type(Block*, const char*); - - // The variable which recieves the converted value. - Expression* val_; - // The variable which receives the indication of success. - Expression* ok_; - // The expression being converted. - Expression* expr_; - // The type to which the expression is being converted. - Type* type_; -}; - -// Traverse a type guard tuple assignment. - -int -Tuple_type_guard_assignment_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT - || this->traverse_expression(traverse, &this->ok_) == TRAVERSE_EXIT - || this->traverse_type(traverse, this->type_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->expr_); -} - -// Lower to a function call. - -Statement* -Tuple_type_guard_assignment_statement::do_lower(Gogo*, Named_object*, - Block* enclosing) -{ - source_location loc = this->location(); - - Type* expr_type = this->expr_->type(); - if (expr_type->interface_type() == NULL) - { - if (!expr_type->is_error_type() && !this->type_->is_error_type()) - this->report_error(_("type assertion only valid for interface types")); - return Statement::make_error_statement(loc); - } - - Block* b = new Block(enclosing, loc); - - // Make sure that any subexpressions on the left hand side are - // evaluated in the right order. - Move_ordered_evals moe(b); - this->val_->traverse_subexpressions(&moe); - this->ok_->traverse_subexpressions(&moe); - - bool expr_is_empty = expr_type->interface_type()->is_empty(); - Call_expression* call; - if (this->type_->interface_type() != NULL) - { - if (this->type_->interface_type()->is_empty()) - call = this->lower_to_empty_interface(expr_is_empty - ? "ifaceE2E2" - : "ifaceI2E2"); - else - call = this->lower_to_type(expr_is_empty ? "ifaceE2I2" : "ifaceI2I2"); - } - else if (this->type_->points_to() != NULL) - call = this->lower_to_type(expr_is_empty ? "ifaceE2T2P" : "ifaceI2T2P"); - else - { - this->lower_to_object_type(b, expr_is_empty ? "ifaceE2T2" : "ifaceI2T2"); - call = NULL; - } - - if (call != NULL) - { - Expression* res = Expression::make_call_result(call, 0); - Statement* s = Statement::make_assignment(this->val_, res, loc); - b->add_statement(s); - - res = Expression::make_call_result(call, 1); - s = Statement::make_assignment(this->ok_, res, loc); - b->add_statement(s); - } - - return Statement::make_block_statement(b, loc); -} - -// Lower a conversion to an empty interface type. - -Call_expression* -Tuple_type_guard_assignment_statement::lower_to_empty_interface( - const char *fnname) -{ - source_location loc = this->location(); - - // func FNNAME(interface) (empty, bool) - source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("i", this->expr_->type(), bloc)); - Typed_identifier_list* ret_types = new Typed_identifier_list(); - ret_types->push_back(Typed_identifier("ret", this->type_, bloc)); - ret_types->push_back(Typed_identifier("ok", Type::lookup_bool_type(), bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, - ret_types, bloc); - Named_object* fn = - Named_object::make_function_declaration(fnname, NULL, fntype, bloc); - std::string asm_name = "runtime."; - asm_name += fnname; - fn->func_declaration_value()->set_asm_name(asm_name); - - // val, ok = FNNAME(expr) - Expression* func = Expression::make_func_reference(fn, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(this->expr_); - return Expression::make_call(func, params, false, loc); -} - -// Lower a conversion to a non-empty interface type or a pointer type. - -Call_expression* -Tuple_type_guard_assignment_statement::lower_to_type(const char* fnname) -{ - source_location loc = this->location(); - - // func FNNAME(*descriptor, interface) (interface, bool) - source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("inter", - Type::make_type_descriptor_ptr_type(), - bloc)); - param_types->push_back(Typed_identifier("i", this->expr_->type(), bloc)); - Typed_identifier_list* ret_types = new Typed_identifier_list(); - ret_types->push_back(Typed_identifier("ret", this->type_, bloc)); - ret_types->push_back(Typed_identifier("ok", Type::lookup_bool_type(), bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, - ret_types, bloc); - Named_object* fn = - Named_object::make_function_declaration(fnname, NULL, fntype, bloc); - std::string asm_name = "runtime."; - asm_name += fnname; - fn->func_declaration_value()->set_asm_name(asm_name); - - // val, ok = FNNAME(type_descriptor, expr) - Expression* func = Expression::make_func_reference(fn, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(Expression::make_type_descriptor(this->type_, loc)); - params->push_back(this->expr_); - return Expression::make_call(func, params, false, loc); -} - -// Lower a conversion to a non-interface non-pointer type. - -void -Tuple_type_guard_assignment_statement::lower_to_object_type(Block* b, - const char *fnname) -{ - source_location loc = this->location(); - - // var val_temp TYPE - Temporary_statement* val_temp = Statement::make_temporary(this->type_, - NULL, loc); - b->add_statement(val_temp); - - // func FNNAME(*descriptor, interface, *T) bool - source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("inter", - Type::make_type_descriptor_ptr_type(), - bloc)); - param_types->push_back(Typed_identifier("i", this->expr_->type(), bloc)); - Type* ptype = Type::make_pointer_type(this->type_); - param_types->push_back(Typed_identifier("v", ptype, bloc)); - Typed_identifier_list* ret_types = new Typed_identifier_list(); - ret_types->push_back(Typed_identifier("ok", Type::lookup_bool_type(), bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, - ret_types, bloc); - Named_object* fn = - Named_object::make_function_declaration(fnname, NULL, fntype, bloc); - std::string asm_name = "runtime."; - asm_name += fnname; - fn->func_declaration_value()->set_asm_name(asm_name); - - // ok = FNNAME(type_descriptor, expr, &val_temp) - Expression* func = Expression::make_func_reference(fn, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(Expression::make_type_descriptor(this->type_, loc)); - params->push_back(this->expr_); - Expression* ref = Expression::make_temporary_reference(val_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - Expression* call = Expression::make_call(func, params, false, loc); - Statement* s = Statement::make_assignment(this->ok_, call, loc); - b->add_statement(s); - - // val = val_temp - ref = Expression::make_temporary_reference(val_temp, loc); - s = Statement::make_assignment(this->val_, ref, loc); - b->add_statement(s); -} - -// Make an assignment from a type guard to a pair of variables. - -Statement* -Statement::make_tuple_type_guard_assignment(Expression* val, Expression* ok, - Expression* expr, Type* type, - source_location location) -{ - return new Tuple_type_guard_assignment_statement(val, ok, expr, type, - location); -} - -// An expression statement. - -class Expression_statement : public Statement -{ - public: - Expression_statement(Expression* expr) - : Statement(STATEMENT_EXPRESSION, expr->location()), - expr_(expr) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return this->traverse_expression(traverse, &this->expr_); } - - void - do_determine_types() - { this->expr_->determine_type_no_context(); } - - bool - do_may_fall_through() const; - - tree - do_get_tree(Translate_context* context) - { return this->expr_->get_tree(context); } - - private: - Expression* expr_; -}; - -// An expression statement may fall through unless it is a call to a -// function which does not return. - -bool -Expression_statement::do_may_fall_through() const -{ - const Call_expression* call = this->expr_->call_expression(); - if (call != NULL) - { - const Expression* fn = call->fn(); - const Func_expression* fe = fn->func_expression(); - if (fe != NULL) - { - const Named_object* no = fe->named_object(); - - Function_type* fntype; - if (no->is_function()) - fntype = no->func_value()->type(); - else if (no->is_function_declaration()) - fntype = no->func_declaration_value()->type(); - else - fntype = NULL; - - // The builtin function panic does not return. - if (fntype != NULL && fntype->is_builtin() && no->name() == "panic") - return false; - } - } - return true; -} - -// Make an expression statement from an Expression. - -Statement* -Statement::make_statement(Expression* expr) -{ - return new Expression_statement(expr); -} - -// A block statement--a list of statements which may include variable -// definitions. - -class Block_statement : public Statement -{ - public: - Block_statement(Block* block, source_location location) - : Statement(STATEMENT_BLOCK, location), - block_(block) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return this->block_->traverse(traverse); } - - void - do_determine_types() - { this->block_->determine_types(); } - - bool - do_may_fall_through() const - { return this->block_->may_fall_through(); } - - tree - do_get_tree(Translate_context* context) - { return this->block_->get_tree(context); } - - private: - Block* block_; -}; - -// Make a block statement. - -Statement* -Statement::make_block_statement(Block* block, source_location location) -{ - return new Block_statement(block, location); -} - -// An increment or decrement statement. - -class Inc_dec_statement : public Statement -{ - public: - Inc_dec_statement(bool is_inc, Expression* expr) - : Statement(STATEMENT_INCDEC, expr->location()), - expr_(expr), is_inc_(is_inc) - { } - - protected: - int - do_traverse(Traverse* traverse) - { return this->traverse_expression(traverse, &this->expr_); } - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // The l-value to increment or decrement. - Expression* expr_; - // Whether to increment or decrement. - bool is_inc_; -}; - -// Lower to += or -=. - -Statement* -Inc_dec_statement::do_lower(Gogo*, Named_object*, Block*) -{ - source_location loc = this->location(); - - mpz_t oval; - mpz_init_set_ui(oval, 1UL); - Expression* oexpr = Expression::make_integer(&oval, NULL, loc); - mpz_clear(oval); - - Operator op = this->is_inc_ ? OPERATOR_PLUSEQ : OPERATOR_MINUSEQ; - return Statement::make_assignment_operation(op, this->expr_, oexpr, loc); -} - -// Make an increment statement. - -Statement* -Statement::make_inc_statement(Expression* expr) -{ - return new Inc_dec_statement(true, expr); -} - -// Make a decrement statement. - -Statement* -Statement::make_dec_statement(Expression* expr) -{ - return new Inc_dec_statement(false, expr); -} - -// Class Thunk_statement. This is the base class for go and defer -// statements. - -const char* const Thunk_statement::thunk_field_fn = "fn"; - -const char* const Thunk_statement::thunk_field_receiver = "receiver"; - -// Constructor. - -Thunk_statement::Thunk_statement(Statement_classification classification, - Call_expression* call, - source_location location) - : Statement(classification, location), - call_(call), struct_type_(NULL) -{ -} - -// Return whether this is a simple statement which does not require a -// thunk. - -bool -Thunk_statement::is_simple(Function_type* fntype) const -{ - // We need a thunk to call a method, or to pass a variable number of - // arguments. - if (fntype->is_method() || fntype->is_varargs()) - return false; - - // A defer statement requires a thunk to set up for whether the - // function can call recover. - if (this->classification() == STATEMENT_DEFER) - return false; - - // We can only permit a single parameter of pointer type. - const Typed_identifier_list* parameters = fntype->parameters(); - if (parameters != NULL - && (parameters->size() > 1 - || (parameters->size() == 1 - && parameters->begin()->type()->points_to() == NULL))) - return false; - - // If the function returns multiple values, or returns a type other - // than integer, floating point, or pointer, then it may get a - // hidden first parameter, in which case we need the more - // complicated approach. This is true even though we are going to - // ignore the return value. - const Typed_identifier_list* results = fntype->results(); - if (results != NULL - && (results->size() > 1 - || (results->size() == 1 - && !results->begin()->type()->is_basic_type() - && results->begin()->type()->points_to() == NULL))) - return false; - - // If this calls something which is not a simple function, then we - // need a thunk. - Expression* fn = this->call_->call_expression()->fn(); - if (fn->bound_method_expression() != NULL - || fn->interface_field_reference_expression() != NULL) - return false; - - return true; -} - -// Traverse a thunk statement. - -int -Thunk_statement::do_traverse(Traverse* traverse) -{ - return this->traverse_expression(traverse, &this->call_); -} - -// We implement traverse_assignment for a thunk statement because it -// effectively copies the function call. - -bool -Thunk_statement::do_traverse_assignments(Traverse_assignments* tassign) -{ - Expression* fn = this->call_->call_expression()->fn(); - Expression* fn2 = fn; - tassign->value(&fn2, true, false); - return true; -} - -// Determine types in a thunk statement. - -void -Thunk_statement::do_determine_types() -{ - this->call_->determine_type_no_context(); - - // Now that we know the types of the call, build the struct used to - // pass parameters. - Call_expression* ce = this->call_->call_expression(); - if (ce == NULL) - return; - Function_type* fntype = ce->get_function_type(); - if (fntype != NULL && !this->is_simple(fntype)) - this->struct_type_ = this->build_struct(fntype); -} - -// Check types in a thunk statement. - -void -Thunk_statement::do_check_types(Gogo*) -{ - Call_expression* ce = this->call_->call_expression(); - if (ce == NULL) - { - if (!this->call_->is_error_expression()) - this->report_error("expected call expression"); - return; - } - Function_type* fntype = ce->get_function_type(); - if (fntype != NULL && fntype->is_method()) - { - Expression* fn = ce->fn(); - if (fn->bound_method_expression() == NULL - && fn->interface_field_reference_expression() == NULL) - this->report_error(_("no object for method call")); - } -} - -// The Traverse class used to find and simplify thunk statements. - -class Simplify_thunk_traverse : public Traverse -{ - public: - Simplify_thunk_traverse(Gogo* gogo) - : Traverse(traverse_blocks), - gogo_(gogo) - { } - - int - block(Block*); - - private: - Gogo* gogo_; -}; - -int -Simplify_thunk_traverse::block(Block* b) -{ - // The parser ensures that thunk statements always appear at the end - // of a block. - if (b->statements()->size() < 1) - return TRAVERSE_CONTINUE; - Thunk_statement* stat = b->statements()->back()->thunk_statement(); - if (stat == NULL) - return TRAVERSE_CONTINUE; - if (stat->simplify_statement(this->gogo_, b)) - return TRAVERSE_SKIP_COMPONENTS; - return TRAVERSE_CONTINUE; -} - -// Simplify all thunk statements. - -void -Gogo::simplify_thunk_statements() -{ - Simplify_thunk_traverse thunk_traverse(this); - this->traverse(&thunk_traverse); -} - -// Simplify complex thunk statements into simple ones. A complicated -// thunk statement is one which takes anything other than zero -// parameters or a single pointer parameter. We rewrite it into code -// which allocates a struct, stores the parameter values into the -// struct, and does a simple go or defer statement which passes the -// struct to a thunk. The thunk does the real call. - -bool -Thunk_statement::simplify_statement(Gogo* gogo, Block* block) -{ - if (this->classification() == STATEMENT_ERROR) - return false; - if (this->call_->is_error_expression()) - return false; - - Call_expression* ce = this->call_->call_expression(); - Function_type* fntype = ce->get_function_type(); - if (fntype == NULL) - { - gcc_assert(saw_errors()); - this->set_is_error(); - return false; - } - if (this->is_simple(fntype)) - return false; - - Expression* fn = ce->fn(); - Bound_method_expression* bound_method = fn->bound_method_expression(); - Interface_field_reference_expression* interface_method = - fn->interface_field_reference_expression(); - const bool is_method = bound_method != NULL || interface_method != NULL; - - source_location location = this->location(); - - std::string thunk_name = Gogo::thunk_name(); - - // Build the thunk. - this->build_thunk(gogo, thunk_name, fntype); - - // Generate code to call the thunk. - - // Get the values to store into the struct which is the single - // argument to the thunk. - - Expression_list* vals = new Expression_list(); - if (fntype->is_builtin()) - ; - else if (!is_method) - vals->push_back(fn); - else if (interface_method != NULL) - vals->push_back(interface_method->expr()); - else if (bound_method != NULL) - { - vals->push_back(bound_method->method()); - Expression* first_arg = bound_method->first_argument(); - - // We always pass a pointer when calling a method. - if (first_arg->type()->points_to() == NULL) - first_arg = Expression::make_unary(OPERATOR_AND, first_arg, location); - - // If we are calling a method which was inherited from an - // embedded struct, and the method did not get a stub, then the - // first type may be wrong. - Type* fatype = bound_method->first_argument_type(); - if (fatype != NULL) - { - if (fatype->points_to() == NULL) - fatype = Type::make_pointer_type(fatype); - Type* unsafe = Type::make_pointer_type(Type::make_void_type()); - first_arg = Expression::make_cast(unsafe, first_arg, location); - first_arg = Expression::make_cast(fatype, first_arg, location); - } - - vals->push_back(first_arg); - } - else - gcc_unreachable(); - - if (ce->args() != NULL) - { - for (Expression_list::const_iterator p = ce->args()->begin(); - p != ce->args()->end(); - ++p) - vals->push_back(*p); - } - - // Build the struct. - Expression* constructor = - Expression::make_struct_composite_literal(this->struct_type_, vals, - location); - - // Allocate the initialized struct on the heap. - constructor = Expression::make_heap_composite(constructor, location); - - // Look up the thunk. - Named_object* named_thunk = gogo->lookup(thunk_name, NULL); - gcc_assert(named_thunk != NULL && named_thunk->is_function()); - - // Build the call. - Expression* func = Expression::make_func_reference(named_thunk, NULL, - location); - Expression_list* params = new Expression_list(); - params->push_back(constructor); - Call_expression* call = Expression::make_call(func, params, false, location); - - // Build the simple go or defer statement. - Statement* s; - if (this->classification() == STATEMENT_GO) - s = Statement::make_go_statement(call, location); - else if (this->classification() == STATEMENT_DEFER) - s = Statement::make_defer_statement(call, location); - else - gcc_unreachable(); - - // The current block should end with the go statement. - gcc_assert(block->statements()->size() >= 1); - gcc_assert(block->statements()->back() == this); - block->replace_statement(block->statements()->size() - 1, s); - - // We already ran the determine_types pass, so we need to run it now - // for the new statement. - s->determine_types(); - - // Sanity check. - gogo->check_types_in_block(block); - - // Return true to tell the block not to keep looking at statements. - return true; -} - -// Set the name to use for thunk parameter N. - -void -Thunk_statement::thunk_field_param(int n, char* buf, size_t buflen) -{ - snprintf(buf, buflen, "a%d", n); -} - -// Build a new struct type to hold the parameters for a complicated -// thunk statement. FNTYPE is the type of the function call. - -Struct_type* -Thunk_statement::build_struct(Function_type* fntype) -{ - source_location location = this->location(); - - Struct_field_list* fields = new Struct_field_list(); - - Call_expression* ce = this->call_->call_expression(); - Expression* fn = ce->fn(); - - Interface_field_reference_expression* interface_method = - fn->interface_field_reference_expression(); - if (interface_method != NULL) - { - // If this thunk statement calls a method on an interface, we - // pass the interface object to the thunk. - Typed_identifier tid(Thunk_statement::thunk_field_fn, - interface_method->expr()->type(), - location); - fields->push_back(Struct_field(tid)); - } - else if (!fntype->is_builtin()) - { - // The function to call. - Typed_identifier tid(Go_statement::thunk_field_fn, fntype, location); - fields->push_back(Struct_field(tid)); - } - else if (ce->is_recover_call()) - { - // The predeclared recover function has no argument. However, - // we add an argument when building recover thunks. Handle that - // here. - fields->push_back(Struct_field(Typed_identifier("can_recover", - Type::lookup_bool_type(), - location))); - } - - if (fn->bound_method_expression() != NULL) - { - gcc_assert(fntype->is_method()); - Type* rtype = fntype->receiver()->type(); - // We always pass the receiver as a pointer. - if (rtype->points_to() == NULL) - rtype = Type::make_pointer_type(rtype); - Typed_identifier tid(Thunk_statement::thunk_field_receiver, rtype, - location); - fields->push_back(Struct_field(tid)); - } - - const Expression_list* args = ce->args(); - if (args != NULL) - { - int i = 0; - for (Expression_list::const_iterator p = args->begin(); - p != args->end(); - ++p, ++i) - { - char buf[50]; - this->thunk_field_param(i, buf, sizeof buf); - fields->push_back(Struct_field(Typed_identifier(buf, (*p)->type(), - location))); - } - } - - return Type::make_struct_type(fields, location); -} - -// Build the thunk we are going to call. This is a brand new, albeit -// artificial, function. - -void -Thunk_statement::build_thunk(Gogo* gogo, const std::string& thunk_name, - Function_type* fntype) -{ - source_location location = this->location(); - - Call_expression* ce = this->call_->call_expression(); - - bool may_call_recover = false; - if (this->classification() == STATEMENT_DEFER) - { - Func_expression* fn = ce->fn()->func_expression(); - if (fn == NULL) - may_call_recover = true; - else - { - const Named_object* no = fn->named_object(); - if (!no->is_function()) - may_call_recover = true; - else - may_call_recover = no->func_value()->calls_recover(); - } - } - - // Build the type of the thunk. The thunk takes a single parameter, - // which is a pointer to the special structure we build. - const char* const parameter_name = "__go_thunk_parameter"; - Typed_identifier_list* thunk_parameters = new Typed_identifier_list(); - Type* pointer_to_struct_type = Type::make_pointer_type(this->struct_type_); - thunk_parameters->push_back(Typed_identifier(parameter_name, - pointer_to_struct_type, - location)); - - Typed_identifier_list* thunk_results = NULL; - if (may_call_recover) - { - // When deferring a function which may call recover, add a - // return value, to disable tail call optimizations which will - // break the way we check whether recover is permitted. - thunk_results = new Typed_identifier_list(); - thunk_results->push_back(Typed_identifier("", Type::lookup_bool_type(), - location)); - } - - Function_type* thunk_type = Type::make_function_type(NULL, thunk_parameters, - thunk_results, - location); - - // Start building the thunk. - Named_object* function = gogo->start_function(thunk_name, thunk_type, true, - location); - - // For a defer statement, start with a call to - // __go_set_defer_retaddr. */ - Label* retaddr_label = NULL; - if (may_call_recover) - { - retaddr_label = gogo->add_label_reference("retaddr"); - Expression* arg = Expression::make_label_addr(retaddr_label, location); - Expression_list* args = new Expression_list(); - args->push_back(arg); - - static Named_object* set_defer_retaddr; - if (set_defer_retaddr == NULL) - { - const source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - Type *voidptr_type = Type::make_pointer_type(Type::make_void_type()); - param_types->push_back(Typed_identifier("r", voidptr_type, bloc)); - - Typed_identifier_list* result_types = new Typed_identifier_list(); - result_types->push_back(Typed_identifier("", - Type::lookup_bool_type(), - bloc)); - - Function_type* t = Type::make_function_type(NULL, param_types, - result_types, bloc); - set_defer_retaddr = - Named_object::make_function_declaration("__go_set_defer_retaddr", - NULL, t, bloc); - const char* n = "__go_set_defer_retaddr"; - set_defer_retaddr->func_declaration_value()->set_asm_name(n); - } - - Expression* fn = Expression::make_func_reference(set_defer_retaddr, - NULL, location); - Expression* call = Expression::make_call(fn, args, false, location); - - // This is a hack to prevent the middle-end from deleting the - // label. - gogo->start_block(location); - gogo->add_statement(Statement::make_goto_statement(retaddr_label, - location)); - Block* then_block = gogo->finish_block(location); - then_block->determine_types(); - - Statement* s = Statement::make_if_statement(call, then_block, NULL, - location); - s->determine_types(); - gogo->add_statement(s); - } - - // Get a reference to the parameter. - Named_object* named_parameter = gogo->lookup(parameter_name, NULL); - gcc_assert(named_parameter != NULL && named_parameter->is_variable()); - - // Build the call. Note that the field names are the same as the - // ones used in build_struct. - Expression* thunk_parameter = Expression::make_var_reference(named_parameter, - location); - thunk_parameter = Expression::make_unary(OPERATOR_MULT, thunk_parameter, - location); - - Bound_method_expression* bound_method = ce->fn()->bound_method_expression(); - Interface_field_reference_expression* interface_method = - ce->fn()->interface_field_reference_expression(); - - Expression* func_to_call; - unsigned int next_index; - if (!fntype->is_builtin()) - { - func_to_call = Expression::make_field_reference(thunk_parameter, - 0, location); - next_index = 1; - } - else - { - gcc_assert(bound_method == NULL && interface_method == NULL); - func_to_call = ce->fn(); - next_index = 0; - } - - if (bound_method != NULL) - { - Expression* r = Expression::make_field_reference(thunk_parameter, 1, - location); - // The main program passes in a function pointer from the - // interface expression, so here we can make a bound method in - // all cases. - func_to_call = Expression::make_bound_method(r, func_to_call, - location); - next_index = 2; - } - else if (interface_method != NULL) - { - // The main program passes the interface object. - const std::string& name(interface_method->name()); - func_to_call = Expression::make_interface_field_reference(func_to_call, - name, - location); - } - - Expression_list* call_params = new Expression_list(); - const Struct_field_list* fields = this->struct_type_->fields(); - Struct_field_list::const_iterator p = fields->begin(); - for (unsigned int i = 0; i < next_index; ++i) - ++p; - bool is_recover_call = ce->is_recover_call(); - Expression* recover_arg = NULL; - for (; p != fields->end(); ++p, ++next_index) - { - Expression* thunk_param = Expression::make_var_reference(named_parameter, - location); - thunk_param = Expression::make_unary(OPERATOR_MULT, thunk_param, - location); - Expression* param = Expression::make_field_reference(thunk_param, - next_index, - location); - if (!is_recover_call) - call_params->push_back(param); - else - { - gcc_assert(call_params->empty()); - recover_arg = param; - } - } - - if (call_params->empty()) - { - delete call_params; - call_params = NULL; - } - - Expression* call = Expression::make_call(func_to_call, call_params, false, - location); - // We need to lower in case this is a builtin function. - call = call->lower(gogo, function, -1); - Call_expression* call_ce = call->call_expression(); - if (call_ce != NULL && may_call_recover) - call_ce->set_is_deferred(); - - Statement* call_statement = Statement::make_statement(call); - - // We already ran the determine_types pass, so we need to run it - // just for this statement now. - call_statement->determine_types(); - - // Sanity check. - call->check_types(gogo); - - if (call_ce != NULL && recover_arg != NULL) - call_ce->set_recover_arg(recover_arg); - - gogo->add_statement(call_statement); - - // If this is a defer statement, the label comes immediately after - // the call. - if (may_call_recover) - { - gogo->add_label_definition("retaddr", location); - - Expression_list* vals = new Expression_list(); - vals->push_back(Expression::make_boolean(false, location)); - const Typed_identifier_list* results = - function->func_value()->type()->results(); - gogo->add_statement(Statement::make_return_statement(results, vals, - location)); - } - - // That is all the thunk has to do. - gogo->finish_function(location); -} - -// Get the function and argument trees. - -void -Thunk_statement::get_fn_and_arg(Translate_context* context, tree* pfn, - tree* parg) -{ - if (this->call_->is_error_expression()) - { - *pfn = error_mark_node; - *parg = error_mark_node; - return; - } - - Call_expression* ce = this->call_->call_expression(); - - Expression* fn = ce->fn(); - *pfn = fn->get_tree(context); - - const Expression_list* args = ce->args(); - if (args == NULL || args->empty()) - *parg = null_pointer_node; - else - { - gcc_assert(args->size() == 1); - *parg = args->front()->get_tree(context); - } -} - -// Class Go_statement. - -tree -Go_statement::do_get_tree(Translate_context* context) -{ - tree fn_tree; - tree arg_tree; - this->get_fn_and_arg(context, &fn_tree, &arg_tree); - - static tree go_fndecl; - - tree fn_arg_type = NULL_TREE; - if (go_fndecl == NULL_TREE) - { - // Only build FN_ARG_TYPE if we need it. - tree subargtypes = tree_cons(NULL_TREE, ptr_type_node, void_list_node); - tree subfntype = build_function_type(ptr_type_node, subargtypes); - fn_arg_type = build_pointer_type(subfntype); - } - - return Gogo::call_builtin(&go_fndecl, - this->location(), - "__go_go", - 2, - void_type_node, - fn_arg_type, - fn_tree, - ptr_type_node, - arg_tree); -} - -// Make a go statement. - -Statement* -Statement::make_go_statement(Call_expression* call, source_location location) -{ - return new Go_statement(call, location); -} - -// Class Defer_statement. - -tree -Defer_statement::do_get_tree(Translate_context* context) -{ - source_location loc = this->location(); - - tree fn_tree; - tree arg_tree; - this->get_fn_and_arg(context, &fn_tree, &arg_tree); - if (fn_tree == error_mark_node || arg_tree == error_mark_node) - return error_mark_node; - - static tree defer_fndecl; - - tree fn_arg_type = NULL_TREE; - if (defer_fndecl == NULL_TREE) - { - // Only build FN_ARG_TYPE if we need it. - tree subargtypes = tree_cons(NULL_TREE, ptr_type_node, void_list_node); - tree subfntype = build_function_type(ptr_type_node, subargtypes); - fn_arg_type = build_pointer_type(subfntype); - } - - tree defer_stack = context->function()->func_value()->defer_stack(loc); - - return Gogo::call_builtin(&defer_fndecl, - loc, - "__go_defer", - 3, - void_type_node, - ptr_type_node, - defer_stack, - fn_arg_type, - fn_tree, - ptr_type_node, - arg_tree); -} - -// Make a defer statement. - -Statement* -Statement::make_defer_statement(Call_expression* call, - source_location location) -{ - return new Defer_statement(call, location); -} - -// Class Return_statement. - -// Traverse assignments. We treat each return value as a top level -// RHS in an expression. - -bool -Return_statement::do_traverse_assignments(Traverse_assignments* tassign) -{ - Expression_list* vals = this->vals_; - if (vals != NULL) - { - for (Expression_list::iterator p = vals->begin(); - p != vals->end(); - ++p) - tassign->value(&*p, true, true); - } - return true; -} - -// Lower a return statement. If we are returning a function call -// which returns multiple values which match the current function, -// split up the call's results. If the function has named result -// variables, and the return statement lists explicit values, then -// implement it by assigning the values to the result variables and -// changing the statement to not list any values. This lets -// panic/recover work correctly. - -Statement* -Return_statement::do_lower(Gogo*, Named_object*, Block* enclosing) -{ - if (this->vals_ == NULL) - return this; - - const Typed_identifier_list* results = this->results_; - if (results == NULL || results->empty()) - return this; - - // If the current function has multiple return values, and we are - // returning a single call expression, split up the call expression. - size_t results_count = results->size(); - if (results_count > 1 - && this->vals_->size() == 1 - && this->vals_->front()->call_expression() != NULL) - { - Call_expression* call = this->vals_->front()->call_expression(); - size_t count = results->size(); - Expression_list* vals = new Expression_list; - for (size_t i = 0; i < count; ++i) - vals->push_back(Expression::make_call_result(call, i)); - delete this->vals_; - this->vals_ = vals; - } - - if (results->front().name().empty()) - return this; - - if (results_count != this->vals_->size()) - { - // Presumably an error which will be reported in check_types. - return this; - } - - // Assign to named return values and then return them. - - source_location loc = this->location(); - const Block* top = enclosing; - while (top->enclosing() != NULL) - top = top->enclosing(); - - const Bindings *bindings = top->bindings(); - Block* b = new Block(enclosing, loc); - - Expression_list* lhs = new Expression_list(); - Expression_list* rhs = new Expression_list(); - - Expression_list::const_iterator pe = this->vals_->begin(); - int i = 1; - for (Typed_identifier_list::const_iterator pr = results->begin(); - pr != results->end(); - ++pr, ++pe, ++i) - { - Named_object* rv = bindings->lookup_local(pr->name()); - if (rv == NULL || !rv->is_result_variable()) - { - // Presumably an error. - delete b; - delete lhs; - delete rhs; - return this; - } - - Expression* e = *pe; - - // Check types now so that we give a good error message. The - // result type is known. We determine the expression type - // early. - - Type *rvtype = rv->result_var_value()->type(); - Type_context type_context(rvtype, false); - e->determine_type(&type_context); - - std::string reason; - if (Type::are_assignable(rvtype, e->type(), &reason)) - { - Expression* ve = Expression::make_var_reference(rv, e->location()); - lhs->push_back(ve); - rhs->push_back(e); - } - else - { - if (reason.empty()) - error_at(e->location(), "incompatible type for return value %d", i); - else - error_at(e->location(), - "incompatible type for return value %d (%s)", - i, reason.c_str()); - } - } - gcc_assert(lhs->size() == rhs->size()); - - if (lhs->empty()) - ; - else if (lhs->size() == 1) - { - b->add_statement(Statement::make_assignment(lhs->front(), rhs->front(), - loc)); - delete lhs; - delete rhs; - } - else - b->add_statement(Statement::make_tuple_assignment(lhs, rhs, loc)); - - b->add_statement(Statement::make_return_statement(this->results_, NULL, - loc)); - - return Statement::make_block_statement(b, loc); -} - -// Determine types. - -void -Return_statement::do_determine_types() -{ - if (this->vals_ == NULL) - return; - const Typed_identifier_list* results = this->results_; - - Typed_identifier_list::const_iterator pt; - if (results != NULL) - pt = results->begin(); - for (Expression_list::iterator pe = this->vals_->begin(); - pe != this->vals_->end(); - ++pe) - { - if (results == NULL || pt == results->end()) - (*pe)->determine_type_no_context(); - else - { - Type_context context(pt->type(), false); - (*pe)->determine_type(&context); - ++pt; - } - } -} - -// Check types. - -void -Return_statement::do_check_types(Gogo*) -{ - if (this->vals_ == NULL) - return; - - const Typed_identifier_list* results = this->results_; - if (results == NULL) - { - this->report_error(_("return with value in function " - "with no return type")); - return; - } - - int i = 1; - Typed_identifier_list::const_iterator pt = results->begin(); - for (Expression_list::const_iterator pe = this->vals_->begin(); - pe != this->vals_->end(); - ++pe, ++pt, ++i) - { - if (pt == results->end()) - { - this->report_error(_("too many values in return statement")); - return; - } - std::string reason; - if (!Type::are_assignable(pt->type(), (*pe)->type(), &reason)) - { - if (reason.empty()) - error_at(this->location(), - "incompatible type for return value %d", - i); - else - error_at(this->location(), - "incompatible type for return value %d (%s)", - i, reason.c_str()); - this->set_is_error(); - } - else if (pt->type()->is_error_type() - || (*pe)->type()->is_error_type() - || pt->type()->is_undefined() - || (*pe)->type()->is_undefined()) - { - // Make sure we get the error for an undefined type. - pt->type()->base(); - (*pe)->type()->base(); - this->set_is_error(); - } - } - - if (pt != results->end()) - this->report_error(_("not enough values in return statement")); -} - -// Build a RETURN_EXPR tree. - -tree -Return_statement::do_get_tree(Translate_context* context) -{ - Function* function = context->function()->func_value(); - tree fndecl = function->get_decl(); - if (fndecl == error_mark_node || DECL_RESULT(fndecl) == error_mark_node) - return error_mark_node; - - const Typed_identifier_list* results = this->results_; - - if (this->vals_ == NULL) - { - tree stmt_list = NULL_TREE; - tree retval = function->return_value(context->gogo(), - context->function(), - this->location(), - &stmt_list); - tree set; - if (retval == NULL_TREE) - set = NULL_TREE; - else if (retval == error_mark_node) - return error_mark_node; - else - set = fold_build2_loc(this->location(), MODIFY_EXPR, void_type_node, - DECL_RESULT(fndecl), retval); - append_to_statement_list(this->build_stmt_1(RETURN_EXPR, set), - &stmt_list); - return stmt_list; - } - else if (this->vals_->size() == 1) - { - gcc_assert(!VOID_TYPE_P(TREE_TYPE(TREE_TYPE(fndecl)))); - tree val = (*this->vals_->begin())->get_tree(context); - gcc_assert(results != NULL && results->size() == 1); - val = Expression::convert_for_assignment(context, - results->begin()->type(), - (*this->vals_->begin())->type(), - val, this->location()); - if (val == error_mark_node) - return error_mark_node; - tree set = build2(MODIFY_EXPR, void_type_node, - DECL_RESULT(fndecl), val); - SET_EXPR_LOCATION(set, this->location()); - return this->build_stmt_1(RETURN_EXPR, set); - } - else - { - gcc_assert(!VOID_TYPE_P(TREE_TYPE(TREE_TYPE(fndecl)))); - tree stmt_list = NULL_TREE; - tree rettype = TREE_TYPE(DECL_RESULT(fndecl)); - tree retvar = create_tmp_var(rettype, "RESULT"); - gcc_assert(results != NULL && results->size() == this->vals_->size()); - Expression_list::const_iterator pv = this->vals_->begin(); - Typed_identifier_list::const_iterator pr = results->begin(); - for (tree field = TYPE_FIELDS(rettype); - field != NULL_TREE; - ++pv, ++pr, field = DECL_CHAIN(field)) - { - gcc_assert(pv != this->vals_->end()); - tree val = (*pv)->get_tree(context); - val = Expression::convert_for_assignment(context, pr->type(), - (*pv)->type(), val, - this->location()); - if (val == error_mark_node) - return error_mark_node; - tree set = build2(MODIFY_EXPR, void_type_node, - build3(COMPONENT_REF, TREE_TYPE(field), - retvar, field, NULL_TREE), - val); - SET_EXPR_LOCATION(set, this->location()); - append_to_statement_list(set, &stmt_list); - } - tree set = build2(MODIFY_EXPR, void_type_node, DECL_RESULT(fndecl), - retvar); - append_to_statement_list(this->build_stmt_1(RETURN_EXPR, set), - &stmt_list); - return stmt_list; - } -} - -// Make a return statement. - -Statement* -Statement::make_return_statement(const Typed_identifier_list* results, - Expression_list* vals, - source_location location) -{ - return new Return_statement(results, vals, location); -} - -// A break or continue statement. - -class Bc_statement : public Statement -{ - public: - Bc_statement(bool is_break, Unnamed_label* label, source_location location) - : Statement(STATEMENT_BREAK_OR_CONTINUE, location), - label_(label), is_break_(is_break) - { } - - bool - is_break() const - { return this->is_break_; } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - bool - do_may_fall_through() const - { return false; } - - tree - do_get_tree(Translate_context*) - { return this->label_->get_goto(this->location()); } - - private: - // The label that this branches to. - Unnamed_label* label_; - // True if this is "break", false if it is "continue". - bool is_break_; -}; - -// Make a break statement. - -Statement* -Statement::make_break_statement(Unnamed_label* label, source_location location) -{ - return new Bc_statement(true, label, location); -} - -// Make a continue statement. - -Statement* -Statement::make_continue_statement(Unnamed_label* label, - source_location location) -{ - return new Bc_statement(false, label, location); -} - -// A goto statement. - -class Goto_statement : public Statement -{ - public: - Goto_statement(Label* label, source_location location) - : Statement(STATEMENT_GOTO, location), - label_(label) - { } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - void - do_check_types(Gogo*); - - bool - do_may_fall_through() const - { return false; } - - tree - do_get_tree(Translate_context*); - - private: - Label* label_; -}; - -// Check types for a label. There aren't any types per se, but we use -// this to give an error if the label was never defined. - -void -Goto_statement::do_check_types(Gogo*) -{ - if (!this->label_->is_defined()) - { - error_at(this->location(), "reference to undefined label %qs", - Gogo::message_name(this->label_->name()).c_str()); - this->set_is_error(); - } -} - -// Return the tree for the goto statement. - -tree -Goto_statement::do_get_tree(Translate_context*) -{ - return this->build_stmt_1(GOTO_EXPR, this->label_->get_decl()); -} - -// Make a goto statement. - -Statement* -Statement::make_goto_statement(Label* label, source_location location) -{ - return new Goto_statement(label, location); -} - -// A goto statement to an unnamed label. - -class Goto_unnamed_statement : public Statement -{ - public: - Goto_unnamed_statement(Unnamed_label* label, source_location location) - : Statement(STATEMENT_GOTO_UNNAMED, location), - label_(label) - { } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - bool - do_may_fall_through() const - { return false; } - - tree - do_get_tree(Translate_context*) - { return this->label_->get_goto(this->location()); } - - private: - Unnamed_label* label_; -}; - -// Make a goto statement to an unnamed label. - -Statement* -Statement::make_goto_unnamed_statement(Unnamed_label* label, - source_location location) -{ - return new Goto_unnamed_statement(label, location); -} - -// Class Label_statement. - -// Traversal. - -int -Label_statement::do_traverse(Traverse*) -{ - return TRAVERSE_CONTINUE; -} - -// Return a tree defining this label. - -tree -Label_statement::do_get_tree(Translate_context*) -{ - return this->build_stmt_1(LABEL_EXPR, this->label_->get_decl()); -} - -// Make a label statement. - -Statement* -Statement::make_label_statement(Label* label, source_location location) -{ - return new Label_statement(label, location); -} - -// An unnamed label statement. - -class Unnamed_label_statement : public Statement -{ - public: - Unnamed_label_statement(Unnamed_label* label) - : Statement(STATEMENT_UNNAMED_LABEL, label->location()), - label_(label) - { } - - protected: - int - do_traverse(Traverse*) - { return TRAVERSE_CONTINUE; } - - tree - do_get_tree(Translate_context*) - { return this->label_->get_definition(); } - - private: - // The label. - Unnamed_label* label_; -}; - -// Make an unnamed label statement. - -Statement* -Statement::make_unnamed_label_statement(Unnamed_label* label) -{ - return new Unnamed_label_statement(label); -} - -// An if statement. - -class If_statement : public Statement -{ - public: - If_statement(Expression* cond, Block* then_block, Block* else_block, - source_location location) - : Statement(STATEMENT_IF, location), - cond_(cond), then_block_(then_block), else_block_(else_block) - { } - - protected: - int - do_traverse(Traverse*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - bool - do_may_fall_through() const; - - tree - do_get_tree(Translate_context*); - - private: - Expression* cond_; - Block* then_block_; - Block* else_block_; -}; - -// Traversal. - -int -If_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->cond_) == TRAVERSE_EXIT - || this->then_block_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->else_block_ != NULL) - { - if (this->else_block_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -void -If_statement::do_determine_types() -{ - Type_context context(Type::lookup_bool_type(), false); - this->cond_->determine_type(&context); - this->then_block_->determine_types(); - if (this->else_block_ != NULL) - this->else_block_->determine_types(); -} - -// Check types. - -void -If_statement::do_check_types(Gogo*) -{ - Type* type = this->cond_->type(); - if (type->is_error_type()) - this->set_is_error(); - else if (!type->is_boolean_type()) - this->report_error(_("expected boolean expression")); -} - -// Whether the overall statement may fall through. - -bool -If_statement::do_may_fall_through() const -{ - return (this->else_block_ == NULL - || this->then_block_->may_fall_through() - || this->else_block_->may_fall_through()); -} - -// Get tree. - -tree -If_statement::do_get_tree(Translate_context* context) -{ - gcc_assert(this->cond_->type()->is_boolean_type() - || this->cond_->type()->is_error_type()); - tree cond_tree = this->cond_->get_tree(context); - tree then_tree = this->then_block_->get_tree(context); - tree else_tree = (this->else_block_ == NULL - ? NULL_TREE - : this->else_block_->get_tree(context)); - if (cond_tree == error_mark_node - || then_tree == error_mark_node - || else_tree == error_mark_node) - return error_mark_node; - tree ret = build3(COND_EXPR, void_type_node, cond_tree, then_tree, - else_tree); - SET_EXPR_LOCATION(ret, this->location()); - return ret; -} - -// Make an if statement. - -Statement* -Statement::make_if_statement(Expression* cond, Block* then_block, - Block* else_block, source_location location) -{ - return new If_statement(cond, then_block, else_block, location); -} - -// Class Case_clauses::Case_clause. - -// Traversal. - -int -Case_clauses::Case_clause::traverse(Traverse* traverse) -{ - if (this->cases_ != NULL - && (traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) != 0) - { - if (this->cases_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->statements_ != NULL) - { - if (this->statements_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Check whether all the case expressions are integer constants. - -bool -Case_clauses::Case_clause::is_constant() const -{ - if (this->cases_ != NULL) - { - for (Expression_list::const_iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - if (!(*p)->is_constant() || (*p)->type()->integer_type() == NULL) - return false; - } - return true; -} - -// Lower a case clause for a nonconstant switch. VAL_TEMP is the -// value we are switching on; it may be NULL. If START_LABEL is not -// NULL, it goes at the start of the statements, after the condition -// test. We branch to FINISH_LABEL at the end of the statements. - -void -Case_clauses::Case_clause::lower(Block* b, Temporary_statement* val_temp, - Unnamed_label* start_label, - Unnamed_label* finish_label) const -{ - source_location loc = this->location_; - Unnamed_label* next_case_label; - if (this->cases_ == NULL || this->cases_->empty()) - { - gcc_assert(this->is_default_); - next_case_label = NULL; - } - else - { - Expression* cond = NULL; - - for (Expression_list::const_iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - { - Expression* this_cond; - if (val_temp == NULL) - this_cond = *p; - else - { - Expression* ref = Expression::make_temporary_reference(val_temp, - loc); - this_cond = Expression::make_binary(OPERATOR_EQEQ, ref, *p, loc); - } - - if (cond == NULL) - cond = this_cond; - else - cond = Expression::make_binary(OPERATOR_OROR, cond, this_cond, loc); - } - - Block* then_block = new Block(b, loc); - next_case_label = new Unnamed_label(UNKNOWN_LOCATION); - Statement* s = Statement::make_goto_unnamed_statement(next_case_label, - loc); - then_block->add_statement(s); - - // if !COND { goto NEXT_CASE_LABEL } - cond = Expression::make_unary(OPERATOR_NOT, cond, loc); - s = Statement::make_if_statement(cond, then_block, NULL, loc); - b->add_statement(s); - } - - if (start_label != NULL) - b->add_statement(Statement::make_unnamed_label_statement(start_label)); - - if (this->statements_ != NULL) - b->add_statement(Statement::make_block_statement(this->statements_, loc)); - - Statement* s = Statement::make_goto_unnamed_statement(finish_label, loc); - b->add_statement(s); - - if (next_case_label != NULL) - b->add_statement(Statement::make_unnamed_label_statement(next_case_label)); -} - -// Determine types. - -void -Case_clauses::Case_clause::determine_types(Type* type) -{ - if (this->cases_ != NULL) - { - Type_context case_context(type, false); - for (Expression_list::iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - (*p)->determine_type(&case_context); - } - if (this->statements_ != NULL) - this->statements_->determine_types(); -} - -// Check types. Returns false if there was an error. - -bool -Case_clauses::Case_clause::check_types(Type* type) -{ - if (this->cases_ != NULL) - { - for (Expression_list::iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - { - if (!Type::are_assignable(type, (*p)->type(), NULL) - && !Type::are_assignable((*p)->type(), type, NULL)) - { - error_at((*p)->location(), - "type mismatch between switch value and case clause"); - return false; - } - } - } - return true; -} - -// Return true if this clause may fall through to the following -// statements. Note that this is not the same as whether the case -// uses the "fallthrough" keyword. - -bool -Case_clauses::Case_clause::may_fall_through() const -{ - if (this->statements_ == NULL) - return true; - return this->statements_->may_fall_through(); -} - -// Build up the body of a SWITCH_EXPR. - -void -Case_clauses::Case_clause::get_constant_tree(Translate_context* context, - Unnamed_label* break_label, - Case_constants* case_constants, - tree* stmt_list) const -{ - if (this->cases_ != NULL) - { - for (Expression_list::const_iterator p = this->cases_->begin(); - p != this->cases_->end(); - ++p) - { - Type* itype; - mpz_t ival; - mpz_init(ival); - if (!(*p)->integer_constant_value(true, ival, &itype)) - { - // Something went wrong. This can happen with a - // negative constant and an unsigned switch value. - gcc_assert(saw_errors()); - continue; - } - gcc_assert(itype != NULL); - tree type_tree = itype->get_tree(context->gogo()); - tree val = Expression::integer_constant_tree(ival, type_tree); - mpz_clear(ival); - - if (val != error_mark_node) - { - gcc_assert(TREE_CODE(val) == INTEGER_CST); - - std::pair ins = - case_constants->insert(val); - if (!ins.second) - { - // Value was already present. - warning_at(this->location_, 0, - "duplicate case value will never match"); - continue; - } - - tree label = create_artificial_label(this->location_); - append_to_statement_list(build3(CASE_LABEL_EXPR, void_type_node, - val, NULL_TREE, label), - stmt_list); - } - } - } - - if (this->is_default_) - { - tree label = create_artificial_label(this->location_); - append_to_statement_list(build3(CASE_LABEL_EXPR, void_type_node, - NULL_TREE, NULL_TREE, label), - stmt_list); - } - - if (this->statements_ != NULL) - { - tree block_tree = this->statements_->get_tree(context); - if (block_tree != error_mark_node) - append_to_statement_list(block_tree, stmt_list); - } - - if (!this->is_fallthrough_) - append_to_statement_list(break_label->get_goto(this->location_), stmt_list); -} - -// Class Case_clauses. - -// Traversal. - -int -Case_clauses::traverse(Traverse* traverse) -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Check whether all the case expressions are constant. - -bool -Case_clauses::is_constant() const -{ - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - if (!p->is_constant()) - return false; - return true; -} - -// Lower case clauses for a nonconstant switch. - -void -Case_clauses::lower(Block* b, Temporary_statement* val_temp, - Unnamed_label* break_label) const -{ - // The default case. - const Case_clause* default_case = NULL; - - // The label for the fallthrough of the previous case. - Unnamed_label* last_fallthrough_label = NULL; - - // The label for the start of the default case. This is used if the - // case before the default case falls through. - Unnamed_label* default_start_label = NULL; - - // The label for the end of the default case. This normally winds - // up as BREAK_LABEL, but it will be different if the default case - // falls through. - Unnamed_label* default_finish_label = NULL; - - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - // The label to use for the start of the statements for this - // case. This is NULL unless the previous case falls through. - Unnamed_label* start_label = last_fallthrough_label; - - // The label to jump to after the end of the statements for this - // case. - Unnamed_label* finish_label = break_label; - - last_fallthrough_label = NULL; - if (p->is_fallthrough() && p + 1 != this->clauses_.end()) - { - finish_label = new Unnamed_label(p->location()); - last_fallthrough_label = finish_label; - } - - if (!p->is_default()) - p->lower(b, val_temp, start_label, finish_label); - else - { - // We have to move the default case to the end, so that we - // only use it if all the other tests fail. - default_case = &*p; - default_start_label = start_label; - default_finish_label = finish_label; - } - } - - if (default_case != NULL) - default_case->lower(b, val_temp, default_start_label, - default_finish_label); - -} - -// Determine types. - -void -Case_clauses::determine_types(Type* type) -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - p->determine_types(type); -} - -// Check types. Returns false if there was an error. - -bool -Case_clauses::check_types(Type* type) -{ - bool ret = true; - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (!p->check_types(type)) - ret = false; - } - return ret; -} - -// Return true if these clauses may fall through to the statements -// following the switch statement. - -bool -Case_clauses::may_fall_through() const -{ - bool found_default = false; - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->may_fall_through() && !p->is_fallthrough()) - return true; - if (p->is_default()) - found_default = true; - } - return !found_default; -} - -// Return a tree when all case expressions are constants. - -tree -Case_clauses::get_constant_tree(Translate_context* context, - Unnamed_label* break_label) const -{ - Case_constants case_constants; - tree stmt_list = NULL_TREE; - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - p->get_constant_tree(context, break_label, &case_constants, - &stmt_list); - return stmt_list; -} - -// A constant switch statement. A Switch_statement is lowered to this -// when all the cases are constants. - -class Constant_switch_statement : public Statement -{ - public: - Constant_switch_statement(Expression* val, Case_clauses* clauses, - Unnamed_label* break_label, - source_location location) - : Statement(STATEMENT_CONSTANT_SWITCH, location), - val_(val), clauses_(clauses), break_label_(break_label) - { } - - protected: - int - do_traverse(Traverse*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - bool - do_may_fall_through() const; - - tree - do_get_tree(Translate_context*); - - private: - // The value to switch on. - Expression* val_; - // The case clauses. - Case_clauses* clauses_; - // The break label, if needed. - Unnamed_label* break_label_; -}; - -// Traversal. - -int -Constant_switch_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->clauses_->traverse(traverse); -} - -// Determine types. - -void -Constant_switch_statement::do_determine_types() -{ - this->val_->determine_type_no_context(); - this->clauses_->determine_types(this->val_->type()); -} - -// Check types. - -void -Constant_switch_statement::do_check_types(Gogo*) -{ - if (!this->clauses_->check_types(this->val_->type())) - this->set_is_error(); -} - -// Return whether this switch may fall through. - -bool -Constant_switch_statement::do_may_fall_through() const -{ - if (this->clauses_ == NULL) - return true; - - // If we have a break label, then some case needed it. That implies - // that the switch statement as a whole can fall through. - if (this->break_label_ != NULL) - return true; - - return this->clauses_->may_fall_through(); -} - -// Convert to GENERIC. - -tree -Constant_switch_statement::do_get_tree(Translate_context* context) -{ - tree switch_val_tree = this->val_->get_tree(context); - - Unnamed_label* break_label = this->break_label_; - if (break_label == NULL) - break_label = new Unnamed_label(this->location()); - - tree stmt_list = NULL_TREE; - tree s = build3(SWITCH_EXPR, void_type_node, switch_val_tree, - this->clauses_->get_constant_tree(context, break_label), - NULL_TREE); - SET_EXPR_LOCATION(s, this->location()); - append_to_statement_list(s, &stmt_list); - - append_to_statement_list(break_label->get_definition(), &stmt_list); - - return stmt_list; -} - -// Class Switch_statement. - -// Traversal. - -int -Switch_statement::do_traverse(Traverse* traverse) -{ - if (this->val_ != NULL) - { - if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return this->clauses_->traverse(traverse); -} - -// Lower a Switch_statement to a Constant_switch_statement or a series -// of if statements. - -Statement* -Switch_statement::do_lower(Gogo*, Named_object*, Block* enclosing) -{ - source_location loc = this->location(); - - if (this->val_ != NULL - && (this->val_->is_error_expression() - || this->val_->type()->is_error_type())) - return Statement::make_error_statement(loc); - - if (this->val_ != NULL - && this->val_->type()->integer_type() != NULL - && !this->clauses_->empty() - && this->clauses_->is_constant()) - return new Constant_switch_statement(this->val_, this->clauses_, - this->break_label_, loc); - - Block* b = new Block(enclosing, loc); - - if (this->clauses_->empty()) - { - Expression* val = this->val_; - if (val == NULL) - val = Expression::make_boolean(true, loc); - return Statement::make_statement(val); - } - - Temporary_statement* val_temp; - if (this->val_ == NULL) - val_temp = NULL; - else - { - // var val_temp VAL_TYPE = VAL - val_temp = Statement::make_temporary(NULL, this->val_, loc); - b->add_statement(val_temp); - } - - this->clauses_->lower(b, val_temp, this->break_label()); - - Statement* s = Statement::make_unnamed_label_statement(this->break_label_); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Return the break label for this switch statement, creating it if -// necessary. - -Unnamed_label* -Switch_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Make a switch statement. - -Switch_statement* -Statement::make_switch_statement(Expression* val, source_location location) -{ - return new Switch_statement(val, location); -} - -// Class Type_case_clauses::Type_case_clause. - -// Traversal. - -int -Type_case_clauses::Type_case_clause::traverse(Traverse* traverse) -{ - if (!this->is_default_ - && ((traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) != 0) - && Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->statements_ != NULL) - return this->statements_->traverse(traverse); - return TRAVERSE_CONTINUE; -} - -// Lower one clause in a type switch. Add statements to the block B. -// The type descriptor we are switching on is in DESCRIPTOR_TEMP. -// BREAK_LABEL is the label at the end of the type switch. -// *STMTS_LABEL, if not NULL, is a label to put at the start of the -// statements. - -void -Type_case_clauses::Type_case_clause::lower(Block* b, - Temporary_statement* descriptor_temp, - Unnamed_label* break_label, - Unnamed_label** stmts_label) const -{ - source_location loc = this->location_; - - Unnamed_label* next_case_label = NULL; - if (!this->is_default_) - { - Type* type = this->type_; - - Expression* cond; - // The language permits case nil, which is of course a constant - // rather than a type. It will appear here as an invalid - // forwarding type. - if (type->is_nil_constant_as_type()) - { - Expression* ref = - Expression::make_temporary_reference(descriptor_temp, loc); - cond = Expression::make_binary(OPERATOR_EQEQ, ref, - Expression::make_nil(loc), - loc); - } - else - { - Expression* func; - if (type->interface_type() == NULL) - { - // func ifacetypeeq(*descriptor, *descriptor) bool - static Named_object* ifacetypeeq; - if (ifacetypeeq == NULL) - { - const source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = - new Typed_identifier_list(); - Type* descriptor_type = Type::make_type_descriptor_ptr_type(); - param_types->push_back(Typed_identifier("a", descriptor_type, - bloc)); - param_types->push_back(Typed_identifier("b", descriptor_type, - bloc)); - Typed_identifier_list* ret_types = - new Typed_identifier_list(); - Type* bool_type = Type::lookup_bool_type(); - ret_types->push_back(Typed_identifier("", bool_type, bloc)); - Function_type* fntype = Type::make_function_type(NULL, - param_types, - ret_types, - bloc); - ifacetypeeq = - Named_object::make_function_declaration("ifacetypeeq", NULL, - fntype, bloc); - const char* n = "runtime.ifacetypeeq"; - ifacetypeeq->func_declaration_value()->set_asm_name(n); - } - - // ifacetypeeq(descriptor_temp, DESCRIPTOR) - func = Expression::make_func_reference(ifacetypeeq, NULL, loc); - } - else - { - // func ifaceI2Tp(*descriptor, *descriptor) bool - static Named_object* ifaceI2Tp; - if (ifaceI2Tp == NULL) - { - const source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = - new Typed_identifier_list(); - Type* descriptor_type = Type::make_type_descriptor_ptr_type(); - param_types->push_back(Typed_identifier("a", descriptor_type, - bloc)); - param_types->push_back(Typed_identifier("b", descriptor_type, - bloc)); - Typed_identifier_list* ret_types = - new Typed_identifier_list(); - Type* bool_type = Type::lookup_bool_type(); - ret_types->push_back(Typed_identifier("", bool_type, bloc)); - Function_type* fntype = Type::make_function_type(NULL, - param_types, - ret_types, - bloc); - ifaceI2Tp = - Named_object::make_function_declaration("ifaceI2Tp", NULL, - fntype, bloc); - const char* n = "runtime.ifaceI2Tp"; - ifaceI2Tp->func_declaration_value()->set_asm_name(n); - } - - // ifaceI2Tp(descriptor_temp, DESCRIPTOR) - func = Expression::make_func_reference(ifaceI2Tp, NULL, loc); - } - Expression_list* params = new Expression_list(); - params->push_back(Expression::make_type_descriptor(type, loc)); - Expression* ref = - Expression::make_temporary_reference(descriptor_temp, loc); - params->push_back(ref); - cond = Expression::make_call(func, params, false, loc); - } - - Unnamed_label* dest; - if (!this->is_fallthrough_) - { - // if !COND { goto NEXT_CASE_LABEL } - next_case_label = new Unnamed_label(UNKNOWN_LOCATION); - dest = next_case_label; - cond = Expression::make_unary(OPERATOR_NOT, cond, loc); - } - else - { - // if COND { goto STMTS_LABEL } - gcc_assert(stmts_label != NULL); - if (*stmts_label == NULL) - *stmts_label = new Unnamed_label(UNKNOWN_LOCATION); - dest = *stmts_label; - } - Block* then_block = new Block(b, loc); - Statement* s = Statement::make_goto_unnamed_statement(dest, loc); - then_block->add_statement(s); - s = Statement::make_if_statement(cond, then_block, NULL, loc); - b->add_statement(s); - } - - if (this->statements_ != NULL - || (!this->is_fallthrough_ - && stmts_label != NULL - && *stmts_label != NULL)) - { - gcc_assert(!this->is_fallthrough_); - if (stmts_label != NULL && *stmts_label != NULL) - { - gcc_assert(!this->is_default_); - if (this->statements_ != NULL) - (*stmts_label)->set_location(this->statements_->start_location()); - Statement* s = Statement::make_unnamed_label_statement(*stmts_label); - b->add_statement(s); - *stmts_label = NULL; - } - if (this->statements_ != NULL) - b->add_statement(Statement::make_block_statement(this->statements_, - loc)); - } - - if (this->is_fallthrough_) - gcc_assert(next_case_label == NULL); - else - { - source_location gloc = (this->statements_ == NULL - ? loc - : this->statements_->end_location()); - b->add_statement(Statement::make_goto_unnamed_statement(break_label, - gloc)); - if (next_case_label != NULL) - { - Statement* s = - Statement::make_unnamed_label_statement(next_case_label); - b->add_statement(s); - } - } -} - -// Class Type_case_clauses. - -// Traversal. - -int -Type_case_clauses::traverse(Traverse* traverse) -{ - for (Type_clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Check for duplicate types. - -void -Type_case_clauses::check_duplicates() const -{ - typedef Unordered_set_hash(const Type*, Type_hash_identical, - Type_identical) Types_seen; - Types_seen types_seen; - for (Type_clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - Type* t = p->type(); - if (t == NULL) - continue; - if (t->is_nil_constant_as_type()) - t = Type::make_nil_type(); - std::pair ins = types_seen.insert(t); - if (!ins.second) - error_at(p->location(), "duplicate type in switch"); - } -} - -// Lower the clauses in a type switch. Add statements to the block B. -// The type descriptor we are switching on is in DESCRIPTOR_TEMP. -// BREAK_LABEL is the label at the end of the type switch. - -void -Type_case_clauses::lower(Block* b, Temporary_statement* descriptor_temp, - Unnamed_label* break_label) const -{ - const Type_case_clause* default_case = NULL; - - Unnamed_label* stmts_label = NULL; - for (Type_clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (!p->is_default()) - p->lower(b, descriptor_temp, break_label, &stmts_label); - else - { - // We are generating a series of tests, which means that we - // need to move the default case to the end. - default_case = &*p; - } - } - gcc_assert(stmts_label == NULL); - - if (default_case != NULL) - default_case->lower(b, descriptor_temp, break_label, NULL); -} - -// Class Type_switch_statement. - -// Traversal. - -int -Type_switch_statement::do_traverse(Traverse* traverse) -{ - if (this->var_ == NULL) - { - if (this->traverse_expression(traverse, &this->expr_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->clauses_ != NULL) - return this->clauses_->traverse(traverse); - return TRAVERSE_CONTINUE; -} - -// Lower a type switch statement to a series of if statements. The gc -// compiler is able to generate a table in some cases. However, that -// does not work for us because we may have type descriptors in -// different shared libraries, so we can't compare them with simple -// equality testing. - -Statement* -Type_switch_statement::do_lower(Gogo*, Named_object*, Block* enclosing) -{ - const source_location loc = this->location(); - - if (this->clauses_ != NULL) - this->clauses_->check_duplicates(); - - Block* b = new Block(enclosing, loc); - - Type* val_type = (this->var_ != NULL - ? this->var_->var_value()->type() - : this->expr_->type()); - - // var descriptor_temp DESCRIPTOR_TYPE - Type* descriptor_type = Type::make_type_descriptor_ptr_type(); - Temporary_statement* descriptor_temp = - Statement::make_temporary(descriptor_type, NULL, loc); - b->add_statement(descriptor_temp); - - if (val_type->interface_type() == NULL) - { - // Doing a type switch on a non-interface type. Should we issue - // a warning for this case? - Expression* lhs = Expression::make_temporary_reference(descriptor_temp, - loc); - Expression* rhs; - if (val_type->is_nil_type()) - rhs = Expression::make_nil(loc); - else - { - if (val_type->is_abstract()) - val_type = val_type->make_non_abstract_type(); - rhs = Expression::make_type_descriptor(val_type, loc); - } - Statement* s = Statement::make_assignment(lhs, rhs, loc); - b->add_statement(s); - } - else - { - const source_location bloc = BUILTINS_LOCATION; - - // func {efacetype,ifacetype}(*interface) *descriptor - // FIXME: This should be inlined. - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("i", val_type, bloc)); - Typed_identifier_list* ret_types = new Typed_identifier_list(); - ret_types->push_back(Typed_identifier("", descriptor_type, bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, - ret_types, bloc); - bool is_empty = val_type->interface_type()->is_empty(); - const char* fnname = is_empty ? "efacetype" : "ifacetype"; - Named_object* fn = - Named_object::make_function_declaration(fnname, NULL, fntype, bloc); - const char* asm_name = (is_empty - ? "runtime.efacetype" - : "runtime.ifacetype"); - fn->func_declaration_value()->set_asm_name(asm_name); - - // descriptor_temp = ifacetype(val_temp) - Expression* func = Expression::make_func_reference(fn, NULL, loc); - Expression_list* params = new Expression_list(); - Expression* ref; - if (this->var_ == NULL) - ref = this->expr_; - else - ref = Expression::make_var_reference(this->var_, loc); - params->push_back(ref); - Expression* call = Expression::make_call(func, params, false, loc); - Expression* lhs = Expression::make_temporary_reference(descriptor_temp, - loc); - Statement* s = Statement::make_assignment(lhs, call, loc); - b->add_statement(s); - } - - if (this->clauses_ != NULL) - this->clauses_->lower(b, descriptor_temp, this->break_label()); - - Statement* s = Statement::make_unnamed_label_statement(this->break_label_); - b->add_statement(s); - - return Statement::make_block_statement(b, loc); -} - -// Return the break label for this type switch statement, creating it -// if necessary. - -Unnamed_label* -Type_switch_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Make a type switch statement. - -Type_switch_statement* -Statement::make_type_switch_statement(Named_object* var, Expression* expr, - source_location location) -{ - return new Type_switch_statement(var, expr, location); -} - -// Class Send_statement. - -// Traversal. - -int -Send_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->channel_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->traverse_expression(traverse, &this->val_); -} - -// Determine types. - -void -Send_statement::do_determine_types() -{ - this->channel_->determine_type_no_context(); - Type* type = this->channel_->type(); - Type_context context; - if (type->channel_type() != NULL) - context.type = type->channel_type()->element_type(); - this->val_->determine_type(&context); -} - -// Check types. - -void -Send_statement::do_check_types(Gogo*) -{ - Type* type = this->channel_->type(); - if (type->is_error_type()) - { - this->set_is_error(); - return; - } - Channel_type* channel_type = type->channel_type(); - if (channel_type == NULL) - { - error_at(this->location(), "left operand of %<<-%> must be channel"); - this->set_is_error(); - return; - } - Type* element_type = channel_type->element_type(); - if (!Type::are_assignable(element_type, this->val_->type(), NULL)) - { - this->report_error(_("incompatible types in send")); - return; - } - if (!channel_type->may_send()) - { - this->report_error(_("invalid send on receive-only channel")); - return; - } -} - -// Get a tree for a send statement. - -tree -Send_statement::do_get_tree(Translate_context* context) -{ - tree channel = this->channel_->get_tree(context); - tree val = this->val_->get_tree(context); - if (channel == error_mark_node || val == error_mark_node) - return error_mark_node; - Channel_type* channel_type = this->channel_->type()->channel_type(); - val = Expression::convert_for_assignment(context, - channel_type->element_type(), - this->val_->type(), - val, - this->location()); - return Gogo::send_on_channel(channel, val, true, this->for_select_, - this->location()); -} - -// Make a send statement. - -Send_statement* -Statement::make_send_statement(Expression* channel, Expression* val, - source_location location) -{ - return new Send_statement(channel, val, location); -} - -// Class Select_clauses::Select_clause. - -// Traversal. - -int -Select_clauses::Select_clause::traverse(Traverse* traverse) -{ - if (!this->is_lowered_ - && (traverse->traverse_mask() - & (Traverse::traverse_types | Traverse::traverse_expressions)) != 0) - { - if (this->channel_ != NULL) - { - if (Expression::traverse(&this->channel_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->val_ != NULL) - { - if (Expression::traverse(&this->val_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->closed_ != NULL) - { - if (Expression::traverse(&this->closed_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - if (this->statements_ != NULL) - { - if (this->statements_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lowering. Here we pull out the channel and the send values, to -// enforce the order of evaluation. We also add explicit send and -// receive statements to the clauses. - -void -Select_clauses::Select_clause::lower(Gogo* gogo, Named_object* function, - Block* b) -{ - if (this->is_default_) - { - gcc_assert(this->channel_ == NULL && this->val_ == NULL); - this->is_lowered_ = true; - return; - } - - source_location loc = this->location_; - - // Evaluate the channel before the select statement. - Temporary_statement* channel_temp = Statement::make_temporary(NULL, - this->channel_, - loc); - b->add_statement(channel_temp); - this->channel_ = Expression::make_temporary_reference(channel_temp, loc); - - // If this is a send clause, evaluate the value to send before the - // select statement. - Temporary_statement* val_temp = NULL; - if (this->is_send_ && !this->val_->is_constant()) - { - val_temp = Statement::make_temporary(NULL, this->val_, loc); - b->add_statement(val_temp); - } - - // Add the send or receive before the rest of the statements if any. - Block *init = new Block(b, loc); - Expression* ref = Expression::make_temporary_reference(channel_temp, loc); - if (this->is_send_) - { - Expression* ref2; - if (val_temp == NULL) - ref2 = this->val_; - else - ref2 = Expression::make_temporary_reference(val_temp, loc); - Send_statement* send = Statement::make_send_statement(ref, ref2, loc); - send->set_for_select(); - init->add_statement(send); - } - else if (this->closed_ != NULL && !this->closed_->is_sink_expression()) - { - gcc_assert(this->var_ == NULL && this->closedvar_ == NULL); - if (this->val_ == NULL) - this->val_ = Expression::make_sink(loc); - Statement* s = Statement::make_tuple_receive_assignment(this->val_, - this->closed_, - ref, true, loc); - init->add_statement(s); - } - else if (this->closedvar_ != NULL) - { - gcc_assert(this->val_ == NULL); - Expression* val; - if (this->var_ == NULL) - val = Expression::make_sink(loc); - else - val = Expression::make_var_reference(this->var_, loc); - Expression* closed = Expression::make_var_reference(this->closedvar_, - loc); - Statement* s = Statement::make_tuple_receive_assignment(val, closed, ref, - true, loc); - // We have to put S in STATEMENTS_, because that is where the - // variables are declared. - gcc_assert(this->statements_ != NULL); - this->statements_->add_statement_at_front(s); - // We have to lower STATEMENTS_ again, to lower the tuple - // receive assignment we just added. - gogo->lower_block(function, this->statements_); - } - else - { - Receive_expression* recv = Expression::make_receive(ref, loc); - recv->set_for_select(); - if (this->val_ != NULL) - { - gcc_assert(this->var_ == NULL); - init->add_statement(Statement::make_assignment(this->val_, recv, - loc)); - } - else if (this->var_ != NULL) - { - this->var_->var_value()->set_init(recv); - this->var_->var_value()->clear_type_from_chan_element(); - } - else - { - init->add_statement(Statement::make_statement(recv)); - } - } - - // Lower any statements we just created. - gogo->lower_block(function, init); - - if (this->statements_ != NULL) - init->add_statement(Statement::make_block_statement(this->statements_, - loc)); - - this->statements_ = init; - - // Now all references should be handled through the statements, not - // through here. - this->is_lowered_ = true; - this->val_ = NULL; - this->var_ = NULL; -} - -// Determine types. - -void -Select_clauses::Select_clause::determine_types() -{ - gcc_assert(this->is_lowered_); - if (this->statements_ != NULL) - this->statements_->determine_types(); -} - -// Whether this clause may fall through to the statement which follows -// the overall select statement. - -bool -Select_clauses::Select_clause::may_fall_through() const -{ - if (this->statements_ == NULL) - return true; - return this->statements_->may_fall_through(); -} - -// Return a tree for the statements to execute. - -tree -Select_clauses::Select_clause::get_statements_tree(Translate_context* context) -{ - if (this->statements_ == NULL) - return NULL_TREE; - return this->statements_->get_tree(context); -} - -// Class Select_clauses. - -// Traversal. - -int -Select_clauses::traverse(Traverse* traverse) -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Lowering. Here we pull out the channel and the send values, to -// enforce the order of evaluation. We also add explicit send and -// receive statements to the clauses. - -void -Select_clauses::lower(Gogo* gogo, Named_object* function, Block* b) -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - p->lower(gogo, function, b); -} - -// Determine types. - -void -Select_clauses::determine_types() -{ - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - p->determine_types(); -} - -// Return whether these select clauses fall through to the statement -// following the overall select statement. - -bool -Select_clauses::may_fall_through() const -{ - for (Clauses::const_iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - if (p->may_fall_through()) - return true; - return false; -} - -// Return a tree. We build a call to -// size_t __go_select(size_t count, _Bool has_default, -// channel* channels, _Bool* is_send) -// -// There are COUNT entries in the CHANNELS and IS_SEND arrays. The -// value in the IS_SEND array is true for send, false for receive. -// __go_select returns an integer from 0 to COUNT, inclusive. A -// return of 0 means that the default case should be run; this only -// happens if HAS_DEFAULT is non-zero. Otherwise the number indicates -// the case to run. - -// FIXME: This doesn't handle channels which send interface types -// where the receiver has a static type which matches that interface. - -tree -Select_clauses::get_tree(Translate_context* context, - Unnamed_label *break_label, - source_location location) -{ - size_t count = this->clauses_.size(); - VEC(constructor_elt, gc)* chan_init = VEC_alloc(constructor_elt, gc, count); - VEC(constructor_elt, gc)* is_send_init = VEC_alloc(constructor_elt, gc, - count); - Select_clause* default_clause = NULL; - tree final_stmt_list = NULL_TREE; - tree channel_type_tree = NULL_TREE; - - size_t i = 0; - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (p->is_default()) - { - default_clause = &*p; - --count; - continue; - } - - if (p->channel()->type()->channel_type() == NULL) - { - // We should have given an error in the send or receive - // statement we created via lowering. - gcc_assert(saw_errors()); - return error_mark_node; - } - - tree channel_tree = p->channel()->get_tree(context); - if (channel_tree == error_mark_node) - return error_mark_node; - channel_type_tree = TREE_TYPE(channel_tree); - - constructor_elt* elt = VEC_quick_push(constructor_elt, chan_init, NULL); - elt->index = build_int_cstu(sizetype, i); - elt->value = channel_tree; - - elt = VEC_quick_push(constructor_elt, is_send_init, NULL); - elt->index = build_int_cstu(sizetype, i); - elt->value = p->is_send() ? boolean_true_node : boolean_false_node; - - ++i; - } - gcc_assert(i == count); - - if (i == 0 && default_clause != NULL) - { - // There is only a default clause. - gcc_assert(final_stmt_list == NULL_TREE); - tree stmt_list = NULL_TREE; - append_to_statement_list(default_clause->get_statements_tree(context), - &stmt_list); - append_to_statement_list(break_label->get_definition(), &stmt_list); - return stmt_list; - } - - tree pointer_chan_type_tree = (channel_type_tree == NULL_TREE - ? ptr_type_node - : build_pointer_type(channel_type_tree)); - tree chans_arg; - tree pointer_boolean_type_tree = build_pointer_type(boolean_type_node); - tree is_sends_arg; - - if (i == 0) - { - chans_arg = fold_convert_loc(location, pointer_chan_type_tree, - null_pointer_node); - is_sends_arg = fold_convert_loc(location, pointer_boolean_type_tree, - null_pointer_node); - } - else - { - tree index_type_tree = build_index_type(size_int(count - 1)); - tree chan_array_type_tree = build_array_type(channel_type_tree, - index_type_tree); - tree chan_constructor = build_constructor(chan_array_type_tree, - chan_init); - tree chan_var = create_tmp_var(chan_array_type_tree, "CHAN"); - DECL_IGNORED_P(chan_var) = 0; - DECL_INITIAL(chan_var) = chan_constructor; - DECL_SOURCE_LOCATION(chan_var) = location; - TREE_ADDRESSABLE(chan_var) = 1; - tree decl_expr = build1(DECL_EXPR, void_type_node, chan_var); - SET_EXPR_LOCATION(decl_expr, location); - append_to_statement_list(decl_expr, &final_stmt_list); - - tree is_send_array_type_tree = build_array_type(boolean_type_node, - index_type_tree); - tree is_send_constructor = build_constructor(is_send_array_type_tree, - is_send_init); - tree is_send_var = create_tmp_var(is_send_array_type_tree, "ISSEND"); - DECL_IGNORED_P(is_send_var) = 0; - DECL_INITIAL(is_send_var) = is_send_constructor; - DECL_SOURCE_LOCATION(is_send_var) = location; - TREE_ADDRESSABLE(is_send_var) = 1; - decl_expr = build1(DECL_EXPR, void_type_node, is_send_var); - SET_EXPR_LOCATION(decl_expr, location); - append_to_statement_list(decl_expr, &final_stmt_list); - - chans_arg = fold_convert_loc(location, pointer_chan_type_tree, - build_fold_addr_expr_loc(location, - chan_var)); - is_sends_arg = fold_convert_loc(location, pointer_boolean_type_tree, - build_fold_addr_expr_loc(location, - is_send_var)); - } - - static tree select_fndecl; - tree call = Gogo::call_builtin(&select_fndecl, - location, - "__go_select", - 4, - sizetype, - sizetype, - size_int(count), - boolean_type_node, - (default_clause == NULL - ? boolean_false_node - : boolean_true_node), - pointer_chan_type_tree, - chans_arg, - pointer_boolean_type_tree, - is_sends_arg); - if (call == error_mark_node) - return error_mark_node; - - tree stmt_list = NULL_TREE; - - if (default_clause != NULL) - this->add_clause_tree(context, 0, default_clause, break_label, &stmt_list); - - i = 1; - for (Clauses::iterator p = this->clauses_.begin(); - p != this->clauses_.end(); - ++p) - { - if (!p->is_default()) - { - this->add_clause_tree(context, i, &*p, break_label, &stmt_list); - ++i; - } - } - - append_to_statement_list(break_label->get_definition(), &stmt_list); - - tree switch_stmt = build3(SWITCH_EXPR, sizetype, call, stmt_list, NULL_TREE); - SET_EXPR_LOCATION(switch_stmt, location); - append_to_statement_list(switch_stmt, &final_stmt_list); - - return final_stmt_list; -} - -// Add the tree for CLAUSE to STMT_LIST. - -void -Select_clauses::add_clause_tree(Translate_context* context, int case_index, - Select_clause* clause, - Unnamed_label* bottom_label, tree* stmt_list) -{ - tree label = create_artificial_label(clause->location()); - append_to_statement_list(build3(CASE_LABEL_EXPR, void_type_node, - build_int_cst(sizetype, case_index), - NULL_TREE, label), - stmt_list); - append_to_statement_list(clause->get_statements_tree(context), stmt_list); - tree g = bottom_label->get_goto(clause->statements() == NULL - ? clause->location() - : clause->statements()->end_location()); - append_to_statement_list(g, stmt_list); -} - -// Class Select_statement. - -// Return the break label for this switch statement, creating it if -// necessary. - -Unnamed_label* -Select_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Lower a select statement. This will still return a select -// statement, but it will be modified to implement the order of -// evaluation rules, and to include the send and receive statements as -// explicit statements in the clauses. - -Statement* -Select_statement::do_lower(Gogo* gogo, Named_object* function, - Block* enclosing) -{ - if (this->is_lowered_) - return this; - Block* b = new Block(enclosing, this->location()); - this->clauses_->lower(gogo, function, b); - this->is_lowered_ = true; - b->add_statement(this); - return Statement::make_block_statement(b, this->location()); -} - -// Return the tree for a select statement. - -tree -Select_statement::do_get_tree(Translate_context* context) -{ - return this->clauses_->get_tree(context, this->break_label(), - this->location()); -} - -// Make a select statement. - -Select_statement* -Statement::make_select_statement(source_location location) -{ - return new Select_statement(location); -} - -// Class For_statement. - -// Traversal. - -int -For_statement::do_traverse(Traverse* traverse) -{ - if (this->init_ != NULL) - { - if (this->init_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->cond_ != NULL) - { - if (this->traverse_expression(traverse, &this->cond_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->post_ != NULL) - { - if (this->post_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return this->statements_->traverse(traverse); -} - -// Lower a For_statement into if statements and gotos. Getting rid of -// complex statements make it easier to handle garbage collection. - -Statement* -For_statement::do_lower(Gogo*, Named_object*, Block* enclosing) -{ - Statement* s; - source_location loc = this->location(); - - Block* b = new Block(enclosing, this->location()); - if (this->init_ != NULL) - { - s = Statement::make_block_statement(this->init_, - this->init_->start_location()); - b->add_statement(s); - } - - Unnamed_label* entry = NULL; - if (this->cond_ != NULL) - { - entry = new Unnamed_label(this->location()); - b->add_statement(Statement::make_goto_unnamed_statement(entry, loc)); - } - - Unnamed_label* top = new Unnamed_label(this->location()); - b->add_statement(Statement::make_unnamed_label_statement(top)); - - s = Statement::make_block_statement(this->statements_, - this->statements_->start_location()); - b->add_statement(s); - - source_location end_loc = this->statements_->end_location(); - - Unnamed_label* cont = this->continue_label_; - if (cont != NULL) - b->add_statement(Statement::make_unnamed_label_statement(cont)); - - if (this->post_ != NULL) - { - s = Statement::make_block_statement(this->post_, - this->post_->start_location()); - b->add_statement(s); - end_loc = this->post_->end_location(); - } - - if (this->cond_ == NULL) - b->add_statement(Statement::make_goto_unnamed_statement(top, end_loc)); - else - { - b->add_statement(Statement::make_unnamed_label_statement(entry)); - - source_location cond_loc = this->cond_->location(); - Block* then_block = new Block(b, cond_loc); - s = Statement::make_goto_unnamed_statement(top, cond_loc); - then_block->add_statement(s); - - s = Statement::make_if_statement(this->cond_, then_block, NULL, cond_loc); - b->add_statement(s); - } - - Unnamed_label* brk = this->break_label_; - if (brk != NULL) - b->add_statement(Statement::make_unnamed_label_statement(brk)); - - b->set_end_location(end_loc); - - return Statement::make_block_statement(b, loc); -} - -// Return the break label, creating it if necessary. - -Unnamed_label* -For_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Return the continue LABEL_EXPR. - -Unnamed_label* -For_statement::continue_label() -{ - if (this->continue_label_ == NULL) - this->continue_label_ = new Unnamed_label(this->location()); - return this->continue_label_; -} - -// Set the break and continue labels a for statement. This is used -// when lowering a for range statement. - -void -For_statement::set_break_continue_labels(Unnamed_label* break_label, - Unnamed_label* continue_label) -{ - gcc_assert(this->break_label_ == NULL && this->continue_label_ == NULL); - this->break_label_ = break_label; - this->continue_label_ = continue_label; -} - -// Make a for statement. - -For_statement* -Statement::make_for_statement(Block* init, Expression* cond, Block* post, - source_location location) -{ - return new For_statement(init, cond, post, location); -} - -// Class For_range_statement. - -// Traversal. - -int -For_range_statement::do_traverse(Traverse* traverse) -{ - if (this->traverse_expression(traverse, &this->index_var_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->value_var_ != NULL) - { - if (this->traverse_expression(traverse, &this->value_var_) - == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - if (this->traverse_expression(traverse, &this->range_) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return this->statements_->traverse(traverse); -} - -// Lower a for range statement. For simplicity we lower this into a -// for statement, which will then be lowered in turn to goto -// statements. - -Statement* -For_range_statement::do_lower(Gogo* gogo, Named_object*, Block* enclosing) -{ - Type* range_type = this->range_->type(); - if (range_type->points_to() != NULL - && range_type->points_to()->array_type() != NULL - && !range_type->points_to()->is_open_array_type()) - range_type = range_type->points_to(); - - Type* index_type; - Type* value_type = NULL; - if (range_type->array_type() != NULL) - { - index_type = Type::lookup_integer_type("int"); - value_type = range_type->array_type()->element_type(); - } - else if (range_type->is_string_type()) - { - index_type = Type::lookup_integer_type("int"); - value_type = index_type; - } - else if (range_type->map_type() != NULL) - { - index_type = range_type->map_type()->key_type(); - value_type = range_type->map_type()->val_type(); - } - else if (range_type->channel_type() != NULL) - { - index_type = range_type->channel_type()->element_type(); - if (this->value_var_ != NULL) - { - if (!this->value_var_->type()->is_error_type()) - this->report_error(_("too many variables for range clause " - "with channel")); - return Statement::make_error_statement(this->location()); - } - } - else - { - this->report_error(_("range clause must have " - "array, slice, setring, map, or channel type")); - return Statement::make_error_statement(this->location()); - } - - source_location loc = this->location(); - Block* temp_block = new Block(enclosing, loc); - - Named_object* range_object = NULL; - Temporary_statement* range_temp = NULL; - Var_expression* ve = this->range_->var_expression(); - if (ve != NULL) - range_object = ve->named_object(); - else - { - range_temp = Statement::make_temporary(NULL, this->range_, loc); - temp_block->add_statement(range_temp); - } - - Temporary_statement* index_temp = Statement::make_temporary(index_type, - NULL, loc); - temp_block->add_statement(index_temp); - - Temporary_statement* value_temp = NULL; - if (this->value_var_ != NULL) - { - value_temp = Statement::make_temporary(value_type, NULL, loc); - temp_block->add_statement(value_temp); - } - - Block* body = new Block(temp_block, loc); - - Block* init; - Expression* cond; - Block* iter_init; - Block* post; - - // Arrange to do a loop appropriate for the type. We will produce - // for INIT ; COND ; POST { - // ITER_INIT - // INDEX = INDEX_TEMP - // VALUE = VALUE_TEMP // If there is a value - // original statements - // } - - if (range_type->array_type() != NULL) - this->lower_range_array(gogo, temp_block, body, range_object, range_temp, - index_temp, value_temp, &init, &cond, &iter_init, - &post); - else if (range_type->is_string_type()) - this->lower_range_string(gogo, temp_block, body, range_object, range_temp, - index_temp, value_temp, &init, &cond, &iter_init, - &post); - else if (range_type->map_type() != NULL) - this->lower_range_map(gogo, temp_block, body, range_object, range_temp, - index_temp, value_temp, &init, &cond, &iter_init, - &post); - else if (range_type->channel_type() != NULL) - this->lower_range_channel(gogo, temp_block, body, range_object, range_temp, - index_temp, value_temp, &init, &cond, &iter_init, - &post); - else - gcc_unreachable(); - - if (iter_init != NULL) - body->add_statement(Statement::make_block_statement(iter_init, loc)); - - Statement* assign; - Expression* index_ref = Expression::make_temporary_reference(index_temp, loc); - if (this->value_var_ == NULL) - { - assign = Statement::make_assignment(this->index_var_, index_ref, loc); - } - else - { - Expression_list* lhs = new Expression_list(); - lhs->push_back(this->index_var_); - lhs->push_back(this->value_var_); - - Expression_list* rhs = new Expression_list(); - rhs->push_back(index_ref); - rhs->push_back(Expression::make_temporary_reference(value_temp, loc)); - - assign = Statement::make_tuple_assignment(lhs, rhs, loc); - } - body->add_statement(assign); - - body->add_statement(Statement::make_block_statement(this->statements_, loc)); - - body->set_end_location(this->statements_->end_location()); - - For_statement* loop = Statement::make_for_statement(init, cond, post, - this->location()); - loop->add_statements(body); - loop->set_break_continue_labels(this->break_label_, this->continue_label_); - - temp_block->add_statement(loop); - - return Statement::make_block_statement(temp_block, loc); -} - -// Return a reference to the range, which may be in RANGE_OBJECT or in -// RANGE_TEMP. - -Expression* -For_range_statement::make_range_ref(Named_object* range_object, - Temporary_statement* range_temp, - source_location loc) -{ - if (range_object != NULL) - return Expression::make_var_reference(range_object, loc); - else - return Expression::make_temporary_reference(range_temp, loc); -} - -// Return a call to the predeclared function FUNCNAME passing a -// reference to the temporary variable ARG. - -Expression* -For_range_statement::call_builtin(Gogo* gogo, const char* funcname, - Expression* arg, - source_location loc) -{ - Named_object* no = gogo->lookup_global(funcname); - gcc_assert(no != NULL && no->is_function_declaration()); - Expression* func = Expression::make_func_reference(no, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(arg); - return Expression::make_call(func, params, false, loc); -} - -// Lower a for range over an array or slice. - -void -For_range_statement::lower_range_array(Gogo* gogo, - Block* enclosing, - Block* body_block, - Named_object* range_object, - Temporary_statement* range_temp, - Temporary_statement* index_temp, - Temporary_statement* value_temp, - Block** pinit, - Expression** pcond, - Block** piter_init, - Block** ppost) -{ - source_location loc = this->location(); - - // The loop we generate: - // len_temp := len(range) - // for index_temp = 0; index_temp < len_temp; index_temp++ { - // value_temp = range[index_temp] - // index = index_temp - // value = value_temp - // original body - // } - - // Set *PINIT to - // var len_temp int - // len_temp = len(range) - // index_temp = 0 - - Block* init = new Block(enclosing, loc); - - Expression* ref = this->make_range_ref(range_object, range_temp, loc); - Expression* len_call = this->call_builtin(gogo, "len", ref, loc); - Temporary_statement* len_temp = Statement::make_temporary(index_temp->type(), - len_call, loc); - init->add_statement(len_temp); - - mpz_t zval; - mpz_init_set_ui(zval, 0UL); - Expression* zexpr = Expression::make_integer(&zval, NULL, loc); - mpz_clear(zval); - - ref = Expression::make_temporary_reference(index_temp, loc); - Statement* s = Statement::make_assignment(ref, zexpr, loc); - init->add_statement(s); - - *pinit = init; - - // Set *PCOND to - // index_temp < len_temp - - ref = Expression::make_temporary_reference(index_temp, loc); - Expression* ref2 = Expression::make_temporary_reference(len_temp, loc); - Expression* lt = Expression::make_binary(OPERATOR_LT, ref, ref2, loc); - - *pcond = lt; - - // Set *PITER_INIT to - // value_temp = range[index_temp] - - Block* iter_init = NULL; - if (value_temp != NULL) - { - iter_init = new Block(body_block, loc); - - ref = this->make_range_ref(range_object, range_temp, loc); - Expression* ref2 = Expression::make_temporary_reference(index_temp, loc); - Expression* index = Expression::make_index(ref, ref2, NULL, loc); - - ref = Expression::make_temporary_reference(value_temp, loc); - s = Statement::make_assignment(ref, index, loc); - - iter_init->add_statement(s); - } - *piter_init = iter_init; - - // Set *PPOST to - // index_temp++ - - Block* post = new Block(enclosing, loc); - ref = Expression::make_temporary_reference(index_temp, loc); - s = Statement::make_inc_statement(ref); - post->add_statement(s); - *ppost = post; -} - -// Lower a for range over a string. - -void -For_range_statement::lower_range_string(Gogo* gogo, - Block* enclosing, - Block* body_block, - Named_object* range_object, - Temporary_statement* range_temp, - Temporary_statement* index_temp, - Temporary_statement* value_temp, - Block** pinit, - Expression** pcond, - Block** piter_init, - Block** ppost) -{ - source_location loc = this->location(); - - // The loop we generate: - // var next_index_temp int - // for index_temp = 0; ; index_temp = next_index_temp { - // next_index_temp, value_temp = stringiter2(range, index_temp) - // if next_index_temp == 0 { - // break - // } - // index = index_temp - // value = value_temp - // original body - // } - - // Set *PINIT to - // var next_index_temp int - // index_temp = 0 - - Block* init = new Block(enclosing, loc); - - Temporary_statement* next_index_temp = - Statement::make_temporary(index_temp->type(), NULL, loc); - init->add_statement(next_index_temp); - - mpz_t zval; - mpz_init_set_ui(zval, 0UL); - Expression* zexpr = Expression::make_integer(&zval, NULL, loc); - - Expression* ref = Expression::make_temporary_reference(index_temp, loc); - Statement* s = Statement::make_assignment(ref, zexpr, loc); - - init->add_statement(s); - *pinit = init; - - // The loop has no condition. - - *pcond = NULL; - - // Set *PITER_INIT to - // next_index_temp = runtime.stringiter(range, index_temp) - // or - // next_index_temp, value_temp = runtime.stringiter2(range, index_temp) - // followed by - // if next_index_temp == 0 { - // break - // } - - Block* iter_init = new Block(body_block, loc); - - Named_object* no; - if (value_temp == NULL) - { - static Named_object* stringiter; - if (stringiter == NULL) - { - source_location bloc = BUILTINS_LOCATION; - Type* int_type = gogo->lookup_global("int")->type_value(); - - Typed_identifier_list* params = new Typed_identifier_list(); - params->push_back(Typed_identifier("s", Type::make_string_type(), - bloc)); - params->push_back(Typed_identifier("k", int_type, bloc)); - - Typed_identifier_list* results = new Typed_identifier_list(); - results->push_back(Typed_identifier("", int_type, bloc)); - - Function_type* fntype = Type::make_function_type(NULL, params, - results, bloc); - stringiter = Named_object::make_function_declaration("stringiter", - NULL, fntype, - bloc); - const char* n = "runtime.stringiter"; - stringiter->func_declaration_value()->set_asm_name(n); - } - no = stringiter; - } - else - { - static Named_object* stringiter2; - if (stringiter2 == NULL) - { - source_location bloc = BUILTINS_LOCATION; - Type* int_type = gogo->lookup_global("int")->type_value(); - - Typed_identifier_list* params = new Typed_identifier_list(); - params->push_back(Typed_identifier("s", Type::make_string_type(), - bloc)); - params->push_back(Typed_identifier("k", int_type, bloc)); - - Typed_identifier_list* results = new Typed_identifier_list(); - results->push_back(Typed_identifier("", int_type, bloc)); - results->push_back(Typed_identifier("", int_type, bloc)); - - Function_type* fntype = Type::make_function_type(NULL, params, - results, bloc); - stringiter2 = Named_object::make_function_declaration("stringiter", - NULL, fntype, - bloc); - const char* n = "runtime.stringiter2"; - stringiter2->func_declaration_value()->set_asm_name(n); - } - no = stringiter2; - } - - Expression* func = Expression::make_func_reference(no, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(this->make_range_ref(range_object, range_temp, loc)); - params->push_back(Expression::make_temporary_reference(index_temp, loc)); - Call_expression* call = Expression::make_call(func, params, false, loc); - - if (value_temp == NULL) - { - ref = Expression::make_temporary_reference(next_index_temp, loc); - s = Statement::make_assignment(ref, call, loc); - } - else - { - Expression_list* lhs = new Expression_list(); - lhs->push_back(Expression::make_temporary_reference(next_index_temp, - loc)); - lhs->push_back(Expression::make_temporary_reference(value_temp, loc)); - - Expression_list* rhs = new Expression_list(); - rhs->push_back(Expression::make_call_result(call, 0)); - rhs->push_back(Expression::make_call_result(call, 1)); - - s = Statement::make_tuple_assignment(lhs, rhs, loc); - } - iter_init->add_statement(s); - - ref = Expression::make_temporary_reference(next_index_temp, loc); - zexpr = Expression::make_integer(&zval, NULL, loc); - mpz_clear(zval); - Expression* equals = Expression::make_binary(OPERATOR_EQEQ, ref, zexpr, loc); - - Block* then_block = new Block(iter_init, loc); - s = Statement::make_break_statement(this->break_label(), loc); - then_block->add_statement(s); - - s = Statement::make_if_statement(equals, then_block, NULL, loc); - iter_init->add_statement(s); - - *piter_init = iter_init; - - // Set *PPOST to - // index_temp = next_index_temp - - Block* post = new Block(enclosing, loc); - - Expression* lhs = Expression::make_temporary_reference(index_temp, loc); - Expression* rhs = Expression::make_temporary_reference(next_index_temp, loc); - s = Statement::make_assignment(lhs, rhs, loc); - - post->add_statement(s); - *ppost = post; -} - -// Lower a for range over a map. - -void -For_range_statement::lower_range_map(Gogo* gogo, - Block* enclosing, - Block* body_block, - Named_object* range_object, - Temporary_statement* range_temp, - Temporary_statement* index_temp, - Temporary_statement* value_temp, - Block** pinit, - Expression** pcond, - Block** piter_init, - Block** ppost) -{ - source_location loc = this->location(); - - // The runtime uses a struct to handle ranges over a map. The - // struct is four pointers long. The first pointer is NULL when we - // have completed the iteration. - - // The loop we generate: - // var hiter map_iteration_struct - // for mapiterinit(range, &hiter); hiter[0] != nil; mapiternext(&hiter) { - // mapiter2(hiter, &index_temp, &value_temp) - // index = index_temp - // value = value_temp - // original body - // } - - // Set *PINIT to - // var hiter map_iteration_struct - // runtime.mapiterinit(range, &hiter) - - Block* init = new Block(enclosing, loc); - - const unsigned long map_iteration_size = 4; - - mpz_t ival; - mpz_init_set_ui(ival, map_iteration_size); - Expression* iexpr = Expression::make_integer(&ival, NULL, loc); - mpz_clear(ival); - - Type* byte_type = gogo->lookup_global("byte")->type_value(); - Type* ptr_type = Type::make_pointer_type(byte_type); - - Type* map_iteration_type = Type::make_array_type(ptr_type, iexpr); - Type* map_iteration_ptr = Type::make_pointer_type(map_iteration_type); - - Temporary_statement* hiter = Statement::make_temporary(map_iteration_type, - NULL, loc); - init->add_statement(hiter); - - source_location bloc = BUILTINS_LOCATION; - Typed_identifier_list* param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("map", this->range_->type(), bloc)); - param_types->push_back(Typed_identifier("it", map_iteration_ptr, bloc)); - Function_type* fntype = Type::make_function_type(NULL, param_types, NULL, - bloc); - - Named_object* mapiterinit = - Named_object::make_function_declaration("mapiterinit", NULL, fntype, bloc); - const char* n = "runtime.mapiterinit"; - mapiterinit->func_declaration_value()->set_asm_name(n); - - Expression* func = Expression::make_func_reference(mapiterinit, NULL, loc); - Expression_list* params = new Expression_list(); - params->push_back(this->make_range_ref(range_object, range_temp, loc)); - Expression* ref = Expression::make_temporary_reference(hiter, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - Expression* call = Expression::make_call(func, params, false, loc); - init->add_statement(Statement::make_statement(call)); - - *pinit = init; - - // Set *PCOND to - // hiter[0] != nil - - ref = Expression::make_temporary_reference(hiter, loc); - - mpz_t zval; - mpz_init_set_ui(zval, 0UL); - Expression* zexpr = Expression::make_integer(&zval, NULL, loc); - mpz_clear(zval); - - Expression* index = Expression::make_index(ref, zexpr, NULL, loc); - - Expression* ne = Expression::make_binary(OPERATOR_NOTEQ, index, - Expression::make_nil(loc), - loc); - - *pcond = ne; - - // Set *PITER_INIT to - // mapiter1(hiter, &index_temp) - // or - // mapiter2(hiter, &index_temp, &value_temp) - - Block* iter_init = new Block(body_block, loc); - - param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("hiter", map_iteration_ptr, bloc)); - Type* pkey_type = Type::make_pointer_type(index_temp->type()); - param_types->push_back(Typed_identifier("key", pkey_type, bloc)); - if (value_temp != NULL) - { - Type* pval_type = Type::make_pointer_type(value_temp->type()); - param_types->push_back(Typed_identifier("val", pval_type, bloc)); - } - fntype = Type::make_function_type(NULL, param_types, NULL, bloc); - n = value_temp == NULL ? "mapiter1" : "mapiter2"; - Named_object* mapiter = Named_object::make_function_declaration(n, NULL, - fntype, bloc); - n = value_temp == NULL ? "runtime.mapiter1" : "runtime.mapiter2"; - mapiter->func_declaration_value()->set_asm_name(n); - - func = Expression::make_func_reference(mapiter, NULL, loc); - params = new Expression_list(); - ref = Expression::make_temporary_reference(hiter, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - ref = Expression::make_temporary_reference(index_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - if (value_temp != NULL) - { - ref = Expression::make_temporary_reference(value_temp, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - } - call = Expression::make_call(func, params, false, loc); - iter_init->add_statement(Statement::make_statement(call)); - - *piter_init = iter_init; - - // Set *PPOST to - // mapiternext(&hiter) - - Block* post = new Block(enclosing, loc); - - static Named_object* mapiternext; - if (mapiternext == NULL) - { - param_types = new Typed_identifier_list(); - param_types->push_back(Typed_identifier("it", map_iteration_ptr, bloc)); - fntype = Type::make_function_type(NULL, param_types, NULL, bloc); - mapiternext = Named_object::make_function_declaration("mapiternext", - NULL, fntype, - bloc); - const char* n = "runtime.mapiternext"; - mapiternext->func_declaration_value()->set_asm_name(n); - } - - func = Expression::make_func_reference(mapiternext, NULL, loc); - params = new Expression_list(); - ref = Expression::make_temporary_reference(hiter, loc); - params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc)); - call = Expression::make_call(func, params, false, loc); - post->add_statement(Statement::make_statement(call)); - - *ppost = post; -} - -// Lower a for range over a channel. - -void -For_range_statement::lower_range_channel(Gogo*, - Block*, - Block* body_block, - Named_object* range_object, - Temporary_statement* range_temp, - Temporary_statement* index_temp, - Temporary_statement* value_temp, - Block** pinit, - Expression** pcond, - Block** piter_init, - Block** ppost) -{ - gcc_assert(value_temp == NULL); - - source_location loc = this->location(); - - // The loop we generate: - // for { - // index_temp, ok_temp = <-range - // if !ok_temp { - // break - // } - // index = index_temp - // original body - // } - - // We have no initialization code, no condition, and no post code. - - *pinit = NULL; - *pcond = NULL; - *ppost = NULL; - - // Set *PITER_INIT to - // index_temp, ok_temp = <-range - // if !ok_temp { - // break - // } - - Block* iter_init = new Block(body_block, loc); - - Temporary_statement* ok_temp = - Statement::make_temporary(Type::lookup_bool_type(), NULL, loc); - iter_init->add_statement(ok_temp); - - Expression* cref = this->make_range_ref(range_object, range_temp, loc); - Expression* iref = Expression::make_temporary_reference(index_temp, loc); - Expression* oref = Expression::make_temporary_reference(ok_temp, loc); - Statement* s = Statement::make_tuple_receive_assignment(iref, oref, cref, - false, loc); - iter_init->add_statement(s); - - Block* then_block = new Block(iter_init, loc); - s = Statement::make_break_statement(this->break_label(), loc); - then_block->add_statement(s); - - oref = Expression::make_temporary_reference(ok_temp, loc); - Expression* cond = Expression::make_unary(OPERATOR_NOT, oref, loc); - s = Statement::make_if_statement(cond, then_block, NULL, loc); - iter_init->add_statement(s); - - *piter_init = iter_init; -} - -// Return the break LABEL_EXPR. - -Unnamed_label* -For_range_statement::break_label() -{ - if (this->break_label_ == NULL) - this->break_label_ = new Unnamed_label(this->location()); - return this->break_label_; -} - -// Return the continue LABEL_EXPR. - -Unnamed_label* -For_range_statement::continue_label() -{ - if (this->continue_label_ == NULL) - this->continue_label_ = new Unnamed_label(this->location()); - return this->continue_label_; -} - -// Make a for statement with a range clause. - -For_range_statement* -Statement::make_for_range_statement(Expression* index_var, - Expression* value_var, - Expression* range, - source_location location) -{ - return new For_range_statement(index_var, value_var, range, location); -} diff --git a/gcc/go/gofrontend/statements.h.merge-left.r167407 b/gcc/go/gofrontend/statements.h.merge-left.r167407 deleted file mode 100644 index 6ca586f10a9..00000000000 --- a/gcc/go/gofrontend/statements.h.merge-left.r167407 +++ /dev/null @@ -1,1420 +0,0 @@ -// statements.h -- Go frontend statements. -*- C++ -*- - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#ifndef GO_STATEMENTS_H -#define GO_STATEMENTS_H - -#include "operator.h" - -class Gogo; -class Traverse; -class Block; -class Function; -class Unnamed_label; -class Temporary_statement; -class Variable_declaration_statement; -class Return_statement; -class Thunk_statement; -class Label_statement; -class For_statement; -class For_range_statement; -class Switch_statement; -class Type_switch_statement; -class Select_statement; -class Variable; -class Named_object; -class Label; -class Translate_context; -class Expression; -class Expression_list; -class Struct_type; -class Call_expression; -class Map_index_expression; -class Receive_expression; -class Case_clauses; -class Type_case_clauses; -class Select_clauses; -class Typed_identifier_list; - -// This class is used to traverse assignments made by a statement -// which makes assignments. - -class Traverse_assignments -{ - public: - Traverse_assignments() - { } - - virtual ~Traverse_assignments() - { } - - // This is called for a variable initialization. - virtual void - initialize_variable(Named_object*) = 0; - - // This is called for each assignment made by the statement. PLHS - // points to the left hand side, and PRHS points to the right hand - // side. PRHS may be NULL if there is no associated expression, as - // in the bool set by a non-blocking receive. - virtual void - assignment(Expression** plhs, Expression** prhs) = 0; - - // This is called for each expression which is not passed to the - // assignment function. This is used for some of the statements - // which assign two values, for which there is no expression which - // describes the value. For ++ and -- the value is passed to both - // the assignment method and the rhs method. IS_STORED is true if - // this value is being stored directly. It is false if the value is - // computed but not stored. IS_LOCAL is true if the value is being - // stored in a local variable or this is being called by a return - // statement. - virtual void - value(Expression**, bool is_stored, bool is_local) = 0; -}; - -// A single statement. - -class Statement -{ - public: - // The types of statements. - enum Statement_classification - { - STATEMENT_ERROR, - STATEMENT_VARIABLE_DECLARATION, - STATEMENT_TEMPORARY, - STATEMENT_ASSIGNMENT, - STATEMENT_EXPRESSION, - STATEMENT_BLOCK, - STATEMENT_GO, - STATEMENT_DEFER, - STATEMENT_RETURN, - STATEMENT_BREAK_OR_CONTINUE, - STATEMENT_GOTO, - STATEMENT_GOTO_UNNAMED, - STATEMENT_LABEL, - STATEMENT_UNNAMED_LABEL, - STATEMENT_IF, - STATEMENT_CONSTANT_SWITCH, - STATEMENT_SELECT, - - // These statements types are created by the parser, but they - // disappear during the lowering pass. - STATEMENT_ASSIGNMENT_OPERATION, - STATEMENT_TUPLE_ASSIGNMENT, - STATEMENT_TUPLE_MAP_ASSIGNMENT, - STATEMENT_MAP_ASSIGNMENT, - STATEMENT_TUPLE_RECEIVE_ASSIGNMENT, - STATEMENT_TUPLE_TYPE_GUARD_ASSIGNMENT, - STATEMENT_INCDEC, - STATEMENT_FOR, - STATEMENT_FOR_RANGE, - STATEMENT_SWITCH, - STATEMENT_TYPE_SWITCH - }; - - Statement(Statement_classification, source_location); - - virtual ~Statement(); - - // Make a variable declaration. - static Statement* - make_variable_declaration(Named_object*); - - // Make a statement which creates a temporary variable and - // initializes it to an expression. The block is used if the - // temporary variable has to be explicitly destroyed; the variable - // must still be added to the block. References to the temporary - // variable may be constructed using make_temporary_reference. - // Either the type or the initialization expression may be NULL, but - // not both. - static Temporary_statement* - make_temporary(Type*, Expression*, source_location); - - // Make an assignment statement. - static Statement* - make_assignment(Expression*, Expression*, source_location); - - // Make an assignment operation (+=, etc.). - static Statement* - make_assignment_operation(Operator, Expression*, Expression*, - source_location); - - // Make a tuple assignment statement. - static Statement* - make_tuple_assignment(Expression_list*, Expression_list*, source_location); - - // Make an assignment from a map index to a pair of variables. - static Statement* - make_tuple_map_assignment(Expression* val, Expression* present, - Expression*, source_location); - - // Make a statement which assigns a pair of values to a map. - static Statement* - make_map_assignment(Expression*, Expression* val, - Expression* should_set, source_location); - - // Make an assignment from a nonblocking receive to a pair of - // variables. - static Statement* - make_tuple_receive_assignment(Expression* val, Expression* success, - Expression* channel, source_location); - - // Make an assignment from a type guard to a pair of variables. - static Statement* - make_tuple_type_guard_assignment(Expression* val, Expression* ok, - Expression* expr, Type* type, - source_location); - - // Make an expression statement from an Expression. - static Statement* - make_statement(Expression*); - - // Make a block statement from a Block. This is an embedded list of - // statements which may also include variable definitions. - static Statement* - make_block_statement(Block*, source_location); - - // Make an increment statement. - static Statement* - make_inc_statement(Expression*); - - // Make a decrement statement. - static Statement* - make_dec_statement(Expression*); - - // Make a go statement. - static Statement* - make_go_statement(Call_expression* call, source_location); - - // Make a defer statement. - static Statement* - make_defer_statement(Call_expression* call, source_location); - - // Make a return statement. - static Statement* - make_return_statement(const Typed_identifier_list*, Expression_list*, - source_location); - - // Make a break statement. - static Statement* - make_break_statement(Unnamed_label* label, source_location); - - // Make a continue statement. - static Statement* - make_continue_statement(Unnamed_label* label, source_location); - - // Make a goto statement. - static Statement* - make_goto_statement(Label* label, source_location); - - // Make a goto statement to an unnamed label. - static Statement* - make_goto_unnamed_statement(Unnamed_label* label, source_location); - - // Make a label statement--where the label is defined. - static Statement* - make_label_statement(Label* label, source_location); - - // Make an unnamed label statement--where the label is defined. - static Statement* - make_unnamed_label_statement(Unnamed_label* label); - - // Make an if statement. - static Statement* - make_if_statement(Expression* cond, Block* then_block, Block* else_block, - source_location); - - // Make a switch statement. - static Switch_statement* - make_switch_statement(Expression* switch_val, source_location); - - // Make a type switch statement. - static Type_switch_statement* - make_type_switch_statement(Named_object* var, Expression*, source_location); - - // Make a select statement. - static Select_statement* - make_select_statement(source_location); - - // Make a for statement. - static For_statement* - make_for_statement(Block* init, Expression* cond, Block* post, - source_location location); - - // Make a for statement with a range clause. - static For_range_statement* - make_for_range_statement(Expression* index_var, Expression* value_var, - Expression* range, source_location); - - // Return the statement classification. - Statement_classification - classification() const - { return this->classification_; } - - // Get the statement location. - source_location - location() const - { return this->location_; } - - // Traverse the tree. - int - traverse(Block*, size_t* index, Traverse*); - - // Traverse the contents of this statement--the expressions and - // statements which it contains. - int - traverse_contents(Traverse*); - - // If this statement assigns some values, it calls a function for - // each value to which this statement assigns a value, and returns - // true. If this statement does not assign any values, it returns - // false. - bool - traverse_assignments(Traverse_assignments* tassign); - - // Lower a statement. This is called immediately after parsing to - // simplify statements for further processing. It returns the same - // Statement or a new one. BLOCK is the block containing this - // statement. - Statement* - lower(Gogo* gogo, Block* block) - { return this->do_lower(gogo, block); } - - // Set type information for unnamed constants. - void - determine_types(); - - // Check types in a statement. This simply checks that any - // expressions used by the statement have the right type. - void - check_types(Gogo* gogo) - { this->do_check_types(gogo); } - - // Return whether this is a block statement. - bool - is_block_statement() const - { return this->classification_ == STATEMENT_BLOCK; } - - // If this is a variable declaration statement, return it. - // Otherwise return NULL. - Variable_declaration_statement* - variable_declaration_statement() - { - return this->convert(); - } - - // If this is a return statement, return it. Otherwise return NULL. - Return_statement* - return_statement() - { return this->convert(); } - - // If this is a thunk statement (a go or defer statement), return - // it. Otherwise return NULL. - Thunk_statement* - thunk_statement(); - - // If this is a label statement, return it. Otherwise return NULL. - Label_statement* - label_statement() - { return this->convert(); } - - // If this is a for statement, return it. Otherwise return NULL. - For_statement* - for_statement() - { return this->convert(); } - - // If this is a for statement over a range clause, return it. - // Otherwise return NULL. - For_range_statement* - for_range_statement() - { return this->convert(); } - - // If this is a switch statement, return it. Otherwise return NULL. - Switch_statement* - switch_statement() - { return this->convert(); } - - // If this is a type switch statement, return it. Otherwise return - // NULL. - Type_switch_statement* - type_switch_statement() - { return this->convert(); } - - // If this is a select statement, return it. Otherwise return NULL. - Select_statement* - select_statement() - { return this->convert(); } - - // Return true if this statement may fall through--if after - // executing this statement we may go on to execute the following - // statement, if any. - bool - may_fall_through() const - { return this->do_may_fall_through(); } - - // Return the tree for a statement. BLOCK is the enclosing block. - tree - get_tree(Translate_context*); - - protected: - // Implemented by child class: traverse the tree. - virtual int - do_traverse(Traverse*) = 0; - - // Implemented by child class: traverse assignments. Any statement - // which includes an assignment should implement this. - virtual bool - do_traverse_assignments(Traverse_assignments*) - { return false; } - - // Implemented by the child class: lower this statement to a simpler - // one. - virtual Statement* - do_lower(Gogo*, Block*) - { return this; } - - // Implemented by child class: set type information for unnamed - // constants. Any statement which includes an expression needs to - // implement this. - virtual void - do_determine_types() - { } - - // Implemented by child class: check types of expressions used in a - // statement. - virtual void - do_check_types(Gogo*) - { } - - // Implemented by child class: return true if this statement may - // fall through. - virtual bool - do_may_fall_through() const - { return true; } - - // Implemented by child class: return a tree. - virtual tree - do_get_tree(Translate_context*) = 0; - - // Traverse an expression in a statement. - int - traverse_expression(Traverse*, Expression**); - - // Traverse an expression list in a statement. The Expression_list - // may be NULL. - int - traverse_expression_list(Traverse*, Expression_list*); - - // Traverse a type in a statement. - int - traverse_type(Traverse*, Type*); - - // Build a tree node with one operand, setting the location. The - // first operand really has type "enum tree_code", but that enum is - // not defined here. - tree - build_stmt_1(int tree_code_value, tree); - - // For children to call when they detect that they are in error. - void - set_is_error(); - - // For children to call to report an error conveniently. - void - report_error(const char*); - - // For children to return an error statement from lower(). - static Statement* - make_error_statement(source_location); - - private: - // Convert to the desired statement classification, or return NULL. - // This is a controlled dynamic cast. - template - Statement_class* - convert() - { - return (this->classification_ == sc - ? static_cast(this) - : NULL); - } - - template - const Statement_class* - convert() const - { - return (this->classification_ == sc - ? static_cast(this) - : NULL); - } - - // The statement classification. - Statement_classification classification_; - // The location in the input file of the start of this statement. - source_location location_; -}; - -// A statement which creates and initializes a temporary variable. - -class Temporary_statement : public Statement -{ - public: - Temporary_statement(Type* type, Expression* init, source_location location) - : Statement(STATEMENT_TEMPORARY, location), - type_(type), init_(init), decl_(NULL), is_address_taken_(false) - { } - - // Return the type of the temporary variable. - Type* - type() const; - - // Return the initialization expression. - Expression* - init() const - { return this->init_; } - - // Record that something takes the address of this temporary - // variable. - void - set_is_address_taken() - { this->is_address_taken_ = true; } - - // Return the tree for the temporary variable itself. This should - // not be called until after the statement itself has been expanded. - tree - get_decl() const - { - gcc_assert(this->decl_ != NULL); - return this->decl_; - } - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - tree - do_get_tree(Translate_context*); - - private: - // The type of the temporary variable. - Type* type_; - // The initial value of the temporary variable. This may be NULL. - Expression* init_; - // The DECL for the temporary variable. - tree decl_; - // True if something takes the address of this temporary variable. - bool is_address_taken_; -}; - -// A variable declaration. This marks the point in the code where a -// variable is declared. The Variable is also attached to a Block. - -class Variable_declaration_statement : public Statement -{ - public: - Variable_declaration_statement(Named_object* var); - - // The variable being declared. - Named_object* - var() - { return this->var_; } - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*); - - tree - do_get_tree(Translate_context*); - - private: - Named_object* var_; -}; - -// A return statement. - -class Return_statement : public Statement -{ - public: - Return_statement(const Typed_identifier_list* results, Expression_list* vals, - source_location location) - : Statement(STATEMENT_RETURN, location), - results_(results), vals_(vals) - { } - - // The list of values being returned. This may be NULL. - const Expression_list* - vals() const - { return this->vals_; } - - protected: - int - do_traverse(Traverse* traverse) - { return this->traverse_expression_list(traverse, this->vals_); } - - bool - do_traverse_assignments(Traverse_assignments*); - - Statement* - do_lower(Gogo*, Block*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - bool - do_may_fall_through() const - { return false; } - - tree - do_get_tree(Translate_context*); - - private: - // The result types of the function we are returning from. This is - // here because in some of the traversals it is inconvenient to get - // it. - const Typed_identifier_list* results_; - // Return values. This may be NULL. - Expression_list* vals_; -}; - -// Select_clauses holds the clauses of a select statement. This is -// built by the parser. - -class Select_clauses -{ - public: - Select_clauses() - : clauses_() - { } - - // Add a new clause. IS_SEND is true if this is a send clause, - // false for a receive clause. For a send clause CHANNEL is the - // channel and VAL is the value to send. For a receive clause - // CHANNEL is the channel and VAL is either NULL or a Var_expression - // for the variable to set; if VAL is NULL, VAR may be a variable - // which is initialized with the received value. IS_DEFAULT is true - // if this is the default clause. STATEMENTS is the list of - // statements to execute. - void - add(bool is_send, Expression* channel, Expression* val, Named_object* var, - bool is_default, Block* statements, source_location location) - { - this->clauses_.push_back(Select_clause(is_send, channel, val, var, - is_default, statements, location)); - } - - // Traverse the select clauses. - int - traverse(Traverse*); - - // Lower statements. - void - lower(Block*); - - // Determine types. - void - determine_types(); - - // Whether the select clauses may fall through to the statement - // which follows the overall select statement. - bool - may_fall_through() const; - - // Return a tree implementing the select statement. - tree - get_tree(Translate_context*, Unnamed_label* break_label, source_location); - - private: - // A single clause. - class Select_clause - { - public: - Select_clause() - : channel_(NULL), val_(NULL), var_(NULL), statements_(NULL), - is_send_(false), is_default_(false) - { } - - Select_clause(bool is_send, Expression* channel, Expression* val, - Named_object* var, bool is_default, Block* statements, - source_location location) - : channel_(channel), val_(val), var_(var), statements_(statements), - location_(location), is_send_(is_send), is_default_(is_default), - is_lowered_(false) - { gcc_assert(is_default ? channel == NULL : channel != NULL); } - - // Traverse the select clause. - int - traverse(Traverse*); - - // Lower statements. - void - lower(Block*); - - // Determine types. - void - determine_types(); - - // Return true if this is the default clause. - bool - is_default() const - { return this->is_default_; } - - // Return the channel. This will return NULL for the default - // clause. - Expression* - channel() const - { return this->channel_; } - - // Return the value. This will return NULL for the default - // clause, or for a receive clause for which no value was given. - Expression* - val() const - { return this->val_; } - - // Return the variable to set when a receive clause is also a - // variable definition (v := <- ch). This will return NULL for - // the default case, or for a send clause, or for a receive clause - // which does not define a variable. - Named_object* - var() const - { return this->var_; } - - // Return true for a send, false for a receive. - bool - is_send() const - { - gcc_assert(!this->is_default_); - return this->is_send_; - } - - // Return the statements. - const Block* - statements() const - { return this->statements_; } - - // Return the location. - source_location - location() const - { return this->location_; } - - // Whether this clause may fall through to the statement which - // follows the overall select statement. - bool - may_fall_through() const; - - // Return a tree for the statements to execute. - tree - get_statements_tree(Translate_context*); - - private: - // The channel. - Expression* channel_; - // The value to send or the variable to set. - Expression* val_; - // The variable to initialize, for "case a := <- ch". - Named_object* var_; - // The statements to execute. - Block* statements_; - // The location of this clause. - source_location location_; - // Whether this is a send or a receive. - bool is_send_; - // Whether this is the default. - bool is_default_; - // Whether this has been lowered. - bool is_lowered_; - }; - - void - add_clause_tree(Translate_context*, int, Select_clause*, Unnamed_label*, - tree*); - - typedef std::vector Clauses; - - Clauses clauses_; -}; - -// A select statement. - -class Select_statement : public Statement -{ - public: - Select_statement(source_location location) - : Statement(STATEMENT_SELECT, location), - clauses_(NULL), break_label_(NULL), is_lowered_(false) - { } - - // Add the clauses. - void - add_clauses(Select_clauses* clauses) - { - gcc_assert(this->clauses_ == NULL); - this->clauses_ = clauses; - } - - // Return the break label for this select statement. - Unnamed_label* - break_label(); - - protected: - int - do_traverse(Traverse* traverse) - { return this->clauses_->traverse(traverse); } - - Statement* - do_lower(Gogo*, Block*); - - void - do_determine_types() - { this->clauses_->determine_types(); } - - bool - do_may_fall_through() const - { return this->clauses_->may_fall_through(); } - - tree - do_get_tree(Translate_context*); - - private: - // The select clauses. - Select_clauses* clauses_; - // The break label. - Unnamed_label* break_label_; - // Whether this statement has been lowered. - bool is_lowered_; -}; - -// A statement which requires a thunk: go or defer. - -class Thunk_statement : public Statement -{ - public: - Thunk_statement(Statement_classification, Call_expression*, - source_location); - - // Return the call expression. - Expression* - call() - { return this->call_; } - - // Simplify a go or defer statement so that it only uses a single - // parameter. - bool - simplify_statement(Gogo*, Block*); - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - // Return the function and argument trees for the call. - void - get_fn_and_arg(Translate_context*, tree* pfn, tree* parg); - - private: - // Return whether this is a simple go statement. - bool - is_simple(Function_type*) const; - - // Build the struct to use for a complex case. - Struct_type* - build_struct(Function_type* fntype); - - // Build the thunk. - void - build_thunk(Gogo*, const std::string&, Function_type* fntype); - - // The field name used in the thunk structure for the function - // pointer. - static const char* const thunk_field_fn; - - // The field name used in the thunk structure for the receiver, if - // there is one. - static const char* const thunk_field_receiver; - - // Set the name to use for thunk field N. - void - thunk_field_param(int n, char* buf, size_t buflen); - - // The function call to be executed in a separate thread (go) or - // later (defer). - Expression* call_; - // The type used for a struct to pass to a thunk, if this is not a - // simple call. - Struct_type* struct_type_; -}; - -// A go statement. - -class Go_statement : public Thunk_statement -{ - public: - Go_statement(Call_expression* call, source_location location) - : Thunk_statement(STATEMENT_GO, call, location) - { } - - protected: - tree - do_get_tree(Translate_context*); -}; - -// A defer statement. - -class Defer_statement : public Thunk_statement -{ - public: - Defer_statement(Call_expression* call, source_location location) - : Thunk_statement(STATEMENT_DEFER, call, location) - { } - - protected: - tree - do_get_tree(Translate_context*); -}; - -// A label statement. - -class Label_statement : public Statement -{ - public: - Label_statement(Label* label, source_location location) - : Statement(STATEMENT_LABEL, location), - label_(label) - { } - - // Return the label itself. - const Label* - label() const - { return this->label_; } - - protected: - int - do_traverse(Traverse*); - - tree - do_get_tree(Translate_context*); - - private: - // The label. - Label* label_; -}; - -// A for statement. - -class For_statement : public Statement -{ - public: - For_statement(Block* init, Expression* cond, Block* post, - source_location location) - : Statement(STATEMENT_FOR, location), - init_(init), cond_(cond), post_(post), statements_(NULL), - break_label_(NULL), continue_label_(NULL) - { } - - // Add the statements. - void - add_statements(Block* statements) - { - gcc_assert(this->statements_ == NULL); - this->statements_ = statements; - } - - // Return the break label for this for statement. - Unnamed_label* - break_label(); - - // Return the continue label for this for statement. - Unnamed_label* - continue_label(); - - // Set the break and continue labels for this statement. - void - set_break_continue_labels(Unnamed_label* break_label, - Unnamed_label* continue_label); - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // The initialization statements. This may be NULL. - Block* init_; - // The condition. This may be NULL. - Expression* cond_; - // The statements to run after each iteration. This may be NULL. - Block* post_; - // The statements in the loop itself. - Block* statements_; - // The break label, if needed. - Unnamed_label* break_label_; - // The continue label, if needed. - Unnamed_label* continue_label_; -}; - -// A for statement over a range clause. - -class For_range_statement : public Statement -{ - public: - For_range_statement(Expression* index_var, Expression* value_var, - Expression* range, source_location location) - : Statement(STATEMENT_FOR_RANGE, location), - index_var_(index_var), value_var_(value_var), range_(range), - statements_(NULL), break_label_(NULL), continue_label_(NULL) - { } - - // Add the statements. - void - add_statements(Block* statements) - { - gcc_assert(this->statements_ == NULL); - this->statements_ = statements; - } - - // Return the break label for this for statement. - Unnamed_label* - break_label(); - - // Return the continue label for this for statement. - Unnamed_label* - continue_label(); - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - Expression* - make_range_ref(Named_object*, Temporary_statement*, source_location); - - Expression* - call_builtin(Gogo*, const char* funcname, Expression* arg, source_location); - - void - lower_range_array(Gogo*, Block*, Block*, Named_object*, Temporary_statement*, - Temporary_statement*, Temporary_statement*, - Block**, Expression**, Block**, Block**); - - void - lower_range_string(Gogo*, Block*, Block*, Named_object*, Temporary_statement*, - Temporary_statement*, Temporary_statement*, - Block**, Expression**, Block**, Block**); - - void - lower_range_map(Gogo*, Block*, Block*, Named_object*, Temporary_statement*, - Temporary_statement*, Temporary_statement*, - Block**, Expression**, Block**, Block**); - - void - lower_range_channel(Gogo*, Block*, Block*, Named_object*, - Temporary_statement*, Temporary_statement*, - Temporary_statement*, Block**, Expression**, Block**, - Block**); - - // The variable which is set to the index value. - Expression* index_var_; - // The variable which is set to the element value. This may be - // NULL. - Expression* value_var_; - // The expression we are ranging over. - Expression* range_; - // The statements in the block. - Block* statements_; - // The break label, if needed. - Unnamed_label* break_label_; - // The continue label, if needed. - Unnamed_label* continue_label_; -}; - -// Class Case_clauses holds the clauses of a switch statement. This -// is built by the parser. - -class Case_clauses -{ - public: - Case_clauses() - : clauses_() - { } - - // Add a new clause. CASES is a list of case expressions; it may be - // NULL. IS_DEFAULT is true if this is the default case. - // STATEMENTS is a block of statements. IS_FALLTHROUGH is true if - // after the statements the case clause should fall through to the - // next clause. - void - add(Expression_list* cases, bool is_default, Block* statements, - bool is_fallthrough, source_location location) - { - this->clauses_.push_back(Case_clause(cases, is_default, statements, - is_fallthrough, location)); - } - - // Return whether there are no clauses. - bool - empty() const - { return this->clauses_.empty(); } - - // Traverse the case clauses. - int - traverse(Traverse*); - - // Lower for a nonconstant switch. - void - lower(Block*, Temporary_statement*, Unnamed_label*) const; - - // Determine types of expressions. The Type parameter is the type - // of the switch value. - void - determine_types(Type*); - - // Check types. The Type parameter is the type of the switch value. - bool - check_types(Type*); - - // Return true if all the clauses are constant values. - bool - is_constant() const; - - // Return true if these clauses may fall through to the statements - // following the switch statement. - bool - may_fall_through() const; - - // Return the body of a SWITCH_EXPR when all the clauses are - // constants. - tree - get_constant_tree(Translate_context*, Unnamed_label* break_label) const; - - private: - // For a constant tree we need to keep a record of constants we have - // already seen. Note that INTEGER_CST trees are interned. - typedef Unordered_set(tree) Case_constants; - - // One case clause. - class Case_clause - { - public: - Case_clause() - : cases_(NULL), statements_(NULL), is_default_(false), - is_fallthrough_(false), location_(UNKNOWN_LOCATION) - { } - - Case_clause(Expression_list* cases, bool is_default, Block* statements, - bool is_fallthrough, source_location location) - : cases_(cases), statements_(statements), is_default_(is_default), - is_fallthrough_(is_fallthrough), location_(location) - { } - - // Whether this clause falls through to the next clause. - bool - is_fallthrough() const - { return this->is_fallthrough_; } - - // Whether this is the default. - bool - is_default() const - { return this->is_default_; } - - // The location of this clause. - source_location - location() const - { return this->location_; } - - // Traversal. - int - traverse(Traverse*); - - // Lower for a nonconstant switch. - void - lower(Block*, Temporary_statement*, Unnamed_label*, Unnamed_label*) const; - - // Determine types. - void - determine_types(Type*); - - // Check types. - bool - check_types(Type*); - - // Return true if all the case expressions are constant. - bool - is_constant() const; - - // Return true if this clause may fall through to execute the - // statements following the switch statement. This is not the - // same as whether this clause falls through to the next clause. - bool - may_fall_through() const; - - // Build up the body of a SWITCH_EXPR when the case expressions - // are constant. - void - get_constant_tree(Translate_context*, Unnamed_label* break_label, - Case_constants* case_constants, tree* stmt_list) const; - - private: - // The list of case expressions. - Expression_list* cases_; - // The statements to execute. - Block* statements_; - // Whether this is the default case. - bool is_default_; - // Whether this falls through after the statements. - bool is_fallthrough_; - // The location of this case clause. - source_location location_; - }; - - friend class Case_clause; - - // The type of the list of clauses. - typedef std::vector Clauses; - - // All the case clauses. - Clauses clauses_; -}; - -// A switch statement. - -class Switch_statement : public Statement -{ - public: - Switch_statement(Expression* val, source_location location) - : Statement(STATEMENT_SWITCH, location), - val_(val), clauses_(NULL), break_label_(NULL) - { } - - // Add the clauses. - void - add_clauses(Case_clauses* clauses) - { - gcc_assert(this->clauses_ == NULL); - this->clauses_ = clauses; - } - - // Return the break label for this switch statement. - Unnamed_label* - break_label(); - - protected: - int - do_traverse(Traverse*); - - Statement* - do_lower(Gogo*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // The value to switch on. This may be NULL. - Expression* val_; - // The case clauses. - Case_clauses* clauses_; - // The break label, if needed. - Unnamed_label* break_label_; -}; - -// Class Type_case_clauses holds the clauses of a type switch -// statement. This is built by the parser. - -class Type_case_clauses -{ - public: - Type_case_clauses() - : clauses_() - { } - - // Add a new clause. TYPE is the type for this clause; it may be - // NULL. IS_FALLTHROUGH is true if this falls through to the next - // clause; in this case STATEMENTS will be NULL. IS_DEFAULT is true - // if this is the default case. STATEMENTS is a block of - // statements; it may be NULL. - void - add(Type* type, bool is_fallthrough, bool is_default, Block* statements, - source_location location) - { - this->clauses_.push_back(Type_case_clause(type, is_fallthrough, is_default, - statements, location)); - } - - // Return whether there are no clauses. - bool - empty() const - { return this->clauses_.empty(); } - - // Traverse the type case clauses. - int - traverse(Traverse*); - - // Check for duplicates. - void - check_duplicates() const; - - // Lower to if and goto statements. - void - lower(Block*, Temporary_statement* descriptor_temp, - Unnamed_label* break_label) const; - - private: - // One type case clause. - class Type_case_clause - { - public: - Type_case_clause() - : type_(NULL), statements_(NULL), is_default_(false), - location_(UNKNOWN_LOCATION) - { } - - Type_case_clause(Type* type, bool is_fallthrough, bool is_default, - Block* statements, source_location location) - : type_(type), statements_(statements), is_fallthrough_(is_fallthrough), - is_default_(is_default), location_(location) - { } - - // The type. - Type* - type() const - { return this->type_; } - - // Whether this is the default. - bool - is_default() const - { return this->is_default_; } - - // The location of this type clause. - source_location - location() const - { return this->location_; } - - // Traversal. - int - traverse(Traverse*); - - // Lower to if and goto statements. - void - lower(Block*, Temporary_statement* descriptor_temp, - Unnamed_label* break_label, Unnamed_label** stmts_label) const; - - private: - // The type for this type clause. - Type* type_; - // The statements to execute. - Block* statements_; - // Whether this falls through--this is true for "case T1, T2". - bool is_fallthrough_; - // Whether this is the default case. - bool is_default_; - // The location of this type case clause. - source_location location_; - }; - - friend class Type_case_clause; - - // The type of the list of type clauses. - typedef std::vector Type_clauses; - - // All the type case clauses. - Type_clauses clauses_; -}; - -// A type switch statement. - -class Type_switch_statement : public Statement -{ - public: - Type_switch_statement(Named_object* var, Expression* expr, - source_location location) - : Statement(STATEMENT_TYPE_SWITCH, location), - var_(var), expr_(expr), clauses_(NULL), break_label_(NULL) - { gcc_assert(var == NULL || expr == NULL); } - - // Add the clauses. - void - add_clauses(Type_case_clauses* clauses) - { - gcc_assert(this->clauses_ == NULL); - this->clauses_ = clauses; - } - - // Return the break label for this type switch statement. - Unnamed_label* - break_label(); - - protected: - int - do_traverse(Traverse*); - - Statement* - do_lower(Gogo*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // Get the type descriptor. - tree - get_type_descriptor(Translate_context*, Type*, tree); - - // The variable holding the value we are switching on. - Named_object* var_; - // The expression we are switching on if there is no variable. - Expression* expr_; - // The type case clauses. - Type_case_clauses* clauses_; - // The break label, if needed. - Unnamed_label* break_label_; -}; - -#endif // !defined(GO_STATEMENTS_H) diff --git a/gcc/go/gofrontend/statements.h.merge-right.r172891 b/gcc/go/gofrontend/statements.h.merge-right.r172891 deleted file mode 100644 index 5c27c117967..00000000000 --- a/gcc/go/gofrontend/statements.h.merge-right.r172891 +++ /dev/null @@ -1,1446 +0,0 @@ -// statements.h -- Go frontend statements. -*- C++ -*- - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#ifndef GO_STATEMENTS_H -#define GO_STATEMENTS_H - -#include "operator.h" - -class Gogo; -class Traverse; -class Block; -class Function; -class Unnamed_label; -class Temporary_statement; -class Variable_declaration_statement; -class Return_statement; -class Thunk_statement; -class Label_statement; -class For_statement; -class For_range_statement; -class Switch_statement; -class Type_switch_statement; -class Send_statement; -class Select_statement; -class Variable; -class Named_object; -class Label; -class Translate_context; -class Expression; -class Expression_list; -class Struct_type; -class Call_expression; -class Map_index_expression; -class Receive_expression; -class Case_clauses; -class Type_case_clauses; -class Select_clauses; -class Typed_identifier_list; -class Bexpression; -class Bstatement; -class Bvariable; - -// This class is used to traverse assignments made by a statement -// which makes assignments. - -class Traverse_assignments -{ - public: - Traverse_assignments() - { } - - virtual ~Traverse_assignments() - { } - - // This is called for a variable initialization. - virtual void - initialize_variable(Named_object*) = 0; - - // This is called for each assignment made by the statement. PLHS - // points to the left hand side, and PRHS points to the right hand - // side. PRHS may be NULL if there is no associated expression, as - // in the bool set by a non-blocking receive. - virtual void - assignment(Expression** plhs, Expression** prhs) = 0; - - // This is called for each expression which is not passed to the - // assignment function. This is used for some of the statements - // which assign two values, for which there is no expression which - // describes the value. For ++ and -- the value is passed to both - // the assignment method and the rhs method. IS_STORED is true if - // this value is being stored directly. It is false if the value is - // computed but not stored. IS_LOCAL is true if the value is being - // stored in a local variable or this is being called by a return - // statement. - virtual void - value(Expression**, bool is_stored, bool is_local) = 0; -}; - -// A single statement. - -class Statement -{ - public: - // The types of statements. - enum Statement_classification - { - STATEMENT_ERROR, - STATEMENT_VARIABLE_DECLARATION, - STATEMENT_TEMPORARY, - STATEMENT_ASSIGNMENT, - STATEMENT_EXPRESSION, - STATEMENT_BLOCK, - STATEMENT_GO, - STATEMENT_DEFER, - STATEMENT_RETURN, - STATEMENT_BREAK_OR_CONTINUE, - STATEMENT_GOTO, - STATEMENT_GOTO_UNNAMED, - STATEMENT_LABEL, - STATEMENT_UNNAMED_LABEL, - STATEMENT_IF, - STATEMENT_CONSTANT_SWITCH, - STATEMENT_SEND, - STATEMENT_SELECT, - - // These statements types are created by the parser, but they - // disappear during the lowering pass. - STATEMENT_ASSIGNMENT_OPERATION, - STATEMENT_TUPLE_ASSIGNMENT, - STATEMENT_TUPLE_MAP_ASSIGNMENT, - STATEMENT_MAP_ASSIGNMENT, - STATEMENT_TUPLE_RECEIVE_ASSIGNMENT, - STATEMENT_TUPLE_TYPE_GUARD_ASSIGNMENT, - STATEMENT_INCDEC, - STATEMENT_FOR, - STATEMENT_FOR_RANGE, - STATEMENT_SWITCH, - STATEMENT_TYPE_SWITCH - }; - - Statement(Statement_classification, source_location); - - virtual ~Statement(); - - // Make a variable declaration. - static Statement* - make_variable_declaration(Named_object*); - - // Make a statement which creates a temporary variable and - // initializes it to an expression. The block is used if the - // temporary variable has to be explicitly destroyed; the variable - // must still be added to the block. References to the temporary - // variable may be constructed using make_temporary_reference. - // Either the type or the initialization expression may be NULL, but - // not both. - static Temporary_statement* - make_temporary(Type*, Expression*, source_location); - - // Make an assignment statement. - static Statement* - make_assignment(Expression*, Expression*, source_location); - - // Make an assignment operation (+=, etc.). - static Statement* - make_assignment_operation(Operator, Expression*, Expression*, - source_location); - - // Make a tuple assignment statement. - static Statement* - make_tuple_assignment(Expression_list*, Expression_list*, source_location); - - // Make an assignment from a map index to a pair of variables. - static Statement* - make_tuple_map_assignment(Expression* val, Expression* present, - Expression*, source_location); - - // Make a statement which assigns a pair of values to a map. - static Statement* - make_map_assignment(Expression*, Expression* val, - Expression* should_set, source_location); - - // Make an assignment from a nonblocking receive to a pair of - // variables. FOR_SELECT is true is this is being created for a - // case x, ok := <-c in a select statement. - static Statement* - make_tuple_receive_assignment(Expression* val, Expression* closed, - Expression* channel, bool for_select, - source_location); - - // Make an assignment from a type guard to a pair of variables. - static Statement* - make_tuple_type_guard_assignment(Expression* val, Expression* ok, - Expression* expr, Type* type, - source_location); - - // Make an expression statement from an Expression. - static Statement* - make_statement(Expression*); - - // Make a block statement from a Block. This is an embedded list of - // statements which may also include variable definitions. - static Statement* - make_block_statement(Block*, source_location); - - // Make an increment statement. - static Statement* - make_inc_statement(Expression*); - - // Make a decrement statement. - static Statement* - make_dec_statement(Expression*); - - // Make a go statement. - static Statement* - make_go_statement(Call_expression* call, source_location); - - // Make a defer statement. - static Statement* - make_defer_statement(Call_expression* call, source_location); - - // Make a return statement. - static Statement* - make_return_statement(Expression_list*, source_location); - - // Make a break statement. - static Statement* - make_break_statement(Unnamed_label* label, source_location); - - // Make a continue statement. - static Statement* - make_continue_statement(Unnamed_label* label, source_location); - - // Make a goto statement. - static Statement* - make_goto_statement(Label* label, source_location); - - // Make a goto statement to an unnamed label. - static Statement* - make_goto_unnamed_statement(Unnamed_label* label, source_location); - - // Make a label statement--where the label is defined. - static Statement* - make_label_statement(Label* label, source_location); - - // Make an unnamed label statement--where the label is defined. - static Statement* - make_unnamed_label_statement(Unnamed_label* label); - - // Make an if statement. - static Statement* - make_if_statement(Expression* cond, Block* then_block, Block* else_block, - source_location); - - // Make a switch statement. - static Switch_statement* - make_switch_statement(Expression* switch_val, source_location); - - // Make a type switch statement. - static Type_switch_statement* - make_type_switch_statement(Named_object* var, Expression*, source_location); - - // Make a send statement. - static Send_statement* - make_send_statement(Expression* channel, Expression* val, source_location); - - // Make a select statement. - static Select_statement* - make_select_statement(source_location); - - // Make a for statement. - static For_statement* - make_for_statement(Block* init, Expression* cond, Block* post, - source_location location); - - // Make a for statement with a range clause. - static For_range_statement* - make_for_range_statement(Expression* index_var, Expression* value_var, - Expression* range, source_location); - - // Return the statement classification. - Statement_classification - classification() const - { return this->classification_; } - - // Get the statement location. - source_location - location() const - { return this->location_; } - - // Traverse the tree. - int - traverse(Block*, size_t* index, Traverse*); - - // Traverse the contents of this statement--the expressions and - // statements which it contains. - int - traverse_contents(Traverse*); - - // If this statement assigns some values, it calls a function for - // each value to which this statement assigns a value, and returns - // true. If this statement does not assign any values, it returns - // false. - bool - traverse_assignments(Traverse_assignments* tassign); - - // Lower a statement. This is called immediately after parsing to - // simplify statements for further processing. It returns the same - // Statement or a new one. FUNCTION is the function containing this - // statement. BLOCK is the block containing this statement. - Statement* - lower(Gogo* gogo, Named_object* function, Block* block) - { return this->do_lower(gogo, function, block); } - - // Set type information for unnamed constants. - void - determine_types(); - - // Check types in a statement. This simply checks that any - // expressions used by the statement have the right type. - void - check_types(Gogo* gogo) - { this->do_check_types(gogo); } - - // Return whether this is a block statement. - bool - is_block_statement() const - { return this->classification_ == STATEMENT_BLOCK; } - - // If this is a variable declaration statement, return it. - // Otherwise return NULL. - Variable_declaration_statement* - variable_declaration_statement() - { - return this->convert(); - } - - // If this is a return statement, return it. Otherwise return NULL. - Return_statement* - return_statement() - { return this->convert(); } - - // If this is a thunk statement (a go or defer statement), return - // it. Otherwise return NULL. - Thunk_statement* - thunk_statement(); - - // If this is a label statement, return it. Otherwise return NULL. - Label_statement* - label_statement() - { return this->convert(); } - - // If this is a for statement, return it. Otherwise return NULL. - For_statement* - for_statement() - { return this->convert(); } - - // If this is a for statement over a range clause, return it. - // Otherwise return NULL. - For_range_statement* - for_range_statement() - { return this->convert(); } - - // If this is a switch statement, return it. Otherwise return NULL. - Switch_statement* - switch_statement() - { return this->convert(); } - - // If this is a type switch statement, return it. Otherwise return - // NULL. - Type_switch_statement* - type_switch_statement() - { return this->convert(); } - - // If this is a select statement, return it. Otherwise return NULL. - Select_statement* - select_statement() - { return this->convert(); } - - // Return true if this statement may fall through--if after - // executing this statement we may go on to execute the following - // statement, if any. - bool - may_fall_through() const - { return this->do_may_fall_through(); } - - // Convert the statement to the backend representation. - Bstatement* - get_backend(Translate_context*); - - protected: - // Implemented by child class: traverse the tree. - virtual int - do_traverse(Traverse*) = 0; - - // Implemented by child class: traverse assignments. Any statement - // which includes an assignment should implement this. - virtual bool - do_traverse_assignments(Traverse_assignments*) - { return false; } - - // Implemented by the child class: lower this statement to a simpler - // one. - virtual Statement* - do_lower(Gogo*, Named_object*, Block*) - { return this; } - - // Implemented by child class: set type information for unnamed - // constants. Any statement which includes an expression needs to - // implement this. - virtual void - do_determine_types() - { } - - // Implemented by child class: check types of expressions used in a - // statement. - virtual void - do_check_types(Gogo*) - { } - - // Implemented by child class: return true if this statement may - // fall through. - virtual bool - do_may_fall_through() const - { return true; } - - // Implemented by child class: convert to backend representation. - virtual Bstatement* - do_get_backend(Translate_context*) = 0; - - // Traverse an expression in a statement. - int - traverse_expression(Traverse*, Expression**); - - // Traverse an expression list in a statement. The Expression_list - // may be NULL. - int - traverse_expression_list(Traverse*, Expression_list*); - - // Traverse a type in a statement. - int - traverse_type(Traverse*, Type*); - - // For children to call when they detect that they are in error. - void - set_is_error(); - - // For children to call to report an error conveniently. - void - report_error(const char*); - - // For children to return an error statement from lower(). - static Statement* - make_error_statement(source_location); - - private: - // Convert to the desired statement classification, or return NULL. - // This is a controlled dynamic cast. - template - Statement_class* - convert() - { - return (this->classification_ == sc - ? static_cast(this) - : NULL); - } - - template - const Statement_class* - convert() const - { - return (this->classification_ == sc - ? static_cast(this) - : NULL); - } - - // The statement classification. - Statement_classification classification_; - // The location in the input file of the start of this statement. - source_location location_; -}; - -// A statement which creates and initializes a temporary variable. - -class Temporary_statement : public Statement -{ - public: - Temporary_statement(Type* type, Expression* init, source_location location) - : Statement(STATEMENT_TEMPORARY, location), - type_(type), init_(init), bvariable_(NULL), is_address_taken_(false) - { } - - // Return the type of the temporary variable. - Type* - type() const; - - // Record that something takes the address of this temporary - // variable. - void - set_is_address_taken() - { this->is_address_taken_ = true; } - - // Return the temporary variable. This should not be called until - // after the statement itself has been converted. - Bvariable* - get_backend_variable(Translate_context*) const; - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - Bstatement* - do_get_backend(Translate_context*); - - private: - // The type of the temporary variable. - Type* type_; - // The initial value of the temporary variable. This may be NULL. - Expression* init_; - // The backend representation of the temporary variable. - Bvariable* bvariable_; - // True if something takes the address of this temporary variable. - bool is_address_taken_; -}; - -// A variable declaration. This marks the point in the code where a -// variable is declared. The Variable is also attached to a Block. - -class Variable_declaration_statement : public Statement -{ - public: - Variable_declaration_statement(Named_object* var); - - // The variable being declared. - Named_object* - var() - { return this->var_; } - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*); - - Bstatement* - do_get_backend(Translate_context*); - - private: - Named_object* var_; -}; - -// A return statement. - -class Return_statement : public Statement -{ - public: - Return_statement(Expression_list* vals, source_location location) - : Statement(STATEMENT_RETURN, location), - vals_(vals), is_lowered_(false) - { } - - // The list of values being returned. This may be NULL. - const Expression_list* - vals() const - { return this->vals_; } - - protected: - int - do_traverse(Traverse* traverse) - { return this->traverse_expression_list(traverse, this->vals_); } - - bool - do_traverse_assignments(Traverse_assignments*); - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - bool - do_may_fall_through() const - { return false; } - - Bstatement* - do_get_backend(Translate_context*); - - private: - // Return values. This may be NULL. - Expression_list* vals_; - // True if this statement has been lowered. - bool is_lowered_; -}; - -// A send statement. - -class Send_statement : public Statement -{ - public: - Send_statement(Expression* channel, Expression* val, - source_location location) - : Statement(STATEMENT_SEND, location), - channel_(channel), val_(val), for_select_(false) - { } - - // Note that this is for a select statement. - void - set_for_select() - { this->for_select_ = true; } - - protected: - int - do_traverse(Traverse* traverse); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - Bstatement* - do_get_backend(Translate_context*); - - private: - // The channel on which to send the value. - Expression* channel_; - // The value to send. - Expression* val_; - // Whether this is for a select statement. - bool for_select_; -}; - -// Select_clauses holds the clauses of a select statement. This is -// built by the parser. - -class Select_clauses -{ - public: - Select_clauses() - : clauses_() - { } - - // Add a new clause. IS_SEND is true if this is a send clause, - // false for a receive clause. For a send clause CHANNEL is the - // channel and VAL is the value to send. For a receive clause - // CHANNEL is the channel, VAL is either NULL or a Var_expression - // for the variable to set, and CLOSED is either NULL or a - // Var_expression to set to whether the channel is closed. If VAL - // is NULL, VAR may be a variable to be initialized with the - // received value, and CLOSEDVAR ma be a variable to be initialized - // with whether the channel is closed. IS_DEFAULT is true if this - // is the default clause. STATEMENTS is the list of statements to - // execute. - void - add(bool is_send, Expression* channel, Expression* val, Expression* closed, - Named_object* var, Named_object* closedvar, bool is_default, - Block* statements, source_location location) - { - this->clauses_.push_back(Select_clause(is_send, channel, val, closed, var, - closedvar, is_default, statements, - location)); - } - - // Traverse the select clauses. - int - traverse(Traverse*); - - // Lower statements. - void - lower(Gogo*, Named_object*, Block*); - - // Determine types. - void - determine_types(); - - // Whether the select clauses may fall through to the statement - // which follows the overall select statement. - bool - may_fall_through() const; - - // Convert to the backend representation. - Bstatement* - get_backend(Translate_context*, Unnamed_label* break_label, source_location); - - private: - // A single clause. - class Select_clause - { - public: - Select_clause() - : channel_(NULL), val_(NULL), closed_(NULL), var_(NULL), - closedvar_(NULL), statements_(NULL), is_send_(false), - is_default_(false) - { } - - Select_clause(bool is_send, Expression* channel, Expression* val, - Expression* closed, Named_object* var, - Named_object* closedvar, bool is_default, Block* statements, - source_location location) - : channel_(channel), val_(val), closed_(closed), var_(var), - closedvar_(closedvar), statements_(statements), location_(location), - is_send_(is_send), is_default_(is_default), is_lowered_(false) - { go_assert(is_default ? channel == NULL : channel != NULL); } - - // Traverse the select clause. - int - traverse(Traverse*); - - // Lower statements. - void - lower(Gogo*, Named_object*, Block*); - - // Determine types. - void - determine_types(); - - // Return true if this is the default clause. - bool - is_default() const - { return this->is_default_; } - - // Return the channel. This will return NULL for the default - // clause. - Expression* - channel() const - { return this->channel_; } - - // Return true for a send, false for a receive. - bool - is_send() const - { - go_assert(!this->is_default_); - return this->is_send_; - } - - // Return the statements. - const Block* - statements() const - { return this->statements_; } - - // Return the location. - source_location - location() const - { return this->location_; } - - // Whether this clause may fall through to the statement which - // follows the overall select statement. - bool - may_fall_through() const; - - // Convert the statements to the backend representation. - Bstatement* - get_statements_backend(Translate_context*); - - private: - // The channel. - Expression* channel_; - // The value to send or the lvalue to receive into. - Expression* val_; - // The lvalue to set to whether the channel is closed on a - // receive. - Expression* closed_; - // The variable to initialize, for "case a := <-ch". - Named_object* var_; - // The variable to initialize to whether the channel is closed, - // for "case a, c := <-ch". - Named_object* closedvar_; - // The statements to execute. - Block* statements_; - // The location of this clause. - source_location location_; - // Whether this is a send or a receive. - bool is_send_; - // Whether this is the default. - bool is_default_; - // Whether this has been lowered. - bool is_lowered_; - }; - - void - add_clause_backend(Translate_context*, source_location, int index, - int case_value, Select_clause*, Unnamed_label*, - std::vector >* cases, - std::vector* clauses); - - typedef std::vector Clauses; - - Clauses clauses_; -}; - -// A select statement. - -class Select_statement : public Statement -{ - public: - Select_statement(source_location location) - : Statement(STATEMENT_SELECT, location), - clauses_(NULL), break_label_(NULL), is_lowered_(false) - { } - - // Add the clauses. - void - add_clauses(Select_clauses* clauses) - { - go_assert(this->clauses_ == NULL); - this->clauses_ = clauses; - } - - // Return the break label for this select statement. - Unnamed_label* - break_label(); - - protected: - int - do_traverse(Traverse* traverse) - { return this->clauses_->traverse(traverse); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - void - do_determine_types() - { this->clauses_->determine_types(); } - - bool - do_may_fall_through() const - { return this->clauses_->may_fall_through(); } - - Bstatement* - do_get_backend(Translate_context*); - - private: - // The select clauses. - Select_clauses* clauses_; - // The break label. - Unnamed_label* break_label_; - // Whether this statement has been lowered. - bool is_lowered_; -}; - -// A statement which requires a thunk: go or defer. - -class Thunk_statement : public Statement -{ - public: - Thunk_statement(Statement_classification, Call_expression*, - source_location); - - // Return the call expression. - Expression* - call() - { return this->call_; } - - // Simplify a go or defer statement so that it only uses a single - // parameter. - bool - simplify_statement(Gogo*, Named_object*, Block*); - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - // Return the function and argument for the call. - bool - get_fn_and_arg(Expression** pfn, Expression** parg); - - private: - // Return whether this is a simple go statement. - bool - is_simple(Function_type*) const; - - // Build the struct to use for a complex case. - Struct_type* - build_struct(Function_type* fntype); - - // Build the thunk. - void - build_thunk(Gogo*, const std::string&, Function_type* fntype); - - // The field name used in the thunk structure for the function - // pointer. - static const char* const thunk_field_fn; - - // The field name used in the thunk structure for the receiver, if - // there is one. - static const char* const thunk_field_receiver; - - // Set the name to use for thunk field N. - void - thunk_field_param(int n, char* buf, size_t buflen); - - // The function call to be executed in a separate thread (go) or - // later (defer). - Expression* call_; - // The type used for a struct to pass to a thunk, if this is not a - // simple call. - Struct_type* struct_type_; -}; - -// A go statement. - -class Go_statement : public Thunk_statement -{ - public: - Go_statement(Call_expression* call, source_location location) - : Thunk_statement(STATEMENT_GO, call, location) - { } - - protected: - Bstatement* - do_get_backend(Translate_context*); -}; - -// A defer statement. - -class Defer_statement : public Thunk_statement -{ - public: - Defer_statement(Call_expression* call, source_location location) - : Thunk_statement(STATEMENT_DEFER, call, location) - { } - - protected: - Bstatement* - do_get_backend(Translate_context*); -}; - -// A label statement. - -class Label_statement : public Statement -{ - public: - Label_statement(Label* label, source_location location) - : Statement(STATEMENT_LABEL, location), - label_(label) - { } - - // Return the label itself. - const Label* - label() const - { return this->label_; } - - protected: - int - do_traverse(Traverse*); - - Bstatement* - do_get_backend(Translate_context*); - - private: - // The label. - Label* label_; -}; - -// A for statement. - -class For_statement : public Statement -{ - public: - For_statement(Block* init, Expression* cond, Block* post, - source_location location) - : Statement(STATEMENT_FOR, location), - init_(init), cond_(cond), post_(post), statements_(NULL), - break_label_(NULL), continue_label_(NULL) - { } - - // Add the statements. - void - add_statements(Block* statements) - { - go_assert(this->statements_ == NULL); - this->statements_ = statements; - } - - // Return the break label for this for statement. - Unnamed_label* - break_label(); - - // Return the continue label for this for statement. - Unnamed_label* - continue_label(); - - // Set the break and continue labels for this statement. - void - set_break_continue_labels(Unnamed_label* break_label, - Unnamed_label* continue_label); - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*) - { go_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - Bstatement* - do_get_backend(Translate_context*) - { go_unreachable(); } - - private: - // The initialization statements. This may be NULL. - Block* init_; - // The condition. This may be NULL. - Expression* cond_; - // The statements to run after each iteration. This may be NULL. - Block* post_; - // The statements in the loop itself. - Block* statements_; - // The break label, if needed. - Unnamed_label* break_label_; - // The continue label, if needed. - Unnamed_label* continue_label_; -}; - -// A for statement over a range clause. - -class For_range_statement : public Statement -{ - public: - For_range_statement(Expression* index_var, Expression* value_var, - Expression* range, source_location location) - : Statement(STATEMENT_FOR_RANGE, location), - index_var_(index_var), value_var_(value_var), range_(range), - statements_(NULL), break_label_(NULL), continue_label_(NULL) - { } - - // Add the statements. - void - add_statements(Block* statements) - { - go_assert(this->statements_ == NULL); - this->statements_ = statements; - } - - // Return the break label for this for statement. - Unnamed_label* - break_label(); - - // Return the continue label for this for statement. - Unnamed_label* - continue_label(); - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*) - { go_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - Bstatement* - do_get_backend(Translate_context*) - { go_unreachable(); } - - private: - Expression* - make_range_ref(Named_object*, Temporary_statement*, source_location); - - Expression* - call_builtin(Gogo*, const char* funcname, Expression* arg, source_location); - - void - lower_range_array(Gogo*, Block*, Block*, Named_object*, Temporary_statement*, - Temporary_statement*, Temporary_statement*, - Block**, Expression**, Block**, Block**); - - void - lower_range_string(Gogo*, Block*, Block*, Named_object*, Temporary_statement*, - Temporary_statement*, Temporary_statement*, - Block**, Expression**, Block**, Block**); - - void - lower_range_map(Gogo*, Block*, Block*, Named_object*, Temporary_statement*, - Temporary_statement*, Temporary_statement*, - Block**, Expression**, Block**, Block**); - - void - lower_range_channel(Gogo*, Block*, Block*, Named_object*, - Temporary_statement*, Temporary_statement*, - Temporary_statement*, Block**, Expression**, Block**, - Block**); - - // The variable which is set to the index value. - Expression* index_var_; - // The variable which is set to the element value. This may be - // NULL. - Expression* value_var_; - // The expression we are ranging over. - Expression* range_; - // The statements in the block. - Block* statements_; - // The break label, if needed. - Unnamed_label* break_label_; - // The continue label, if needed. - Unnamed_label* continue_label_; -}; - -// Class Case_clauses holds the clauses of a switch statement. This -// is built by the parser. - -class Case_clauses -{ - public: - Case_clauses() - : clauses_() - { } - - // Add a new clause. CASES is a list of case expressions; it may be - // NULL. IS_DEFAULT is true if this is the default case. - // STATEMENTS is a block of statements. IS_FALLTHROUGH is true if - // after the statements the case clause should fall through to the - // next clause. - void - add(Expression_list* cases, bool is_default, Block* statements, - bool is_fallthrough, source_location location) - { - this->clauses_.push_back(Case_clause(cases, is_default, statements, - is_fallthrough, location)); - } - - // Return whether there are no clauses. - bool - empty() const - { return this->clauses_.empty(); } - - // Traverse the case clauses. - int - traverse(Traverse*); - - // Lower for a nonconstant switch. - void - lower(Block*, Temporary_statement*, Unnamed_label*) const; - - // Determine types of expressions. The Type parameter is the type - // of the switch value. - void - determine_types(Type*); - - // Check types. The Type parameter is the type of the switch value. - bool - check_types(Type*); - - // Return true if all the clauses are constant values. - bool - is_constant() const; - - // Return true if these clauses may fall through to the statements - // following the switch statement. - bool - may_fall_through() const; - - // Return the body of a SWITCH_EXPR when all the clauses are - // constants. - void - get_backend(Translate_context*, Unnamed_label* break_label, - std::vector >* all_cases, - std::vector* all_statements) const; - - private: - // For a constant switch we need to keep a record of constants we - // have already seen. - class Hash_integer_value; - class Eq_integer_value; - typedef Unordered_set_hash(Expression*, Hash_integer_value, - Eq_integer_value) Case_constants; - - // One case clause. - class Case_clause - { - public: - Case_clause() - : cases_(NULL), statements_(NULL), is_default_(false), - is_fallthrough_(false), location_(UNKNOWN_LOCATION) - { } - - Case_clause(Expression_list* cases, bool is_default, Block* statements, - bool is_fallthrough, source_location location) - : cases_(cases), statements_(statements), is_default_(is_default), - is_fallthrough_(is_fallthrough), location_(location) - { } - - // Whether this clause falls through to the next clause. - bool - is_fallthrough() const - { return this->is_fallthrough_; } - - // Whether this is the default. - bool - is_default() const - { return this->is_default_; } - - // The location of this clause. - source_location - location() const - { return this->location_; } - - // Traversal. - int - traverse(Traverse*); - - // Lower for a nonconstant switch. - void - lower(Block*, Temporary_statement*, Unnamed_label*, Unnamed_label*) const; - - // Determine types. - void - determine_types(Type*); - - // Check types. - bool - check_types(Type*); - - // Return true if all the case expressions are constant. - bool - is_constant() const; - - // Return true if this clause may fall through to execute the - // statements following the switch statement. This is not the - // same as whether this clause falls through to the next clause. - bool - may_fall_through() const; - - // Convert the case values and statements to the backend - // representation. - Bstatement* - get_backend(Translate_context*, Unnamed_label* break_label, - Case_constants*, std::vector* cases) const; - - private: - // The list of case expressions. - Expression_list* cases_; - // The statements to execute. - Block* statements_; - // Whether this is the default case. - bool is_default_; - // Whether this falls through after the statements. - bool is_fallthrough_; - // The location of this case clause. - source_location location_; - }; - - friend class Case_clause; - - // The type of the list of clauses. - typedef std::vector Clauses; - - // All the case clauses. - Clauses clauses_; -}; - -// A switch statement. - -class Switch_statement : public Statement -{ - public: - Switch_statement(Expression* val, source_location location) - : Statement(STATEMENT_SWITCH, location), - val_(val), clauses_(NULL), break_label_(NULL) - { } - - // Add the clauses. - void - add_clauses(Case_clauses* clauses) - { - go_assert(this->clauses_ == NULL); - this->clauses_ = clauses; - } - - // Return the break label for this switch statement. - Unnamed_label* - break_label(); - - protected: - int - do_traverse(Traverse*); - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - Bstatement* - do_get_backend(Translate_context*) - { go_unreachable(); } - - private: - // The value to switch on. This may be NULL. - Expression* val_; - // The case clauses. - Case_clauses* clauses_; - // The break label, if needed. - Unnamed_label* break_label_; -}; - -// Class Type_case_clauses holds the clauses of a type switch -// statement. This is built by the parser. - -class Type_case_clauses -{ - public: - Type_case_clauses() - : clauses_() - { } - - // Add a new clause. TYPE is the type for this clause; it may be - // NULL. IS_FALLTHROUGH is true if this falls through to the next - // clause; in this case STATEMENTS will be NULL. IS_DEFAULT is true - // if this is the default case. STATEMENTS is a block of - // statements; it may be NULL. - void - add(Type* type, bool is_fallthrough, bool is_default, Block* statements, - source_location location) - { - this->clauses_.push_back(Type_case_clause(type, is_fallthrough, is_default, - statements, location)); - } - - // Return whether there are no clauses. - bool - empty() const - { return this->clauses_.empty(); } - - // Traverse the type case clauses. - int - traverse(Traverse*); - - // Check for duplicates. - void - check_duplicates() const; - - // Lower to if and goto statements. - void - lower(Block*, Temporary_statement* descriptor_temp, - Unnamed_label* break_label) const; - - private: - // One type case clause. - class Type_case_clause - { - public: - Type_case_clause() - : type_(NULL), statements_(NULL), is_default_(false), - location_(UNKNOWN_LOCATION) - { } - - Type_case_clause(Type* type, bool is_fallthrough, bool is_default, - Block* statements, source_location location) - : type_(type), statements_(statements), is_fallthrough_(is_fallthrough), - is_default_(is_default), location_(location) - { } - - // The type. - Type* - type() const - { return this->type_; } - - // Whether this is the default. - bool - is_default() const - { return this->is_default_; } - - // The location of this type clause. - source_location - location() const - { return this->location_; } - - // Traversal. - int - traverse(Traverse*); - - // Lower to if and goto statements. - void - lower(Block*, Temporary_statement* descriptor_temp, - Unnamed_label* break_label, Unnamed_label** stmts_label) const; - - private: - // The type for this type clause. - Type* type_; - // The statements to execute. - Block* statements_; - // Whether this falls through--this is true for "case T1, T2". - bool is_fallthrough_; - // Whether this is the default case. - bool is_default_; - // The location of this type case clause. - source_location location_; - }; - - friend class Type_case_clause; - - // The type of the list of type clauses. - typedef std::vector Type_clauses; - - // All the type case clauses. - Type_clauses clauses_; -}; - -// A type switch statement. - -class Type_switch_statement : public Statement -{ - public: - Type_switch_statement(Named_object* var, Expression* expr, - source_location location) - : Statement(STATEMENT_TYPE_SWITCH, location), - var_(var), expr_(expr), clauses_(NULL), break_label_(NULL) - { go_assert(var == NULL || expr == NULL); } - - // Add the clauses. - void - add_clauses(Type_case_clauses* clauses) - { - go_assert(this->clauses_ == NULL); - this->clauses_ = clauses; - } - - // Return the break label for this type switch statement. - Unnamed_label* - break_label(); - - protected: - int - do_traverse(Traverse*); - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - Bstatement* - do_get_backend(Translate_context*) - { go_unreachable(); } - - private: - // The variable holding the value we are switching on. - Named_object* var_; - // The expression we are switching on if there is no variable. - Expression* expr_; - // The type case clauses. - Type_case_clauses* clauses_; - // The break label, if needed. - Unnamed_label* break_label_; -}; - -#endif // !defined(GO_STATEMENTS_H) diff --git a/gcc/go/gofrontend/statements.h.working b/gcc/go/gofrontend/statements.h.working deleted file mode 100644 index 5199981ea64..00000000000 --- a/gcc/go/gofrontend/statements.h.working +++ /dev/null @@ -1,1461 +0,0 @@ -// statements.h -- Go frontend statements. -*- C++ -*- - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#ifndef GO_STATEMENTS_H -#define GO_STATEMENTS_H - -#include "operator.h" - -class Gogo; -class Traverse; -class Block; -class Function; -class Unnamed_label; -class Temporary_statement; -class Variable_declaration_statement; -class Return_statement; -class Thunk_statement; -class Label_statement; -class For_statement; -class For_range_statement; -class Switch_statement; -class Type_switch_statement; -class Send_statement; -class Select_statement; -class Variable; -class Named_object; -class Label; -class Translate_context; -class Expression; -class Expression_list; -class Struct_type; -class Call_expression; -class Map_index_expression; -class Receive_expression; -class Case_clauses; -class Type_case_clauses; -class Select_clauses; -class Typed_identifier_list; - -// This class is used to traverse assignments made by a statement -// which makes assignments. - -class Traverse_assignments -{ - public: - Traverse_assignments() - { } - - virtual ~Traverse_assignments() - { } - - // This is called for a variable initialization. - virtual void - initialize_variable(Named_object*) = 0; - - // This is called for each assignment made by the statement. PLHS - // points to the left hand side, and PRHS points to the right hand - // side. PRHS may be NULL if there is no associated expression, as - // in the bool set by a non-blocking receive. - virtual void - assignment(Expression** plhs, Expression** prhs) = 0; - - // This is called for each expression which is not passed to the - // assignment function. This is used for some of the statements - // which assign two values, for which there is no expression which - // describes the value. For ++ and -- the value is passed to both - // the assignment method and the rhs method. IS_STORED is true if - // this value is being stored directly. It is false if the value is - // computed but not stored. IS_LOCAL is true if the value is being - // stored in a local variable or this is being called by a return - // statement. - virtual void - value(Expression**, bool is_stored, bool is_local) = 0; -}; - -// A single statement. - -class Statement -{ - public: - // The types of statements. - enum Statement_classification - { - STATEMENT_ERROR, - STATEMENT_VARIABLE_DECLARATION, - STATEMENT_TEMPORARY, - STATEMENT_ASSIGNMENT, - STATEMENT_EXPRESSION, - STATEMENT_BLOCK, - STATEMENT_GO, - STATEMENT_DEFER, - STATEMENT_RETURN, - STATEMENT_BREAK_OR_CONTINUE, - STATEMENT_GOTO, - STATEMENT_GOTO_UNNAMED, - STATEMENT_LABEL, - STATEMENT_UNNAMED_LABEL, - STATEMENT_IF, - STATEMENT_CONSTANT_SWITCH, - STATEMENT_SEND, - STATEMENT_SELECT, - - // These statements types are created by the parser, but they - // disappear during the lowering pass. - STATEMENT_ASSIGNMENT_OPERATION, - STATEMENT_TUPLE_ASSIGNMENT, - STATEMENT_TUPLE_MAP_ASSIGNMENT, - STATEMENT_MAP_ASSIGNMENT, - STATEMENT_TUPLE_RECEIVE_ASSIGNMENT, - STATEMENT_TUPLE_TYPE_GUARD_ASSIGNMENT, - STATEMENT_INCDEC, - STATEMENT_FOR, - STATEMENT_FOR_RANGE, - STATEMENT_SWITCH, - STATEMENT_TYPE_SWITCH - }; - - Statement(Statement_classification, source_location); - - virtual ~Statement(); - - // Make a variable declaration. - static Statement* - make_variable_declaration(Named_object*); - - // Make a statement which creates a temporary variable and - // initializes it to an expression. The block is used if the - // temporary variable has to be explicitly destroyed; the variable - // must still be added to the block. References to the temporary - // variable may be constructed using make_temporary_reference. - // Either the type or the initialization expression may be NULL, but - // not both. - static Temporary_statement* - make_temporary(Type*, Expression*, source_location); - - // Make an assignment statement. - static Statement* - make_assignment(Expression*, Expression*, source_location); - - // Make an assignment operation (+=, etc.). - static Statement* - make_assignment_operation(Operator, Expression*, Expression*, - source_location); - - // Make a tuple assignment statement. - static Statement* - make_tuple_assignment(Expression_list*, Expression_list*, source_location); - - // Make an assignment from a map index to a pair of variables. - static Statement* - make_tuple_map_assignment(Expression* val, Expression* present, - Expression*, source_location); - - // Make a statement which assigns a pair of values to a map. - static Statement* - make_map_assignment(Expression*, Expression* val, - Expression* should_set, source_location); - - // Make an assignment from a nonblocking receive to a pair of - // variables. FOR_SELECT is true is this is being created for a - // case x, ok := <-c in a select statement. - static Statement* - make_tuple_receive_assignment(Expression* val, Expression* closed, - Expression* channel, bool for_select, - source_location); - - // Make an assignment from a type guard to a pair of variables. - static Statement* - make_tuple_type_guard_assignment(Expression* val, Expression* ok, - Expression* expr, Type* type, - source_location); - - // Make an expression statement from an Expression. - static Statement* - make_statement(Expression*); - - // Make a block statement from a Block. This is an embedded list of - // statements which may also include variable definitions. - static Statement* - make_block_statement(Block*, source_location); - - // Make an increment statement. - static Statement* - make_inc_statement(Expression*); - - // Make a decrement statement. - static Statement* - make_dec_statement(Expression*); - - // Make a go statement. - static Statement* - make_go_statement(Call_expression* call, source_location); - - // Make a defer statement. - static Statement* - make_defer_statement(Call_expression* call, source_location); - - // Make a return statement. - static Statement* - make_return_statement(const Typed_identifier_list*, Expression_list*, - source_location); - - // Make a break statement. - static Statement* - make_break_statement(Unnamed_label* label, source_location); - - // Make a continue statement. - static Statement* - make_continue_statement(Unnamed_label* label, source_location); - - // Make a goto statement. - static Statement* - make_goto_statement(Label* label, source_location); - - // Make a goto statement to an unnamed label. - static Statement* - make_goto_unnamed_statement(Unnamed_label* label, source_location); - - // Make a label statement--where the label is defined. - static Statement* - make_label_statement(Label* label, source_location); - - // Make an unnamed label statement--where the label is defined. - static Statement* - make_unnamed_label_statement(Unnamed_label* label); - - // Make an if statement. - static Statement* - make_if_statement(Expression* cond, Block* then_block, Block* else_block, - source_location); - - // Make a switch statement. - static Switch_statement* - make_switch_statement(Expression* switch_val, source_location); - - // Make a type switch statement. - static Type_switch_statement* - make_type_switch_statement(Named_object* var, Expression*, source_location); - - // Make a send statement. - static Send_statement* - make_send_statement(Expression* channel, Expression* val, source_location); - - // Make a select statement. - static Select_statement* - make_select_statement(source_location); - - // Make a for statement. - static For_statement* - make_for_statement(Block* init, Expression* cond, Block* post, - source_location location); - - // Make a for statement with a range clause. - static For_range_statement* - make_for_range_statement(Expression* index_var, Expression* value_var, - Expression* range, source_location); - - // Return the statement classification. - Statement_classification - classification() const - { return this->classification_; } - - // Get the statement location. - source_location - location() const - { return this->location_; } - - // Traverse the tree. - int - traverse(Block*, size_t* index, Traverse*); - - // Traverse the contents of this statement--the expressions and - // statements which it contains. - int - traverse_contents(Traverse*); - - // If this statement assigns some values, it calls a function for - // each value to which this statement assigns a value, and returns - // true. If this statement does not assign any values, it returns - // false. - bool - traverse_assignments(Traverse_assignments* tassign); - - // Lower a statement. This is called immediately after parsing to - // simplify statements for further processing. It returns the same - // Statement or a new one. FUNCTION is the function containing this - // statement. BLOCK is the block containing this statement. - Statement* - lower(Gogo* gogo, Named_object* function, Block* block) - { return this->do_lower(gogo, function, block); } - - // Set type information for unnamed constants. - void - determine_types(); - - // Check types in a statement. This simply checks that any - // expressions used by the statement have the right type. - void - check_types(Gogo* gogo) - { this->do_check_types(gogo); } - - // Return whether this is a block statement. - bool - is_block_statement() const - { return this->classification_ == STATEMENT_BLOCK; } - - // If this is a variable declaration statement, return it. - // Otherwise return NULL. - Variable_declaration_statement* - variable_declaration_statement() - { - return this->convert(); - } - - // If this is a return statement, return it. Otherwise return NULL. - Return_statement* - return_statement() - { return this->convert(); } - - // If this is a thunk statement (a go or defer statement), return - // it. Otherwise return NULL. - Thunk_statement* - thunk_statement(); - - // If this is a label statement, return it. Otherwise return NULL. - Label_statement* - label_statement() - { return this->convert(); } - - // If this is a for statement, return it. Otherwise return NULL. - For_statement* - for_statement() - { return this->convert(); } - - // If this is a for statement over a range clause, return it. - // Otherwise return NULL. - For_range_statement* - for_range_statement() - { return this->convert(); } - - // If this is a switch statement, return it. Otherwise return NULL. - Switch_statement* - switch_statement() - { return this->convert(); } - - // If this is a type switch statement, return it. Otherwise return - // NULL. - Type_switch_statement* - type_switch_statement() - { return this->convert(); } - - // If this is a select statement, return it. Otherwise return NULL. - Select_statement* - select_statement() - { return this->convert(); } - - // Return true if this statement may fall through--if after - // executing this statement we may go on to execute the following - // statement, if any. - bool - may_fall_through() const - { return this->do_may_fall_through(); } - - // Return the tree for a statement. BLOCK is the enclosing block. - tree - get_tree(Translate_context*); - - protected: - // Implemented by child class: traverse the tree. - virtual int - do_traverse(Traverse*) = 0; - - // Implemented by child class: traverse assignments. Any statement - // which includes an assignment should implement this. - virtual bool - do_traverse_assignments(Traverse_assignments*) - { return false; } - - // Implemented by the child class: lower this statement to a simpler - // one. - virtual Statement* - do_lower(Gogo*, Named_object*, Block*) - { return this; } - - // Implemented by child class: set type information for unnamed - // constants. Any statement which includes an expression needs to - // implement this. - virtual void - do_determine_types() - { } - - // Implemented by child class: check types of expressions used in a - // statement. - virtual void - do_check_types(Gogo*) - { } - - // Implemented by child class: return true if this statement may - // fall through. - virtual bool - do_may_fall_through() const - { return true; } - - // Implemented by child class: return a tree. - virtual tree - do_get_tree(Translate_context*) = 0; - - // Traverse an expression in a statement. - int - traverse_expression(Traverse*, Expression**); - - // Traverse an expression list in a statement. The Expression_list - // may be NULL. - int - traverse_expression_list(Traverse*, Expression_list*); - - // Traverse a type in a statement. - int - traverse_type(Traverse*, Type*); - - // Build a tree node with one operand, setting the location. The - // first operand really has type "enum tree_code", but that enum is - // not defined here. - tree - build_stmt_1(int tree_code_value, tree); - - // For children to call when they detect that they are in error. - void - set_is_error(); - - // For children to call to report an error conveniently. - void - report_error(const char*); - - // For children to return an error statement from lower(). - static Statement* - make_error_statement(source_location); - - private: - // Convert to the desired statement classification, or return NULL. - // This is a controlled dynamic cast. - template - Statement_class* - convert() - { - return (this->classification_ == sc - ? static_cast(this) - : NULL); - } - - template - const Statement_class* - convert() const - { - return (this->classification_ == sc - ? static_cast(this) - : NULL); - } - - // The statement classification. - Statement_classification classification_; - // The location in the input file of the start of this statement. - source_location location_; -}; - -// A statement which creates and initializes a temporary variable. - -class Temporary_statement : public Statement -{ - public: - Temporary_statement(Type* type, Expression* init, source_location location) - : Statement(STATEMENT_TEMPORARY, location), - type_(type), init_(init), decl_(NULL), is_address_taken_(false) - { } - - // Return the type of the temporary variable. - Type* - type() const; - - // Return the initialization expression. - Expression* - init() const - { return this->init_; } - - // Record that something takes the address of this temporary - // variable. - void - set_is_address_taken() - { this->is_address_taken_ = true; } - - // Return the tree for the temporary variable itself. This should - // not be called until after the statement itself has been expanded. - tree - get_decl() const; - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - tree - do_get_tree(Translate_context*); - - private: - // The type of the temporary variable. - Type* type_; - // The initial value of the temporary variable. This may be NULL. - Expression* init_; - // The DECL for the temporary variable. - tree decl_; - // True if something takes the address of this temporary variable. - bool is_address_taken_; -}; - -// A variable declaration. This marks the point in the code where a -// variable is declared. The Variable is also attached to a Block. - -class Variable_declaration_statement : public Statement -{ - public: - Variable_declaration_statement(Named_object* var); - - // The variable being declared. - Named_object* - var() - { return this->var_; } - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*); - - tree - do_get_tree(Translate_context*); - - private: - Named_object* var_; -}; - -// A return statement. - -class Return_statement : public Statement -{ - public: - Return_statement(const Typed_identifier_list* results, Expression_list* vals, - source_location location) - : Statement(STATEMENT_RETURN, location), - results_(results), vals_(vals) - { } - - // The list of values being returned. This may be NULL. - const Expression_list* - vals() const - { return this->vals_; } - - protected: - int - do_traverse(Traverse* traverse) - { return this->traverse_expression_list(traverse, this->vals_); } - - bool - do_traverse_assignments(Traverse_assignments*); - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - bool - do_may_fall_through() const - { return false; } - - tree - do_get_tree(Translate_context*); - - private: - // The result types of the function we are returning from. This is - // here because in some of the traversals it is inconvenient to get - // it. - const Typed_identifier_list* results_; - // Return values. This may be NULL. - Expression_list* vals_; -}; - -// A send statement. - -class Send_statement : public Statement -{ - public: - Send_statement(Expression* channel, Expression* val, - source_location location) - : Statement(STATEMENT_SEND, location), - channel_(channel), val_(val), for_select_(false) - { } - - // Note that this is for a select statement. - void - set_for_select() - { this->for_select_ = true; } - - protected: - int - do_traverse(Traverse* traverse); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - tree - do_get_tree(Translate_context*); - - private: - // The channel on which to send the value. - Expression* channel_; - // The value to send. - Expression* val_; - // Whether this is for a select statement. - bool for_select_; -}; - -// Select_clauses holds the clauses of a select statement. This is -// built by the parser. - -class Select_clauses -{ - public: - Select_clauses() - : clauses_() - { } - - // Add a new clause. IS_SEND is true if this is a send clause, - // false for a receive clause. For a send clause CHANNEL is the - // channel and VAL is the value to send. For a receive clause - // CHANNEL is the channel, VAL is either NULL or a Var_expression - // for the variable to set, and CLOSED is either NULL or a - // Var_expression to set to whether the channel is closed. If VAL - // is NULL, VAR may be a variable to be initialized with the - // received value, and CLOSEDVAR ma be a variable to be initialized - // with whether the channel is closed. IS_DEFAULT is true if this - // is the default clause. STATEMENTS is the list of statements to - // execute. - void - add(bool is_send, Expression* channel, Expression* val, Expression* closed, - Named_object* var, Named_object* closedvar, bool is_default, - Block* statements, source_location location) - { - this->clauses_.push_back(Select_clause(is_send, channel, val, closed, var, - closedvar, is_default, statements, - location)); - } - - // Traverse the select clauses. - int - traverse(Traverse*); - - // Lower statements. - void - lower(Gogo*, Named_object*, Block*); - - // Determine types. - void - determine_types(); - - // Whether the select clauses may fall through to the statement - // which follows the overall select statement. - bool - may_fall_through() const; - - // Return a tree implementing the select statement. - tree - get_tree(Translate_context*, Unnamed_label* break_label, source_location); - - private: - // A single clause. - class Select_clause - { - public: - Select_clause() - : channel_(NULL), val_(NULL), closed_(NULL), var_(NULL), - closedvar_(NULL), statements_(NULL), is_send_(false), - is_default_(false) - { } - - Select_clause(bool is_send, Expression* channel, Expression* val, - Expression* closed, Named_object* var, - Named_object* closedvar, bool is_default, Block* statements, - source_location location) - : channel_(channel), val_(val), closed_(closed), var_(var), - closedvar_(closedvar), statements_(statements), location_(location), - is_send_(is_send), is_default_(is_default), is_lowered_(false) - { gcc_assert(is_default ? channel == NULL : channel != NULL); } - - // Traverse the select clause. - int - traverse(Traverse*); - - // Lower statements. - void - lower(Gogo*, Named_object*, Block*); - - // Determine types. - void - determine_types(); - - // Return true if this is the default clause. - bool - is_default() const - { return this->is_default_; } - - // Return the channel. This will return NULL for the default - // clause. - Expression* - channel() const - { return this->channel_; } - - // Return true for a send, false for a receive. - bool - is_send() const - { - gcc_assert(!this->is_default_); - return this->is_send_; - } - - // Return the statements. - const Block* - statements() const - { return this->statements_; } - - // Return the location. - source_location - location() const - { return this->location_; } - - // Whether this clause may fall through to the statement which - // follows the overall select statement. - bool - may_fall_through() const; - - // Return a tree for the statements to execute. - tree - get_statements_tree(Translate_context*); - - private: - // The channel. - Expression* channel_; - // The value to send or the lvalue to receive into. - Expression* val_; - // The lvalue to set to whether the channel is closed on a - // receive. - Expression* closed_; - // The variable to initialize, for "case a := <-ch". - Named_object* var_; - // The variable to initialize to whether the channel is closed, - // for "case a, c := <-ch". - Named_object* closedvar_; - // The statements to execute. - Block* statements_; - // The location of this clause. - source_location location_; - // Whether this is a send or a receive. - bool is_send_; - // Whether this is the default. - bool is_default_; - // Whether this has been lowered. - bool is_lowered_; - }; - - void - add_clause_tree(Translate_context*, int, Select_clause*, Unnamed_label*, - tree*); - - typedef std::vector Clauses; - - Clauses clauses_; -}; - -// A select statement. - -class Select_statement : public Statement -{ - public: - Select_statement(source_location location) - : Statement(STATEMENT_SELECT, location), - clauses_(NULL), break_label_(NULL), is_lowered_(false) - { } - - // Add the clauses. - void - add_clauses(Select_clauses* clauses) - { - gcc_assert(this->clauses_ == NULL); - this->clauses_ = clauses; - } - - // Return the break label for this select statement. - Unnamed_label* - break_label(); - - protected: - int - do_traverse(Traverse* traverse) - { return this->clauses_->traverse(traverse); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - void - do_determine_types() - { this->clauses_->determine_types(); } - - bool - do_may_fall_through() const - { return this->clauses_->may_fall_through(); } - - tree - do_get_tree(Translate_context*); - - private: - // The select clauses. - Select_clauses* clauses_; - // The break label. - Unnamed_label* break_label_; - // Whether this statement has been lowered. - bool is_lowered_; -}; - -// A statement which requires a thunk: go or defer. - -class Thunk_statement : public Statement -{ - public: - Thunk_statement(Statement_classification, Call_expression*, - source_location); - - // Return the call expression. - Expression* - call() - { return this->call_; } - - // Simplify a go or defer statement so that it only uses a single - // parameter. - bool - simplify_statement(Gogo*, Block*); - - protected: - int - do_traverse(Traverse* traverse); - - bool - do_traverse_assignments(Traverse_assignments*); - - void - do_determine_types(); - - void - do_check_types(Gogo*); - - // Return the function and argument trees for the call. - void - get_fn_and_arg(Translate_context*, tree* pfn, tree* parg); - - private: - // Return whether this is a simple go statement. - bool - is_simple(Function_type*) const; - - // Build the struct to use for a complex case. - Struct_type* - build_struct(Function_type* fntype); - - // Build the thunk. - void - build_thunk(Gogo*, const std::string&, Function_type* fntype); - - // The field name used in the thunk structure for the function - // pointer. - static const char* const thunk_field_fn; - - // The field name used in the thunk structure for the receiver, if - // there is one. - static const char* const thunk_field_receiver; - - // Set the name to use for thunk field N. - void - thunk_field_param(int n, char* buf, size_t buflen); - - // The function call to be executed in a separate thread (go) or - // later (defer). - Expression* call_; - // The type used for a struct to pass to a thunk, if this is not a - // simple call. - Struct_type* struct_type_; -}; - -// A go statement. - -class Go_statement : public Thunk_statement -{ - public: - Go_statement(Call_expression* call, source_location location) - : Thunk_statement(STATEMENT_GO, call, location) - { } - - protected: - tree - do_get_tree(Translate_context*); -}; - -// A defer statement. - -class Defer_statement : public Thunk_statement -{ - public: - Defer_statement(Call_expression* call, source_location location) - : Thunk_statement(STATEMENT_DEFER, call, location) - { } - - protected: - tree - do_get_tree(Translate_context*); -}; - -// A label statement. - -class Label_statement : public Statement -{ - public: - Label_statement(Label* label, source_location location) - : Statement(STATEMENT_LABEL, location), - label_(label) - { } - - // Return the label itself. - const Label* - label() const - { return this->label_; } - - protected: - int - do_traverse(Traverse*); - - tree - do_get_tree(Translate_context*); - - private: - // The label. - Label* label_; -}; - -// A for statement. - -class For_statement : public Statement -{ - public: - For_statement(Block* init, Expression* cond, Block* post, - source_location location) - : Statement(STATEMENT_FOR, location), - init_(init), cond_(cond), post_(post), statements_(NULL), - break_label_(NULL), continue_label_(NULL) - { } - - // Add the statements. - void - add_statements(Block* statements) - { - gcc_assert(this->statements_ == NULL); - this->statements_ = statements; - } - - // Return the break label for this for statement. - Unnamed_label* - break_label(); - - // Return the continue label for this for statement. - Unnamed_label* - continue_label(); - - // Set the break and continue labels for this statement. - void - set_break_continue_labels(Unnamed_label* break_label, - Unnamed_label* continue_label); - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // The initialization statements. This may be NULL. - Block* init_; - // The condition. This may be NULL. - Expression* cond_; - // The statements to run after each iteration. This may be NULL. - Block* post_; - // The statements in the loop itself. - Block* statements_; - // The break label, if needed. - Unnamed_label* break_label_; - // The continue label, if needed. - Unnamed_label* continue_label_; -}; - -// A for statement over a range clause. - -class For_range_statement : public Statement -{ - public: - For_range_statement(Expression* index_var, Expression* value_var, - Expression* range, source_location location) - : Statement(STATEMENT_FOR_RANGE, location), - index_var_(index_var), value_var_(value_var), range_(range), - statements_(NULL), break_label_(NULL), continue_label_(NULL) - { } - - // Add the statements. - void - add_statements(Block* statements) - { - gcc_assert(this->statements_ == NULL); - this->statements_ = statements; - } - - // Return the break label for this for statement. - Unnamed_label* - break_label(); - - // Return the continue label for this for statement. - Unnamed_label* - continue_label(); - - protected: - int - do_traverse(Traverse*); - - bool - do_traverse_assignments(Traverse_assignments*) - { gcc_unreachable(); } - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - Expression* - make_range_ref(Named_object*, Temporary_statement*, source_location); - - Expression* - call_builtin(Gogo*, const char* funcname, Expression* arg, source_location); - - void - lower_range_array(Gogo*, Block*, Block*, Named_object*, Temporary_statement*, - Temporary_statement*, Temporary_statement*, - Block**, Expression**, Block**, Block**); - - void - lower_range_string(Gogo*, Block*, Block*, Named_object*, Temporary_statement*, - Temporary_statement*, Temporary_statement*, - Block**, Expression**, Block**, Block**); - - void - lower_range_map(Gogo*, Block*, Block*, Named_object*, Temporary_statement*, - Temporary_statement*, Temporary_statement*, - Block**, Expression**, Block**, Block**); - - void - lower_range_channel(Gogo*, Block*, Block*, Named_object*, - Temporary_statement*, Temporary_statement*, - Temporary_statement*, Block**, Expression**, Block**, - Block**); - - // The variable which is set to the index value. - Expression* index_var_; - // The variable which is set to the element value. This may be - // NULL. - Expression* value_var_; - // The expression we are ranging over. - Expression* range_; - // The statements in the block. - Block* statements_; - // The break label, if needed. - Unnamed_label* break_label_; - // The continue label, if needed. - Unnamed_label* continue_label_; -}; - -// Class Case_clauses holds the clauses of a switch statement. This -// is built by the parser. - -class Case_clauses -{ - public: - Case_clauses() - : clauses_() - { } - - // Add a new clause. CASES is a list of case expressions; it may be - // NULL. IS_DEFAULT is true if this is the default case. - // STATEMENTS is a block of statements. IS_FALLTHROUGH is true if - // after the statements the case clause should fall through to the - // next clause. - void - add(Expression_list* cases, bool is_default, Block* statements, - bool is_fallthrough, source_location location) - { - this->clauses_.push_back(Case_clause(cases, is_default, statements, - is_fallthrough, location)); - } - - // Return whether there are no clauses. - bool - empty() const - { return this->clauses_.empty(); } - - // Traverse the case clauses. - int - traverse(Traverse*); - - // Lower for a nonconstant switch. - void - lower(Block*, Temporary_statement*, Unnamed_label*) const; - - // Determine types of expressions. The Type parameter is the type - // of the switch value. - void - determine_types(Type*); - - // Check types. The Type parameter is the type of the switch value. - bool - check_types(Type*); - - // Return true if all the clauses are constant values. - bool - is_constant() const; - - // Return true if these clauses may fall through to the statements - // following the switch statement. - bool - may_fall_through() const; - - // Return the body of a SWITCH_EXPR when all the clauses are - // constants. - tree - get_constant_tree(Translate_context*, Unnamed_label* break_label) const; - - private: - // For a constant tree we need to keep a record of constants we have - // already seen. Note that INTEGER_CST trees are interned. - typedef Unordered_set(tree) Case_constants; - - // One case clause. - class Case_clause - { - public: - Case_clause() - : cases_(NULL), statements_(NULL), is_default_(false), - is_fallthrough_(false), location_(UNKNOWN_LOCATION) - { } - - Case_clause(Expression_list* cases, bool is_default, Block* statements, - bool is_fallthrough, source_location location) - : cases_(cases), statements_(statements), is_default_(is_default), - is_fallthrough_(is_fallthrough), location_(location) - { } - - // Whether this clause falls through to the next clause. - bool - is_fallthrough() const - { return this->is_fallthrough_; } - - // Whether this is the default. - bool - is_default() const - { return this->is_default_; } - - // The location of this clause. - source_location - location() const - { return this->location_; } - - // Traversal. - int - traverse(Traverse*); - - // Lower for a nonconstant switch. - void - lower(Block*, Temporary_statement*, Unnamed_label*, Unnamed_label*) const; - - // Determine types. - void - determine_types(Type*); - - // Check types. - bool - check_types(Type*); - - // Return true if all the case expressions are constant. - bool - is_constant() const; - - // Return true if this clause may fall through to execute the - // statements following the switch statement. This is not the - // same as whether this clause falls through to the next clause. - bool - may_fall_through() const; - - // Build up the body of a SWITCH_EXPR when the case expressions - // are constant. - void - get_constant_tree(Translate_context*, Unnamed_label* break_label, - Case_constants* case_constants, tree* stmt_list) const; - - private: - // The list of case expressions. - Expression_list* cases_; - // The statements to execute. - Block* statements_; - // Whether this is the default case. - bool is_default_; - // Whether this falls through after the statements. - bool is_fallthrough_; - // The location of this case clause. - source_location location_; - }; - - friend class Case_clause; - - // The type of the list of clauses. - typedef std::vector Clauses; - - // All the case clauses. - Clauses clauses_; -}; - -// A switch statement. - -class Switch_statement : public Statement -{ - public: - Switch_statement(Expression* val, source_location location) - : Statement(STATEMENT_SWITCH, location), - val_(val), clauses_(NULL), break_label_(NULL) - { } - - // Add the clauses. - void - add_clauses(Case_clauses* clauses) - { - gcc_assert(this->clauses_ == NULL); - this->clauses_ = clauses; - } - - // Return the break label for this switch statement. - Unnamed_label* - break_label(); - - protected: - int - do_traverse(Traverse*); - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // The value to switch on. This may be NULL. - Expression* val_; - // The case clauses. - Case_clauses* clauses_; - // The break label, if needed. - Unnamed_label* break_label_; -}; - -// Class Type_case_clauses holds the clauses of a type switch -// statement. This is built by the parser. - -class Type_case_clauses -{ - public: - Type_case_clauses() - : clauses_() - { } - - // Add a new clause. TYPE is the type for this clause; it may be - // NULL. IS_FALLTHROUGH is true if this falls through to the next - // clause; in this case STATEMENTS will be NULL. IS_DEFAULT is true - // if this is the default case. STATEMENTS is a block of - // statements; it may be NULL. - void - add(Type* type, bool is_fallthrough, bool is_default, Block* statements, - source_location location) - { - this->clauses_.push_back(Type_case_clause(type, is_fallthrough, is_default, - statements, location)); - } - - // Return whether there are no clauses. - bool - empty() const - { return this->clauses_.empty(); } - - // Traverse the type case clauses. - int - traverse(Traverse*); - - // Check for duplicates. - void - check_duplicates() const; - - // Lower to if and goto statements. - void - lower(Block*, Temporary_statement* descriptor_temp, - Unnamed_label* break_label) const; - - private: - // One type case clause. - class Type_case_clause - { - public: - Type_case_clause() - : type_(NULL), statements_(NULL), is_default_(false), - location_(UNKNOWN_LOCATION) - { } - - Type_case_clause(Type* type, bool is_fallthrough, bool is_default, - Block* statements, source_location location) - : type_(type), statements_(statements), is_fallthrough_(is_fallthrough), - is_default_(is_default), location_(location) - { } - - // The type. - Type* - type() const - { return this->type_; } - - // Whether this is the default. - bool - is_default() const - { return this->is_default_; } - - // The location of this type clause. - source_location - location() const - { return this->location_; } - - // Traversal. - int - traverse(Traverse*); - - // Lower to if and goto statements. - void - lower(Block*, Temporary_statement* descriptor_temp, - Unnamed_label* break_label, Unnamed_label** stmts_label) const; - - private: - // The type for this type clause. - Type* type_; - // The statements to execute. - Block* statements_; - // Whether this falls through--this is true for "case T1, T2". - bool is_fallthrough_; - // Whether this is the default case. - bool is_default_; - // The location of this type case clause. - source_location location_; - }; - - friend class Type_case_clause; - - // The type of the list of type clauses. - typedef std::vector Type_clauses; - - // All the type case clauses. - Type_clauses clauses_; -}; - -// A type switch statement. - -class Type_switch_statement : public Statement -{ - public: - Type_switch_statement(Named_object* var, Expression* expr, - source_location location) - : Statement(STATEMENT_TYPE_SWITCH, location), - var_(var), expr_(expr), clauses_(NULL), break_label_(NULL) - { gcc_assert(var == NULL || expr == NULL); } - - // Add the clauses. - void - add_clauses(Type_case_clauses* clauses) - { - gcc_assert(this->clauses_ == NULL); - this->clauses_ = clauses; - } - - // Return the break label for this type switch statement. - Unnamed_label* - break_label(); - - protected: - int - do_traverse(Traverse*); - - Statement* - do_lower(Gogo*, Named_object*, Block*); - - tree - do_get_tree(Translate_context*) - { gcc_unreachable(); } - - private: - // Get the type descriptor. - tree - get_type_descriptor(Translate_context*, Type*, tree); - - // The variable holding the value we are switching on. - Named_object* var_; - // The expression we are switching on if there is no variable. - Expression* expr_; - // The type case clauses. - Type_case_clauses* clauses_; - // The break label, if needed. - Unnamed_label* break_label_; -}; - -#endif // !defined(GO_STATEMENTS_H) diff --git a/gcc/go/gofrontend/types.cc.merge-left.r167407 b/gcc/go/gofrontend/types.cc.merge-left.r167407 deleted file mode 100644 index b030a420fe0..00000000000 --- a/gcc/go/gofrontend/types.cc.merge-left.r167407 +++ /dev/null @@ -1,8078 +0,0 @@ -// types.cc -- Go frontend types. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include - -#ifndef ENABLE_BUILD_WITH_CXX -extern "C" -{ -#endif - -#include "toplev.h" -#include "intl.h" -#include "tree.h" -#include "gimple.h" -#include "real.h" -#include "convert.h" - -#ifndef ENABLE_BUILD_WITH_CXX -} -#endif - -#include "go-c.h" -#include "gogo.h" -#include "operator.h" -#include "expressions.h" -#include "statements.h" -#include "export.h" -#include "import.h" -#include "types.h" - -// Class Type. - -Type::Type(Type_classification classification) - : classification_(classification), tree_(NULL_TREE), - type_descriptor_decl_(NULL_TREE) -{ -} - -Type::~Type() -{ -} - -// Get the base type for a type--skip names and forward declarations. - -Type* -Type::base() -{ - switch (this->classification_) - { - case TYPE_NAMED: - return static_cast(this)->real_type()->base(); - case TYPE_FORWARD: - return static_cast(this)->real_type()->base(); - default: - return this; - } -} - -const Type* -Type::base() const -{ - switch (this->classification_) - { - case TYPE_NAMED: - return static_cast(this)->real_type()->base(); - case TYPE_FORWARD: - { - const Forward_declaration_type* ftype = - static_cast(this); - return ftype->real_type()->base(); - } - default: - return this; - } -} - -// Skip defined forward declarations. - -Type* -Type::forwarded() -{ - Type* t = this; - Forward_declaration_type* ftype = t->forward_declaration_type(); - while (ftype != NULL && ftype->is_defined()) - { - t = ftype->real_type(); - ftype = t->forward_declaration_type(); - } - return t; -} - -const Type* -Type::forwarded() const -{ - const Type* t = this; - const Forward_declaration_type* ftype = t->forward_declaration_type(); - while (ftype != NULL && ftype->is_defined()) - { - t = ftype->real_type(); - ftype = t->forward_declaration_type(); - } - return t; -} - -// If this is a named type, return it. Otherwise, return NULL. - -Named_type* -Type::named_type() -{ - return this->forwarded()->convert_no_base(); -} - -const Named_type* -Type::named_type() const -{ - return this->forwarded()->convert_no_base(); -} - -// Return true if this type is not defined. - -bool -Type::is_undefined() const -{ - return this->forwarded()->forward_declaration_type() != NULL; -} - -// Return true if this is a basic type: a type which is not composed -// of other types, and is not void. - -bool -Type::is_basic_type() const -{ - switch (this->classification_) - { - case TYPE_INTEGER: - case TYPE_FLOAT: - case TYPE_COMPLEX: - case TYPE_BOOLEAN: - case TYPE_STRING: - case TYPE_NIL: - return true; - - case TYPE_ERROR: - case TYPE_VOID: - case TYPE_FUNCTION: - case TYPE_POINTER: - case TYPE_STRUCT: - case TYPE_ARRAY: - case TYPE_MAP: - case TYPE_CHANNEL: - case TYPE_INTERFACE: - return false; - - case TYPE_NAMED: - case TYPE_FORWARD: - return this->base()->is_basic_type(); - - default: - gcc_unreachable(); - } -} - -// Return true if this is an abstract type. - -bool -Type::is_abstract() const -{ - switch (this->classification()) - { - case TYPE_INTEGER: - return this->integer_type()->is_abstract(); - case TYPE_FLOAT: - return this->float_type()->is_abstract(); - case TYPE_COMPLEX: - return this->complex_type()->is_abstract(); - case TYPE_STRING: - return this->is_abstract_string_type(); - case TYPE_BOOLEAN: - return this->is_abstract_boolean_type(); - default: - return false; - } -} - -// Return a non-abstract version of an abstract type. - -Type* -Type::make_non_abstract_type() -{ - gcc_assert(this->is_abstract()); - switch (this->classification()) - { - case TYPE_INTEGER: - return Type::lookup_integer_type("int"); - case TYPE_FLOAT: - return Type::lookup_float_type("float"); - case TYPE_COMPLEX: - return Type::lookup_complex_type("complex"); - case TYPE_STRING: - return Type::lookup_string_type(); - case TYPE_BOOLEAN: - return Type::lookup_bool_type(); - default: - gcc_unreachable(); - } -} - -// Return true if this is an error type. Don't give an error if we -// try to dereference an undefined forwarding type, as this is called -// in the parser when the type may legitimately be undefined. - -bool -Type::is_error_type() const -{ - const Type* t = this->forwarded(); - // Note that we return false for an undefined forward type. - switch (t->classification_) - { - case TYPE_ERROR: - return true; - case TYPE_NAMED: - return t->named_type()->real_type()->is_error_type(); - default: - return false; - } -} - -// If this is a pointer type, return the type to which it points. -// Otherwise, return NULL. - -Type* -Type::points_to() const -{ - const Pointer_type* ptype = this->convert(); - return ptype == NULL ? NULL : ptype->points_to(); -} - -// Return whether this is an open array type. - -bool -Type::is_open_array_type() const -{ - return this->array_type() != NULL && this->array_type()->length() == NULL; -} - -// Return whether this is the predeclared constant nil being used as a -// type. - -bool -Type::is_nil_constant_as_type() const -{ - const Type* t = this->forwarded(); - if (t->forward_declaration_type() != NULL) - { - const Named_object* no = t->forward_declaration_type()->named_object(); - if (no->is_unknown()) - no = no->unknown_value()->real_named_object(); - if (no != NULL - && no->is_const() - && no->const_value()->expr()->is_nil_expression()) - return true; - } - return false; -} - -// Traverse a type. - -int -Type::traverse(Type* type, Traverse* traverse) -{ - gcc_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0 - || (traverse->traverse_mask() - & Traverse::traverse_expressions) != 0); - if (traverse->remember_type(type)) - { - // We have already traversed this type. - return TRAVERSE_CONTINUE; - } - if ((traverse->traverse_mask() & Traverse::traverse_types) != 0) - { - int t = traverse->type(type); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - return TRAVERSE_CONTINUE; - } - // An array type has an expression which we need to traverse if - // traverse_expressions is set. - if (type->do_traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Default implementation for do_traverse for child class. - -int -Type::do_traverse(Traverse*) -{ - return TRAVERSE_CONTINUE; -} - -// Return whether two types are identical. If REASON is not NULL, -// optionally set *REASON to the reason the types are not identical. - -bool -Type::are_identical(const Type* t1, const Type* t2, std::string* reason) -{ - if (t1 == NULL || t2 == NULL) - { - // Something is wrong. Return true to avoid cascading errors. - return true; - } - - // Skip defined forward declarations. - t1 = t1->forwarded(); - t2 = t2->forwarded(); - - if (t1 == t2) - return true; - - // An undefined forward declaration is an error, so we return true - // to avoid cascading errors. - if (t1->forward_declaration_type() != NULL - || t2->forward_declaration_type() != NULL) - return true; - - // Avoid cascading errors with error types. - if (t1->is_error_type() || t2->is_error_type()) - return true; - - // Get a good reason for the sink type. Note that the sink type on - // the left hand side of an assignment is handled in are_assignable. - if (t1->is_sink_type() || t2->is_sink_type()) - { - if (reason != NULL) - *reason = "invalid use of _"; - return false; - } - - // A named type is only identical to itself. - if (t1->named_type() != NULL || t2->named_type() != NULL) - return false; - - // Check type shapes. - if (t1->classification() != t2->classification()) - return false; - - switch (t1->classification()) - { - case TYPE_VOID: - case TYPE_BOOLEAN: - case TYPE_STRING: - case TYPE_NIL: - // These types are always identical. - return true; - - case TYPE_INTEGER: - return t1->integer_type()->is_identical(t2->integer_type()); - - case TYPE_FLOAT: - return t1->float_type()->is_identical(t2->float_type()); - - case TYPE_COMPLEX: - return t1->complex_type()->is_identical(t2->complex_type()); - - case TYPE_FUNCTION: - return t1->function_type()->is_identical(t2->function_type(), - false, - reason); - - case TYPE_POINTER: - return Type::are_identical(t1->points_to(), t2->points_to(), reason); - - case TYPE_STRUCT: - return t1->struct_type()->is_identical(t2->struct_type()); - - case TYPE_ARRAY: - return t1->array_type()->is_identical(t2->array_type()); - - case TYPE_MAP: - return t1->map_type()->is_identical(t2->map_type()); - - case TYPE_CHANNEL: - return t1->channel_type()->is_identical(t2->channel_type()); - - case TYPE_INTERFACE: - return t1->interface_type()->is_identical(t2->interface_type()); - - default: - gcc_unreachable(); - } -} - -// Return true if it's OK to have a binary operation with types LHS -// and RHS. This is not used for shifts or comparisons. - -bool -Type::are_compatible_for_binop(const Type* lhs, const Type* rhs) -{ - if (Type::are_identical(lhs, rhs, NULL)) - return true; - - // A constant of abstract bool type may be mixed with any bool type. - if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type()) - || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type())) - return true; - - // A constant of abstract string type may be mixed with any string - // type. - if ((rhs->is_abstract_string_type() && lhs->is_string_type()) - || (lhs->is_abstract_string_type() && rhs->is_string_type())) - return true; - - lhs = lhs->base(); - rhs = rhs->base(); - - // A constant of abstract integer, float, or complex type may be - // mixed with an integer, float, or complex type. - if ((rhs->is_abstract() - && (rhs->integer_type() != NULL - || rhs->float_type() != NULL - || rhs->complex_type() != NULL) - && (lhs->integer_type() != NULL - || lhs->float_type() != NULL - || lhs->complex_type() != NULL)) - || (lhs->is_abstract() - && (lhs->integer_type() != NULL - || lhs->float_type() != NULL - || lhs->complex_type() != NULL) - && (rhs->integer_type() != NULL - || rhs->float_type() != NULL - || rhs->complex_type() != NULL))) - return true; - - // The nil type may be compared to a pointer, an interface type, a - // slice type, a channel type, a map type, or a function type. - if (lhs->is_nil_type() - && (rhs->points_to() != NULL - || rhs->interface_type() != NULL - || rhs->is_open_array_type() - || rhs->map_type() != NULL - || rhs->channel_type() != NULL - || rhs->function_type() != NULL)) - return true; - if (rhs->is_nil_type() - && (lhs->points_to() != NULL - || lhs->interface_type() != NULL - || lhs->is_open_array_type() - || lhs->map_type() != NULL - || lhs->channel_type() != NULL - || lhs->function_type() != NULL)) - return true; - - return false; -} - -// Return true if a value with type RHS may be assigned to a variable -// with type LHS. If REASON is not NULL, set *REASON to the reason -// the types are not assignable. - -bool -Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason) -{ - // Do some checks first. Make sure the types are defined. - if (lhs != NULL && lhs->forwarded()->forward_declaration_type() == NULL) - { - // Any value may be assigned to the blank identifier. - if (lhs->is_sink_type()) - return true; - - // All fields of a struct must be exported, or the assignment - // must be in the same package. - if (rhs != NULL && rhs->forwarded()->forward_declaration_type() == NULL) - { - if (lhs->has_hidden_fields(NULL, reason) - || rhs->has_hidden_fields(NULL, reason)) - return false; - } - } - - // Identical types are assignable. - if (Type::are_identical(lhs, rhs, reason)) - return true; - - // The types are assignable if they have identical underlying types - // and either LHS or RHS is not a named type. - if (((lhs->named_type() != NULL && rhs->named_type() == NULL) - || (rhs->named_type() != NULL && lhs->named_type() == NULL)) - && Type::are_identical(lhs->base(), rhs->base(), reason)) - return true; - - // The types are assignable if LHS is an interface type and RHS - // implements the required methods. - const Interface_type* lhs_interface_type = lhs->interface_type(); - if (lhs_interface_type != NULL) - { - if (lhs_interface_type->implements_interface(rhs, reason)) - return true; - const Interface_type* rhs_interface_type = rhs->interface_type(); - if (rhs_interface_type != NULL - && lhs_interface_type->is_compatible_for_assign(rhs_interface_type, - reason)) - return true; - } - - // The type are assignable if RHS is a bidirectional channel type, - // LHS is a channel type, they have identical element types, and - // either LHS or RHS is not a named type. - if (lhs->channel_type() != NULL - && rhs->channel_type() != NULL - && rhs->channel_type()->may_send() - && rhs->channel_type()->may_receive() - && (lhs->named_type() == NULL || rhs->named_type() == NULL) - && Type::are_identical(lhs->channel_type()->element_type(), - rhs->channel_type()->element_type(), - reason)) - return true; - - // The nil type may be assigned to a pointer, function, slice, map, - // channel, or interface type. - if (rhs->is_nil_type() - && (lhs->points_to() != NULL - || lhs->function_type() != NULL - || lhs->is_open_array_type() - || lhs->map_type() != NULL - || lhs->channel_type() != NULL - || lhs->interface_type() != NULL)) - return true; - - // An untyped constant may be assigned to a numeric type if it is - // representable in that type. - if (rhs->is_abstract() - && (lhs->integer_type() != NULL - || lhs->float_type() != NULL - || lhs->complex_type() != NULL)) - return true; - - - // Give some better error messages. - if (reason != NULL && reason->empty()) - { - if (rhs->interface_type() != NULL) - reason->assign(_("need explicit conversion")); - else if (rhs->is_call_multiple_result_type()) - reason->assign(_("multiple value function call in " - "single value context")); - else if (lhs->named_type() != NULL && rhs->named_type() != NULL) - { - size_t len = (lhs->named_type()->name().length() - + rhs->named_type()->name().length() - + 100); - char* buf = new char[len]; - snprintf(buf, len, _("cannot use type %s as type %s"), - rhs->named_type()->message_name().c_str(), - lhs->named_type()->message_name().c_str()); - reason->assign(buf); - delete[] buf; - } - } - - return false; -} - -// Return true if a value with type RHS may be converted to type LHS. -// If REASON is not NULL, set *REASON to the reason the types are not -// convertible. - -bool -Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason) -{ - // The types are convertible if they are assignable. - if (Type::are_assignable(lhs, rhs, reason)) - return true; - - // The types are convertible if they have identical underlying - // types. - if ((lhs->named_type() != NULL || rhs->named_type() != NULL) - && Type::are_identical(lhs->base(), rhs->base(), reason)) - return true; - - // The types are convertible if they are both unnamed pointer types - // and their pointer base types have identical underlying types. - if (lhs->named_type() == NULL - && rhs->named_type() == NULL - && lhs->points_to() != NULL - && rhs->points_to() != NULL - && (lhs->points_to()->named_type() != NULL - || rhs->points_to()->named_type() != NULL) - && Type::are_identical(lhs->points_to()->base(), - rhs->points_to()->base(), - reason)) - return true; - - // Integer and floating point types are convertible to each other. - if ((lhs->integer_type() != NULL || lhs->float_type() != NULL) - && (rhs->integer_type() != NULL || rhs->float_type() != NULL)) - return true; - - // Complex types are convertible to each other. - if (lhs->complex_type() != NULL && rhs->complex_type() != NULL) - return true; - - // An integer, or []byte, or []int, may be converted to a string. - if (lhs->is_string_type()) - { - if (rhs->integer_type() != NULL) - return true; - if (rhs->is_open_array_type() && rhs->named_type() == NULL) - { - const Type* e = rhs->array_type()->element_type()->forwarded(); - if (e->integer_type() != NULL - && (e == Type::lookup_integer_type("uint8") - || e == Type::lookup_integer_type("int"))) - return true; - } - } - - // A string may be converted to []byte or []int. - if (rhs->is_string_type() - && lhs->is_open_array_type() - && lhs->named_type() == NULL) - { - const Type* e = lhs->array_type()->element_type()->forwarded(); - if (e->integer_type() != NULL - && (e == Type::lookup_integer_type("uint8") - || e == Type::lookup_integer_type("int"))) - return true; - } - - // An unsafe.Pointer type may be converted to any pointer type or to - // uintptr, and vice-versa. - if (lhs->is_unsafe_pointer_type() - && (rhs->points_to() != NULL - || (rhs->integer_type() != NULL - && rhs->forwarded() == Type::lookup_integer_type("uintptr")))) - return true; - if (rhs->is_unsafe_pointer_type() - && (lhs->points_to() != NULL - || (lhs->integer_type() != NULL - && lhs->forwarded() == Type::lookup_integer_type("uintptr")))) - return true; - - // Give a better error message. - if (reason != NULL) - { - if (reason->empty()) - *reason = "invalid type conversion"; - else - { - std::string s = "invalid type conversion ("; - s += *reason; - s += ')'; - *reason = s; - } - } - - return false; -} - -// Return whether this type has any hidden fields. This is only a -// possibility for a few types. - -bool -Type::has_hidden_fields(const Named_type* within, std::string* reason) const -{ - switch (this->forwarded()->classification_) - { - case TYPE_NAMED: - return this->named_type()->named_type_has_hidden_fields(reason); - case TYPE_STRUCT: - return this->struct_type()->struct_has_hidden_fields(within, reason); - case TYPE_ARRAY: - return this->array_type()->array_has_hidden_fields(within, reason); - default: - return false; - } -} - -// Return a hash code for the type to be used for method lookup. - -unsigned int -Type::hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - if (this->classification_ != TYPE_FORWARD) - ret += this->classification_; - return ret + this->do_hash_for_method(gogo); -} - -// Default implementation of do_hash_for_method. This is appropriate -// for types with no subfields. - -unsigned int -Type::do_hash_for_method(Gogo*) const -{ - return 0; -} - -// Return a hash code for a string, given a starting hash. - -unsigned int -Type::hash_string(const std::string& s, unsigned int h) -{ - const char* p = s.data(); - size_t len = s.length(); - for (; len > 0; --len) - { - h ^= *p++; - h*= 16777619; - } - return h; -} - -// Default check for the expression passed to make. Any type which -// may be used with make implements its own version of this. - -bool -Type::do_check_make_expression(Expression_list*, source_location) -{ - gcc_unreachable(); -} - -// Return whether an expression has an integer value. Report an error -// if not. This is used when handling calls to the predeclared make -// function. - -bool -Type::check_int_value(Expression* e, const char* errmsg, - source_location location) -{ - if (e->type()->integer_type() != NULL) - return true; - - // Check for a floating point constant with integer value. - mpfr_t fval; - mpfr_init(fval); - - Type* dummy; - if (e->float_constant_value(fval, &dummy)) - { - mpz_t ival; - mpz_init(ival); - - bool ok = false; - - mpfr_clear_overflow(); - mpfr_clear_erangeflag(); - mpfr_get_z(ival, fval, GMP_RNDN); - if (!mpfr_overflow_p() - && !mpfr_erangeflag_p() - && mpz_sgn(ival) >= 0) - { - Named_type* ntype = Type::lookup_integer_type("int"); - Integer_type* inttype = ntype->integer_type(); - mpz_t max; - mpz_init_set_ui(max, 1); - mpz_mul_2exp(max, max, inttype->bits() - 1); - ok = mpz_cmp(ival, max) < 0; - mpz_clear(max); - } - mpz_clear(ival); - - if (ok) - { - mpfr_clear(fval); - return true; - } - } - - mpfr_clear(fval); - - error_at(location, "%s", errmsg); - return false; -} - -// A hash table mapping unnamed types to trees. - -Type::Type_trees Type::type_trees; - -// Return a tree representing this type. - -tree -Type::get_tree(Gogo* gogo) -{ - if (this->tree_ != NULL) - return this->tree_; - - if (this->forward_declaration_type() != NULL - || this->named_type() != NULL) - return this->get_tree_without_hash(gogo); - - // To avoid confusing GIMPLE, we need to translate all identical Go - // types to the same GIMPLE type. We use a hash table to do that. - // There is no need to use the hash table for named types, as named - // types are only identical to themselves. - - std::pair val(this, NULL); - std::pair ins = - Type::type_trees.insert(val); - if (!ins.second && ins.first->second != NULL_TREE) - { - this->tree_ = ins.first->second; - return this->tree_; - } - - tree t = this->get_tree_without_hash(gogo); - - if (ins.first->second == NULL_TREE) - ins.first->second = t; - else - { - // We have already created a tree for this type. This can - // happen when an unnamed type is defined using a named type - // which in turns uses an identical unnamed type. Use the tree - // we created earlier and ignore the one we just built. - t = ins.first->second; - this->tree_ = t; - } - - return t; -} - -// Return a tree for a type without looking in the hash table for -// identical types. This is used for named types, since there is no -// point to looking in the hash table for them. - -tree -Type::get_tree_without_hash(Gogo* gogo) -{ - if (this->tree_ == NULL_TREE) - { - tree t = this->do_get_tree(gogo); - - // For a recursive function or pointer type, we will temporarily - // return ptr_type_node during the recursion. We don't want to - // record that for a forwarding type, as it may confuse us - // later. - if (t == ptr_type_node && this->forward_declaration_type() != NULL) - return t; - - this->tree_ = t; - go_preserve_from_gc(t); - } - - return this->tree_; -} - -// Return a tree representing a zero initialization for this type. - -tree -Type::get_init_tree(Gogo* gogo, bool is_clear) -{ - tree type_tree = this->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - return this->do_get_init_tree(gogo, type_tree, is_clear); -} - -// Any type which supports the builtin make function must implement -// this. - -tree -Type::do_make_expression_tree(Translate_context*, Expression_list*, - source_location) -{ - gcc_unreachable(); -} - -// Return a pointer to the type descriptor for this type. - -tree -Type::type_descriptor_pointer(Gogo* gogo) -{ - Type* t = this->forwarded(); - if (t->type_descriptor_decl_ == NULL_TREE) - { - Expression* e = t->do_type_descriptor(gogo, NULL); - gogo->build_type_descriptor_decl(t, e, &t->type_descriptor_decl_); - gcc_assert(t->type_descriptor_decl_ != NULL_TREE - && (t->type_descriptor_decl_ == error_mark_node - || DECL_P(t->type_descriptor_decl_))); - } - if (t->type_descriptor_decl_ == error_mark_node) - return error_mark_node; - return build_fold_addr_expr(t->type_descriptor_decl_); -} - -// Return a composite literal for a type descriptor. - -Expression* -Type::type_descriptor(Gogo* gogo, Type* type) -{ - return type->do_type_descriptor(gogo, NULL); -} - -// Return a composite literal for a type descriptor with a name. - -Expression* -Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name) -{ - gcc_assert(name != NULL && type->named_type() != name); - return type->do_type_descriptor(gogo, name); -} - -// Make a builtin struct type from a list of fields. The fields are -// pairs of a name and a type. - -Struct_type* -Type::make_builtin_struct_type(int nfields, ...) -{ - va_list ap; - va_start(ap, nfields); - - source_location bloc = BUILTINS_LOCATION; - Struct_field_list* sfl = new Struct_field_list(); - for (int i = 0; i < nfields; i++) - { - const char* field_name = va_arg(ap, const char *); - Type* type = va_arg(ap, Type*); - sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc))); - } - - va_end(ap); - - return Type::make_struct_type(sfl, bloc); -} - -// Make a builtin named type. - -Named_type* -Type::make_builtin_named_type(const char* name, Type* type) -{ - source_location bloc = BUILTINS_LOCATION; - Named_object* no = Named_object::make_type(name, NULL, type, bloc); - return no->type_value(); -} - -// Return the type of a type descriptor. We should really tie this to -// runtime.Type rather than copying it. This must match commonType in -// libgo/go/runtime/type.go. - -Type* -Type::make_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - source_location bloc = BUILTINS_LOCATION; - - Type* uint8_type = Type::lookup_integer_type("uint8"); - Type* uint32_type = Type::lookup_integer_type("uint32"); - Type* uintptr_type = Type::lookup_integer_type("uintptr"); - Type* string_type = Type::lookup_string_type(); - Type* pointer_string_type = Type::make_pointer_type(string_type); - - // This is an unnamed version of unsafe.Pointer. Perhaps we - // should use the named version instead, although that would - // require us to create the unsafe package if it has not been - // imported. It probably doesn't matter. - Type* void_type = Type::make_void_type(); - Type* unsafe_pointer_type = Type::make_pointer_type(void_type); - - // Forward declaration for the type descriptor type. - Named_object* named_type_descriptor_type = - Named_object::make_type_declaration("commonType", NULL, bloc); - Type* ft = Type::make_forward_declaration(named_type_descriptor_type); - Type* pointer_type_descriptor_type = Type::make_pointer_type(ft); - - // The type of a method on a concrete type. - Struct_type* method_type = - Type::make_builtin_struct_type(5, - "name", pointer_string_type, - "pkgPath", pointer_string_type, - "mtyp", pointer_type_descriptor_type, - "typ", pointer_type_descriptor_type, - "tfn", unsafe_pointer_type); - Named_type* named_method_type = - Type::make_builtin_named_type("method", method_type); - - // Information for types with a name or methods. - Type* slice_named_method_type = - Type::make_array_type(named_method_type, NULL); - Struct_type* uncommon_type = - Type::make_builtin_struct_type(3, - "name", pointer_string_type, - "pkgPath", pointer_string_type, - "methods", slice_named_method_type); - Named_type* named_uncommon_type = - Type::make_builtin_named_type("uncommonType", uncommon_type); - - Type* pointer_uncommon_type = - Type::make_pointer_type(named_uncommon_type); - - // The type descriptor type. - - Typed_identifier_list* params = new Typed_identifier_list(); - params->push_back(Typed_identifier("", unsafe_pointer_type, bloc)); - params->push_back(Typed_identifier("", uintptr_type, bloc)); - - Typed_identifier_list* results = new Typed_identifier_list(); - results->push_back(Typed_identifier("", uintptr_type, bloc)); - - Type* hashfn_type = Type::make_function_type(NULL, params, results, bloc); - - params = new Typed_identifier_list(); - params->push_back(Typed_identifier("", unsafe_pointer_type, bloc)); - params->push_back(Typed_identifier("", unsafe_pointer_type, bloc)); - params->push_back(Typed_identifier("", uintptr_type, bloc)); - - results = new Typed_identifier_list(); - results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc)); - - Type* equalfn_type = Type::make_function_type(NULL, params, results, - bloc); - - Struct_type* type_descriptor_type = - Type::make_builtin_struct_type(9, - "Kind", uint8_type, - "align", uint8_type, - "fieldAlign", uint8_type, - "size", uintptr_type, - "hash", uint32_type, - "hashfn", hashfn_type, - "equalfn", equalfn_type, - "string", pointer_string_type, - "", pointer_uncommon_type); - - Named_type* named = Type::make_builtin_named_type("commonType", - type_descriptor_type); - - named_type_descriptor_type->set_type_value(named); - - ret = named; - } - - return ret; -} - -// Make the type of a pointer to a type descriptor as represented in -// Go. - -Type* -Type::make_type_descriptor_ptr_type() -{ - static Type* ret; - if (ret == NULL) - ret = Type::make_pointer_type(Type::make_type_descriptor_type()); - return ret; -} - -// Return the names of runtime functions which compute a hash code for -// this type and which compare whether two values of this type are -// equal. - -void -Type::type_functions(const char** hash_fn, const char** equal_fn) const -{ - switch (this->base()->classification()) - { - case Type::TYPE_ERROR: - case Type::TYPE_VOID: - case Type::TYPE_NIL: - // These types can not be hashed or compared. - *hash_fn = "__go_type_hash_error"; - *equal_fn = "__go_type_equal_error"; - break; - - case Type::TYPE_BOOLEAN: - case Type::TYPE_INTEGER: - case Type::TYPE_FLOAT: - case Type::TYPE_COMPLEX: - case Type::TYPE_POINTER: - case Type::TYPE_FUNCTION: - case Type::TYPE_MAP: - case Type::TYPE_CHANNEL: - *hash_fn = "__go_type_hash_identity"; - *equal_fn = "__go_type_equal_identity"; - break; - - case Type::TYPE_STRING: - *hash_fn = "__go_type_hash_string"; - *equal_fn = "__go_type_equal_string"; - break; - - case Type::TYPE_STRUCT: - case Type::TYPE_ARRAY: - // These types can not be hashed or compared. - *hash_fn = "__go_type_hash_error"; - *equal_fn = "__go_type_equal_error"; - break; - - case Type::TYPE_INTERFACE: - if (this->interface_type()->is_empty()) - { - *hash_fn = "__go_type_hash_empty_interface"; - *equal_fn = "__go_type_equal_empty_interface"; - } - else - { - *hash_fn = "__go_type_hash_interface"; - *equal_fn = "__go_type_equal_interface"; - } - break; - - case Type::TYPE_NAMED: - case Type::TYPE_FORWARD: - gcc_unreachable(); - - default: - gcc_unreachable(); - } -} - -// Return a composite literal for the type descriptor for a plain type -// of kind RUNTIME_TYPE_KIND named NAME. - -Expression* -Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind, - Named_type* name, const Methods* methods, - bool only_value_methods) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* td_type = Type::make_type_descriptor_type(); - const Struct_field_list* fields = td_type->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(9); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "Kind"); - mpz_t iv; - mpz_init_set_ui(iv, runtime_type_kind); - vals->push_back(Expression::make_integer(&iv, p->type(), bloc)); - - ++p; - gcc_assert(p->field_name() == "align"); - Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT; - vals->push_back(Expression::make_type_info(this, type_info)); - - ++p; - gcc_assert(p->field_name() == "fieldAlign"); - type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT; - vals->push_back(Expression::make_type_info(this, type_info)); - - ++p; - gcc_assert(p->field_name() == "size"); - type_info = Expression::TYPE_INFO_SIZE; - vals->push_back(Expression::make_type_info(this, type_info)); - - ++p; - gcc_assert(p->field_name() == "hash"); - mpz_set_ui(iv, this->hash_for_method(gogo)); - vals->push_back(Expression::make_integer(&iv, p->type(), bloc)); - - const char* hash_fn; - const char* equal_fn; - this->type_functions(&hash_fn, &equal_fn); - - ++p; - gcc_assert(p->field_name() == "hashfn"); - Function_type* fntype = p->type()->function_type(); - Named_object* no = Named_object::make_function_declaration(hash_fn, NULL, - fntype, - bloc); - no->func_declaration_value()->set_asm_name(hash_fn); - vals->push_back(Expression::make_func_reference(no, NULL, bloc)); - - ++p; - gcc_assert(p->field_name() == "equalfn"); - fntype = p->type()->function_type(); - no = Named_object::make_function_declaration(equal_fn, NULL, fntype, bloc); - no->func_declaration_value()->set_asm_name(equal_fn); - vals->push_back(Expression::make_func_reference(no, NULL, bloc)); - - ++p; - gcc_assert(p->field_name() == "string"); - Expression* s = Expression::make_string((name != NULL - ? name->reflection(gogo) - : this->reflection(gogo)), - bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - - ++p; - gcc_assert(p->field_name() == "uncommonType"); - if (name == NULL && methods == NULL) - vals->push_back(Expression::make_nil(bloc)); - else - { - if (methods == NULL) - methods = name->methods(); - vals->push_back(this->uncommon_type_constructor(gogo, - p->type()->deref(), - name, methods, - only_value_methods)); - } - - ++p; - gcc_assert(p == fields->end()); - - mpz_clear(iv); - - return Expression::make_struct_composite_literal(td_type, vals, bloc); -} - -// Return a composite literal for the uncommon type information for -// this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type -// struct. If name is not NULL, it is the name of the type. If -// METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS -// is true if only value methods should be included. At least one of -// NAME and METHODS must not be NULL. - -Expression* -Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type, - Named_type* name, const Methods* methods, - bool only_value_methods) const -{ - source_location bloc = BUILTINS_LOCATION; - - const Struct_field_list* fields = uncommon_type->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(3); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "name"); - - ++p; - gcc_assert(p->field_name() == "pkgPath"); - - if (name == NULL) - { - vals->push_back(Expression::make_nil(bloc)); - vals->push_back(Expression::make_nil(bloc)); - } - else - { - Named_object* no = name->named_object(); - std::string n = Gogo::unpack_hidden_name(no->name()); - Expression* s = Expression::make_string(n, bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - - if (name->is_builtin()) - vals->push_back(Expression::make_nil(bloc)); - else - { - const Package* package = no->package(); - const std::string& unique_prefix(package == NULL - ? gogo->unique_prefix() - : package->unique_prefix()); - const std::string& package_name(package == NULL - ? gogo->package_name() - : package->name()); - n.assign(unique_prefix); - n.append(1, '.'); - n.append(package_name); - if (name->in_function() != NULL) - { - n.append(1, '.'); - n.append(Gogo::unpack_hidden_name(name->in_function()->name())); - } - s = Expression::make_string(n, bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - } - - ++p; - gcc_assert(p->field_name() == "methods"); - vals->push_back(this->methods_constructor(gogo, p->type(), methods, - only_value_methods)); - - ++p; - gcc_assert(p == fields->end()); - - Expression* r = Expression::make_struct_composite_literal(uncommon_type, - vals, bloc); - return Expression::make_unary(OPERATOR_AND, r, bloc); -} - -// Sort methods by name. - -class Sort_methods -{ - public: - bool - operator()(const std::pair& m1, - const std::pair& m2) const - { return m1.first < m2.first; } -}; - -// Return a composite literal for the type method table for this type. -// METHODS_TYPE is the type of the table, and is a slice type. -// METHODS is the list of methods. If ONLY_VALUE_METHODS is true, -// then only value methods are used. - -Expression* -Type::methods_constructor(Gogo* gogo, Type* methods_type, - const Methods* methods, - bool only_value_methods) const -{ - source_location bloc = BUILTINS_LOCATION; - - std::vector > smethods; - if (methods != NULL) - { - smethods.reserve(methods->count()); - for (Methods::const_iterator p = methods->begin(); - p != methods->end(); - ++p) - { - if (p->second->is_ambiguous()) - continue; - if (only_value_methods && !p->second->is_value_method()) - continue; - smethods.push_back(std::make_pair(p->first, p->second)); - } - } - - if (smethods.empty()) - return Expression::make_slice_composite_literal(methods_type, NULL, bloc); - - std::sort(smethods.begin(), smethods.end(), Sort_methods()); - - Type* method_type = methods_type->array_type()->element_type(); - - Expression_list* vals = new Expression_list(); - vals->reserve(smethods.size()); - for (std::vector >::const_iterator p - = smethods.begin(); - p != smethods.end(); - ++p) - vals->push_back(this->method_constructor(gogo, method_type, p->first, - p->second)); - - return Expression::make_slice_composite_literal(methods_type, vals, bloc); -} - -// Return a composite literal for a single method. METHOD_TYPE is the -// type of the entry. METHOD_NAME is the name of the method and M is -// the method information. - -Expression* -Type::method_constructor(Gogo*, Type* method_type, - const std::string& method_name, - const Method* m) const -{ - source_location bloc = BUILTINS_LOCATION; - - const Struct_field_list* fields = method_type->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(5); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "name"); - const std::string n = Gogo::unpack_hidden_name(method_name); - Expression* s = Expression::make_string(n, bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - - ++p; - gcc_assert(p->field_name() == "pkgPath"); - if (!Gogo::is_hidden_name(method_name)) - vals->push_back(Expression::make_nil(bloc)); - else - { - s = Expression::make_string(Gogo::hidden_name_prefix(method_name), bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - - Named_object* no = (m->needs_stub_method() - ? m->stub_object() - : m->named_object()); - - Function_type* mtype; - if (no->is_function()) - mtype = no->func_value()->type(); - else - mtype = no->func_declaration_value()->type(); - gcc_assert(mtype->is_method()); - Type* nonmethod_type = mtype->copy_without_receiver(); - - ++p; - gcc_assert(p->field_name() == "mtyp"); - vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc)); - - ++p; - gcc_assert(p->field_name() == "typ"); - vals->push_back(Expression::make_type_descriptor(mtype, bloc)); - - ++p; - gcc_assert(p->field_name() == "tfn"); - vals->push_back(Expression::make_func_reference(no, NULL, bloc)); - - ++p; - gcc_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(method_type, vals, bloc); -} - -// Return a composite literal for the type descriptor of a plain type. -// RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not -// NULL, it is the name to use as well as the list of methods. - -Expression* -Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind, - Named_type* name) -{ - return this->type_descriptor_constructor(gogo, runtime_type_kind, - name, NULL, true); -} - -// Return the type reflection string for this type. - -std::string -Type::reflection(Gogo* gogo) const -{ - std::string ret; - - // The do_reflection virtual function should set RET to the - // reflection string. - this->do_reflection(gogo, &ret); - - return ret; -} - -// Return a mangled name for the type. - -std::string -Type::mangled_name(Gogo* gogo) const -{ - std::string ret; - - // The do_mangled_name virtual function should set RET to the - // mangled name. For a composite type it should append a code for - // the composition and then call do_mangled_name on the components. - this->do_mangled_name(gogo, &ret); - - return ret; -} - -// Default function to export a type. - -void -Type::do_export(Export*) const -{ - gcc_unreachable(); -} - -// Import a type. - -Type* -Type::import_type(Import* imp) -{ - if (imp->match_c_string("(")) - return Function_type::do_import(imp); - else if (imp->match_c_string("*")) - return Pointer_type::do_import(imp); - else if (imp->match_c_string("struct ")) - return Struct_type::do_import(imp); - else if (imp->match_c_string("[")) - return Array_type::do_import(imp); - else if (imp->match_c_string("map ")) - return Map_type::do_import(imp); - else if (imp->match_c_string("chan ")) - return Channel_type::do_import(imp); - else if (imp->match_c_string("interface")) - return Interface_type::do_import(imp); - else - { - error_at(imp->location(), "import error: expected type"); - return Type::make_error_type(); - } -} - -// A type used to indicate a parsing error. This exists to simplify -// later error detection. - -class Error_type : public Type -{ - public: - Error_type() - : Type(TYPE_ERROR) - { } - - protected: - tree - do_get_tree(Gogo*) - { return error_mark_node; } - - tree - do_get_init_tree(Gogo*, tree, bool) - { return error_mark_node; } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { return Expression::make_error(BUILTINS_LOCATION); } - - void - do_reflection(Gogo*, std::string*) const - { gcc_assert(saw_errors()); } - - void - do_mangled_name(Gogo*, std::string* ret) const - { ret->push_back('E'); } -}; - -Type* -Type::make_error_type() -{ - static Error_type singleton_error_type; - return &singleton_error_type; -} - -// The void type. - -class Void_type : public Type -{ - public: - Void_type() - : Type(TYPE_VOID) - { } - - protected: - tree - do_get_tree(Gogo*) - { return void_type_node; } - - tree - do_get_init_tree(Gogo*, tree, bool) - { gcc_unreachable(); } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { gcc_unreachable(); } - - void - do_reflection(Gogo*, std::string*) const - { } - - void - do_mangled_name(Gogo*, std::string* ret) const - { ret->push_back('v'); } -}; - -Type* -Type::make_void_type() -{ - static Void_type singleton_void_type; - return &singleton_void_type; -} - -// The boolean type. - -class Boolean_type : public Type -{ - public: - Boolean_type() - : Type(TYPE_BOOLEAN) - { } - - protected: - tree - do_get_tree(Gogo*) - { return boolean_type_node; } - - tree - do_get_init_tree(Gogo*, tree type_tree, bool is_clear) - { return is_clear ? NULL : fold_convert(type_tree, boolean_false_node); } - - Expression* - do_type_descriptor(Gogo*, Named_type* name); - - // We should not be asked for the reflection string of a basic type. - void - do_reflection(Gogo*, std::string* ret) const - { ret->append("bool"); } - - void - do_mangled_name(Gogo*, std::string* ret) const - { ret->push_back('b'); } -}; - -// Make the type descriptor. - -Expression* -Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (name != NULL) - return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name); - else - { - Named_object* no = gogo->lookup_global("bool"); - gcc_assert(no != NULL); - return Type::type_descriptor(gogo, no->type_value()); - } -} - -Type* -Type::make_boolean_type() -{ - static Boolean_type boolean_type; - return &boolean_type; -} - -// The named type "bool". - -static Named_type* named_bool_type; - -// Get the named type "bool". - -Named_type* -Type::lookup_bool_type() -{ - return named_bool_type; -} - -// Make the named type "bool". - -Named_type* -Type::make_named_bool_type() -{ - Type* bool_type = Type::make_boolean_type(); - Named_object* named_object = Named_object::make_type("bool", NULL, - bool_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - named_bool_type = named_type; - return named_type; -} - -// Class Integer_type. - -Integer_type::Named_integer_types Integer_type::named_integer_types; - -// Create a new integer type. Non-abstract integer types always have -// names. - -Named_type* -Integer_type::create_integer_type(const char* name, bool is_unsigned, - int bits, int runtime_type_kind) -{ - Integer_type* integer_type = new Integer_type(false, is_unsigned, bits, - runtime_type_kind); - std::string sname(name); - Named_object* named_object = Named_object::make_type(sname, NULL, - integer_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - std::pair ins = - Integer_type::named_integer_types.insert(std::make_pair(sname, named_type)); - gcc_assert(ins.second); - return named_type; -} - -// Look up an existing integer type. - -Named_type* -Integer_type::lookup_integer_type(const char* name) -{ - Named_integer_types::const_iterator p = - Integer_type::named_integer_types.find(name); - gcc_assert(p != Integer_type::named_integer_types.end()); - return p->second; -} - -// Create a new abstract integer type. - -Integer_type* -Integer_type::create_abstract_integer_type() -{ - static Integer_type* abstract_type; - if (abstract_type == NULL) - abstract_type = new Integer_type(true, false, INT_TYPE_SIZE, - RUNTIME_TYPE_KIND_INT); - return abstract_type; -} - -// Integer type compatibility. - -bool -Integer_type::is_identical(const Integer_type* t) const -{ - if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_) - return false; - return this->is_abstract_ == t->is_abstract_; -} - -// Hash code. - -unsigned int -Integer_type::do_hash_for_method(Gogo*) const -{ - return ((this->bits_ << 4) - + ((this->is_unsigned_ ? 1 : 0) << 8) - + ((this->is_abstract_ ? 1 : 0) << 9)); -} - -// Get the tree for an Integer_type. - -tree -Integer_type::do_get_tree(Gogo*) -{ - gcc_assert(!this->is_abstract_); - if (this->is_unsigned_) - { - if (this->bits_ == INT_TYPE_SIZE) - return unsigned_type_node; - else if (this->bits_ == CHAR_TYPE_SIZE) - return unsigned_char_type_node; - else if (this->bits_ == SHORT_TYPE_SIZE) - return short_unsigned_type_node; - else if (this->bits_ == LONG_TYPE_SIZE) - return long_unsigned_type_node; - else if (this->bits_ == LONG_LONG_TYPE_SIZE) - return long_long_unsigned_type_node; - else - return make_unsigned_type(this->bits_); - } - else - { - if (this->bits_ == INT_TYPE_SIZE) - return integer_type_node; - else if (this->bits_ == CHAR_TYPE_SIZE) - return signed_char_type_node; - else if (this->bits_ == SHORT_TYPE_SIZE) - return short_integer_type_node; - else if (this->bits_ == LONG_TYPE_SIZE) - return long_integer_type_node; - else if (this->bits_ == LONG_LONG_TYPE_SIZE) - return long_long_integer_type_node; - else - return make_signed_type(this->bits_); - } -} - -tree -Integer_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - return is_clear ? NULL : build_int_cst(type_tree, 0); -} - -// The type descriptor for an integer type. Integer types are always -// named. - -Expression* -Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - gcc_assert(name != NULL); - return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name); -} - -// We should not be asked for the reflection string of a basic type. - -void -Integer_type::do_reflection(Gogo*, std::string*) const -{ - gcc_unreachable(); -} - -// Mangled name. - -void -Integer_type::do_mangled_name(Gogo*, std::string* ret) const -{ - char buf[100]; - snprintf(buf, sizeof buf, "i%s%s%de", - this->is_abstract_ ? "a" : "", - this->is_unsigned_ ? "u" : "", - this->bits_); - ret->append(buf); -} - -// Make an integer type. - -Named_type* -Type::make_integer_type(const char* name, bool is_unsigned, int bits, - int runtime_type_kind) -{ - return Integer_type::create_integer_type(name, is_unsigned, bits, - runtime_type_kind); -} - -// Make an abstract integer type. - -Integer_type* -Type::make_abstract_integer_type() -{ - return Integer_type::create_abstract_integer_type(); -} - -// Look up an integer type. - -Named_type* -Type::lookup_integer_type(const char* name) -{ - return Integer_type::lookup_integer_type(name); -} - -// Class Float_type. - -Float_type::Named_float_types Float_type::named_float_types; - -// Create a new float type. Non-abstract float types always have -// names. - -Named_type* -Float_type::create_float_type(const char* name, int bits, - int runtime_type_kind) -{ - Float_type* float_type = new Float_type(false, bits, runtime_type_kind); - std::string sname(name); - Named_object* named_object = Named_object::make_type(sname, NULL, float_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - std::pair ins = - Float_type::named_float_types.insert(std::make_pair(sname, named_type)); - gcc_assert(ins.second); - return named_type; -} - -// Look up an existing float type. - -Named_type* -Float_type::lookup_float_type(const char* name) -{ - Named_float_types::const_iterator p = - Float_type::named_float_types.find(name); - gcc_assert(p != Float_type::named_float_types.end()); - return p->second; -} - -// Create a new abstract float type. - -Float_type* -Float_type::create_abstract_float_type() -{ - static Float_type* abstract_type; - if (abstract_type == NULL) - abstract_type = new Float_type(true, FLOAT_TYPE_SIZE, - RUNTIME_TYPE_KIND_FLOAT); - return abstract_type; -} - -// Whether this type is identical with T. - -bool -Float_type::is_identical(const Float_type* t) const -{ - if (this->bits_ != t->bits_) - return false; - return this->is_abstract_ == t->is_abstract_; -} - -// Hash code. - -unsigned int -Float_type::do_hash_for_method(Gogo*) const -{ - return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8); -} - -// Get a tree without using a Gogo*. - -tree -Float_type::type_tree() const -{ - if (this->bits_ == FLOAT_TYPE_SIZE) - return float_type_node; - else if (this->bits_ == DOUBLE_TYPE_SIZE) - return double_type_node; - else if (this->bits_ == LONG_DOUBLE_TYPE_SIZE) - return long_double_type_node; - else - { - tree ret = make_node(REAL_TYPE); - TYPE_PRECISION(ret) = this->bits_; - layout_type(ret); - return ret; - } -} - -// Get a tree. - -tree -Float_type::do_get_tree(Gogo*) -{ - return this->type_tree(); -} - -tree -Float_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - REAL_VALUE_TYPE r; - real_from_integer(&r, TYPE_MODE(type_tree), 0, 0, 0); - return build_real(type_tree, r); -} - -// The type descriptor for a float type. Float types are always named. - -Expression* -Float_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - gcc_assert(name != NULL); - return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name); -} - -// We should not be asked for the reflection string of a basic type. - -void -Float_type::do_reflection(Gogo*, std::string*) const -{ - gcc_unreachable(); -} - -// Mangled name. - -void -Float_type::do_mangled_name(Gogo*, std::string* ret) const -{ - char buf[100]; - snprintf(buf, sizeof buf, "f%s%de", - this->is_abstract_ ? "a" : "", - this->bits_); - ret->append(buf); -} - -// Make a floating point type. - -Named_type* -Type::make_float_type(const char* name, int bits, int runtime_type_kind) -{ - return Float_type::create_float_type(name, bits, runtime_type_kind); -} - -// Make an abstract float type. - -Float_type* -Type::make_abstract_float_type() -{ - return Float_type::create_abstract_float_type(); -} - -// Look up a float type. - -Named_type* -Type::lookup_float_type(const char* name) -{ - return Float_type::lookup_float_type(name); -} - -// Class Complex_type. - -Complex_type::Named_complex_types Complex_type::named_complex_types; - -// Create a new complex type. Non-abstract complex types always have -// names. - -Named_type* -Complex_type::create_complex_type(const char* name, int bits, - int runtime_type_kind) -{ - Complex_type* complex_type = new Complex_type(false, bits, - runtime_type_kind); - std::string sname(name); - Named_object* named_object = Named_object::make_type(sname, NULL, - complex_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - std::pair ins = - Complex_type::named_complex_types.insert(std::make_pair(sname, - named_type)); - gcc_assert(ins.second); - return named_type; -} - -// Look up an existing complex type. - -Named_type* -Complex_type::lookup_complex_type(const char* name) -{ - Named_complex_types::const_iterator p = - Complex_type::named_complex_types.find(name); - gcc_assert(p != Complex_type::named_complex_types.end()); - return p->second; -} - -// Create a new abstract complex type. - -Complex_type* -Complex_type::create_abstract_complex_type() -{ - static Complex_type* abstract_type; - if (abstract_type == NULL) - abstract_type = new Complex_type(true, FLOAT_TYPE_SIZE * 2, - RUNTIME_TYPE_KIND_FLOAT); - return abstract_type; -} - -// Whether this type is identical with T. - -bool -Complex_type::is_identical(const Complex_type *t) const -{ - if (this->bits_ != t->bits_) - return false; - return this->is_abstract_ == t->is_abstract_; -} - -// Hash code. - -unsigned int -Complex_type::do_hash_for_method(Gogo*) const -{ - return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8); -} - -// Get a tree without using a Gogo*. - -tree -Complex_type::type_tree() const -{ - if (this->bits_ == FLOAT_TYPE_SIZE * 2) - return complex_float_type_node; - else if (this->bits_ == DOUBLE_TYPE_SIZE * 2) - return complex_double_type_node; - else if (this->bits_ == LONG_DOUBLE_TYPE_SIZE * 2) - return complex_long_double_type_node; - else - { - tree ret = make_node(REAL_TYPE); - TYPE_PRECISION(ret) = this->bits_ / 2; - layout_type(ret); - return build_complex_type(ret); - } -} - -// Get a tree. - -tree -Complex_type::do_get_tree(Gogo*) -{ - return this->type_tree(); -} - -// Zero initializer. - -tree -Complex_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - REAL_VALUE_TYPE r; - real_from_integer(&r, TYPE_MODE(TREE_TYPE(type_tree)), 0, 0, 0); - return build_complex(type_tree, build_real(TREE_TYPE(type_tree), r), - build_real(TREE_TYPE(type_tree), r)); -} - -// The type descriptor for a complex type. Complex types are always -// named. - -Expression* -Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - gcc_assert(name != NULL); - return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name); -} - -// We should not be asked for the reflection string of a basic type. - -void -Complex_type::do_reflection(Gogo*, std::string*) const -{ - gcc_unreachable(); -} - -// Mangled name. - -void -Complex_type::do_mangled_name(Gogo*, std::string* ret) const -{ - char buf[100]; - snprintf(buf, sizeof buf, "c%s%de", - this->is_abstract_ ? "a" : "", - this->bits_); - ret->append(buf); -} - -// Make a complex type. - -Named_type* -Type::make_complex_type(const char* name, int bits, int runtime_type_kind) -{ - return Complex_type::create_complex_type(name, bits, runtime_type_kind); -} - -// Make an abstract complex type. - -Complex_type* -Type::make_abstract_complex_type() -{ - return Complex_type::create_abstract_complex_type(); -} - -// Look up a complex type. - -Named_type* -Type::lookup_complex_type(const char* name) -{ - return Complex_type::lookup_complex_type(name); -} - -// Class String_type. - -// Return the tree for String_type. A string is a struct with two -// fields: a pointer to the characters and a length. - -tree -String_type::do_get_tree(Gogo*) -{ - static tree struct_type; - return Gogo::builtin_struct(&struct_type, "__go_string", NULL_TREE, 2, - "__data", - build_pointer_type(unsigned_char_type_node), - "__length", - integer_type_node); -} - -// Return a tree for the length of STRING. - -tree -String_type::length_tree(Gogo*, tree string) -{ - tree string_type = TREE_TYPE(string); - gcc_assert(TREE_CODE(string_type) == RECORD_TYPE); - tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)), - "__length") == 0); - return fold_build3(COMPONENT_REF, integer_type_node, string, - length_field, NULL_TREE); -} - -// Return a tree for a pointer to the bytes of STRING. - -tree -String_type::bytes_tree(Gogo*, tree string) -{ - tree string_type = TREE_TYPE(string); - gcc_assert(TREE_CODE(string_type) == RECORD_TYPE); - tree bytes_field = TYPE_FIELDS(string_type); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)), - "__data") == 0); - return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string, - bytes_field, NULL_TREE); -} - -// We initialize a string to { NULL, 0 }. - -tree -String_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL_TREE; - - gcc_assert(TREE_CODE(type_tree) == RECORD_TYPE); - - VEC(constructor_elt, gc)* init = VEC_alloc(constructor_elt, gc, 2); - - for (tree field = TYPE_FIELDS(type_tree); - field != NULL_TREE; - field = DECL_CHAIN(field)) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), size_zero_node); - } - - tree ret = build_constructor(type_tree, init); - TREE_CONSTANT(ret) = 1; - return ret; -} - -// The type descriptor for the string type. - -Expression* -String_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (name != NULL) - return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name); - else - { - Named_object* no = gogo->lookup_global("string"); - gcc_assert(no != NULL); - return Type::type_descriptor(gogo, no->type_value()); - } -} - -// We should not be asked for the reflection string of a basic type. - -void -String_type::do_reflection(Gogo*, std::string* ret) const -{ - ret->append("string"); -} - -// Mangled name of a string type. - -void -String_type::do_mangled_name(Gogo*, std::string* ret) const -{ - ret->push_back('z'); -} - -// Make a string type. - -Type* -Type::make_string_type() -{ - static String_type string_type; - return &string_type; -} - -// The named type "string". - -static Named_type* named_string_type; - -// Get the named type "string". - -Named_type* -Type::lookup_string_type() -{ - return named_string_type; -} - -// Make the named type string. - -Named_type* -Type::make_named_string_type() -{ - Type* string_type = Type::make_string_type(); - Named_object* named_object = Named_object::make_type("string", NULL, - string_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - named_string_type = named_type; - return named_type; -} - -// The sink type. This is the type of the blank identifier _. Any -// type may be assigned to it. - -class Sink_type : public Type -{ - public: - Sink_type() - : Type(TYPE_SINK) - { } - - protected: - tree - do_get_tree(Gogo*) - { gcc_unreachable(); } - - tree - do_get_init_tree(Gogo*, tree, bool) - { gcc_unreachable(); } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { gcc_unreachable(); } - - void - do_reflection(Gogo*, std::string*) const - { gcc_unreachable(); } - - void - do_mangled_name(Gogo*, std::string*) const - { gcc_unreachable(); } -}; - -// Make the sink type. - -Type* -Type::make_sink_type() -{ - static Sink_type sink_type; - return &sink_type; -} - -// Class Function_type. - -// Traversal. - -int -Function_type::do_traverse(Traverse* traverse) -{ - if (this->receiver_ != NULL - && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->parameters_ != NULL - && this->parameters_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->results_ != NULL - && this->results_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Returns whether T is a valid redeclaration of this type. If this -// returns false, and REASON is not NULL, *REASON may be set to a -// brief explanation of why it returned false. - -bool -Function_type::is_valid_redeclaration(const Function_type* t, - std::string* reason) const -{ - if (!this->is_identical(t, false, reason)) - return false; - - // A redeclaration of a function is required to use the same names - // for the receiver and parameters. - if (this->receiver() != NULL - && this->receiver()->name() != t->receiver()->name() - && this->receiver()->name() != Import::import_marker - && t->receiver()->name() != Import::import_marker) - { - if (reason != NULL) - *reason = "receiver name changed"; - return false; - } - - const Typed_identifier_list* parms1 = this->parameters(); - const Typed_identifier_list* parms2 = t->parameters(); - if (parms1 != NULL) - { - Typed_identifier_list::const_iterator p1 = parms1->begin(); - for (Typed_identifier_list::const_iterator p2 = parms2->begin(); - p2 != parms2->end(); - ++p2, ++p1) - { - if (p1->name() != p2->name() - && p1->name() != Import::import_marker - && p2->name() != Import::import_marker) - { - if (reason != NULL) - *reason = "parameter name changed"; - return false; - } - - // This is called at parse time, so we may have unknown - // types. - Type* t1 = p1->type()->forwarded(); - Type* t2 = p2->type()->forwarded(); - if (t1 != t2 - && t1->forward_declaration_type() != NULL - && (t2->forward_declaration_type() == NULL - || (t1->forward_declaration_type()->named_object() - != t2->forward_declaration_type()->named_object()))) - return false; - } - } - - const Typed_identifier_list* results1 = this->results(); - const Typed_identifier_list* results2 = t->results(); - if (results1 != NULL) - { - Typed_identifier_list::const_iterator res1 = results1->begin(); - for (Typed_identifier_list::const_iterator res2 = results2->begin(); - res2 != results2->end(); - ++res2, ++res1) - { - if (res1->name() != res2->name() - && res1->name() != Import::import_marker - && res2->name() != Import::import_marker) - { - if (reason != NULL) - *reason = "result name changed"; - return false; - } - - // This is called at parse time, so we may have unknown - // types. - Type* t1 = res1->type()->forwarded(); - Type* t2 = res2->type()->forwarded(); - if (t1 != t2 - && t1->forward_declaration_type() != NULL - && (t2->forward_declaration_type() == NULL - || (t1->forward_declaration_type()->named_object() - != t2->forward_declaration_type()->named_object()))) - return false; - } - } - - return true; -} - -// Check whether T is the same as this type. - -bool -Function_type::is_identical(const Function_type* t, bool ignore_receiver, - std::string* reason) const -{ - if (!ignore_receiver) - { - const Typed_identifier* r1 = this->receiver(); - const Typed_identifier* r2 = t->receiver(); - if ((r1 != NULL) != (r2 != NULL)) - { - if (reason != NULL) - *reason = _("different receiver types"); - return false; - } - if (r1 != NULL) - { - if (!Type::are_identical(r1->type(), r2->type(), reason)) - { - if (reason != NULL && !reason->empty()) - *reason = "receiver: " + *reason; - return false; - } - } - } - - const Typed_identifier_list* parms1 = this->parameters(); - const Typed_identifier_list* parms2 = t->parameters(); - if ((parms1 != NULL) != (parms2 != NULL)) - { - if (reason != NULL) - *reason = _("different number of parameters"); - return false; - } - if (parms1 != NULL) - { - Typed_identifier_list::const_iterator p1 = parms1->begin(); - for (Typed_identifier_list::const_iterator p2 = parms2->begin(); - p2 != parms2->end(); - ++p2, ++p1) - { - if (p1 == parms1->end()) - { - if (reason != NULL) - *reason = _("different number of parameters"); - return false; - } - - if (!Type::are_identical(p1->type(), p2->type(), NULL)) - { - if (reason != NULL) - *reason = _("different parameter types"); - return false; - } - } - if (p1 != parms1->end()) - { - if (reason != NULL) - *reason = _("different number of parameters"); - return false; - } - } - - if (this->is_varargs() != t->is_varargs()) - { - if (reason != NULL) - *reason = _("different varargs"); - return false; - } - - const Typed_identifier_list* results1 = this->results(); - const Typed_identifier_list* results2 = t->results(); - if ((results1 != NULL) != (results2 != NULL)) - { - if (reason != NULL) - *reason = _("different number of results"); - return false; - } - if (results1 != NULL) - { - Typed_identifier_list::const_iterator res1 = results1->begin(); - for (Typed_identifier_list::const_iterator res2 = results2->begin(); - res2 != results2->end(); - ++res2, ++res1) - { - if (res1 == results1->end()) - { - if (reason != NULL) - *reason = _("different number of results"); - return false; - } - - if (!Type::are_identical(res1->type(), res2->type(), NULL)) - { - if (reason != NULL) - *reason = _("different result types"); - return false; - } - } - if (res1 != results1->end()) - { - if (reason != NULL) - *reason = _("different number of results"); - return false; - } - } - - return true; -} - -// Hash code. - -unsigned int -Function_type::do_hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - // We ignore the receiver type for hash codes, because we need to - // get the same hash code for a method in an interface and a method - // declared for a type. The former will not have a receiver. - if (this->parameters_ != NULL) - { - int shift = 1; - for (Typed_identifier_list::const_iterator p = this->parameters_->begin(); - p != this->parameters_->end(); - ++p, ++shift) - ret += p->type()->hash_for_method(gogo) << shift; - } - if (this->results_ != NULL) - { - int shift = 2; - for (Typed_identifier_list::const_iterator p = this->results_->begin(); - p != this->results_->end(); - ++p, ++shift) - ret += p->type()->hash_for_method(gogo) << shift; - } - if (this->is_varargs_) - ret += 1; - ret <<= 4; - return ret; -} - -// Get the tree for a function type. - -tree -Function_type::do_get_tree(Gogo* gogo) -{ - tree args = NULL_TREE; - tree* pp = &args; - - if (this->receiver_ != NULL) - { - Type* rtype = this->receiver_->type(); - tree ptype = rtype->get_tree(gogo); - if (ptype == error_mark_node) - return error_mark_node; - - // We always pass the address of the receiver parameter, in - // order to make interface calls work with unknown types. - if (rtype->points_to() == NULL) - ptype = build_pointer_type(ptype); - - *pp = tree_cons (NULL_TREE, ptype, NULL_TREE); - pp = &TREE_CHAIN (*pp); - } - - if (this->parameters_ != NULL) - { - for (Typed_identifier_list::const_iterator p = this->parameters_->begin(); - p != this->parameters_->end(); - ++p) - { - tree ptype = p->type()->get_tree(gogo); - if (ptype == error_mark_node) - return error_mark_node; - *pp = tree_cons (NULL_TREE, ptype, NULL_TREE); - pp = &TREE_CHAIN (*pp); - } - } - - // Varargs is handled entirely at the Go level. At the tree level, - // functions are not varargs. - *pp = void_list_node; - - tree result; - if (this->results_ == NULL) - result = void_type_node; - else if (this->results_->size() == 1) - result = this->results_->begin()->type()->get_tree(gogo); - else - { - result = make_node(RECORD_TYPE); - tree field_trees = NULL_TREE; - tree* pp = &field_trees; - for (Typed_identifier_list::const_iterator p = this->results_->begin(); - p != this->results_->end(); - ++p) - { - const std::string name = (p->name().empty() - ? "UNNAMED" - : Gogo::unpack_hidden_name(p->name())); - tree name_tree = get_identifier_with_length(name.data(), - name.length()); - tree field_type_tree = p->type()->get_tree(gogo); - if (field_type_tree == error_mark_node) - return error_mark_node; - tree field = build_decl(this->location_, FIELD_DECL, name_tree, - field_type_tree); - DECL_CONTEXT(field) = result; - *pp = field; - pp = &DECL_CHAIN(field); - } - TYPE_FIELDS(result) = field_trees; - layout_type(result); - } - - if (result == error_mark_node) - return error_mark_node; - - tree fntype = build_function_type(result, args); - if (fntype == error_mark_node) - return fntype; - - return build_pointer_type(fntype); -} - -// Functions are initialized to NULL. - -tree -Function_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - return fold_convert(type_tree, null_pointer_node); -} - -// The type of a function type descriptor. - -Type* -Function_type::make_function_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* bool_type = Type::lookup_bool_type(); - - Type* slice_type = Type::make_array_type(ptdt, NULL); - - Struct_type* s = Type::make_builtin_struct_type(4, - "", tdt, - "dotdotdot", bool_type, - "in", slice_type, - "out", slice_type); - - ret = Type::make_builtin_named_type("FuncType", s); - } - - return ret; -} - -// The type descriptor for a function type. - -Expression* -Function_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* ftdt = Function_type::make_function_type_descriptor_type(); - - const Struct_field_list* fields = ftdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(4); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_FUNC, - name, NULL, true)); - - ++p; - gcc_assert(p->field_name() == "dotdotdot"); - vals->push_back(Expression::make_boolean(this->is_varargs(), bloc)); - - ++p; - gcc_assert(p->field_name() == "in"); - vals->push_back(this->type_descriptor_params(p->type(), this->receiver(), - this->parameters())); - - ++p; - gcc_assert(p->field_name() == "out"); - vals->push_back(this->type_descriptor_params(p->type(), NULL, - this->results())); - - ++p; - gcc_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(ftdt, vals, bloc); -} - -// Return a composite literal for the parameters or results of a type -// descriptor. - -Expression* -Function_type::type_descriptor_params(Type* params_type, - const Typed_identifier* receiver, - const Typed_identifier_list* params) -{ - source_location bloc = BUILTINS_LOCATION; - - if (receiver == NULL && params == NULL) - return Expression::make_slice_composite_literal(params_type, NULL, bloc); - - Expression_list* vals = new Expression_list(); - vals->reserve((params == NULL ? 0 : params->size()) - + (receiver != NULL ? 1 : 0)); - - if (receiver != NULL) - { - Type* rtype = receiver->type(); - // The receiver is always passed as a pointer. FIXME: Is this - // right? Should that fact affect the type descriptor? - if (rtype->points_to() == NULL) - rtype = Type::make_pointer_type(rtype); - vals->push_back(Expression::make_type_descriptor(rtype, bloc)); - } - - if (params != NULL) - { - for (Typed_identifier_list::const_iterator p = params->begin(); - p != params->end(); - ++p) - vals->push_back(Expression::make_type_descriptor(p->type(), bloc)); - } - - return Expression::make_slice_composite_literal(params_type, vals, bloc); -} - -// The reflection string. - -void -Function_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - // FIXME: Turn this off until we straighten out the type of the - // struct field used in a go statement which calls a method. - // gcc_assert(this->receiver_ == NULL); - - ret->append("func"); - - if (this->receiver_ != NULL) - { - ret->push_back('('); - this->append_reflection(this->receiver_->type(), gogo, ret); - ret->push_back(')'); - } - - ret->push_back('('); - const Typed_identifier_list* params = this->parameters(); - if (params != NULL) - { - bool is_varargs = this->is_varargs_; - for (Typed_identifier_list::const_iterator p = params->begin(); - p != params->end(); - ++p) - { - if (p != params->begin()) - ret->append(", "); - if (!is_varargs || p + 1 != params->end()) - this->append_reflection(p->type(), gogo, ret); - else - { - ret->append("..."); - this->append_reflection(p->type()->array_type()->element_type(), - gogo, ret); - } - } - } - ret->push_back(')'); - - const Typed_identifier_list* results = this->results(); - if (results != NULL && !results->empty()) - { - if (results->size() == 1) - ret->push_back(' '); - else - ret->append(" ("); - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p) - { - if (p != results->begin()) - ret->append(", "); - this->append_reflection(p->type(), gogo, ret); - } - if (results->size() > 1) - ret->push_back(')'); - } -} - -// Mangled name. - -void -Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('F'); - - if (this->receiver_ != NULL) - { - ret->push_back('m'); - this->append_mangled_name(this->receiver_->type(), gogo, ret); - } - - const Typed_identifier_list* params = this->parameters(); - if (params != NULL) - { - ret->push_back('p'); - for (Typed_identifier_list::const_iterator p = params->begin(); - p != params->end(); - ++p) - this->append_mangled_name(p->type(), gogo, ret); - if (this->is_varargs_) - ret->push_back('V'); - ret->push_back('e'); - } - - const Typed_identifier_list* results = this->results(); - if (results != NULL) - { - ret->push_back('r'); - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p) - this->append_mangled_name(p->type(), gogo, ret); - ret->push_back('e'); - } - - ret->push_back('e'); -} - -// Export a function type. - -void -Function_type::do_export(Export* exp) const -{ - // We don't write out the receiver. The only function types which - // should have a receiver are the ones associated with explicitly - // defined methods. For those the receiver type is written out by - // Function::export_func. - - exp->write_c_string("("); - bool first = true; - if (this->parameters_ != NULL) - { - bool is_varargs = this->is_varargs_; - for (Typed_identifier_list::const_iterator p = - this->parameters_->begin(); - p != this->parameters_->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - if (!is_varargs || p + 1 != this->parameters_->end()) - exp->write_type(p->type()); - else - { - exp->write_c_string("..."); - exp->write_type(p->type()->array_type()->element_type()); - } - } - } - exp->write_c_string(")"); - - const Typed_identifier_list* results = this->results_; - if (results != NULL) - { - exp->write_c_string(" "); - if (results->size() == 1) - exp->write_type(results->begin()->type()); - else - { - first = true; - exp->write_c_string("("); - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - exp->write_type(p->type()); - } - exp->write_c_string(")"); - } - } -} - -// Import a function type. - -Function_type* -Function_type::do_import(Import* imp) -{ - imp->require_c_string("("); - Typed_identifier_list* parameters; - bool is_varargs = false; - if (imp->peek_char() == ')') - parameters = NULL; - else - { - parameters = new Typed_identifier_list(); - while (true) - { - if (imp->match_c_string("...")) - { - imp->advance(3); - is_varargs = true; - } - - Type* ptype = imp->read_type(); - if (is_varargs) - ptype = Type::make_array_type(ptype, NULL); - parameters->push_back(Typed_identifier(Import::import_marker, - ptype, imp->location())); - if (imp->peek_char() != ',') - break; - gcc_assert(!is_varargs); - imp->require_c_string(", "); - } - } - imp->require_c_string(")"); - - Typed_identifier_list* results; - if (imp->peek_char() != ' ') - results = NULL; - else - { - imp->advance(1); - results = new Typed_identifier_list; - if (imp->peek_char() != '(') - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, rtype, - imp->location())); - } - else - { - imp->advance(1); - while (true) - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, - rtype, imp->location())); - if (imp->peek_char() != ',') - break; - imp->require_c_string(", "); - } - imp->require_c_string(")"); - } - } - - Function_type* ret = Type::make_function_type(NULL, parameters, results, - imp->location()); - if (is_varargs) - ret->set_is_varargs(); - return ret; -} - -// Make a copy of a function type without a receiver. - -Function_type* -Function_type::copy_without_receiver() const -{ - gcc_assert(this->is_method()); - Function_type *ret = Type::make_function_type(NULL, this->parameters_, - this->results_, - this->location_); - if (this->is_varargs()) - ret->set_is_varargs(); - if (this->is_builtin()) - ret->set_is_builtin(); - return ret; -} - -// Make a copy of a function type with a receiver. - -Function_type* -Function_type::copy_with_receiver(Type* receiver_type) const -{ - gcc_assert(!this->is_method()); - Typed_identifier* receiver = new Typed_identifier("", receiver_type, - this->location_); - return Type::make_function_type(receiver, this->parameters_, - this->results_, this->location_); -} - -// Make a function type. - -Function_type* -Type::make_function_type(Typed_identifier* receiver, - Typed_identifier_list* parameters, - Typed_identifier_list* results, - source_location location) -{ - return new Function_type(receiver, parameters, results, location); -} - -// Class Pointer_type. - -// Traversal. - -int -Pointer_type::do_traverse(Traverse* traverse) -{ - return Type::traverse(this->to_type_, traverse); -} - -// Hash code. - -unsigned int -Pointer_type::do_hash_for_method(Gogo* gogo) const -{ - return this->to_type_->hash_for_method(gogo) << 4; -} - -// The tree for a pointer type. - -tree -Pointer_type::do_get_tree(Gogo* gogo) -{ - return build_pointer_type(this->to_type_->get_tree(gogo)); -} - -// Initialize a pointer type. - -tree -Pointer_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - return fold_convert(type_tree, null_pointer_node); -} - -// The type of a pointer type descriptor. - -Type* -Pointer_type::make_pointer_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Struct_type* s = Type::make_builtin_struct_type(2, - "", tdt, - "elem", ptdt); - - ret = Type::make_builtin_named_type("PtrType", s); - } - - return ret; -} - -// The type descriptor for a pointer type. - -Expression* -Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (this->is_unsafe_pointer_type()) - { - gcc_assert(name != NULL); - return this->plain_type_descriptor(gogo, - RUNTIME_TYPE_KIND_UNSAFE_POINTER, - name); - } - else - { - source_location bloc = BUILTINS_LOCATION; - - const Methods* methods; - Type* deref = this->points_to(); - if (deref->named_type() != NULL) - methods = deref->named_type()->methods(); - else if (deref->struct_type() != NULL) - methods = deref->struct_type()->methods(); - else - methods = NULL; - - Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type(); - - const Struct_field_list* fields = ptr_tdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(2); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_PTR, - name, methods, false)); - - ++p; - gcc_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(deref, bloc)); - - return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc); - } -} - -// Reflection string. - -void -Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->push_back('*'); - this->append_reflection(this->to_type_, gogo, ret); -} - -// Mangled name. - -void -Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('p'); - this->append_mangled_name(this->to_type_, gogo, ret); -} - -// Export. - -void -Pointer_type::do_export(Export* exp) const -{ - exp->write_c_string("*"); - if (this->is_unsafe_pointer_type()) - exp->write_c_string("any"); - else - exp->write_type(this->to_type_); -} - -// Import. - -Pointer_type* -Pointer_type::do_import(Import* imp) -{ - imp->require_c_string("*"); - if (imp->match_c_string("any")) - { - imp->advance(3); - return Type::make_pointer_type(Type::make_void_type()); - } - Type* to = imp->read_type(); - return Type::make_pointer_type(to); -} - -// Make a pointer type. - -Pointer_type* -Type::make_pointer_type(Type* to_type) -{ - typedef Unordered_map(Type*, Pointer_type*) Hashtable; - static Hashtable pointer_types; - Hashtable::const_iterator p = pointer_types.find(to_type); - if (p != pointer_types.end()) - return p->second; - Pointer_type* ret = new Pointer_type(to_type); - pointer_types[to_type] = ret; - return ret; -} - -// The nil type. We use a special type for nil because it is not the -// same as any other type. In C term nil has type void*, but there is -// no such type in Go. - -class Nil_type : public Type -{ - public: - Nil_type() - : Type(TYPE_NIL) - { } - - protected: - tree - do_get_tree(Gogo*) - { return ptr_type_node; } - - tree - do_get_init_tree(Gogo*, tree type_tree, bool is_clear) - { return is_clear ? NULL : fold_convert(type_tree, null_pointer_node); } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { gcc_unreachable(); } - - void - do_reflection(Gogo*, std::string*) const - { gcc_unreachable(); } - - void - do_mangled_name(Gogo*, std::string* ret) const - { ret->push_back('n'); } -}; - -// Make the nil type. - -Type* -Type::make_nil_type() -{ - static Nil_type singleton_nil_type; - return &singleton_nil_type; -} - -// The type of a function call which returns multiple values. This is -// really a struct, but we don't want to confuse a function call which -// returns a struct with a function call which returns multiple -// values. - -class Call_multiple_result_type : public Type -{ - public: - Call_multiple_result_type(Call_expression* call) - : Type(TYPE_CALL_MULTIPLE_RESULT), - call_(call) - { } - - protected: - bool - do_has_pointer() const - { gcc_unreachable(); } - - tree - do_get_tree(Gogo*); - - tree - do_get_init_tree(Gogo*, tree, bool) - { gcc_unreachable(); } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { gcc_unreachable(); } - - void - do_reflection(Gogo*, std::string*) const - { gcc_unreachable(); } - - void - do_mangled_name(Gogo*, std::string*) const - { gcc_unreachable(); } - - private: - // The expression being called. - Call_expression* call_; -}; - -// Return the tree for a call result. - -tree -Call_multiple_result_type::do_get_tree(Gogo* gogo) -{ - Function_type* fntype = this->call_->get_function_type(); - gcc_assert(fntype != NULL); - const Typed_identifier_list* results = fntype->results(); - gcc_assert(results != NULL && results->size() > 1); - - Struct_field_list* sfl = new Struct_field_list; - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p) - { - const std::string name = ((p->name().empty() - || p->name() == Import::import_marker) - ? "UNNAMED" - : p->name()); - sfl->push_back(Struct_field(Typed_identifier(name, p->type(), - this->call_->location()))); - } - return Type::make_struct_type(sfl, this->call_->location())->get_tree(gogo); -} - -// Make a call result type. - -Type* -Type::make_call_multiple_result_type(Call_expression* call) -{ - return new Call_multiple_result_type(call); -} - -// Class Struct_field. - -// Get the name of a field. - -const std::string& -Struct_field::field_name() const -{ - const std::string& name(this->typed_identifier_.name()); - if (!name.empty()) - return name; - else - { - // This is called during parsing, before anything is lowered, so - // we have to be pretty careful to avoid dereferencing an - // unknown type name. - Type* t = this->typed_identifier_.type(); - Type* dt = t; - if (t->classification() == Type::TYPE_POINTER) - { - // Very ugly. - Pointer_type* ptype = static_cast(t); - dt = ptype->points_to(); - } - if (dt->forward_declaration_type() != NULL) - return dt->forward_declaration_type()->name(); - else if (dt->named_type() != NULL) - return dt->named_type()->name(); - else if (t->is_error_type() || dt->is_error_type()) - { - static const std::string error_string = "*error*"; - return error_string; - } - else - { - // Avoid crashing in the erroneous case where T is named but - // DT is not. - gcc_assert(t != dt); - if (t->forward_declaration_type() != NULL) - return t->forward_declaration_type()->name(); - else if (t->named_type() != NULL) - return t->named_type()->name(); - else - gcc_unreachable(); - } - } -} - -// Class Struct_type. - -// Traversal. - -int -Struct_type::do_traverse(Traverse* traverse) -{ - Struct_field_list* fields = this->fields_; - if (fields != NULL) - { - for (Struct_field_list::iterator p = fields->begin(); - p != fields->end(); - ++p) - { - if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - return TRAVERSE_CONTINUE; -} - -// Verify that the struct type is complete and valid. - -bool -Struct_type::do_verify() -{ - Struct_field_list* fields = this->fields_; - if (fields == NULL) - return true; - for (Struct_field_list::iterator p = fields->begin(); - p != fields->end(); - ++p) - { - Type* t = p->type(); - if (t->is_undefined()) - { - error_at(p->location(), "struct field type is incomplete"); - p->set_type(Type::make_error_type()); - return false; - } - else if (p->is_anonymous()) - { - if (t->named_type() != NULL && t->points_to() != NULL) - { - error_at(p->location(), "embedded type may not be a pointer"); - p->set_type(Type::make_error_type()); - return false; - } - } - } - return true; -} - -// Whether this contains a pointer. - -bool -Struct_type::do_has_pointer() const -{ - const Struct_field_list* fields = this->fields(); - if (fields == NULL) - return false; - for (Struct_field_list::const_iterator p = fields->begin(); - p != fields->end(); - ++p) - { - if (p->type()->has_pointer()) - return true; - } - return false; -} - -// Whether this type is identical to T. - -bool -Struct_type::is_identical(const Struct_type* t) const -{ - const Struct_field_list* fields1 = this->fields(); - const Struct_field_list* fields2 = t->fields(); - if (fields1 == NULL || fields2 == NULL) - return fields1 == fields2; - Struct_field_list::const_iterator pf2 = fields2->begin(); - for (Struct_field_list::const_iterator pf1 = fields1->begin(); - pf1 != fields1->end(); - ++pf1, ++pf2) - { - if (pf2 == fields2->end()) - return false; - if (pf1->field_name() != pf2->field_name()) - return false; - if (pf1->is_anonymous() != pf2->is_anonymous() - || !Type::are_identical(pf1->type(), pf2->type(), NULL)) - return false; - if (!pf1->has_tag()) - { - if (pf2->has_tag()) - return false; - } - else - { - if (!pf2->has_tag()) - return false; - if (pf1->tag() != pf2->tag()) - return false; - } - } - if (pf2 != fields2->end()) - return false; - return true; -} - -// Whether this struct type has any hidden fields. - -bool -Struct_type::struct_has_hidden_fields(const Named_type* within, - std::string* reason) const -{ - const Struct_field_list* fields = this->fields(); - if (fields == NULL) - return false; - const Package* within_package = (within == NULL - ? NULL - : within->named_object()->package()); - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - if (within_package != NULL - && !pf->is_anonymous() - && Gogo::is_hidden_name(pf->field_name())) - { - if (reason != NULL) - { - std::string within_name = within->named_object()->message_name(); - std::string name = Gogo::message_name(pf->field_name()); - size_t bufsize = 200 + within_name.length() + name.length(); - char* buf = new char[bufsize]; - snprintf(buf, bufsize, - _("implicit assignment of %s%s%s hidden field %s%s%s"), - open_quote, within_name.c_str(), close_quote, - open_quote, name.c_str(), close_quote); - reason->assign(buf); - delete[] buf; - } - return true; - } - - if (pf->type()->has_hidden_fields(within, reason)) - return true; - } - - return false; -} - -// Hash code. - -unsigned int -Struct_type::do_hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - if (this->fields() != NULL) - { - for (Struct_field_list::const_iterator pf = this->fields()->begin(); - pf != this->fields()->end(); - ++pf) - ret = (ret << 1) + pf->type()->hash_for_method(gogo); - } - return ret <<= 2; -} - -// Find the local field NAME. - -const Struct_field* -Struct_type::find_local_field(const std::string& name, - unsigned int *pindex) const -{ - const Struct_field_list* fields = this->fields_; - if (fields == NULL) - return NULL; - unsigned int i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++i) - { - if (pf->field_name() == name) - { - if (pindex != NULL) - *pindex = i; - return &*pf; - } - } - return NULL; -} - -// Return an expression for field NAME in STRUCT_EXPR, or NULL. - -Field_reference_expression* -Struct_type::field_reference(Expression* struct_expr, const std::string& name, - source_location location) const -{ - unsigned int depth; - return this->field_reference_depth(struct_expr, name, location, &depth); -} - -// Return an expression for a field, along with the depth at which it -// was found. - -Field_reference_expression* -Struct_type::field_reference_depth(Expression* struct_expr, - const std::string& name, - source_location location, - unsigned int* depth) const -{ - const Struct_field_list* fields = this->fields_; - if (fields == NULL) - return NULL; - - // Look for a field with this name. - unsigned int i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++i) - { - if (pf->field_name() == name) - { - *depth = 0; - return Expression::make_field_reference(struct_expr, i, location); - } - } - - // Look for an anonymous field which contains a field with this - // name. - unsigned int found_depth = 0; - Field_reference_expression* ret = NULL; - i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++i) - { - if (!pf->is_anonymous()) - continue; - - Struct_type* st = pf->type()->deref()->struct_type(); - if (st == NULL) - continue; - - // Look for a reference using a NULL struct expression. If we - // find one, fill in the struct expression with a reference to - // this field. - unsigned int subdepth; - Field_reference_expression* sub = st->field_reference_depth(NULL, name, - location, - &subdepth); - if (sub == NULL) - continue; - - if (ret == NULL || subdepth < found_depth) - { - if (ret != NULL) - delete ret; - ret = sub; - found_depth = subdepth; - Expression* here = Expression::make_field_reference(struct_expr, i, - location); - if (pf->type()->points_to() != NULL) - here = Expression::make_unary(OPERATOR_MULT, here, location); - while (sub->expr() != NULL) - { - sub = sub->expr()->deref()->field_reference_expression(); - gcc_assert(sub != NULL); - } - sub->set_struct_expression(here); - } - else if (subdepth > found_depth) - delete sub; - else - { - // We do not handle ambiguity here--it should be handled by - // Type::bind_field_or_method. - delete sub; - found_depth = 0; - ret = NULL; - } - } - - if (ret != NULL) - *depth = found_depth + 1; - - return ret; -} - -// Return the total number of fields, including embedded fields. - -unsigned int -Struct_type::total_field_count() const -{ - if (this->fields_ == NULL) - return 0; - unsigned int ret = 0; - for (Struct_field_list::const_iterator pf = this->fields_->begin(); - pf != this->fields_->end(); - ++pf) - { - if (!pf->is_anonymous() || pf->type()->deref()->struct_type() == NULL) - ++ret; - else - ret += pf->type()->struct_type()->total_field_count(); - } - return ret; -} - -// Return whether NAME is an unexported field, for better error reporting. - -bool -Struct_type::is_unexported_local_field(Gogo* gogo, - const std::string& name) const -{ - const Struct_field_list* fields = this->fields_; - if (fields != NULL) - { - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - const std::string& field_name(pf->field_name()); - if (Gogo::is_hidden_name(field_name) - && name == Gogo::unpack_hidden_name(field_name) - && gogo->pack_hidden_name(name, false) != field_name) - return true; - } - } - return false; -} - -// Finalize the methods of an unnamed struct. - -void -Struct_type::finalize_methods(Gogo* gogo) -{ - Type::finalize_methods(gogo, this, this->location_, &this->all_methods_); -} - -// Return the method NAME, or NULL if there isn't one or if it is -// ambiguous. Set *IS_AMBIGUOUS if the method exists but is -// ambiguous. - -Method* -Struct_type::method_function(const std::string& name, bool* is_ambiguous) const -{ - return Type::method_function(this->all_methods_, name, is_ambiguous); -} - -// Get the tree for a struct type. - -tree -Struct_type::do_get_tree(Gogo* gogo) -{ - tree type = make_node(RECORD_TYPE); - return this->fill_in_tree(gogo, type); -} - -// Fill in the fields for a struct type. - -tree -Struct_type::fill_in_tree(Gogo* gogo, tree type) -{ - tree field_trees = NULL_TREE; - tree* pp = &field_trees; - for (Struct_field_list::const_iterator p = this->fields_->begin(); - p != this->fields_->end(); - ++p) - { - std::string name = Gogo::unpack_hidden_name(p->field_name()); - tree name_tree = get_identifier_with_length(name.data(), name.length()); - tree field_type_tree = p->type()->get_tree(gogo); - if (field_type_tree == error_mark_node) - return error_mark_node; - tree field = build_decl(p->location(), FIELD_DECL, name_tree, - field_type_tree); - DECL_CONTEXT(field) = type; - *pp = field; - pp = &DECL_CHAIN(field); - } - - TYPE_FIELDS(type) = field_trees; - - layout_type(type); - - return type; -} - -// Initialize struct fields. - -tree -Struct_type::do_get_init_tree(Gogo* gogo, tree type_tree, bool is_clear) -{ - if (this->fields_ == NULL || this->fields_->empty()) - { - if (is_clear) - return NULL; - else - { - tree ret = build_constructor(type_tree, - VEC_alloc(constructor_elt, gc, 0)); - TREE_CONSTANT(ret) = 1; - return ret; - } - } - - bool is_constant = true; - bool any_fields_set = false; - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, - this->fields_->size()); - Struct_field_list::const_iterator p = this->fields_->begin(); - for (tree field = TYPE_FIELDS(type_tree); - field != NULL_TREE; - field = DECL_CHAIN(field), ++p) - { - gcc_assert(p != this->fields_->end()); - tree value = p->type()->get_init_tree(gogo, is_clear); - if (value != NULL) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = value; - any_fields_set = true; - if (!TREE_CONSTANT(value)) - is_constant = false; - } - } - gcc_assert(p == this->fields_->end()); - - if (!any_fields_set) - { - gcc_assert(is_clear); - VEC_free(constructor_elt, gc, init); - return NULL; - } - - tree ret = build_constructor(type_tree, init); - if (is_constant) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// The type of a struct type descriptor. - -Type* -Struct_type::make_struct_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* uintptr_type = Type::lookup_integer_type("uintptr"); - Type* string_type = Type::lookup_string_type(); - Type* pointer_string_type = Type::make_pointer_type(string_type); - - Struct_type* sf = - Type::make_builtin_struct_type(5, - "name", pointer_string_type, - "pkgPath", pointer_string_type, - "typ", ptdt, - "tag", pointer_string_type, - "offset", uintptr_type); - Type* nsf = Type::make_builtin_named_type("structField", sf); - - Type* slice_type = Type::make_array_type(nsf, NULL); - - Struct_type* s = Type::make_builtin_struct_type(2, - "", tdt, - "fields", slice_type); - - ret = Type::make_builtin_named_type("StructType", s); - } - - return ret; -} - -// Build a type descriptor for a struct type. - -Expression* -Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* stdt = Struct_type::make_struct_type_descriptor_type(); - - const Struct_field_list* fields = stdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(2); - - const Methods* methods = this->methods(); - // A named struct should not have methods--the methods should attach - // to the named type. - gcc_assert(methods == NULL || name == NULL); - - Struct_field_list::const_iterator ps = fields->begin(); - gcc_assert(ps->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_STRUCT, - name, methods, true)); - - ++ps; - gcc_assert(ps->field_name() == "fields"); - - Expression_list* elements = new Expression_list(); - elements->reserve(this->fields_->size()); - Type* element_type = ps->type()->array_type()->element_type(); - for (Struct_field_list::const_iterator pf = this->fields_->begin(); - pf != this->fields_->end(); - ++pf) - { - const Struct_field_list* f = element_type->struct_type()->fields(); - - Expression_list* fvals = new Expression_list(); - fvals->reserve(5); - - Struct_field_list::const_iterator q = f->begin(); - gcc_assert(q->field_name() == "name"); - if (pf->is_anonymous()) - fvals->push_back(Expression::make_nil(bloc)); - else - { - std::string n = Gogo::unpack_hidden_name(pf->field_name()); - Expression* s = Expression::make_string(n, bloc); - fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - - ++q; - gcc_assert(q->field_name() == "pkgPath"); - if (!Gogo::is_hidden_name(pf->field_name())) - fvals->push_back(Expression::make_nil(bloc)); - else - { - std::string n = Gogo::hidden_name_prefix(pf->field_name()); - Expression* s = Expression::make_string(n, bloc); - fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - - ++q; - gcc_assert(q->field_name() == "typ"); - fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc)); - - ++q; - gcc_assert(q->field_name() == "tag"); - if (!pf->has_tag()) - fvals->push_back(Expression::make_nil(bloc)); - else - { - Expression* s = Expression::make_string(pf->tag(), bloc); - fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - - ++q; - gcc_assert(q->field_name() == "offset"); - fvals->push_back(Expression::make_struct_field_offset(this, &*pf)); - - Expression* v = Expression::make_struct_composite_literal(element_type, - fvals, bloc); - elements->push_back(v); - } - - vals->push_back(Expression::make_slice_composite_literal(ps->type(), - elements, bloc)); - - return Expression::make_struct_composite_literal(stdt, vals, bloc); -} - -// Reflection string. - -void -Struct_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->append("struct { "); - - for (Struct_field_list::const_iterator p = this->fields_->begin(); - p != this->fields_->end(); - ++p) - { - if (p != this->fields_->begin()) - ret->append("; "); - if (p->is_anonymous()) - ret->push_back('?'); - else - ret->append(Gogo::unpack_hidden_name(p->field_name())); - ret->push_back(' '); - this->append_reflection(p->type(), gogo, ret); - - if (p->has_tag()) - { - const std::string& tag(p->tag()); - ret->append(" \""); - for (std::string::const_iterator p = tag.begin(); - p != tag.end(); - ++p) - { - if (*p == '\0') - ret->append("\\x00"); - else if (*p == '\n') - ret->append("\\n"); - else if (*p == '\t') - ret->append("\\t"); - else if (*p == '"') - ret->append("\\\""); - else if (*p == '\\') - ret->append("\\\\"); - else - ret->push_back(*p); - } - ret->push_back('"'); - } - } - - ret->append(" }"); -} - -// Mangled name. - -void -Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('S'); - - const Struct_field_list* fields = this->fields_; - if (fields != NULL) - { - for (Struct_field_list::const_iterator p = fields->begin(); - p != fields->end(); - ++p) - { - if (p->is_anonymous()) - ret->append("0_"); - else - { - std::string n = Gogo::unpack_hidden_name(p->field_name()); - char buf[20]; - snprintf(buf, sizeof buf, "%u_", - static_cast(n.length())); - ret->append(buf); - ret->append(n); - } - this->append_mangled_name(p->type(), gogo, ret); - if (p->has_tag()) - { - const std::string& tag(p->tag()); - std::string out; - for (std::string::const_iterator p = tag.begin(); - p != tag.end(); - ++p) - { - if (ISALNUM(*p) || *p == '_') - out.push_back(*p); - else - { - char buf[20]; - snprintf(buf, sizeof buf, ".%x.", - static_cast(*p)); - out.append(buf); - } - } - char buf[20]; - snprintf(buf, sizeof buf, "T%u_", - static_cast(out.length())); - ret->append(buf); - ret->append(out); - } - } - } - - ret->push_back('e'); -} - -// Export. - -void -Struct_type::do_export(Export* exp) const -{ - exp->write_c_string("struct { "); - const Struct_field_list* fields = this->fields_; - gcc_assert(fields != NULL); - for (Struct_field_list::const_iterator p = fields->begin(); - p != fields->end(); - ++p) - { - if (p->is_anonymous()) - exp->write_string("? "); - else - { - exp->write_string(p->field_name()); - exp->write_c_string(" "); - } - exp->write_type(p->type()); - - if (p->has_tag()) - { - exp->write_c_string(" "); - Expression* expr = Expression::make_string(p->tag(), - BUILTINS_LOCATION); - expr->export_expression(exp); - delete expr; - } - - exp->write_c_string("; "); - } - exp->write_c_string("}"); -} - -// Import. - -Struct_type* -Struct_type::do_import(Import* imp) -{ - imp->require_c_string("struct { "); - Struct_field_list* fields = new Struct_field_list; - if (imp->peek_char() != '}') - { - while (true) - { - std::string name; - if (imp->match_c_string("? ")) - imp->advance(2); - else - { - name = imp->read_identifier(); - imp->require_c_string(" "); - } - Type* ftype = imp->read_type(); - - Struct_field sf(Typed_identifier(name, ftype, imp->location())); - - if (imp->peek_char() == ' ') - { - imp->advance(1); - Expression* expr = Expression::import_expression(imp); - String_expression* sexpr = expr->string_expression(); - gcc_assert(sexpr != NULL); - sf.set_tag(sexpr->val()); - delete sexpr; - } - - imp->require_c_string("; "); - fields->push_back(sf); - if (imp->peek_char() == '}') - break; - } - } - imp->require_c_string("}"); - - return Type::make_struct_type(fields, imp->location()); -} - -// Make a struct type. - -Struct_type* -Type::make_struct_type(Struct_field_list* fields, - source_location location) -{ - return new Struct_type(fields, location); -} - -// Class Array_type. - -// Whether two array types are identical. - -bool -Array_type::is_identical(const Array_type* t) const -{ - if (!Type::are_identical(this->element_type(), t->element_type(), NULL)) - return false; - - Expression* l1 = this->length(); - Expression* l2 = t->length(); - - // Slices of the same element type are identical. - if (l1 == NULL && l2 == NULL) - return true; - - // Arrays of the same element type are identical if they have the - // same length. - if (l1 != NULL && l2 != NULL) - { - if (l1 == l2) - return true; - - // Try to determine the lengths. If we can't, assume the arrays - // are not identical. - bool ret = false; - mpz_t v1; - mpz_init(v1); - Type* type1; - mpz_t v2; - mpz_init(v2); - Type* type2; - if (l1->integer_constant_value(true, v1, &type1) - && l2->integer_constant_value(true, v2, &type2)) - ret = mpz_cmp(v1, v2) == 0; - mpz_clear(v1); - mpz_clear(v2); - return ret; - } - - // Otherwise the arrays are not identical. - return false; -} - -// Traversal. - -int -Array_type::do_traverse(Traverse* traverse) -{ - if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->length_ != NULL - && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Check that the length is valid. - -bool -Array_type::verify_length() -{ - if (this->length_ == NULL) - return true; - if (!this->length_->is_constant()) - { - error_at(this->length_->location(), "array bound is not constant"); - return false; - } - - mpz_t val; - - Type* t = this->length_->type(); - if (t->integer_type() != NULL) - { - Type* vt; - mpz_init(val); - if (!this->length_->integer_constant_value(true, val, &vt)) - { - error_at(this->length_->location(), - "array bound is not constant"); - mpz_clear(val); - return false; - } - } - else if (t->float_type() != NULL) - { - Type* vt; - mpfr_t fval; - mpfr_init(fval); - if (!this->length_->float_constant_value(fval, &vt)) - { - error_at(this->length_->location(), - "array bound is not constant"); - mpfr_clear(fval); - return false; - } - if (!mpfr_integer_p(fval)) - { - error_at(this->length_->location(), - "array bound truncated to integer"); - mpfr_clear(fval); - return false; - } - mpz_init(val); - mpfr_get_z(val, fval, GMP_RNDN); - mpfr_clear(fval); - } - else - { - if (!t->is_error_type()) - error_at(this->length_->location(), "array bound is not numeric"); - return false; - } - - if (mpz_sgn(val) < 0) - { - error_at(this->length_->location(), "negative array bound"); - mpz_clear(val); - return false; - } - - Type* int_type = Type::lookup_integer_type("int"); - int tbits = int_type->integer_type()->bits(); - int vbits = mpz_sizeinbase(val, 2); - if (vbits + 1 > tbits) - { - error_at(this->length_->location(), "array bound overflows"); - mpz_clear(val); - return false; - } - - mpz_clear(val); - - return true; -} - -// Verify the type. - -bool -Array_type::do_verify() -{ - if (!this->verify_length()) - { - this->length_ = Expression::make_error(this->length_->location()); - return false; - } - return true; -} - -// Array type hash code. - -unsigned int -Array_type::do_hash_for_method(Gogo* gogo) const -{ - // There is no very convenient way to get a hash code for the - // length. - return this->element_type_->hash_for_method(gogo) + 1; -} - -// See if the expression passed to make is suitable. The first -// argument is required, and gives the length. An optional second -// argument is permitted for the capacity. - -bool -Array_type::do_check_make_expression(Expression_list* args, - source_location location) -{ - gcc_assert(this->length_ == NULL); - if (args == NULL || args->empty()) - { - error_at(location, "length required when allocating a slice"); - return false; - } - else if (args->size() > 2) - { - error_at(location, "too many expressions passed to make"); - return false; - } - else - { - if (!Type::check_int_value(args->front(), - _("bad length when making slice"), location)) - return false; - - if (args->size() > 1) - { - if (!Type::check_int_value(args->back(), - _("bad capacity when making slice"), - location)) - return false; - } - - return true; - } -} - -// Get a tree for the length of a fixed array. The length may be -// computed using a function call, so we must only evaluate it once. - -tree -Array_type::get_length_tree(Gogo* gogo) -{ - gcc_assert(this->length_ != NULL); - if (this->length_tree_ == NULL_TREE) - { - mpz_t val; - mpz_init(val); - Type* t; - if (this->length_->integer_constant_value(true, val, &t)) - { - if (t == NULL) - t = Type::lookup_integer_type("int"); - else if (t->is_abstract()) - t = t->make_non_abstract_type(); - tree tt = t->get_tree(gogo); - this->length_tree_ = Expression::integer_constant_tree(val, tt); - mpz_clear(val); - } - else - { - mpz_clear(val); - - // Make up a translation context for the array length - // expression. FIXME: This won't work in general. - Translate_context context(gogo, NULL, NULL, NULL_TREE); - tree len = this->length_->get_tree(&context); - len = convert_to_integer(integer_type_node, len); - this->length_tree_ = save_expr(len); - } - } - return this->length_tree_; -} - -// Get a tree for the type of this array. A fixed array is simply -// represented as ARRAY_TYPE with the appropriate index--i.e., it is -// just like an array in C. An open array is a struct with three -// fields: a data pointer, the length, and the capacity. - -tree -Array_type::do_get_tree(Gogo* gogo) -{ - if (this->length_ == NULL) - { - tree struct_type = gogo->slice_type_tree(void_type_node); - return this->fill_in_tree(gogo, struct_type); - } - else - { - tree element_type_tree = this->element_type_->get_tree(gogo); - tree length_tree = this->get_length_tree(gogo); - if (element_type_tree == error_mark_node - || length_tree == error_mark_node) - return error_mark_node; - - length_tree = fold_convert(sizetype, length_tree); - - // build_index_type takes the maximum index, which is one less - // than the length. - tree index_type = build_index_type(fold_build2(MINUS_EXPR, sizetype, - length_tree, - size_one_node)); - - return build_array_type(element_type_tree, index_type); - } -} - -// Fill in the fields for a slice type. This is used for named slice -// types. - -tree -Array_type::fill_in_tree(Gogo* gogo, tree struct_type) -{ - gcc_assert(this->length_ == NULL); - - tree element_type_tree = this->element_type_->get_tree(gogo); - tree field = TYPE_FIELDS(struct_type); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0); - gcc_assert(POINTER_TYPE_P(TREE_TYPE(field)) - && TREE_TYPE(TREE_TYPE(field)) == void_type_node); - TREE_TYPE(field) = build_pointer_type(element_type_tree); - - return struct_type; -} - -// Return an initializer for an array type. - -tree -Array_type::do_get_init_tree(Gogo* gogo, tree type_tree, bool is_clear) -{ - if (this->length_ == NULL) - { - // Open array. - - if (is_clear) - return NULL; - - gcc_assert(TREE_CODE(type_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - for (tree field = TYPE_FIELDS(type_tree); - field != NULL_TREE; - field = DECL_CHAIN(field)) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, init, - NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), size_zero_node); - } - - tree ret = build_constructor(type_tree, init); - TREE_CONSTANT(ret) = 1; - return ret; - } - else - { - // Fixed array. - - tree value = this->element_type_->get_init_tree(gogo, is_clear); - if (value == NULL) - return NULL; - - tree length_tree = this->get_length_tree(gogo); - length_tree = fold_convert(sizetype, length_tree); - tree range = build2(RANGE_EXPR, sizetype, size_zero_node, - fold_build2(MINUS_EXPR, sizetype, - length_tree, size_one_node)); - tree ret = build_constructor_single(type_tree, range, value); - if (TREE_CONSTANT(value)) - TREE_CONSTANT(ret) = 1; - return ret; - } -} - -// Handle the builtin make function for a slice. - -tree -Array_type::do_make_expression_tree(Translate_context* context, - Expression_list* args, - source_location location) -{ - gcc_assert(this->length_ == NULL); - - Gogo* gogo = context->gogo(); - tree type_tree = this->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - - tree values_field = TYPE_FIELDS(type_tree); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(values_field)), - "__values") == 0); - - tree count_field = DECL_CHAIN(values_field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(count_field)), - "__count") == 0); - - tree element_type_tree = this->element_type_->get_tree(gogo); - if (element_type_tree == error_mark_node) - return error_mark_node; - tree element_size_tree = TYPE_SIZE_UNIT(element_type_tree); - - tree value = this->element_type_->get_init_tree(gogo, true); - - // The first argument is the number of elements, the optional second - // argument is the capacity. - gcc_assert(args != NULL && args->size() >= 1 && args->size() <= 2); - - tree length_tree = args->front()->get_tree(context); - if (length_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(length_tree)) - length_tree = save_expr(length_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(length_tree))) - length_tree = convert_to_integer(TREE_TYPE(count_field), length_tree); - - tree bad_index = Expression::check_bounds(length_tree, - TREE_TYPE(count_field), - NULL_TREE, location); - - length_tree = fold_convert_loc(location, TREE_TYPE(count_field), length_tree); - tree capacity_tree; - if (args->size() == 1) - capacity_tree = length_tree; - else - { - capacity_tree = args->back()->get_tree(context); - if (capacity_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(capacity_tree)) - capacity_tree = save_expr(capacity_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(capacity_tree))) - capacity_tree = convert_to_integer(TREE_TYPE(count_field), - capacity_tree); - - bad_index = Expression::check_bounds(capacity_tree, - TREE_TYPE(count_field), - bad_index, location); - - tree chktype = (((TYPE_SIZE(TREE_TYPE(capacity_tree)) - > TYPE_SIZE(TREE_TYPE(length_tree))) - || ((TYPE_SIZE(TREE_TYPE(capacity_tree)) - == TYPE_SIZE(TREE_TYPE(length_tree))) - && TYPE_UNSIGNED(TREE_TYPE(capacity_tree)))) - ? TREE_TYPE(capacity_tree) - : TREE_TYPE(length_tree)); - tree chk = fold_build2_loc(location, LT_EXPR, boolean_type_node, - fold_convert_loc(location, chktype, - capacity_tree), - fold_convert_loc(location, chktype, - length_tree)); - if (bad_index == NULL_TREE) - bad_index = chk; - else - bad_index = fold_build2_loc(location, TRUTH_OR_EXPR, boolean_type_node, - bad_index, chk); - - capacity_tree = fold_convert_loc(location, TREE_TYPE(count_field), - capacity_tree); - } - - tree size_tree = fold_build2_loc(location, MULT_EXPR, sizetype, - element_size_tree, - fold_convert_loc(location, sizetype, - capacity_tree)); - - tree chk = fold_build2_loc(location, TRUTH_AND_EXPR, boolean_type_node, - fold_build2_loc(location, GT_EXPR, - boolean_type_node, - fold_convert_loc(location, - sizetype, - capacity_tree), - size_zero_node), - fold_build2_loc(location, LT_EXPR, - boolean_type_node, - size_tree, element_size_tree)); - if (bad_index == NULL_TREE) - bad_index = chk; - else - bad_index = fold_build2_loc(location, TRUTH_OR_EXPR, boolean_type_node, - bad_index, chk); - - tree space = context->gogo()->allocate_memory(this->element_type_, - size_tree, location); - - if (value != NULL_TREE) - space = save_expr(space); - - space = fold_convert(TREE_TYPE(values_field), space); - - if (bad_index != NULL_TREE && bad_index != boolean_false_node) - { - tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_SLICE_OUT_OF_BOUNDS, - location); - space = build2(COMPOUND_EXPR, TREE_TYPE(space), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - space); - } - - tree constructor = gogo->slice_constructor(type_tree, space, length_tree, - capacity_tree); - - if (value == NULL_TREE) - { - // The array contents are zero initialized. - return constructor; - } - - // The elements must be initialized. - - tree max = fold_build2_loc(location, MINUS_EXPR, TREE_TYPE(count_field), - capacity_tree, - fold_convert_loc(location, TREE_TYPE(count_field), - integer_one_node)); - - tree array_type = build_array_type(element_type_tree, - build_index_type(max)); - - tree value_pointer = fold_convert_loc(location, - build_pointer_type(array_type), - space); - - tree range = build2(RANGE_EXPR, sizetype, size_zero_node, max); - tree space_init = build_constructor_single(array_type, range, value); - - return build2(COMPOUND_EXPR, TREE_TYPE(space), - build2(MODIFY_EXPR, void_type_node, - build_fold_indirect_ref(value_pointer), - space_init), - constructor); -} - -// Return a tree for a pointer to the values in ARRAY. - -tree -Array_type::value_pointer_tree(Gogo*, tree array) const -{ - tree ret; - if (this->length() != NULL) - { - // Fixed array. - ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))), - build_fold_addr_expr(array)); - } - else - { - // Open array. - tree field = TYPE_FIELDS(TREE_TYPE(array)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__values") == 0); - ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field, - NULL_TREE); - } - if (TREE_CONSTANT(array)) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Return a tree for the length of the array ARRAY which has this -// type. - -tree -Array_type::length_tree(Gogo* gogo, tree array) -{ - if (this->length_ != NULL) - { - if (TREE_CODE(array) == SAVE_EXPR) - return fold_convert(integer_type_node, this->get_length_tree(gogo)); - else - return omit_one_operand(integer_type_node, - this->get_length_tree(gogo), array); - } - - // This is an open array. We need to read the length field. - - tree type = TREE_TYPE(array); - gcc_assert(TREE_CODE(type) == RECORD_TYPE); - - tree field = DECL_CHAIN(TYPE_FIELDS(type)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0); - - tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE); - if (TREE_CONSTANT(array)) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Return a tree for the capacity of the array ARRAY which has this -// type. - -tree -Array_type::capacity_tree(Gogo* gogo, tree array) -{ - if (this->length_ != NULL) - return omit_one_operand(sizetype, this->get_length_tree(gogo), array); - - // This is an open array. We need to read the capacity field. - - tree type = TREE_TYPE(array); - gcc_assert(TREE_CODE(type) == RECORD_TYPE); - - tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type))); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0); - - return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE); -} - -// Export. - -void -Array_type::do_export(Export* exp) const -{ - exp->write_c_string("["); - if (this->length_ != NULL) - this->length_->export_expression(exp); - exp->write_c_string("] "); - exp->write_type(this->element_type_); -} - -// Import. - -Array_type* -Array_type::do_import(Import* imp) -{ - imp->require_c_string("["); - Expression* length; - if (imp->peek_char() == ']') - length = NULL; - else - length = Expression::import_expression(imp); - imp->require_c_string("] "); - Type* element_type = imp->read_type(); - return Type::make_array_type(element_type, length); -} - -// The type of an array type descriptor. - -Type* -Array_type::make_array_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* uintptr_type = Type::lookup_integer_type("uintptr"); - - Struct_type* sf = - Type::make_builtin_struct_type(3, - "", tdt, - "elem", ptdt, - "len", uintptr_type); - - ret = Type::make_builtin_named_type("ArrayType", sf); - } - - return ret; -} - -// The type of an slice type descriptor. - -Type* -Array_type::make_slice_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Struct_type* sf = - Type::make_builtin_struct_type(2, - "", tdt, - "elem", ptdt); - - ret = Type::make_builtin_named_type("SliceType", sf); - } - - return ret; -} - -// Build a type descriptor for an array/slice type. - -Expression* -Array_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (this->length_ != NULL) - return this->array_type_descriptor(gogo, name); - else - return this->slice_type_descriptor(gogo, name); -} - -// Build a type descriptor for an array type. - -Expression* -Array_type::array_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* atdt = Array_type::make_array_type_descriptor_type(); - - const Struct_field_list* fields = atdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(3); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_ARRAY, - name, NULL, true)); - - ++p; - gcc_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc)); - - ++p; - gcc_assert(p->field_name() == "len"); - vals->push_back(this->length_); - - ++p; - gcc_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(atdt, vals, bloc); -} - -// Build a type descriptor for a slice type. - -Expression* -Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* stdt = Array_type::make_slice_type_descriptor_type(); - - const Struct_field_list* fields = stdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(2); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_SLICE, - name, NULL, true)); - - ++p; - gcc_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc)); - - ++p; - gcc_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(stdt, vals, bloc); -} - -// Reflection string. - -void -Array_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->push_back('['); - if (this->length_ != NULL) - { - mpz_t val; - mpz_init(val); - Type* type; - if (!this->length_->integer_constant_value(true, val, &type)) - error_at(this->length_->location(), - "array length must be integer constant expression"); - else if (mpz_cmp_si(val, 0) < 0) - error_at(this->length_->location(), "array length is negative"); - else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0) - error_at(this->length_->location(), "array length is too large"); - else - { - char buf[50]; - snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val)); - ret->append(buf); - } - mpz_clear(val); - } - ret->push_back(']'); - - this->append_reflection(this->element_type_, gogo, ret); -} - -// Mangled name. - -void -Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('A'); - this->append_mangled_name(this->element_type_, gogo, ret); - if (this->length_ != NULL) - { - mpz_t val; - mpz_init(val); - Type* type; - if (!this->length_->integer_constant_value(true, val, &type)) - error_at(this->length_->location(), - "array length must be integer constant expression"); - else if (mpz_cmp_si(val, 0) < 0) - error_at(this->length_->location(), "array length is negative"); - else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0) - error_at(this->length_->location(), "array size is too large"); - else - { - char buf[50]; - snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val)); - ret->append(buf); - } - mpz_clear(val); - } - ret->push_back('e'); -} - -// Make an array type. - -Array_type* -Type::make_array_type(Type* element_type, Expression* length) -{ - return new Array_type(element_type, length); -} - -// Class Map_type. - -// Traversal. - -int -Map_type::do_traverse(Traverse* traverse) -{ - if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT - || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Check that the map type is OK. - -bool -Map_type::do_verify() -{ - if (this->key_type_->struct_type() != NULL - || this->key_type_->array_type() != NULL) - { - error_at(this->location_, "invalid map key type"); - return false; - } - return true; -} - -// Whether two map types are identical. - -bool -Map_type::is_identical(const Map_type* t) const -{ - return (Type::are_identical(this->key_type(), t->key_type(), NULL) - && Type::are_identical(this->val_type(), t->val_type(), NULL)); -} - -// Hash code. - -unsigned int -Map_type::do_hash_for_method(Gogo* gogo) const -{ - return (this->key_type_->hash_for_method(gogo) - + this->val_type_->hash_for_method(gogo) - + 2); -} - -// Check that a call to the builtin make function is valid. For a map -// the optional argument is the number of spaces to preallocate for -// values. - -bool -Map_type::do_check_make_expression(Expression_list* args, - source_location location) -{ - if (args != NULL && !args->empty()) - { - if (!Type::check_int_value(args->front(), _("bad size when making map"), - location)) - return false; - else if (args->size() > 1) - { - error_at(location, "too many arguments when making map"); - return false; - } - } - return true; -} - -// Get a tree for a map type. A map type is represented as a pointer -// to a struct. The struct is __go_map in libgo/map.h. - -tree -Map_type::do_get_tree(Gogo* gogo) -{ - static tree type_tree; - if (type_tree == NULL_TREE) - { - tree struct_type = make_node(RECORD_TYPE); - - tree map_descriptor_type = gogo->map_descriptor_type(); - tree const_map_descriptor_type = - build_qualified_type(map_descriptor_type, TYPE_QUAL_CONST); - tree name = get_identifier("__descriptor"); - tree field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name, - build_pointer_type(const_map_descriptor_type)); - DECL_CONTEXT(field) = struct_type; - TYPE_FIELDS(struct_type) = field; - tree last_field = field; - - name = get_identifier("__element_count"); - field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name, sizetype); - DECL_CONTEXT(field) = struct_type; - DECL_CHAIN(last_field) = field; - last_field = field; - - name = get_identifier("__bucket_count"); - field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name, sizetype); - DECL_CONTEXT(field) = struct_type; - DECL_CHAIN(last_field) = field; - last_field = field; - - name = get_identifier("__buckets"); - field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name, - build_pointer_type(ptr_type_node)); - DECL_CONTEXT(field) = struct_type; - DECL_CHAIN(last_field) = field; - - layout_type(struct_type); - - // Give the struct a name for better debugging info. - name = get_identifier("__go_map"); - tree type_decl = build_decl(BUILTINS_LOCATION, TYPE_DECL, name, - struct_type); - DECL_ARTIFICIAL(type_decl) = 1; - TYPE_NAME(struct_type) = type_decl; - go_preserve_from_gc(type_decl); - rest_of_decl_compilation(type_decl, 1, 0); - - type_tree = build_pointer_type(struct_type); - go_preserve_from_gc(type_tree); - } - - return type_tree; -} - -// Initialize a map. - -tree -Map_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - return fold_convert(type_tree, null_pointer_node); -} - -// Return an expression for a newly allocated map. - -tree -Map_type::do_make_expression_tree(Translate_context* context, - Expression_list* args, - source_location location) -{ - tree bad_index = NULL_TREE; - - tree expr_tree; - if (args == NULL || args->empty()) - expr_tree = size_zero_node; - else - { - expr_tree = args->front()->get_tree(context); - if (expr_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(expr_tree)) - expr_tree = save_expr(expr_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(expr_tree))) - expr_tree = convert_to_integer(sizetype, expr_tree); - bad_index = Expression::check_bounds(expr_tree, sizetype, bad_index, - location); - } - - tree map_type = this->get_tree(context->gogo()); - - static tree new_map_fndecl; - tree ret = Gogo::call_builtin(&new_map_fndecl, - location, - "__go_new_map", - 2, - map_type, - TREE_TYPE(TYPE_FIELDS(TREE_TYPE(map_type))), - context->gogo()->map_descriptor(this), - sizetype, - expr_tree); - // This can panic if the capacity is out of range. - TREE_NOTHROW(new_map_fndecl) = 0; - - if (bad_index == NULL_TREE) - return ret; - else - { - tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_MAP_OUT_OF_BOUNDS, - location); - return build2(COMPOUND_EXPR, TREE_TYPE(ret), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - ret); - } -} - -// The type of a map type descriptor. - -Type* -Map_type::make_map_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Struct_type* sf = - Type::make_builtin_struct_type(3, - "", tdt, - "key", ptdt, - "elem", ptdt); - - ret = Type::make_builtin_named_type("MapType", sf); - } - - return ret; -} - -// Build a type descriptor for a map type. - -Expression* -Map_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* mtdt = Map_type::make_map_type_descriptor_type(); - - const Struct_field_list* fields = mtdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(3); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_MAP, - name, NULL, true)); - - ++p; - gcc_assert(p->field_name() == "key"); - vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc)); - - ++p; - gcc_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc)); - - ++p; - gcc_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(mtdt, vals, bloc); -} - -// Reflection string for a map. - -void -Map_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->append("map["); - this->append_reflection(this->key_type_, gogo, ret); - ret->append("] "); - this->append_reflection(this->val_type_, gogo, ret); -} - -// Mangled name for a map. - -void -Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('M'); - this->append_mangled_name(this->key_type_, gogo, ret); - ret->append("__"); - this->append_mangled_name(this->val_type_, gogo, ret); -} - -// Export a map type. - -void -Map_type::do_export(Export* exp) const -{ - exp->write_c_string("map ["); - exp->write_type(this->key_type_); - exp->write_c_string("] "); - exp->write_type(this->val_type_); -} - -// Import a map type. - -Map_type* -Map_type::do_import(Import* imp) -{ - imp->require_c_string("map ["); - Type* key_type = imp->read_type(); - imp->require_c_string("] "); - Type* val_type = imp->read_type(); - return Type::make_map_type(key_type, val_type, imp->location()); -} - -// Make a map type. - -Map_type* -Type::make_map_type(Type* key_type, Type* val_type, source_location location) -{ - return new Map_type(key_type, val_type, location); -} - -// Class Channel_type. - -// Hash code. - -unsigned int -Channel_type::do_hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - if (this->may_send_) - ret += 1; - if (this->may_receive_) - ret += 2; - if (this->element_type_ != NULL) - ret += this->element_type_->hash_for_method(gogo) << 2; - return ret << 3; -} - -// Whether this type is the same as T. - -bool -Channel_type::is_identical(const Channel_type* t) const -{ - if (!Type::are_identical(this->element_type(), t->element_type(), NULL)) - return false; - return (this->may_send_ == t->may_send_ - && this->may_receive_ == t->may_receive_); -} - -// Check whether the parameters for a call to the builtin function -// make are OK for a channel. A channel can take an optional single -// parameter which is the buffer size. - -bool -Channel_type::do_check_make_expression(Expression_list* args, - source_location location) -{ - if (args != NULL && !args->empty()) - { - if (!Type::check_int_value(args->front(), - _("bad buffer size when making channel"), - location)) - return false; - else if (args->size() > 1) - { - error_at(location, "too many arguments when making channel"); - return false; - } - } - return true; -} - -// Return the tree for a channel type. A channel is a pointer to a -// __go_channel struct. The __go_channel struct is defined in -// libgo/runtime/channel.h. - -tree -Channel_type::do_get_tree(Gogo*) -{ - static tree type_tree; - if (type_tree == NULL_TREE) - { - tree ret = make_node(RECORD_TYPE); - TYPE_NAME(ret) = get_identifier("__go_channel"); - TYPE_STUB_DECL(ret) = build_decl(BUILTINS_LOCATION, TYPE_DECL, NULL_TREE, - ret); - type_tree = build_pointer_type(ret); - go_preserve_from_gc(type_tree); - } - return type_tree; -} - -// Initialize a channel variable. - -tree -Channel_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - return fold_convert(type_tree, null_pointer_node); -} - -// Handle the builtin function make for a channel. - -tree -Channel_type::do_make_expression_tree(Translate_context* context, - Expression_list* args, - source_location location) -{ - Gogo* gogo = context->gogo(); - tree channel_type = this->get_tree(gogo); - - tree element_tree = this->element_type_->get_tree(gogo); - tree element_size_tree = size_in_bytes(element_tree); - - tree bad_index = NULL_TREE; - - tree expr_tree; - if (args == NULL || args->empty()) - expr_tree = size_zero_node; - else - { - expr_tree = args->front()->get_tree(context); - if (expr_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(expr_tree)) - expr_tree = save_expr(expr_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(expr_tree))) - expr_tree = convert_to_integer(sizetype, expr_tree); - bad_index = Expression::check_bounds(expr_tree, sizetype, bad_index, - location); - } - - static tree new_channel_fndecl; - tree ret = Gogo::call_builtin(&new_channel_fndecl, - location, - "__go_new_channel", - 2, - channel_type, - sizetype, - element_size_tree, - sizetype, - expr_tree); - // This can panic if the capacity is out of range. - TREE_NOTHROW(new_channel_fndecl) = 0; - - if (bad_index == NULL_TREE) - return ret; - else - { - tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_CHAN_OUT_OF_BOUNDS, - location); - return build2(COMPOUND_EXPR, TREE_TYPE(ret), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - ret); - } -} - -// Build a type descriptor for a channel type. - -Type* -Channel_type::make_chan_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* uintptr_type = Type::lookup_integer_type("uintptr"); - - Struct_type* sf = - Type::make_builtin_struct_type(3, - "", tdt, - "elem", ptdt, - "dir", uintptr_type); - - ret = Type::make_builtin_named_type("ChanType", sf); - } - - return ret; -} - -// Build a type descriptor for a map type. - -Expression* -Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* ctdt = Channel_type::make_chan_type_descriptor_type(); - - const Struct_field_list* fields = ctdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(3); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_CHAN, - name, NULL, true)); - - ++p; - gcc_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc)); - - ++p; - gcc_assert(p->field_name() == "dir"); - // These bits must match the ones in libgo/runtime/go-type.h. - int val = 0; - if (this->may_receive_) - val |= 1; - if (this->may_send_) - val |= 2; - mpz_t iv; - mpz_init_set_ui(iv, val); - vals->push_back(Expression::make_integer(&iv, p->type(), bloc)); - mpz_clear(iv); - - ++p; - gcc_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(ctdt, vals, bloc); -} - -// Reflection string. - -void -Channel_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - if (!this->may_send_) - ret->append("<-"); - ret->append("chan"); - if (!this->may_receive_) - ret->append("<-"); - ret->push_back(' '); - this->append_reflection(this->element_type_, gogo, ret); -} - -// Mangled name. - -void -Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('C'); - this->append_mangled_name(this->element_type_, gogo, ret); - if (this->may_send_) - ret->push_back('s'); - if (this->may_receive_) - ret->push_back('r'); - ret->push_back('e'); -} - -// Export. - -void -Channel_type::do_export(Export* exp) const -{ - exp->write_c_string("chan "); - if (this->may_send_ && !this->may_receive_) - exp->write_c_string("-< "); - else if (this->may_receive_ && !this->may_send_) - exp->write_c_string("<- "); - exp->write_type(this->element_type_); -} - -// Import. - -Channel_type* -Channel_type::do_import(Import* imp) -{ - imp->require_c_string("chan "); - - bool may_send; - bool may_receive; - if (imp->match_c_string("-< ")) - { - imp->advance(3); - may_send = true; - may_receive = false; - } - else if (imp->match_c_string("<- ")) - { - imp->advance(3); - may_receive = true; - may_send = false; - } - else - { - may_send = true; - may_receive = true; - } - - Type* element_type = imp->read_type(); - - return Type::make_channel_type(may_send, may_receive, element_type); -} - -// Make a new channel type. - -Channel_type* -Type::make_channel_type(bool send, bool receive, Type* element_type) -{ - return new Channel_type(send, receive, element_type); -} - -// Class Interface_type. - -// Traversal. - -int -Interface_type::do_traverse(Traverse* traverse) -{ - if (this->methods_ == NULL) - return TRAVERSE_CONTINUE; - return this->methods_->traverse(traverse); -} - -// Finalize the methods. This handles interface inheritance. - -void -Interface_type::finalize_methods() -{ - if (this->methods_ == NULL) - return; - bool is_recursive = false; - size_t from = 0; - size_t to = 0; - while (from < this->methods_->size()) - { - const Typed_identifier* p = &this->methods_->at(from); - if (!p->name().empty()) - { - if (from != to) - this->methods_->set(to, *p); - ++from; - ++to; - continue; - } - Interface_type* it = p->type()->interface_type(); - if (it == NULL) - { - error_at(p->location(), "interface contains embedded non-interface"); - ++from; - continue; - } - if (it == this) - { - if (!is_recursive) - { - error_at(p->location(), "invalid recursive interface"); - is_recursive = true; - } - ++from; - continue; - } - const Typed_identifier_list* methods = it->methods(); - if (methods == NULL) - { - ++from; - continue; - } - for (Typed_identifier_list::const_iterator q = methods->begin(); - q != methods->end(); - ++q) - { - if (q->name().empty() || this->find_method(q->name()) == NULL) - this->methods_->push_back(Typed_identifier(q->name(), q->type(), - p->location())); - else - { - if (!is_recursive) - error_at(p->location(), "inherited method %qs is ambiguous", - Gogo::message_name(q->name()).c_str()); - } - } - ++from; - } - if (to == 0) - { - delete this->methods_; - this->methods_ = NULL; - } - else - { - this->methods_->resize(to); - this->methods_->sort_by_name(); - } -} - -// Return the method NAME, or NULL. - -const Typed_identifier* -Interface_type::find_method(const std::string& name) const -{ - if (this->methods_ == NULL) - return NULL; - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - if (p->name() == name) - return &*p; - return NULL; -} - -// Return the method index. - -size_t -Interface_type::method_index(const std::string& name) const -{ - gcc_assert(this->methods_ != NULL); - size_t ret = 0; - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p, ++ret) - if (p->name() == name) - return ret; - gcc_unreachable(); -} - -// Return whether NAME is an unexported method, for better error -// reporting. - -bool -Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const -{ - if (this->methods_ == NULL) - return false; - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - const std::string& method_name(p->name()); - if (Gogo::is_hidden_name(method_name) - && name == Gogo::unpack_hidden_name(method_name) - && gogo->pack_hidden_name(name, false) != method_name) - return true; - } - return false; -} - -// Whether this type is identical with T. - -bool -Interface_type::is_identical(const Interface_type* t) const -{ - // We require the same methods with the same types. The methods - // have already been sorted. - if (this->methods() == NULL || t->methods() == NULL) - return this->methods() == t->methods(); - - Typed_identifier_list::const_iterator p1 = this->methods()->begin(); - for (Typed_identifier_list::const_iterator p2 = t->methods()->begin(); - p2 != t->methods()->end(); - ++p1, ++p2) - { - if (p1 == this->methods()->end()) - return false; - if (p1->name() != p2->name() - || !Type::are_identical(p1->type(), p2->type(), NULL)) - return false; - } - if (p1 != this->methods()->end()) - return false; - return true; -} - -// Whether we can assign the interface type T to this type. The types -// are known to not be identical. An interface assignment is only -// permitted if T is known to implement all methods in THIS. -// Otherwise a type guard is required. - -bool -Interface_type::is_compatible_for_assign(const Interface_type* t, - std::string* reason) const -{ - if (this->methods() == NULL) - return true; - for (Typed_identifier_list::const_iterator p = this->methods()->begin(); - p != this->methods()->end(); - ++p) - { - const Typed_identifier* m = t->find_method(p->name()); - if (m == NULL) - { - if (reason != NULL) - { - char buf[200]; - snprintf(buf, sizeof buf, - _("need explicit conversion; missing method %s%s%s"), - open_quote, Gogo::message_name(p->name()).c_str(), - close_quote); - reason->assign(buf); - } - return false; - } - - std::string subreason; - if (!Type::are_identical(p->type(), m->type(), &subreason)) - { - if (reason != NULL) - { - std::string n = Gogo::message_name(p->name()); - size_t len = 100 + n.length() + subreason.length(); - char* buf = new char[len]; - if (subreason.empty()) - snprintf(buf, len, _("incompatible type for method %s%s%s"), - open_quote, n.c_str(), close_quote); - else - snprintf(buf, len, - _("incompatible type for method %s%s%s (%s)"), - open_quote, n.c_str(), close_quote, - subreason.c_str()); - reason->assign(buf); - delete[] buf; - } - return false; - } - } - - return true; -} - -// Hash code. - -unsigned int -Interface_type::do_hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - if (this->methods_ != NULL) - { - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - ret = Type::hash_string(p->name(), ret); - ret += p->type()->hash_for_method(gogo); - ret <<= 1; - } - } - return ret; -} - -// Return true if T implements the interface. If it does not, and -// REASON is not NULL, set *REASON to a useful error message. - -bool -Interface_type::implements_interface(const Type* t, std::string* reason) const -{ - if (this->methods_ == NULL) - return true; - - bool is_pointer = false; - const Named_type* nt = t->named_type(); - const Struct_type* st = t->struct_type(); - // If we start with a named type, we don't dereference it to find - // methods. - if (nt == NULL) - { - const Type* pt = t->points_to(); - if (pt != NULL) - { - // If T is a pointer to a named type, then we need to look at - // the type to which it points. - is_pointer = true; - nt = pt->named_type(); - st = pt->struct_type(); - } - } - - // If we have a named type, get the methods from it rather than from - // any struct type. - if (nt != NULL) - st = NULL; - - // Only named and struct types have methods. - if (nt == NULL && st == NULL) - { - if (reason != NULL) - { - if (t->points_to() != NULL - && t->points_to()->interface_type() != NULL) - reason->assign(_("pointer to interface type has no methods")); - else - reason->assign(_("type has no methods")); - } - return false; - } - - if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods()) - { - if (reason != NULL) - { - if (t->points_to() != NULL - && t->points_to()->interface_type() != NULL) - reason->assign(_("pointer to interface type has no methods")); - else - reason->assign(_("type has no methods")); - } - return false; - } - - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - bool is_ambiguous = false; - Method* m = (nt != NULL - ? nt->method_function(p->name(), &is_ambiguous) - : st->method_function(p->name(), &is_ambiguous)); - if (m == NULL) - { - if (reason != NULL) - { - std::string n = Gogo::message_name(p->name()); - size_t len = n.length() + 100; - char* buf = new char[len]; - if (is_ambiguous) - snprintf(buf, len, _("ambiguous method %s%s%s"), - open_quote, n.c_str(), close_quote); - else - snprintf(buf, len, _("missing method %s%s%s"), - open_quote, n.c_str(), close_quote); - reason->assign(buf); - delete[] buf; - } - return false; - } - - Function_type *p_fn_type = p->type()->function_type(); - Function_type* m_fn_type = m->type()->function_type(); - gcc_assert(p_fn_type != NULL && m_fn_type != NULL); - std::string subreason; - if (!p_fn_type->is_identical(m_fn_type, true, &subreason)) - { - if (reason != NULL) - { - std::string n = Gogo::message_name(p->name()); - size_t len = 100 + n.length() + subreason.length(); - char* buf = new char[len]; - if (subreason.empty()) - snprintf(buf, len, _("incompatible type for method %s%s%s"), - open_quote, n.c_str(), close_quote); - else - snprintf(buf, len, - _("incompatible type for method %s%s%s (%s)"), - open_quote, n.c_str(), close_quote, - subreason.c_str()); - reason->assign(buf); - delete[] buf; - } - return false; - } - - if (!is_pointer && !m->is_value_method()) - { - if (reason != NULL) - { - std::string n = Gogo::message_name(p->name()); - size_t len = 100 + n.length(); - char* buf = new char[len]; - snprintf(buf, len, _("method %s%s%s requires a pointer"), - open_quote, n.c_str(), close_quote); - reason->assign(buf); - delete[] buf; - } - return false; - } - } - - return true; -} - -// Return a tree for an interface type. An interface is a pointer to -// a struct. The struct has three fields. The first field is a -// pointer to the type descriptor for the dynamic type of the object. -// The second field is a pointer to a table of methods for the -// interface to be used with the object. The third field is the value -// of the object itself. - -tree -Interface_type::do_get_tree(Gogo* gogo) -{ - if (this->methods_ == NULL) - { - // At the tree level, use the same type for all empty - // interfaces. This lets us assign them to each other directly - // without triggering GIMPLE type errors. - tree dtype = Type::make_type_descriptor_type()->get_tree(gogo); - dtype = build_pointer_type(build_qualified_type(dtype, TYPE_QUAL_CONST)); - static tree empty_interface; - return Gogo::builtin_struct(&empty_interface, "__go_empty_interface", - NULL_TREE, 2, - "__type_descriptor", - dtype, - "__object", - ptr_type_node); - } - - return this->fill_in_tree(gogo, make_node(RECORD_TYPE)); -} - -// Fill in the tree for an interface type. This is used for named -// interface types. - -tree -Interface_type::fill_in_tree(Gogo* gogo, tree type) -{ - gcc_assert(this->methods_ != NULL); - - // Build the type of the table of methods. - - tree method_table = make_node(RECORD_TYPE); - - // The first field is a pointer to the type descriptor. - tree name_tree = get_identifier("__type_descriptor"); - tree dtype = Type::make_type_descriptor_type()->get_tree(gogo); - dtype = build_pointer_type(build_qualified_type(dtype, TYPE_QUAL_CONST)); - tree field = build_decl(this->location_, FIELD_DECL, name_tree, dtype); - DECL_CONTEXT(field) = method_table; - TYPE_FIELDS(method_table) = field; - - std::string last_name = ""; - tree* pp = &DECL_CHAIN(field); - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - std::string name = Gogo::unpack_hidden_name(p->name()); - name_tree = get_identifier_with_length(name.data(), name.length()); - tree field_type = p->type()->get_tree(gogo); - if (field_type == error_mark_node) - return error_mark_node; - field = build_decl(this->location_, FIELD_DECL, name_tree, field_type); - DECL_CONTEXT(field) = method_table; - *pp = field; - pp = &DECL_CHAIN(field); - // Sanity check: the names should be sorted. - gcc_assert(p->name() > last_name); - last_name = p->name(); - } - layout_type(method_table); - - tree mtype = build_pointer_type(method_table); - - tree field_trees = NULL_TREE; - pp = &field_trees; - - name_tree = get_identifier("__methods"); - field = build_decl(this->location_, FIELD_DECL, name_tree, mtype); - DECL_CONTEXT(field) = type; - *pp = field; - pp = &DECL_CHAIN(field); - - name_tree = get_identifier("__object"); - field = build_decl(this->location_, FIELD_DECL, name_tree, ptr_type_node); - DECL_CONTEXT(field) = type; - *pp = field; - - TYPE_FIELDS(type) = field_trees; - - layout_type(type); - - return type; -} - -// Initialization value. - -tree -Interface_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - for (tree field = TYPE_FIELDS(type_tree); - field != NULL_TREE; - field = DECL_CHAIN(field)) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), null_pointer_node); - } - - tree ret = build_constructor(type_tree, init); - TREE_CONSTANT(ret) = 1; - return ret; -} - -// The type of an interface type descriptor. - -Type* -Interface_type::make_interface_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* string_type = Type::lookup_string_type(); - Type* pointer_string_type = Type::make_pointer_type(string_type); - - Struct_type* sm = - Type::make_builtin_struct_type(3, - "name", pointer_string_type, - "pkgPath", pointer_string_type, - "typ", ptdt); - - Type* nsm = Type::make_builtin_named_type("imethod", sm); - - Type* slice_nsm = Type::make_array_type(nsm, NULL); - - Struct_type* s = Type::make_builtin_struct_type(2, - "", tdt, - "methods", slice_nsm); - - ret = Type::make_builtin_named_type("InterfaceType", s); - } - - return ret; -} - -// Build a type descriptor for an interface type. - -Expression* -Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* itdt = Interface_type::make_interface_type_descriptor_type(); - - const Struct_field_list* ifields = itdt->struct_type()->fields(); - - Expression_list* ivals = new Expression_list(); - ivals->reserve(2); - - Struct_field_list::const_iterator pif = ifields->begin(); - gcc_assert(pif->field_name() == "commonType"); - ivals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_INTERFACE, - name, NULL, true)); - - ++pif; - gcc_assert(pif->field_name() == "methods"); - - Expression_list* methods = new Expression_list(); - if (this->methods_ != NULL && !this->methods_->empty()) - { - Type* elemtype = pif->type()->array_type()->element_type(); - - methods->reserve(this->methods_->size()); - for (Typed_identifier_list::const_iterator pm = this->methods_->begin(); - pm != this->methods_->end(); - ++pm) - { - const Struct_field_list* mfields = elemtype->struct_type()->fields(); - - Expression_list* mvals = new Expression_list(); - mvals->reserve(3); - - Struct_field_list::const_iterator pmf = mfields->begin(); - gcc_assert(pmf->field_name() == "name"); - std::string s = Gogo::unpack_hidden_name(pm->name()); - Expression* e = Expression::make_string(s, bloc); - mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc)); - - ++pmf; - gcc_assert(pmf->field_name() == "pkgPath"); - if (!Gogo::is_hidden_name(pm->name())) - mvals->push_back(Expression::make_nil(bloc)); - else - { - s = Gogo::hidden_name_prefix(pm->name()); - e = Expression::make_string(s, bloc); - mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc)); - } - - ++pmf; - gcc_assert(pmf->field_name() == "typ"); - mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc)); - - ++pmf; - gcc_assert(pmf == mfields->end()); - - e = Expression::make_struct_composite_literal(elemtype, mvals, - bloc); - methods->push_back(e); - } - } - - ivals->push_back(Expression::make_slice_composite_literal(pif->type(), - methods, bloc)); - - ++pif; - gcc_assert(pif == ifields->end()); - - return Expression::make_struct_composite_literal(itdt, ivals, bloc); -} - -// Reflection string. - -void -Interface_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->append("interface {"); - if (this->methods_ != NULL) - { - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - if (p != this->methods_->begin()) - ret->append(";"); - ret->push_back(' '); - ret->append(Gogo::unpack_hidden_name(p->name())); - std::string sub = p->type()->reflection(gogo); - gcc_assert(sub.compare(0, 4, "func") == 0); - sub = sub.substr(4); - ret->append(sub); - } - } - ret->append(" }"); -} - -// Mangled name. - -void -Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('I'); - - const Typed_identifier_list* methods = this->methods_; - if (methods != NULL) - { - for (Typed_identifier_list::const_iterator p = methods->begin(); - p != methods->end(); - ++p) - { - std::string n = Gogo::unpack_hidden_name(p->name()); - char buf[20]; - snprintf(buf, sizeof buf, "%u_", - static_cast(n.length())); - ret->append(buf); - ret->append(n); - this->append_mangled_name(p->type(), gogo, ret); - } - } - - ret->push_back('e'); -} - -// Export. - -void -Interface_type::do_export(Export* exp) const -{ - exp->write_c_string("interface { "); - - const Typed_identifier_list* methods = this->methods_; - if (methods != NULL) - { - for (Typed_identifier_list::const_iterator pm = methods->begin(); - pm != methods->end(); - ++pm) - { - exp->write_string(pm->name()); - exp->write_c_string(" ("); - - const Function_type* fntype = pm->type()->function_type(); - - bool first = true; - const Typed_identifier_list* parameters = fntype->parameters(); - if (parameters != NULL) - { - bool is_varargs = fntype->is_varargs(); - for (Typed_identifier_list::const_iterator pp = - parameters->begin(); - pp != parameters->end(); - ++pp) - { - if (first) - first = false; - else - exp->write_c_string(", "); - if (!is_varargs || pp + 1 != parameters->end()) - exp->write_type(pp->type()); - else - { - exp->write_c_string("..."); - Type *pptype = pp->type(); - exp->write_type(pptype->array_type()->element_type()); - } - } - } - - exp->write_c_string(")"); - - const Typed_identifier_list* results = fntype->results(); - if (results != NULL) - { - exp->write_c_string(" "); - if (results->size() == 1) - exp->write_type(results->begin()->type()); - else - { - first = true; - exp->write_c_string("("); - for (Typed_identifier_list::const_iterator p = - results->begin(); - p != results->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - exp->write_type(p->type()); - } - exp->write_c_string(")"); - } - } - - exp->write_c_string("; "); - } - } - - exp->write_c_string("}"); -} - -// Import an interface type. - -Interface_type* -Interface_type::do_import(Import* imp) -{ - imp->require_c_string("interface { "); - - Typed_identifier_list* methods = new Typed_identifier_list; - while (imp->peek_char() != '}') - { - std::string name = imp->read_identifier(); - imp->require_c_string(" ("); - - Typed_identifier_list* parameters; - bool is_varargs = false; - if (imp->peek_char() == ')') - parameters = NULL; - else - { - parameters = new Typed_identifier_list; - while (true) - { - if (imp->match_c_string("...")) - { - imp->advance(3); - is_varargs = true; - } - - Type* ptype = imp->read_type(); - if (is_varargs) - ptype = Type::make_array_type(ptype, NULL); - parameters->push_back(Typed_identifier(Import::import_marker, - ptype, imp->location())); - if (imp->peek_char() != ',') - break; - gcc_assert(!is_varargs); - imp->require_c_string(", "); - } - } - imp->require_c_string(")"); - - Typed_identifier_list* results; - if (imp->peek_char() != ' ') - results = NULL; - else - { - results = new Typed_identifier_list; - imp->advance(1); - if (imp->peek_char() != '(') - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, - rtype, imp->location())); - } - else - { - imp->advance(1); - while (true) - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, - rtype, imp->location())); - if (imp->peek_char() != ',') - break; - imp->require_c_string(", "); - } - imp->require_c_string(")"); - } - } - - Function_type* fntype = Type::make_function_type(NULL, parameters, - results, - imp->location()); - if (is_varargs) - fntype->set_is_varargs(); - methods->push_back(Typed_identifier(name, fntype, imp->location())); - - imp->require_c_string("; "); - } - - imp->require_c_string("}"); - - if (methods->empty()) - { - delete methods; - methods = NULL; - } - - return Type::make_interface_type(methods, imp->location()); -} - -// Make an interface type. - -Interface_type* -Type::make_interface_type(Typed_identifier_list* methods, - source_location location) -{ - return new Interface_type(methods, location); -} - -// Class Method. - -// Bind a method to an object. - -Expression* -Method::bind_method(Expression* expr, source_location location) const -{ - if (this->stub_ == NULL) - { - // When there is no stub object, the binding is determined by - // the child class. - return this->do_bind_method(expr, location); - } - - Expression* func = Expression::make_func_reference(this->stub_, NULL, - location); - return Expression::make_bound_method(expr, func, location); -} - -// Return the named object associated with a method. This may only be -// called after methods are finalized. - -Named_object* -Method::named_object() const -{ - if (this->stub_ != NULL) - return this->stub_; - return this->do_named_object(); -} - -// Class Named_method. - -// The type of the method. - -Function_type* -Named_method::do_type() const -{ - if (this->named_object_->is_function()) - return this->named_object_->func_value()->type(); - else if (this->named_object_->is_function_declaration()) - return this->named_object_->func_declaration_value()->type(); - else - gcc_unreachable(); -} - -// Return the location of the method receiver. - -source_location -Named_method::do_receiver_location() const -{ - return this->do_type()->receiver()->location(); -} - -// Bind a method to an object. - -Expression* -Named_method::do_bind_method(Expression* expr, source_location location) const -{ - Expression* func = Expression::make_func_reference(this->named_object_, NULL, - location); - Bound_method_expression* bme = Expression::make_bound_method(expr, func, - location); - // If this is not a local method, and it does not use a stub, then - // the real method expects a different type. We need to cast the - // first argument. - if (this->depth() > 0 && !this->needs_stub_method()) - { - Function_type* ftype = this->do_type(); - gcc_assert(ftype->is_method()); - Type* frtype = ftype->receiver()->type(); - bme->set_first_argument_type(frtype); - } - return bme; -} - -// Class Interface_method. - -// Bind a method to an object. - -Expression* -Interface_method::do_bind_method(Expression* expr, - source_location location) const -{ - return Expression::make_interface_field_reference(expr, this->name_, - location); -} - -// Class Methods. - -// Insert a new method. Return true if it was inserted, false -// otherwise. - -bool -Methods::insert(const std::string& name, Method* m) -{ - std::pair ins = - this->methods_.insert(std::make_pair(name, m)); - if (ins.second) - return true; - else - { - Method* old_method = ins.first->second; - if (m->depth() < old_method->depth()) - { - delete old_method; - ins.first->second = m; - return true; - } - else - { - if (m->depth() == old_method->depth()) - old_method->set_is_ambiguous(); - return false; - } - } -} - -// Return the number of unambiguous methods. - -size_t -Methods::count() const -{ - size_t ret = 0; - for (Method_map::const_iterator p = this->methods_.begin(); - p != this->methods_.end(); - ++p) - if (!p->second->is_ambiguous()) - ++ret; - return ret; -} - -// Class Named_type. - -// Return the name of the type. - -const std::string& -Named_type::name() const -{ - return this->named_object_->name(); -} - -// Return the name of the type to use in an error message. - -std::string -Named_type::message_name() const -{ - return this->named_object_->message_name(); -} - -// Add a method to this type. - -Named_object* -Named_type::add_method(const std::string& name, Function* function) -{ - if (this->local_methods_ == NULL) - this->local_methods_ = new Bindings(NULL); - return this->local_methods_->add_function(name, NULL, function); -} - -// Add a method declaration to this type. - -Named_object* -Named_type::add_method_declaration(const std::string& name, Package* package, - Function_type* type, - source_location location) -{ - if (this->local_methods_ == NULL) - this->local_methods_ = new Bindings(NULL); - return this->local_methods_->add_function_declaration(name, package, type, - location); -} - -// Add an existing method to this type. - -void -Named_type::add_existing_method(Named_object* no) -{ - if (this->local_methods_ == NULL) - this->local_methods_ = new Bindings(NULL); - this->local_methods_->add_named_object(no); -} - -// Look for a local method NAME, and returns its named object, or NULL -// if not there. - -Named_object* -Named_type::find_local_method(const std::string& name) const -{ - if (this->local_methods_ == NULL) - return NULL; - return this->local_methods_->lookup(name); -} - -// Return whether NAME is an unexported field or method, for better -// error reporting. - -bool -Named_type::is_unexported_local_method(Gogo* gogo, - const std::string& name) const -{ - Bindings* methods = this->local_methods_; - if (methods != NULL) - { - for (Bindings::const_declarations_iterator p = - methods->begin_declarations(); - p != methods->end_declarations(); - ++p) - { - if (Gogo::is_hidden_name(p->first) - && name == Gogo::unpack_hidden_name(p->first) - && gogo->pack_hidden_name(name, false) != p->first) - return true; - } - } - return false; -} - -// Build the complete list of methods for this type, which means -// recursively including all methods for anonymous fields. Create all -// stub methods. - -void -Named_type::finalize_methods(Gogo* gogo) -{ - if (this->local_methods_ != NULL - && (this->points_to() != NULL || this->interface_type() != NULL)) - { - const Bindings* lm = this->local_methods_; - for (Bindings::const_declarations_iterator p = lm->begin_declarations(); - p != lm->end_declarations(); - ++p) - error_at(p->second->location(), - "invalid pointer or interface receiver type"); - delete this->local_methods_; - this->local_methods_ = NULL; - return; - } - - Type::finalize_methods(gogo, this, this->location_, &this->all_methods_); -} - -// Return the method NAME, or NULL if there isn't one or if it is -// ambiguous. Set *IS_AMBIGUOUS if the method exists but is -// ambiguous. - -Method* -Named_type::method_function(const std::string& name, bool* is_ambiguous) const -{ - return Type::method_function(this->all_methods_, name, is_ambiguous); -} - -// Return a pointer to the interface method table for this type for -// the interface INTERFACE. IS_POINTER is true if this is for a -// pointer to THIS. - -tree -Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface, - bool is_pointer) -{ - gcc_assert(!interface->is_empty()); - - Interface_method_tables** pimt = (is_pointer - ? &this->interface_method_tables_ - : &this->pointer_interface_method_tables_); - - if (*pimt == NULL) - *pimt = new Interface_method_tables(5); - - std::pair val(interface, NULL_TREE); - std::pair ins = (*pimt)->insert(val); - - if (ins.second) - { - // This is a new entry in the hash table. - gcc_assert(ins.first->second == NULL_TREE); - ins.first->second = gogo->interface_method_table_for_type(interface, - this, - is_pointer); - } - - tree decl = ins.first->second; - if (decl == error_mark_node) - return error_mark_node; - gcc_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL); - return build_fold_addr_expr(decl); -} - -// Return whether a named type has any hidden fields. - -bool -Named_type::named_type_has_hidden_fields(std::string* reason) const -{ - if (this->seen_) - return false; - this->seen_ = true; - bool ret = this->type_->has_hidden_fields(this, reason); - this->seen_ = false; - return ret; -} - -// Look for a use of a complete type within another type. This is -// used to check that we don't try to use a type within itself. - -class Find_type_use : public Traverse -{ - public: - Find_type_use(Type* find_type) - : Traverse(traverse_types), - find_type_(find_type), found_(false) - { } - - // Whether we found the type. - bool - found() const - { return this->found_; } - - protected: - int - type(Type*); - - private: - // The type we are looking for. - Type* find_type_; - // Whether we found the type. - bool found_; -}; - -// Check for FIND_TYPE in TYPE. - -int -Find_type_use::type(Type* type) -{ - if (this->find_type_ == type) - { - this->found_ = true; - return TRAVERSE_EXIT; - } - // It's OK if we see a reference to the type in any type which is - // essentially a pointer: a pointer, a slice, a function, a map, or - // a channel. - if (type->points_to() != NULL - || type->is_open_array_type() - || type->function_type() != NULL - || type->map_type() != NULL - || type->channel_type() != NULL) - return TRAVERSE_SKIP_COMPONENTS; - - // For an interface, a reference to the type in a method type should - // be ignored, but we have to consider direct inheritance. When - // this is called, there may be cases of direct inheritance - // represented as a method with no name. - if (type->interface_type() != NULL) - { - const Typed_identifier_list* methods = type->interface_type()->methods(); - if (methods != NULL) - { - for (Typed_identifier_list::const_iterator p = methods->begin(); - p != methods->end(); - ++p) - { - if (p->name().empty()) - { - if (Type::traverse(p->type(), this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - } - return TRAVERSE_SKIP_COMPONENTS; - } - - return TRAVERSE_CONTINUE; -} - -// Verify that a named type does not refer to itself. - -bool -Named_type::do_verify() -{ - Find_type_use find(this); - Type::traverse(this->type_, &find); - if (find.found()) - { - error_at(this->location_, "invalid recursive type %qs", - this->message_name().c_str()); - this->is_error_ = true; - return false; - } - - // Check whether any of the local methods overloads an existing - // struct field or interface method. We don't need to check the - // list of methods against itself: that is handled by the Bindings - // code. - if (this->local_methods_ != NULL) - { - Struct_type* st = this->type_->struct_type(); - Interface_type* it = this->type_->interface_type(); - bool found_dup = false; - if (st != NULL || it != NULL) - { - for (Bindings::const_declarations_iterator p = - this->local_methods_->begin_declarations(); - p != this->local_methods_->end_declarations(); - ++p) - { - const std::string& name(p->first); - if (st != NULL && st->find_local_field(name, NULL) != NULL) - { - error_at(p->second->location(), - "method %qs redeclares struct field name", - Gogo::message_name(name).c_str()); - found_dup = true; - } - if (it != NULL && it->find_method(name) != NULL) - { - error_at(p->second->location(), - "method %qs redeclares interface method name", - Gogo::message_name(name).c_str()); - found_dup = true; - } - } - } - if (found_dup) - return false; - } - - return true; -} - -// Return a hash code. This is used for method lookup. We simply -// hash on the name itself. - -unsigned int -Named_type::do_hash_for_method(Gogo* gogo) const -{ - const std::string& name(this->named_object()->name()); - unsigned int ret = Type::hash_string(name, 0); - - // GOGO will be NULL here when called from Type_hash_identical. - // That is OK because that is only used for internal hash tables - // where we are going to be comparing named types for equality. In - // other cases, which are cases where the runtime is going to - // compare hash codes to see if the types are the same, we need to - // include the package prefix and name in the hash. - if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin()) - { - const Package* package = this->named_object()->package(); - if (package == NULL) - { - ret = Type::hash_string(gogo->unique_prefix(), ret); - ret = Type::hash_string(gogo->package_name(), ret); - } - else - { - ret = Type::hash_string(package->unique_prefix(), ret); - ret = Type::hash_string(package->name(), ret); - } - } - - return ret; -} - -// Get a tree for a named type. - -tree -Named_type::do_get_tree(Gogo* gogo) -{ - if (this->is_error_) - return error_mark_node; - - // Go permits types to refer to themselves in various ways. Break - // the recursion here. - tree t; - switch (this->type_->forwarded()->classification()) - { - case TYPE_ERROR: - return error_mark_node; - - case TYPE_VOID: - case TYPE_BOOLEAN: - case TYPE_INTEGER: - case TYPE_FLOAT: - case TYPE_COMPLEX: - case TYPE_STRING: - case TYPE_NIL: - // These types can not refer to themselves. - case TYPE_MAP: - case TYPE_CHANNEL: - // All maps and channels have the same type in GENERIC. - t = Type::get_named_type_tree(gogo, this->type_); - if (t == error_mark_node) - return error_mark_node; - // Build a copy to set TYPE_NAME. - t = build_variant_type_copy(t); - break; - - case TYPE_FUNCTION: - // GENERIC can't handle a pointer to a function type whose - // return type is a pointer to the function type itself. It - // does into infinite loops when walking the types. - if (this->seen_ - && this->function_type()->results() != NULL - && this->function_type()->results()->size() == 1 - && (this->function_type()->results()->front().type()->forwarded() - == this)) - return ptr_type_node; - this->seen_ = true; - t = Type::get_named_type_tree(gogo, this->type_); - this->seen_ = false; - if (t == error_mark_node) - return error_mark_node; - t = build_variant_type_copy(t); - break; - - case TYPE_POINTER: - // GENERIC can't handle a pointer type which points to itself. - // It goes into infinite loops when walking the types. - if (this->seen_ && this->points_to()->forwarded() == this) - return ptr_type_node; - this->seen_ = true; - t = Type::get_named_type_tree(gogo, this->type_); - this->seen_ = false; - if (t == error_mark_node) - return error_mark_node; - t = build_variant_type_copy(t); - break; - - case TYPE_STRUCT: - if (this->named_tree_ != NULL_TREE) - return this->named_tree_; - t = make_node(RECORD_TYPE); - this->named_tree_ = t; - this->type_->struct_type()->fill_in_tree(gogo, t); - break; - - case TYPE_ARRAY: - if (!this->is_open_array_type()) - t = Type::get_named_type_tree(gogo, this->type_); - else - { - if (this->named_tree_ != NULL_TREE) - return this->named_tree_; - t = gogo->slice_type_tree(void_type_node); - this->named_tree_ = t; - t = this->type_->array_type()->fill_in_tree(gogo, t); - } - if (t == error_mark_node) - return error_mark_node; - t = build_variant_type_copy(t); - break; - - case TYPE_INTERFACE: - if (this->type_->interface_type()->is_empty()) - { - t = Type::get_named_type_tree(gogo, this->type_); - if (t == error_mark_node) - return error_mark_node; - t = build_variant_type_copy(t); - } - else - { - if (this->named_tree_ != NULL_TREE) - return this->named_tree_; - t = make_node(RECORD_TYPE); - this->named_tree_ = t; - t = this->type_->interface_type()->fill_in_tree(gogo, t); - } - break; - - case TYPE_NAMED: - { - // When a named type T1 is defined as another named type T2, - // the definition must simply be "type T1 T2". If the - // definition of T2 may refer to T1, then we must simply - // return the type for T2 here. It's not precisely correct, - // but it's as close as we can get with GENERIC. - bool was_seen = this->seen_; - this->seen_ = true; - t = Type::get_named_type_tree(gogo, this->type_); - this->seen_ = was_seen; - if (was_seen) - return t; - if (t == error_mark_node) - return error_mark_node; - t = build_variant_type_copy(t); - } - break; - - case TYPE_FORWARD: - // An undefined forwarding type. Make sure the error is - // emitted. - this->type_->forward_declaration_type()->real_type(); - return error_mark_node; - - default: - case TYPE_SINK: - case TYPE_CALL_MULTIPLE_RESULT: - gcc_unreachable(); - } - - tree id = this->named_object_->get_id(gogo); - tree decl = build_decl(this->location_, TYPE_DECL, id, t); - TYPE_NAME(t) = decl; - - return t; -} - -// Build a type descriptor for a named type. - -Expression* -Named_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - // If NAME is not NULL, then we don't really want the type - // descriptor for this type; we want the descriptor for the - // underlying type, giving it the name NAME. - return this->named_type_descriptor(gogo, this->type_, - name == NULL ? this : name); -} - -// Add to the reflection string. This is used mostly for the name of -// the type used in a type descriptor, not for actual reflection -// strings. - -void -Named_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - if (this->location() != BUILTINS_LOCATION) - { - const Package* package = this->named_object_->package(); - if (package != NULL) - ret->append(package->name()); - else - ret->append(gogo->package_name()); - ret->push_back('.'); - } - if (this->in_function_ != NULL) - { - ret->append(Gogo::unpack_hidden_name(this->in_function_->name())); - ret->push_back('$'); - } - ret->append(Gogo::unpack_hidden_name(this->named_object_->name())); -} - -// Get the mangled name. - -void -Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - Named_object* no = this->named_object_; - std::string name; - if (this->location() == BUILTINS_LOCATION) - gcc_assert(this->in_function_ == NULL); - else - { - const std::string& unique_prefix(no->package() == NULL - ? gogo->unique_prefix() - : no->package()->unique_prefix()); - const std::string& package_name(no->package() == NULL - ? gogo->package_name() - : no->package()->name()); - name = unique_prefix; - name.append(1, '.'); - name.append(package_name); - name.append(1, '.'); - if (this->in_function_ != NULL) - { - name.append(Gogo::unpack_hidden_name(this->in_function_->name())); - name.append(1, '$'); - } - } - name.append(Gogo::unpack_hidden_name(no->name())); - char buf[20]; - snprintf(buf, sizeof buf, "N%u_", static_cast(name.length())); - ret->append(buf); - ret->append(name); -} - -// Export the type. This is called to export a global type. - -void -Named_type::export_named_type(Export* exp, const std::string&) const -{ - // We don't need to write the name of the type here, because it will - // be written by Export::write_type anyhow. - exp->write_c_string("type "); - exp->write_type(this); - exp->write_c_string(";\n"); -} - -// Import a named type. - -void -Named_type::import_named_type(Import* imp, Named_type** ptype) -{ - imp->require_c_string("type "); - Type *type = imp->read_type(); - *ptype = type->named_type(); - gcc_assert(*ptype != NULL); - imp->require_c_string(";\n"); -} - -// Export the type when it is referenced by another type. In this -// case Export::export_type will already have issued the name. - -void -Named_type::do_export(Export* exp) const -{ - exp->write_type(this->type_); - - // To save space, we only export the methods directly attached to - // this type. - Bindings* methods = this->local_methods_; - if (methods == NULL) - return; - - exp->write_c_string("\n"); - for (Bindings::const_definitions_iterator p = methods->begin_definitions(); - p != methods->end_definitions(); - ++p) - { - exp->write_c_string(" "); - (*p)->export_named_object(exp); - } - - for (Bindings::const_declarations_iterator p = methods->begin_declarations(); - p != methods->end_declarations(); - ++p) - { - if (p->second->is_function_declaration()) - { - exp->write_c_string(" "); - p->second->export_named_object(exp); - } - } -} - -// Make a named type. - -Named_type* -Type::make_named_type(Named_object* named_object, Type* type, - source_location location) -{ - return new Named_type(named_object, type, location); -} - -// Finalize the methods for TYPE. It will be a named type or a struct -// type. This sets *ALL_METHODS to the list of methods, and builds -// all required stubs. - -void -Type::finalize_methods(Gogo* gogo, const Type* type, source_location location, - Methods** all_methods) -{ - *all_methods = NULL; - Types_seen types_seen; - Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen, - all_methods); - Type::build_stub_methods(gogo, type, *all_methods, location); -} - -// Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to -// build up the struct field indexes as we go. DEPTH is the depth of -// the field within TYPE. IS_EMBEDDED_POINTER is true if we are -// adding these methods for an anonymous field with pointer type. -// NEEDS_STUB_METHOD is true if we need to use a stub method which -// calls the real method. TYPES_SEEN is used to avoid infinite -// recursion. - -void -Type::add_methods_for_type(const Type* type, - const Method::Field_indexes* field_indexes, - unsigned int depth, - bool is_embedded_pointer, - bool needs_stub_method, - Types_seen* types_seen, - Methods** methods) -{ - // Pointer types may not have methods. - if (type->points_to() != NULL) - return; - - const Named_type* nt = type->named_type(); - if (nt != NULL) - { - std::pair ins = types_seen->insert(nt); - if (!ins.second) - return; - } - - if (nt != NULL) - Type::add_local_methods_for_type(nt, field_indexes, depth, - is_embedded_pointer, needs_stub_method, - methods); - - Type::add_embedded_methods_for_type(type, field_indexes, depth, - is_embedded_pointer, needs_stub_method, - types_seen, methods); - - // If we are called with depth > 0, then we are looking at an - // anonymous field of a struct. If such a field has interface type, - // then we need to add the interface methods. We don't want to add - // them when depth == 0, because we will already handle them - // following the usual rules for an interface type. - if (depth > 0) - Type::add_interface_methods_for_type(type, field_indexes, depth, methods); -} - -// Add the local methods for the named type NT to *METHODS. The -// parameters are as for add_methods_to_type. - -void -Type::add_local_methods_for_type(const Named_type* nt, - const Method::Field_indexes* field_indexes, - unsigned int depth, - bool is_embedded_pointer, - bool needs_stub_method, - Methods** methods) -{ - const Bindings* local_methods = nt->local_methods(); - if (local_methods == NULL) - return; - - if (*methods == NULL) - *methods = new Methods(); - - for (Bindings::const_declarations_iterator p = - local_methods->begin_declarations(); - p != local_methods->end_declarations(); - ++p) - { - Named_object* no = p->second; - bool is_value_method = (is_embedded_pointer - || !Type::method_expects_pointer(no)); - Method* m = new Named_method(no, field_indexes, depth, is_value_method, - (needs_stub_method - || (depth > 0 && is_value_method))); - if (!(*methods)->insert(no->name(), m)) - delete m; - } -} - -// Add the embedded methods for TYPE to *METHODS. These are the -// methods attached to anonymous fields. The parameters are as for -// add_methods_to_type. - -void -Type::add_embedded_methods_for_type(const Type* type, - const Method::Field_indexes* field_indexes, - unsigned int depth, - bool is_embedded_pointer, - bool needs_stub_method, - Types_seen* types_seen, - Methods** methods) -{ - // Look for anonymous fields in TYPE. TYPE has fields if it is a - // struct. - const Struct_type* st = type->struct_type(); - if (st == NULL) - return; - - const Struct_field_list* fields = st->fields(); - if (fields == NULL) - return; - - unsigned int i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++i) - { - if (!pf->is_anonymous()) - continue; - - Type* ftype = pf->type(); - bool is_pointer = false; - if (ftype->points_to() != NULL) - { - ftype = ftype->points_to(); - is_pointer = true; - } - Named_type* fnt = ftype->named_type(); - if (fnt == NULL) - { - // This is an error, but it will be diagnosed elsewhere. - continue; - } - - Method::Field_indexes* sub_field_indexes = new Method::Field_indexes(); - sub_field_indexes->next = field_indexes; - sub_field_indexes->field_index = i; - - Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1, - (is_embedded_pointer || is_pointer), - (needs_stub_method - || is_pointer - || i > 0), - types_seen, - methods); - } -} - -// If TYPE is an interface type, then add its method to *METHODS. -// This is for interface methods attached to an anonymous field. The -// parameters are as for add_methods_for_type. - -void -Type::add_interface_methods_for_type(const Type* type, - const Method::Field_indexes* field_indexes, - unsigned int depth, - Methods** methods) -{ - const Interface_type* it = type->interface_type(); - if (it == NULL) - return; - - const Typed_identifier_list* imethods = it->methods(); - if (imethods == NULL) - return; - - if (*methods == NULL) - *methods = new Methods(); - - for (Typed_identifier_list::const_iterator pm = imethods->begin(); - pm != imethods->end(); - ++pm) - { - Function_type* fntype = pm->type()->function_type(); - gcc_assert(fntype != NULL && !fntype->is_method()); - fntype = fntype->copy_with_receiver(const_cast(type)); - Method* m = new Interface_method(pm->name(), pm->location(), fntype, - field_indexes, depth); - if (!(*methods)->insert(pm->name(), m)) - delete m; - } -} - -// Build stub methods for TYPE as needed. METHODS is the set of -// methods for the type. A stub method may be needed when a type -// inherits a method from an anonymous field. When we need the -// address of the method, as in a type descriptor, we need to build a -// little stub which does the required field dereferences and jumps to -// the real method. LOCATION is the location of the type definition. - -void -Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods, - source_location location) -{ - if (methods == NULL) - return; - for (Methods::const_iterator p = methods->begin(); - p != methods->end(); - ++p) - { - Method* m = p->second; - if (m->is_ambiguous() || !m->needs_stub_method()) - continue; - - const std::string& name(p->first); - - // Build a stub method. - - const Function_type* fntype = m->type(); - - static unsigned int counter; - char buf[100]; - snprintf(buf, sizeof buf, "$this%u", counter); - ++counter; - - Type* receiver_type = const_cast(type); - if (!m->is_value_method()) - receiver_type = Type::make_pointer_type(receiver_type); - source_location receiver_location = m->receiver_location(); - Typed_identifier* receiver = new Typed_identifier(buf, receiver_type, - receiver_location); - - const Typed_identifier_list* fnparams = fntype->parameters(); - Typed_identifier_list* stub_params; - if (fnparams == NULL || fnparams->empty()) - stub_params = NULL; - else - { - // We give each stub parameter a unique name. - stub_params = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator pp = fnparams->begin(); - pp != fnparams->end(); - ++pp) - { - char pbuf[100]; - snprintf(pbuf, sizeof pbuf, "$p%u", counter); - stub_params->push_back(Typed_identifier(pbuf, pp->type(), - pp->location())); - ++counter; - } - } - - const Typed_identifier_list* fnresults = fntype->results(); - Typed_identifier_list* stub_results; - if (fnresults == NULL || fnresults->empty()) - stub_results = NULL; - else - { - // We create the result parameters without any names, since - // we won't refer to them. - stub_results = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator pr = fnresults->begin(); - pr != fnresults->end(); - ++pr) - stub_results->push_back(Typed_identifier("", pr->type(), - pr->location())); - } - - Function_type* stub_type = Type::make_function_type(receiver, - stub_params, - stub_results, - fntype->location()); - if (fntype->is_varargs()) - stub_type->set_is_varargs(); - - // We only create the function in the package which creates the - // type. - const Package* package; - if (type->named_type() == NULL) - package = NULL; - else - package = type->named_type()->named_object()->package(); - Named_object* stub; - if (package != NULL) - stub = Named_object::make_function_declaration(name, package, - stub_type, location); - else - { - stub = gogo->start_function(name, stub_type, false, - fntype->location()); - Type::build_one_stub_method(gogo, m, buf, stub_params, - fntype->is_varargs(), location); - gogo->finish_function(fntype->location()); - } - - m->set_stub_object(stub); - } -} - -// Build a stub method which adjusts the receiver as required to call -// METHOD. RECEIVER_NAME is the name we used for the receiver. -// PARAMS is the list of function parameters. - -void -Type::build_one_stub_method(Gogo* gogo, Method* method, - const char* receiver_name, - const Typed_identifier_list* params, - bool is_varargs, - source_location location) -{ - Named_object* receiver_object = gogo->lookup(receiver_name, NULL); - gcc_assert(receiver_object != NULL); - - Expression* expr = Expression::make_var_reference(receiver_object, location); - expr = Type::apply_field_indexes(expr, method->field_indexes(), location); - if (expr->type()->points_to() == NULL) - expr = Expression::make_unary(OPERATOR_AND, expr, location); - - Expression_list* arguments; - if (params == NULL || params->empty()) - arguments = NULL; - else - { - arguments = new Expression_list(); - for (Typed_identifier_list::const_iterator p = params->begin(); - p != params->end(); - ++p) - { - Named_object* param = gogo->lookup(p->name(), NULL); - gcc_assert(param != NULL); - Expression* param_ref = Expression::make_var_reference(param, - location); - arguments->push_back(param_ref); - } - } - - Expression* func = method->bind_method(expr, location); - gcc_assert(func != NULL); - Call_expression* call = Expression::make_call(func, arguments, is_varargs, - location); - size_t count = call->result_count(); - if (count == 0) - gogo->add_statement(Statement::make_statement(call)); - else - { - Expression_list* retvals = new Expression_list(); - if (count <= 1) - retvals->push_back(call); - else - { - for (size_t i = 0; i < count; ++i) - retvals->push_back(Expression::make_call_result(call, i)); - } - const Function* function = gogo->current_function()->func_value(); - const Typed_identifier_list* results = function->type()->results(); - Statement* retstat = Statement::make_return_statement(results, retvals, - location); - gogo->add_statement(retstat); - } -} - -// Apply FIELD_INDEXES to EXPR. The field indexes have to be applied -// in reverse order. - -Expression* -Type::apply_field_indexes(Expression* expr, - const Method::Field_indexes* field_indexes, - source_location location) -{ - if (field_indexes == NULL) - return expr; - expr = Type::apply_field_indexes(expr, field_indexes->next, location); - Struct_type* stype = expr->type()->deref()->struct_type(); - gcc_assert(stype != NULL - && field_indexes->field_index < stype->field_count()); - if (expr->type()->struct_type() == NULL) - { - gcc_assert(expr->type()->points_to() != NULL); - expr = Expression::make_unary(OPERATOR_MULT, expr, location); - gcc_assert(expr->type()->struct_type() == stype); - } - return Expression::make_field_reference(expr, field_indexes->field_index, - location); -} - -// Return whether NO is a method for which the receiver is a pointer. - -bool -Type::method_expects_pointer(const Named_object* no) -{ - const Function_type *fntype; - if (no->is_function()) - fntype = no->func_value()->type(); - else if (no->is_function_declaration()) - fntype = no->func_declaration_value()->type(); - else - gcc_unreachable(); - return fntype->receiver()->type()->points_to() != NULL; -} - -// Given a set of methods for a type, METHODS, return the method NAME, -// or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS -// is not NULL, then set *IS_AMBIGUOUS to true if the method exists -// but is ambiguous (and return NULL). - -Method* -Type::method_function(const Methods* methods, const std::string& name, - bool* is_ambiguous) -{ - if (is_ambiguous != NULL) - *is_ambiguous = false; - if (methods == NULL) - return NULL; - Methods::const_iterator p = methods->find(name); - if (p == methods->end()) - return NULL; - Method* m = p->second; - if (m->is_ambiguous()) - { - if (is_ambiguous != NULL) - *is_ambiguous = true; - return NULL; - } - return m; -} - -// Look for field or method NAME for TYPE. Return an Expression for -// the field or method bound to EXPR. If there is no such field or -// method, give an appropriate error and return an error expression. - -Expression* -Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr, - const std::string& name, - source_location location) -{ - if (type->is_error_type()) - return Expression::make_error(location); - - const Named_type* nt = type->named_type(); - if (nt == NULL) - nt = type->deref()->named_type(); - const Struct_type* st = type->deref()->struct_type(); - const Interface_type* it = type->deref()->interface_type(); - - // If this is a pointer to a pointer, then it is possible that the - // pointed-to type has methods. - if (nt == NULL - && st == NULL - && it == NULL - && type->points_to() != NULL - && type->points_to()->points_to() != NULL) - { - expr = Expression::make_unary(OPERATOR_MULT, expr, location); - type = type->points_to(); - nt = type->points_to()->named_type(); - st = type->points_to()->struct_type(); - it = type->points_to()->interface_type(); - } - - bool receiver_can_be_pointer = (expr->type()->points_to() != NULL - || expr->is_addressable()); - bool is_method = false; - bool found_pointer_method = false; - std::string ambig1; - std::string ambig2; - if (Type::find_field_or_method(type, name, receiver_can_be_pointer, NULL, - &is_method, &found_pointer_method, - &ambig1, &ambig2)) - { - Expression* ret; - if (!is_method) - { - gcc_assert(st != NULL); - if (type->struct_type() == NULL) - { - gcc_assert(type->points_to() != NULL); - expr = Expression::make_unary(OPERATOR_MULT, expr, - location); - gcc_assert(expr->type()->struct_type() == st); - } - ret = st->field_reference(expr, name, location); - } - else if (it != NULL && it->find_method(name) != NULL) - ret = Expression::make_interface_field_reference(expr, name, - location); - else - { - Method* m; - if (nt != NULL) - m = nt->method_function(name, NULL); - else if (st != NULL) - m = st->method_function(name, NULL); - else - gcc_unreachable(); - gcc_assert(m != NULL); - if (!m->is_value_method() && expr->type()->points_to() == NULL) - expr = Expression::make_unary(OPERATOR_AND, expr, location); - ret = m->bind_method(expr, location); - } - gcc_assert(ret != NULL); - return ret; - } - else - { - if (!ambig1.empty()) - error_at(location, "%qs is ambiguous via %qs and %qs", - Gogo::message_name(name).c_str(), - Gogo::message_name(ambig1).c_str(), - Gogo::message_name(ambig2).c_str()); - else if (found_pointer_method) - error_at(location, "method requires a pointer"); - else if (nt == NULL && st == NULL && it == NULL) - error_at(location, - ("reference to field %qs in object which " - "has no fields or methods"), - Gogo::message_name(name).c_str()); - else - { - bool is_unexported; - if (!Gogo::is_hidden_name(name)) - is_unexported = false; - else - { - std::string unpacked = Gogo::unpack_hidden_name(name); - is_unexported = Type::is_unexported_field_or_method(gogo, type, - unpacked); - } - if (is_unexported) - error_at(location, "reference to unexported field or method %qs", - Gogo::message_name(name).c_str()); - else - error_at(location, "reference to undefined field or method %qs", - Gogo::message_name(name).c_str()); - } - return Expression::make_error(location); - } -} - -// Look in TYPE for a field or method named NAME, return true if one -// is found. This looks through embedded anonymous fields and handles -// ambiguity. If a method is found, sets *IS_METHOD to true; -// otherwise, if a field is found, set it to false. If -// RECEIVER_CAN_BE_POINTER is false, then the receiver is a value -// whose address can not be taken. When returning false, this sets -// *FOUND_POINTER_METHOD if we found a method we couldn't use because -// it requires a pointer. LEVEL is used for recursive calls, and can -// be NULL for a non-recursive call. When this function returns false -// because it finds that the name is ambiguous, it will store a path -// to the ambiguous names in *AMBIG1 and *AMBIG2. If the name is not -// found at all, *AMBIG1 and *AMBIG2 will be unchanged. - -// This function just returns whether or not there is a field or -// method, and whether it is a field or method. It doesn't build an -// expression to refer to it. If it is a method, we then look in the -// list of all methods for the type. If it is a field, the search has -// to be done again, looking only for fields, and building up the -// expression as we go. - -bool -Type::find_field_or_method(const Type* type, - const std::string& name, - bool receiver_can_be_pointer, - int* level, - bool* is_method, - bool* found_pointer_method, - std::string* ambig1, - std::string* ambig2) -{ - // Named types can have locally defined methods. - const Named_type* nt = type->named_type(); - if (nt == NULL && type->points_to() != NULL) - nt = type->points_to()->named_type(); - if (nt != NULL) - { - Named_object* no = nt->find_local_method(name); - if (no != NULL) - { - if (receiver_can_be_pointer || !Type::method_expects_pointer(no)) - { - *is_method = true; - return true; - } - - // Record that we have found a pointer method in order to - // give a better error message if we don't find anything - // else. - *found_pointer_method = true; - } - } - - // Interface types can have methods. - const Interface_type* it = type->deref()->interface_type(); - if (it != NULL && it->find_method(name) != NULL) - { - *is_method = true; - return true; - } - - // Struct types can have fields. They can also inherit fields and - // methods from anonymous fields. - const Struct_type* st = type->deref()->struct_type(); - if (st == NULL) - return false; - const Struct_field_list* fields = st->fields(); - if (fields == NULL) - return false; - - int found_level = 0; - bool found_is_method = false; - std::string found_ambig1; - std::string found_ambig2; - const Struct_field* found_parent = NULL; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - if (pf->field_name() == name) - { - *is_method = false; - return true; - } - - if (!pf->is_anonymous()) - continue; - - Named_type* fnt = pf->type()->deref()->named_type(); - gcc_assert(fnt != NULL); - - int sublevel = level == NULL ? 1 : *level + 1; - bool sub_is_method; - std::string subambig1; - std::string subambig2; - bool subfound = Type::find_field_or_method(fnt, - name, - receiver_can_be_pointer, - &sublevel, - &sub_is_method, - found_pointer_method, - &subambig1, - &subambig2); - if (!subfound) - { - if (!subambig1.empty()) - { - // The name was found via this field, but is ambiguous. - // if the ambiguity is lower or at the same level as - // anything else we have already found, then we want to - // pass the ambiguity back to the caller. - if (found_level == 0 || sublevel <= found_level) - { - found_ambig1 = pf->field_name() + '.' + subambig1; - found_ambig2 = pf->field_name() + '.' + subambig2; - found_level = sublevel; - } - } - } - else - { - // The name was found via this field. Use the level to see - // if we want to use this one, or whether it introduces an - // ambiguity. - if (found_level == 0 || sublevel < found_level) - { - found_level = sublevel; - found_is_method = sub_is_method; - found_ambig1.clear(); - found_ambig2.clear(); - found_parent = &*pf; - } - else if (sublevel > found_level) - ; - else if (found_ambig1.empty()) - { - // We found an ambiguity. - gcc_assert(found_parent != NULL); - found_ambig1 = found_parent->field_name(); - found_ambig2 = pf->field_name(); - } - else - { - // We found an ambiguity, but we already know of one. - // Just report the earlier one. - } - } - } - - // Here if we didn't find anything FOUND_LEVEL is 0. If we found - // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and - // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL - // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty. - - if (found_level == 0) - return false; - else if (!found_ambig1.empty()) - { - gcc_assert(!found_ambig1.empty()); - ambig1->assign(found_ambig1); - ambig2->assign(found_ambig2); - if (level != NULL) - *level = found_level; - return false; - } - else - { - if (level != NULL) - *level = found_level; - *is_method = found_is_method; - return true; - } -} - -// Return whether NAME is an unexported field or method for TYPE. - -bool -Type::is_unexported_field_or_method(Gogo* gogo, const Type* type, - const std::string& name) -{ - type = type->deref(); - - const Named_type* nt = type->named_type(); - if (nt != NULL && nt->is_unexported_local_method(gogo, name)) - return true; - - const Interface_type* it = type->interface_type(); - if (it != NULL && it->is_unexported_method(gogo, name)) - return true; - - const Struct_type* st = type->struct_type(); - if (st != NULL && st->is_unexported_local_field(gogo, name)) - return true; - - if (st == NULL) - return false; - - const Struct_field_list* fields = st->fields(); - if (fields == NULL) - return false; - - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - if (pf->is_anonymous()) - { - Named_type* subtype = pf->type()->deref()->named_type(); - gcc_assert(subtype != NULL); - if (Type::is_unexported_field_or_method(gogo, subtype, name)) - return true; - } - } - - return false; -} - -// Class Forward_declaration. - -Forward_declaration_type::Forward_declaration_type(Named_object* named_object) - : Type(TYPE_FORWARD), - named_object_(named_object->resolve()), warned_(false) -{ - gcc_assert(this->named_object_->is_unknown() - || this->named_object_->is_type_declaration()); -} - -// Return the named object. - -Named_object* -Forward_declaration_type::named_object() -{ - return this->named_object_->resolve(); -} - -const Named_object* -Forward_declaration_type::named_object() const -{ - return this->named_object_->resolve(); -} - -// Return the name of the forward declared type. - -const std::string& -Forward_declaration_type::name() const -{ - return this->named_object()->name(); -} - -// Warn about a use of a type which has been declared but not defined. - -void -Forward_declaration_type::warn() const -{ - Named_object* no = this->named_object_->resolve(); - if (no->is_unknown()) - { - // The name was not defined anywhere. - if (!this->warned_) - { - error_at(this->named_object_->location(), - "use of undefined type %qs", - no->message_name().c_str()); - this->warned_ = true; - } - } - else if (no->is_type_declaration()) - { - // The name was seen as a type, but the type was never defined. - if (no->type_declaration_value()->using_type()) - { - error_at(this->named_object_->location(), - "use of undefined type %qs", - no->message_name().c_str()); - this->warned_ = true; - } - } - else - { - // The name was defined, but not as a type. - if (!this->warned_) - { - error_at(this->named_object_->location(), "expected type"); - this->warned_ = true; - } - } -} - -// Get the base type of a declaration. This gives an error if the -// type has not yet been defined. - -Type* -Forward_declaration_type::real_type() -{ - if (this->is_defined()) - return this->named_object()->type_value(); - else - { - this->warn(); - return Type::make_error_type(); - } -} - -const Type* -Forward_declaration_type::real_type() const -{ - if (this->is_defined()) - return this->named_object()->type_value(); - else - { - this->warn(); - return Type::make_error_type(); - } -} - -// Return whether the base type is defined. - -bool -Forward_declaration_type::is_defined() const -{ - return this->named_object()->is_type(); -} - -// Add a method. This is used when methods are defined before the -// type. - -Named_object* -Forward_declaration_type::add_method(const std::string& name, - Function* function) -{ - Named_object* no = this->named_object(); - gcc_assert(no->is_type_declaration()); - return no->type_declaration_value()->add_method(name, function); -} - -// Add a method declaration. This is used when methods are declared -// before the type. - -Named_object* -Forward_declaration_type::add_method_declaration(const std::string& name, - Function_type* type, - source_location location) -{ - Named_object* no = this->named_object(); - gcc_assert(no->is_type_declaration()); - Type_declaration* td = no->type_declaration_value(); - return td->add_method_declaration(name, type, location); -} - -// Traversal. - -int -Forward_declaration_type::do_traverse(Traverse* traverse) -{ - if (this->is_defined() - && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Get a tree for the type. - -tree -Forward_declaration_type::do_get_tree(Gogo* gogo) -{ - if (this->is_defined()) - return Type::get_named_type_tree(gogo, this->real_type()); - - if (this->warned_) - return error_mark_node; - - // We represent an undefined type as a struct with no fields. That - // should work fine for the middle-end, since the same case can - // arise in C. - Named_object* no = this->named_object(); - tree type_tree = make_node(RECORD_TYPE); - tree id = no->get_id(gogo); - tree decl = build_decl(no->location(), TYPE_DECL, id, type_tree); - TYPE_NAME(type_tree) = decl; - return type_tree; -} - -// Build a type descriptor for a forwarded type. - -Expression* -Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (!this->is_defined()) - return Expression::make_nil(BUILTINS_LOCATION); - else - { - Type* t = this->real_type(); - if (name != NULL) - return this->named_type_descriptor(gogo, t, name); - else - return Expression::make_type_descriptor(t, BUILTINS_LOCATION); - } -} - -// The reflection string. - -void -Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - this->append_reflection(this->real_type(), gogo, ret); -} - -// The mangled name. - -void -Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - if (this->is_defined()) - this->append_mangled_name(this->real_type(), gogo, ret); - else - { - const Named_object* no = this->named_object(); - std::string name; - if (no->package() == NULL) - name = gogo->package_name(); - else - name = no->package()->name(); - name += '.'; - name += Gogo::unpack_hidden_name(no->name()); - char buf[20]; - snprintf(buf, sizeof buf, "N%u_", - static_cast(name.length())); - ret->append(buf); - ret->append(name); - } -} - -// Export a forward declaration. This can happen when a defined type -// refers to a type which is only declared (and is presumably defined -// in some other file in the same package). - -void -Forward_declaration_type::do_export(Export*) const -{ - // If there is a base type, that should be exported instead of this. - gcc_assert(!this->is_defined()); - - // We don't output anything. -} - -// Make a forward declaration. - -Type* -Type::make_forward_declaration(Named_object* named_object) -{ - return new Forward_declaration_type(named_object); -} - -// Class Typed_identifier_list. - -// Sort the entries by name. - -struct Typed_identifier_list_sort -{ - public: - bool - operator()(const Typed_identifier& t1, const Typed_identifier& t2) const - { return t1.name() < t2.name(); } -}; - -void -Typed_identifier_list::sort_by_name() -{ - std::sort(this->entries_.begin(), this->entries_.end(), - Typed_identifier_list_sort()); -} - -// Traverse types. - -int -Typed_identifier_list::traverse(Traverse* traverse) -{ - for (Typed_identifier_list::const_iterator p = this->begin(); - p != this->end(); - ++p) - { - if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Copy the list. - -Typed_identifier_list* -Typed_identifier_list::copy() const -{ - Typed_identifier_list* ret = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator p = this->begin(); - p != this->end(); - ++p) - ret->push_back(Typed_identifier(p->name(), p->type(), p->location())); - return ret; -} diff --git a/gcc/go/gofrontend/types.cc.merge-right.r172891 b/gcc/go/gofrontend/types.cc.merge-right.r172891 deleted file mode 100644 index 86d65c1a048..00000000000 --- a/gcc/go/gofrontend/types.cc.merge-right.r172891 +++ /dev/null @@ -1,8676 +0,0 @@ -// types.cc -- Go frontend types. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include - -#ifndef ENABLE_BUILD_WITH_CXX -extern "C" -{ -#endif - -#include "toplev.h" -#include "intl.h" -#include "tree.h" -#include "gimple.h" -#include "real.h" -#include "convert.h" - -#ifndef ENABLE_BUILD_WITH_CXX -} -#endif - -#include "go-c.h" -#include "gogo.h" -#include "operator.h" -#include "expressions.h" -#include "statements.h" -#include "export.h" -#include "import.h" -#include "types.h" - -// Class Type. - -Type::Type(Type_classification classification) - : classification_(classification), tree_(NULL_TREE), - type_descriptor_decl_(NULL_TREE) -{ -} - -Type::~Type() -{ -} - -// Get the base type for a type--skip names and forward declarations. - -Type* -Type::base() -{ - switch (this->classification_) - { - case TYPE_NAMED: - return this->named_type()->named_base(); - case TYPE_FORWARD: - return this->forward_declaration_type()->real_type()->base(); - default: - return this; - } -} - -const Type* -Type::base() const -{ - switch (this->classification_) - { - case TYPE_NAMED: - return this->named_type()->named_base(); - case TYPE_FORWARD: - return this->forward_declaration_type()->real_type()->base(); - default: - return this; - } -} - -// Skip defined forward declarations. - -Type* -Type::forwarded() -{ - Type* t = this; - Forward_declaration_type* ftype = t->forward_declaration_type(); - while (ftype != NULL && ftype->is_defined()) - { - t = ftype->real_type(); - ftype = t->forward_declaration_type(); - } - return t; -} - -const Type* -Type::forwarded() const -{ - const Type* t = this; - const Forward_declaration_type* ftype = t->forward_declaration_type(); - while (ftype != NULL && ftype->is_defined()) - { - t = ftype->real_type(); - ftype = t->forward_declaration_type(); - } - return t; -} - -// If this is a named type, return it. Otherwise, return NULL. - -Named_type* -Type::named_type() -{ - return this->forwarded()->convert_no_base(); -} - -const Named_type* -Type::named_type() const -{ - return this->forwarded()->convert_no_base(); -} - -// Return true if this type is not defined. - -bool -Type::is_undefined() const -{ - return this->forwarded()->forward_declaration_type() != NULL; -} - -// Return true if this is a basic type: a type which is not composed -// of other types, and is not void. - -bool -Type::is_basic_type() const -{ - switch (this->classification_) - { - case TYPE_INTEGER: - case TYPE_FLOAT: - case TYPE_COMPLEX: - case TYPE_BOOLEAN: - case TYPE_STRING: - case TYPE_NIL: - return true; - - case TYPE_ERROR: - case TYPE_VOID: - case TYPE_FUNCTION: - case TYPE_POINTER: - case TYPE_STRUCT: - case TYPE_ARRAY: - case TYPE_MAP: - case TYPE_CHANNEL: - case TYPE_INTERFACE: - return false; - - case TYPE_NAMED: - case TYPE_FORWARD: - return this->base()->is_basic_type(); - - default: - go_unreachable(); - } -} - -// Return true if this is an abstract type. - -bool -Type::is_abstract() const -{ - switch (this->classification()) - { - case TYPE_INTEGER: - return this->integer_type()->is_abstract(); - case TYPE_FLOAT: - return this->float_type()->is_abstract(); - case TYPE_COMPLEX: - return this->complex_type()->is_abstract(); - case TYPE_STRING: - return this->is_abstract_string_type(); - case TYPE_BOOLEAN: - return this->is_abstract_boolean_type(); - default: - return false; - } -} - -// Return a non-abstract version of an abstract type. - -Type* -Type::make_non_abstract_type() -{ - go_assert(this->is_abstract()); - switch (this->classification()) - { - case TYPE_INTEGER: - return Type::lookup_integer_type("int"); - case TYPE_FLOAT: - return Type::lookup_float_type("float64"); - case TYPE_COMPLEX: - return Type::lookup_complex_type("complex128"); - case TYPE_STRING: - return Type::lookup_string_type(); - case TYPE_BOOLEAN: - return Type::lookup_bool_type(); - default: - go_unreachable(); - } -} - -// Return true if this is an error type. Don't give an error if we -// try to dereference an undefined forwarding type, as this is called -// in the parser when the type may legitimately be undefined. - -bool -Type::is_error_type() const -{ - const Type* t = this->forwarded(); - // Note that we return false for an undefined forward type. - switch (t->classification_) - { - case TYPE_ERROR: - return true; - case TYPE_NAMED: - return t->named_type()->is_named_error_type(); - default: - return false; - } -} - -// If this is a pointer type, return the type to which it points. -// Otherwise, return NULL. - -Type* -Type::points_to() const -{ - const Pointer_type* ptype = this->convert(); - return ptype == NULL ? NULL : ptype->points_to(); -} - -// Return whether this is an open array type. - -bool -Type::is_open_array_type() const -{ - return this->array_type() != NULL && this->array_type()->length() == NULL; -} - -// Return whether this is the predeclared constant nil being used as a -// type. - -bool -Type::is_nil_constant_as_type() const -{ - const Type* t = this->forwarded(); - if (t->forward_declaration_type() != NULL) - { - const Named_object* no = t->forward_declaration_type()->named_object(); - if (no->is_unknown()) - no = no->unknown_value()->real_named_object(); - if (no != NULL - && no->is_const() - && no->const_value()->expr()->is_nil_expression()) - return true; - } - return false; -} - -// Traverse a type. - -int -Type::traverse(Type* type, Traverse* traverse) -{ - go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0 - || (traverse->traverse_mask() - & Traverse::traverse_expressions) != 0); - if (traverse->remember_type(type)) - { - // We have already traversed this type. - return TRAVERSE_CONTINUE; - } - if ((traverse->traverse_mask() & Traverse::traverse_types) != 0) - { - int t = traverse->type(type); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - return TRAVERSE_CONTINUE; - } - // An array type has an expression which we need to traverse if - // traverse_expressions is set. - if (type->do_traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Default implementation for do_traverse for child class. - -int -Type::do_traverse(Traverse*) -{ - return TRAVERSE_CONTINUE; -} - -// Return whether two types are identical. If ERRORS_ARE_IDENTICAL, -// then return true for all erroneous types; this is used to avoid -// cascading errors. If REASON is not NULL, optionally set *REASON to -// the reason the types are not identical. - -bool -Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical, - std::string* reason) -{ - if (t1 == NULL || t2 == NULL) - { - // Something is wrong. - return errors_are_identical ? true : t1 == t2; - } - - // Skip defined forward declarations. - t1 = t1->forwarded(); - t2 = t2->forwarded(); - - if (t1 == t2) - return true; - - // An undefined forward declaration is an error. - if (t1->forward_declaration_type() != NULL - || t2->forward_declaration_type() != NULL) - return errors_are_identical; - - // Avoid cascading errors with error types. - if (t1->is_error_type() || t2->is_error_type()) - { - if (errors_are_identical) - return true; - return t1->is_error_type() && t2->is_error_type(); - } - - // Get a good reason for the sink type. Note that the sink type on - // the left hand side of an assignment is handled in are_assignable. - if (t1->is_sink_type() || t2->is_sink_type()) - { - if (reason != NULL) - *reason = "invalid use of _"; - return false; - } - - // A named type is only identical to itself. - if (t1->named_type() != NULL || t2->named_type() != NULL) - return false; - - // Check type shapes. - if (t1->classification() != t2->classification()) - return false; - - switch (t1->classification()) - { - case TYPE_VOID: - case TYPE_BOOLEAN: - case TYPE_STRING: - case TYPE_NIL: - // These types are always identical. - return true; - - case TYPE_INTEGER: - return t1->integer_type()->is_identical(t2->integer_type()); - - case TYPE_FLOAT: - return t1->float_type()->is_identical(t2->float_type()); - - case TYPE_COMPLEX: - return t1->complex_type()->is_identical(t2->complex_type()); - - case TYPE_FUNCTION: - return t1->function_type()->is_identical(t2->function_type(), - false, - errors_are_identical, - reason); - - case TYPE_POINTER: - return Type::are_identical(t1->points_to(), t2->points_to(), - errors_are_identical, reason); - - case TYPE_STRUCT: - return t1->struct_type()->is_identical(t2->struct_type(), - errors_are_identical); - - case TYPE_ARRAY: - return t1->array_type()->is_identical(t2->array_type(), - errors_are_identical); - - case TYPE_MAP: - return t1->map_type()->is_identical(t2->map_type(), - errors_are_identical); - - case TYPE_CHANNEL: - return t1->channel_type()->is_identical(t2->channel_type(), - errors_are_identical); - - case TYPE_INTERFACE: - return t1->interface_type()->is_identical(t2->interface_type(), - errors_are_identical); - - case TYPE_CALL_MULTIPLE_RESULT: - if (reason != NULL) - *reason = "invalid use of multiple value function call"; - return false; - - default: - go_unreachable(); - } -} - -// Return true if it's OK to have a binary operation with types LHS -// and RHS. This is not used for shifts or comparisons. - -bool -Type::are_compatible_for_binop(const Type* lhs, const Type* rhs) -{ - if (Type::are_identical(lhs, rhs, true, NULL)) - return true; - - // A constant of abstract bool type may be mixed with any bool type. - if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type()) - || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type())) - return true; - - // A constant of abstract string type may be mixed with any string - // type. - if ((rhs->is_abstract_string_type() && lhs->is_string_type()) - || (lhs->is_abstract_string_type() && rhs->is_string_type())) - return true; - - lhs = lhs->base(); - rhs = rhs->base(); - - // A constant of abstract integer, float, or complex type may be - // mixed with an integer, float, or complex type. - if ((rhs->is_abstract() - && (rhs->integer_type() != NULL - || rhs->float_type() != NULL - || rhs->complex_type() != NULL) - && (lhs->integer_type() != NULL - || lhs->float_type() != NULL - || lhs->complex_type() != NULL)) - || (lhs->is_abstract() - && (lhs->integer_type() != NULL - || lhs->float_type() != NULL - || lhs->complex_type() != NULL) - && (rhs->integer_type() != NULL - || rhs->float_type() != NULL - || rhs->complex_type() != NULL))) - return true; - - // The nil type may be compared to a pointer, an interface type, a - // slice type, a channel type, a map type, or a function type. - if (lhs->is_nil_type() - && (rhs->points_to() != NULL - || rhs->interface_type() != NULL - || rhs->is_open_array_type() - || rhs->map_type() != NULL - || rhs->channel_type() != NULL - || rhs->function_type() != NULL)) - return true; - if (rhs->is_nil_type() - && (lhs->points_to() != NULL - || lhs->interface_type() != NULL - || lhs->is_open_array_type() - || lhs->map_type() != NULL - || lhs->channel_type() != NULL - || lhs->function_type() != NULL)) - return true; - - return false; -} - -// Return true if a value with type RHS may be assigned to a variable -// with type LHS. If CHECK_HIDDEN_FIELDS is true, check whether any -// hidden fields are modified. If REASON is not NULL, set *REASON to -// the reason the types are not assignable. - -bool -Type::are_assignable_check_hidden(const Type* lhs, const Type* rhs, - bool check_hidden_fields, - std::string* reason) -{ - // Do some checks first. Make sure the types are defined. - if (rhs != NULL - && rhs->forwarded()->forward_declaration_type() == NULL - && rhs->is_void_type()) - { - if (reason != NULL) - *reason = "non-value used as value"; - return false; - } - - if (lhs != NULL && lhs->forwarded()->forward_declaration_type() == NULL) - { - // Any value may be assigned to the blank identifier. - if (lhs->is_sink_type()) - return true; - - // All fields of a struct must be exported, or the assignment - // must be in the same package. - if (check_hidden_fields - && rhs != NULL - && rhs->forwarded()->forward_declaration_type() == NULL) - { - if (lhs->has_hidden_fields(NULL, reason) - || rhs->has_hidden_fields(NULL, reason)) - return false; - } - } - - // Identical types are assignable. - if (Type::are_identical(lhs, rhs, true, reason)) - return true; - - // The types are assignable if they have identical underlying types - // and either LHS or RHS is not a named type. - if (((lhs->named_type() != NULL && rhs->named_type() == NULL) - || (rhs->named_type() != NULL && lhs->named_type() == NULL)) - && Type::are_identical(lhs->base(), rhs->base(), true, reason)) - return true; - - // The types are assignable if LHS is an interface type and RHS - // implements the required methods. - const Interface_type* lhs_interface_type = lhs->interface_type(); - if (lhs_interface_type != NULL) - { - if (lhs_interface_type->implements_interface(rhs, reason)) - return true; - const Interface_type* rhs_interface_type = rhs->interface_type(); - if (rhs_interface_type != NULL - && lhs_interface_type->is_compatible_for_assign(rhs_interface_type, - reason)) - return true; - } - - // The type are assignable if RHS is a bidirectional channel type, - // LHS is a channel type, they have identical element types, and - // either LHS or RHS is not a named type. - if (lhs->channel_type() != NULL - && rhs->channel_type() != NULL - && rhs->channel_type()->may_send() - && rhs->channel_type()->may_receive() - && (lhs->named_type() == NULL || rhs->named_type() == NULL) - && Type::are_identical(lhs->channel_type()->element_type(), - rhs->channel_type()->element_type(), - true, - reason)) - return true; - - // The nil type may be assigned to a pointer, function, slice, map, - // channel, or interface type. - if (rhs->is_nil_type() - && (lhs->points_to() != NULL - || lhs->function_type() != NULL - || lhs->is_open_array_type() - || lhs->map_type() != NULL - || lhs->channel_type() != NULL - || lhs->interface_type() != NULL)) - return true; - - // An untyped numeric constant may be assigned to a numeric type if - // it is representable in that type. - if ((rhs->is_abstract() - && (rhs->integer_type() != NULL - || rhs->float_type() != NULL - || rhs->complex_type() != NULL)) - && (lhs->integer_type() != NULL - || lhs->float_type() != NULL - || lhs->complex_type() != NULL)) - return true; - - // Give some better error messages. - if (reason != NULL && reason->empty()) - { - if (rhs->interface_type() != NULL) - reason->assign(_("need explicit conversion")); - else if (rhs->is_call_multiple_result_type()) - reason->assign(_("multiple value function call in " - "single value context")); - else if (lhs->named_type() != NULL && rhs->named_type() != NULL) - { - size_t len = (lhs->named_type()->name().length() - + rhs->named_type()->name().length() - + 100); - char* buf = new char[len]; - snprintf(buf, len, _("cannot use type %s as type %s"), - rhs->named_type()->message_name().c_str(), - lhs->named_type()->message_name().c_str()); - reason->assign(buf); - delete[] buf; - } - } - - return false; -} - -// Return true if a value with type RHS may be assigned to a variable -// with type LHS. If REASON is not NULL, set *REASON to the reason -// the types are not assignable. - -bool -Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason) -{ - return Type::are_assignable_check_hidden(lhs, rhs, true, reason); -} - -// Like are_assignable but don't check for hidden fields. - -bool -Type::are_assignable_hidden_ok(const Type* lhs, const Type* rhs, - std::string* reason) -{ - return Type::are_assignable_check_hidden(lhs, rhs, false, reason); -} - -// Return true if a value with type RHS may be converted to type LHS. -// If REASON is not NULL, set *REASON to the reason the types are not -// convertible. - -bool -Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason) -{ - // The types are convertible if they are assignable. - if (Type::are_assignable(lhs, rhs, reason)) - return true; - - // The types are convertible if they have identical underlying - // types. - if ((lhs->named_type() != NULL || rhs->named_type() != NULL) - && Type::are_identical(lhs->base(), rhs->base(), true, reason)) - return true; - - // The types are convertible if they are both unnamed pointer types - // and their pointer base types have identical underlying types. - if (lhs->named_type() == NULL - && rhs->named_type() == NULL - && lhs->points_to() != NULL - && rhs->points_to() != NULL - && (lhs->points_to()->named_type() != NULL - || rhs->points_to()->named_type() != NULL) - && Type::are_identical(lhs->points_to()->base(), - rhs->points_to()->base(), - true, - reason)) - return true; - - // Integer and floating point types are convertible to each other. - if ((lhs->integer_type() != NULL || lhs->float_type() != NULL) - && (rhs->integer_type() != NULL || rhs->float_type() != NULL)) - return true; - - // Complex types are convertible to each other. - if (lhs->complex_type() != NULL && rhs->complex_type() != NULL) - return true; - - // An integer, or []byte, or []int, may be converted to a string. - if (lhs->is_string_type()) - { - if (rhs->integer_type() != NULL) - return true; - if (rhs->is_open_array_type() && rhs->named_type() == NULL) - { - const Type* e = rhs->array_type()->element_type()->forwarded(); - if (e->integer_type() != NULL - && (e == Type::lookup_integer_type("uint8") - || e == Type::lookup_integer_type("int"))) - return true; - } - } - - // A string may be converted to []byte or []int. - if (rhs->is_string_type() - && lhs->is_open_array_type() - && lhs->named_type() == NULL) - { - const Type* e = lhs->array_type()->element_type()->forwarded(); - if (e->integer_type() != NULL - && (e == Type::lookup_integer_type("uint8") - || e == Type::lookup_integer_type("int"))) - return true; - } - - // An unsafe.Pointer type may be converted to any pointer type or to - // uintptr, and vice-versa. - if (lhs->is_unsafe_pointer_type() - && (rhs->points_to() != NULL - || (rhs->integer_type() != NULL - && rhs->forwarded() == Type::lookup_integer_type("uintptr")))) - return true; - if (rhs->is_unsafe_pointer_type() - && (lhs->points_to() != NULL - || (lhs->integer_type() != NULL - && lhs->forwarded() == Type::lookup_integer_type("uintptr")))) - return true; - - // Give a better error message. - if (reason != NULL) - { - if (reason->empty()) - *reason = "invalid type conversion"; - else - { - std::string s = "invalid type conversion ("; - s += *reason; - s += ')'; - *reason = s; - } - } - - return false; -} - -// Return whether this type has any hidden fields. This is only a -// possibility for a few types. - -bool -Type::has_hidden_fields(const Named_type* within, std::string* reason) const -{ - switch (this->forwarded()->classification_) - { - case TYPE_NAMED: - return this->named_type()->named_type_has_hidden_fields(reason); - case TYPE_STRUCT: - return this->struct_type()->struct_has_hidden_fields(within, reason); - case TYPE_ARRAY: - return this->array_type()->array_has_hidden_fields(within, reason); - default: - return false; - } -} - -// Return a hash code for the type to be used for method lookup. - -unsigned int -Type::hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - if (this->classification_ != TYPE_FORWARD) - ret += this->classification_; - return ret + this->do_hash_for_method(gogo); -} - -// Default implementation of do_hash_for_method. This is appropriate -// for types with no subfields. - -unsigned int -Type::do_hash_for_method(Gogo*) const -{ - return 0; -} - -// Return a hash code for a string, given a starting hash. - -unsigned int -Type::hash_string(const std::string& s, unsigned int h) -{ - const char* p = s.data(); - size_t len = s.length(); - for (; len > 0; --len) - { - h ^= *p++; - h*= 16777619; - } - return h; -} - -// Default check for the expression passed to make. Any type which -// may be used with make implements its own version of this. - -bool -Type::do_check_make_expression(Expression_list*, source_location) -{ - go_unreachable(); -} - -// Return whether an expression has an integer value. Report an error -// if not. This is used when handling calls to the predeclared make -// function. - -bool -Type::check_int_value(Expression* e, const char* errmsg, - source_location location) -{ - if (e->type()->integer_type() != NULL) - return true; - - // Check for a floating point constant with integer value. - mpfr_t fval; - mpfr_init(fval); - - Type* dummy; - if (e->float_constant_value(fval, &dummy) && mpfr_integer_p(fval)) - { - mpz_t ival; - mpz_init(ival); - - bool ok = false; - - mpfr_clear_overflow(); - mpfr_clear_erangeflag(); - mpfr_get_z(ival, fval, GMP_RNDN); - if (!mpfr_overflow_p() - && !mpfr_erangeflag_p() - && mpz_sgn(ival) >= 0) - { - Named_type* ntype = Type::lookup_integer_type("int"); - Integer_type* inttype = ntype->integer_type(); - mpz_t max; - mpz_init_set_ui(max, 1); - mpz_mul_2exp(max, max, inttype->bits() - 1); - ok = mpz_cmp(ival, max) < 0; - mpz_clear(max); - } - mpz_clear(ival); - - if (ok) - { - mpfr_clear(fval); - return true; - } - } - - mpfr_clear(fval); - - error_at(location, "%s", errmsg); - return false; -} - -// A hash table mapping unnamed types to trees. - -Type::Type_trees Type::type_trees; - -// Return a tree representing this type. - -tree -Type::get_tree(Gogo* gogo) -{ - if (this->tree_ != NULL) - return this->tree_; - - if (this->forward_declaration_type() != NULL - || this->named_type() != NULL) - return this->get_tree_without_hash(gogo); - - if (this->is_error_type()) - return error_mark_node; - - // To avoid confusing GIMPLE, we need to translate all identical Go - // types to the same GIMPLE type. We use a hash table to do that. - // There is no need to use the hash table for named types, as named - // types are only identical to themselves. - - std::pair val(this, NULL); - std::pair ins = - Type::type_trees.insert(val); - if (!ins.second && ins.first->second != NULL_TREE) - { - if (gogo != NULL && gogo->named_types_are_converted()) - this->tree_ = ins.first->second; - return ins.first->second; - } - - tree t = this->get_tree_without_hash(gogo); - - if (ins.first->second == NULL_TREE) - ins.first->second = t; - else - { - // We have already created a tree for this type. This can - // happen when an unnamed type is defined using a named type - // which in turns uses an identical unnamed type. Use the tree - // we created earlier and ignore the one we just built. - t = ins.first->second; - if (gogo == NULL || !gogo->named_types_are_converted()) - return t; - this->tree_ = t; - } - - return t; -} - -// Return a tree for a type without looking in the hash table for -// identical types. This is used for named types, since there is no -// point to looking in the hash table for them. - -tree -Type::get_tree_without_hash(Gogo* gogo) -{ - if (this->tree_ == NULL_TREE) - { - tree t = this->do_get_tree(gogo); - - // For a recursive function or pointer type, we will temporarily - // return ptr_type_node during the recursion. We don't want to - // record that for a forwarding type, as it may confuse us - // later. - if (t == ptr_type_node && this->forward_declaration_type() != NULL) - return t; - - if (gogo == NULL || !gogo->named_types_are_converted()) - return t; - - this->tree_ = t; - go_preserve_from_gc(t); - } - - return this->tree_; -} - -// Return a tree representing a zero initialization for this type. - -tree -Type::get_init_tree(Gogo* gogo, bool is_clear) -{ - tree type_tree = this->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - return this->do_get_init_tree(gogo, type_tree, is_clear); -} - -// Any type which supports the builtin make function must implement -// this. - -tree -Type::do_make_expression_tree(Translate_context*, Expression_list*, - source_location) -{ - go_unreachable(); -} - -// Return a pointer to the type descriptor for this type. - -tree -Type::type_descriptor_pointer(Gogo* gogo) -{ - Type* t = this->forwarded(); - if (t->type_descriptor_decl_ == NULL_TREE) - { - Expression* e = t->do_type_descriptor(gogo, NULL); - gogo->build_type_descriptor_decl(t, e, &t->type_descriptor_decl_); - go_assert(t->type_descriptor_decl_ != NULL_TREE - && (t->type_descriptor_decl_ == error_mark_node - || DECL_P(t->type_descriptor_decl_))); - } - if (t->type_descriptor_decl_ == error_mark_node) - return error_mark_node; - return build_fold_addr_expr(t->type_descriptor_decl_); -} - -// Return a composite literal for a type descriptor. - -Expression* -Type::type_descriptor(Gogo* gogo, Type* type) -{ - return type->do_type_descriptor(gogo, NULL); -} - -// Return a composite literal for a type descriptor with a name. - -Expression* -Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name) -{ - go_assert(name != NULL && type->named_type() != name); - return type->do_type_descriptor(gogo, name); -} - -// Make a builtin struct type from a list of fields. The fields are -// pairs of a name and a type. - -Struct_type* -Type::make_builtin_struct_type(int nfields, ...) -{ - va_list ap; - va_start(ap, nfields); - - source_location bloc = BUILTINS_LOCATION; - Struct_field_list* sfl = new Struct_field_list(); - for (int i = 0; i < nfields; i++) - { - const char* field_name = va_arg(ap, const char *); - Type* type = va_arg(ap, Type*); - sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc))); - } - - va_end(ap); - - return Type::make_struct_type(sfl, bloc); -} - -// A list of builtin named types. - -std::vector Type::named_builtin_types; - -// Make a builtin named type. - -Named_type* -Type::make_builtin_named_type(const char* name, Type* type) -{ - source_location bloc = BUILTINS_LOCATION; - Named_object* no = Named_object::make_type(name, NULL, type, bloc); - Named_type* ret = no->type_value(); - Type::named_builtin_types.push_back(ret); - return ret; -} - -// Convert the named builtin types. - -void -Type::convert_builtin_named_types(Gogo* gogo) -{ - for (std::vector::const_iterator p = - Type::named_builtin_types.begin(); - p != Type::named_builtin_types.end(); - ++p) - { - bool r = (*p)->verify(); - go_assert(r); - (*p)->convert(gogo); - } -} - -// Return the type of a type descriptor. We should really tie this to -// runtime.Type rather than copying it. This must match commonType in -// libgo/go/runtime/type.go. - -Type* -Type::make_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - source_location bloc = BUILTINS_LOCATION; - - Type* uint8_type = Type::lookup_integer_type("uint8"); - Type* uint32_type = Type::lookup_integer_type("uint32"); - Type* uintptr_type = Type::lookup_integer_type("uintptr"); - Type* string_type = Type::lookup_string_type(); - Type* pointer_string_type = Type::make_pointer_type(string_type); - - // This is an unnamed version of unsafe.Pointer. Perhaps we - // should use the named version instead, although that would - // require us to create the unsafe package if it has not been - // imported. It probably doesn't matter. - Type* void_type = Type::make_void_type(); - Type* unsafe_pointer_type = Type::make_pointer_type(void_type); - - // Forward declaration for the type descriptor type. - Named_object* named_type_descriptor_type = - Named_object::make_type_declaration("commonType", NULL, bloc); - Type* ft = Type::make_forward_declaration(named_type_descriptor_type); - Type* pointer_type_descriptor_type = Type::make_pointer_type(ft); - - // The type of a method on a concrete type. - Struct_type* method_type = - Type::make_builtin_struct_type(5, - "name", pointer_string_type, - "pkgPath", pointer_string_type, - "mtyp", pointer_type_descriptor_type, - "typ", pointer_type_descriptor_type, - "tfn", unsafe_pointer_type); - Named_type* named_method_type = - Type::make_builtin_named_type("method", method_type); - - // Information for types with a name or methods. - Type* slice_named_method_type = - Type::make_array_type(named_method_type, NULL); - Struct_type* uncommon_type = - Type::make_builtin_struct_type(3, - "name", pointer_string_type, - "pkgPath", pointer_string_type, - "methods", slice_named_method_type); - Named_type* named_uncommon_type = - Type::make_builtin_named_type("uncommonType", uncommon_type); - - Type* pointer_uncommon_type = - Type::make_pointer_type(named_uncommon_type); - - // The type descriptor type. - - Typed_identifier_list* params = new Typed_identifier_list(); - params->push_back(Typed_identifier("", unsafe_pointer_type, bloc)); - params->push_back(Typed_identifier("", uintptr_type, bloc)); - - Typed_identifier_list* results = new Typed_identifier_list(); - results->push_back(Typed_identifier("", uintptr_type, bloc)); - - Type* hashfn_type = Type::make_function_type(NULL, params, results, bloc); - - params = new Typed_identifier_list(); - params->push_back(Typed_identifier("", unsafe_pointer_type, bloc)); - params->push_back(Typed_identifier("", unsafe_pointer_type, bloc)); - params->push_back(Typed_identifier("", uintptr_type, bloc)); - - results = new Typed_identifier_list(); - results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc)); - - Type* equalfn_type = Type::make_function_type(NULL, params, results, - bloc); - - Struct_type* type_descriptor_type = - Type::make_builtin_struct_type(10, - "Kind", uint8_type, - "align", uint8_type, - "fieldAlign", uint8_type, - "size", uintptr_type, - "hash", uint32_type, - "hashfn", hashfn_type, - "equalfn", equalfn_type, - "string", pointer_string_type, - "", pointer_uncommon_type, - "ptrToThis", - pointer_type_descriptor_type); - - Named_type* named = Type::make_builtin_named_type("commonType", - type_descriptor_type); - - named_type_descriptor_type->set_type_value(named); - - ret = named; - } - - return ret; -} - -// Make the type of a pointer to a type descriptor as represented in -// Go. - -Type* -Type::make_type_descriptor_ptr_type() -{ - static Type* ret; - if (ret == NULL) - ret = Type::make_pointer_type(Type::make_type_descriptor_type()); - return ret; -} - -// Return the names of runtime functions which compute a hash code for -// this type and which compare whether two values of this type are -// equal. - -void -Type::type_functions(const char** hash_fn, const char** equal_fn) const -{ - switch (this->base()->classification()) - { - case Type::TYPE_ERROR: - case Type::TYPE_VOID: - case Type::TYPE_NIL: - // These types can not be hashed or compared. - *hash_fn = "__go_type_hash_error"; - *equal_fn = "__go_type_equal_error"; - break; - - case Type::TYPE_BOOLEAN: - case Type::TYPE_INTEGER: - case Type::TYPE_FLOAT: - case Type::TYPE_COMPLEX: - case Type::TYPE_POINTER: - case Type::TYPE_FUNCTION: - case Type::TYPE_MAP: - case Type::TYPE_CHANNEL: - *hash_fn = "__go_type_hash_identity"; - *equal_fn = "__go_type_equal_identity"; - break; - - case Type::TYPE_STRING: - *hash_fn = "__go_type_hash_string"; - *equal_fn = "__go_type_equal_string"; - break; - - case Type::TYPE_STRUCT: - case Type::TYPE_ARRAY: - // These types can not be hashed or compared. - *hash_fn = "__go_type_hash_error"; - *equal_fn = "__go_type_equal_error"; - break; - - case Type::TYPE_INTERFACE: - if (this->interface_type()->is_empty()) - { - *hash_fn = "__go_type_hash_empty_interface"; - *equal_fn = "__go_type_equal_empty_interface"; - } - else - { - *hash_fn = "__go_type_hash_interface"; - *equal_fn = "__go_type_equal_interface"; - } - break; - - case Type::TYPE_NAMED: - case Type::TYPE_FORWARD: - go_unreachable(); - - default: - go_unreachable(); - } -} - -// Return a composite literal for the type descriptor for a plain type -// of kind RUNTIME_TYPE_KIND named NAME. - -Expression* -Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind, - Named_type* name, const Methods* methods, - bool only_value_methods) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* td_type = Type::make_type_descriptor_type(); - const Struct_field_list* fields = td_type->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(9); - - Struct_field_list::const_iterator p = fields->begin(); - go_assert(p->field_name() == "Kind"); - mpz_t iv; - mpz_init_set_ui(iv, runtime_type_kind); - vals->push_back(Expression::make_integer(&iv, p->type(), bloc)); - - ++p; - go_assert(p->field_name() == "align"); - Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT; - vals->push_back(Expression::make_type_info(this, type_info)); - - ++p; - go_assert(p->field_name() == "fieldAlign"); - type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT; - vals->push_back(Expression::make_type_info(this, type_info)); - - ++p; - go_assert(p->field_name() == "size"); - type_info = Expression::TYPE_INFO_SIZE; - vals->push_back(Expression::make_type_info(this, type_info)); - - ++p; - go_assert(p->field_name() == "hash"); - mpz_set_ui(iv, this->hash_for_method(gogo)); - vals->push_back(Expression::make_integer(&iv, p->type(), bloc)); - - const char* hash_fn; - const char* equal_fn; - this->type_functions(&hash_fn, &equal_fn); - - ++p; - go_assert(p->field_name() == "hashfn"); - Function_type* fntype = p->type()->function_type(); - Named_object* no = Named_object::make_function_declaration(hash_fn, NULL, - fntype, - bloc); - no->func_declaration_value()->set_asm_name(hash_fn); - vals->push_back(Expression::make_func_reference(no, NULL, bloc)); - - ++p; - go_assert(p->field_name() == "equalfn"); - fntype = p->type()->function_type(); - no = Named_object::make_function_declaration(equal_fn, NULL, fntype, bloc); - no->func_declaration_value()->set_asm_name(equal_fn); - vals->push_back(Expression::make_func_reference(no, NULL, bloc)); - - ++p; - go_assert(p->field_name() == "string"); - Expression* s = Expression::make_string((name != NULL - ? name->reflection(gogo) - : this->reflection(gogo)), - bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - - ++p; - go_assert(p->field_name() == "uncommonType"); - if (name == NULL && methods == NULL) - vals->push_back(Expression::make_nil(bloc)); - else - { - if (methods == NULL) - methods = name->methods(); - vals->push_back(this->uncommon_type_constructor(gogo, - p->type()->deref(), - name, methods, - only_value_methods)); - } - - ++p; - go_assert(p->field_name() == "ptrToThis"); - if (name == NULL) - vals->push_back(Expression::make_nil(bloc)); - else - { - Type* pt = Type::make_pointer_type(name); - vals->push_back(Expression::make_type_descriptor(pt, bloc)); - } - - ++p; - go_assert(p == fields->end()); - - mpz_clear(iv); - - return Expression::make_struct_composite_literal(td_type, vals, bloc); -} - -// Return a composite literal for the uncommon type information for -// this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type -// struct. If name is not NULL, it is the name of the type. If -// METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS -// is true if only value methods should be included. At least one of -// NAME and METHODS must not be NULL. - -Expression* -Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type, - Named_type* name, const Methods* methods, - bool only_value_methods) const -{ - source_location bloc = BUILTINS_LOCATION; - - const Struct_field_list* fields = uncommon_type->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(3); - - Struct_field_list::const_iterator p = fields->begin(); - go_assert(p->field_name() == "name"); - - ++p; - go_assert(p->field_name() == "pkgPath"); - - if (name == NULL) - { - vals->push_back(Expression::make_nil(bloc)); - vals->push_back(Expression::make_nil(bloc)); - } - else - { - Named_object* no = name->named_object(); - std::string n = Gogo::unpack_hidden_name(no->name()); - Expression* s = Expression::make_string(n, bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - - if (name->is_builtin()) - vals->push_back(Expression::make_nil(bloc)); - else - { - const Package* package = no->package(); - const std::string& unique_prefix(package == NULL - ? gogo->unique_prefix() - : package->unique_prefix()); - const std::string& package_name(package == NULL - ? gogo->package_name() - : package->name()); - n.assign(unique_prefix); - n.append(1, '.'); - n.append(package_name); - if (name->in_function() != NULL) - { - n.append(1, '.'); - n.append(Gogo::unpack_hidden_name(name->in_function()->name())); - } - s = Expression::make_string(n, bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - } - - ++p; - go_assert(p->field_name() == "methods"); - vals->push_back(this->methods_constructor(gogo, p->type(), methods, - only_value_methods)); - - ++p; - go_assert(p == fields->end()); - - Expression* r = Expression::make_struct_composite_literal(uncommon_type, - vals, bloc); - return Expression::make_unary(OPERATOR_AND, r, bloc); -} - -// Sort methods by name. - -class Sort_methods -{ - public: - bool - operator()(const std::pair& m1, - const std::pair& m2) const - { return m1.first < m2.first; } -}; - -// Return a composite literal for the type method table for this type. -// METHODS_TYPE is the type of the table, and is a slice type. -// METHODS is the list of methods. If ONLY_VALUE_METHODS is true, -// then only value methods are used. - -Expression* -Type::methods_constructor(Gogo* gogo, Type* methods_type, - const Methods* methods, - bool only_value_methods) const -{ - source_location bloc = BUILTINS_LOCATION; - - std::vector > smethods; - if (methods != NULL) - { - smethods.reserve(methods->count()); - for (Methods::const_iterator p = methods->begin(); - p != methods->end(); - ++p) - { - if (p->second->is_ambiguous()) - continue; - if (only_value_methods && !p->second->is_value_method()) - continue; - smethods.push_back(std::make_pair(p->first, p->second)); - } - } - - if (smethods.empty()) - return Expression::make_slice_composite_literal(methods_type, NULL, bloc); - - std::sort(smethods.begin(), smethods.end(), Sort_methods()); - - Type* method_type = methods_type->array_type()->element_type(); - - Expression_list* vals = new Expression_list(); - vals->reserve(smethods.size()); - for (std::vector >::const_iterator p - = smethods.begin(); - p != smethods.end(); - ++p) - vals->push_back(this->method_constructor(gogo, method_type, p->first, - p->second)); - - return Expression::make_slice_composite_literal(methods_type, vals, bloc); -} - -// Return a composite literal for a single method. METHOD_TYPE is the -// type of the entry. METHOD_NAME is the name of the method and M is -// the method information. - -Expression* -Type::method_constructor(Gogo*, Type* method_type, - const std::string& method_name, - const Method* m) const -{ - source_location bloc = BUILTINS_LOCATION; - - const Struct_field_list* fields = method_type->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(5); - - Struct_field_list::const_iterator p = fields->begin(); - go_assert(p->field_name() == "name"); - const std::string n = Gogo::unpack_hidden_name(method_name); - Expression* s = Expression::make_string(n, bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - - ++p; - go_assert(p->field_name() == "pkgPath"); - if (!Gogo::is_hidden_name(method_name)) - vals->push_back(Expression::make_nil(bloc)); - else - { - s = Expression::make_string(Gogo::hidden_name_prefix(method_name), bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - - Named_object* no = (m->needs_stub_method() - ? m->stub_object() - : m->named_object()); - - Function_type* mtype; - if (no->is_function()) - mtype = no->func_value()->type(); - else - mtype = no->func_declaration_value()->type(); - go_assert(mtype->is_method()); - Type* nonmethod_type = mtype->copy_without_receiver(); - - ++p; - go_assert(p->field_name() == "mtyp"); - vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc)); - - ++p; - go_assert(p->field_name() == "typ"); - vals->push_back(Expression::make_type_descriptor(mtype, bloc)); - - ++p; - go_assert(p->field_name() == "tfn"); - vals->push_back(Expression::make_func_reference(no, NULL, bloc)); - - ++p; - go_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(method_type, vals, bloc); -} - -// Return a composite literal for the type descriptor of a plain type. -// RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not -// NULL, it is the name to use as well as the list of methods. - -Expression* -Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind, - Named_type* name) -{ - return this->type_descriptor_constructor(gogo, runtime_type_kind, - name, NULL, true); -} - -// Return the type reflection string for this type. - -std::string -Type::reflection(Gogo* gogo) const -{ - std::string ret; - - // The do_reflection virtual function should set RET to the - // reflection string. - this->do_reflection(gogo, &ret); - - return ret; -} - -// Return a mangled name for the type. - -std::string -Type::mangled_name(Gogo* gogo) const -{ - std::string ret; - - // The do_mangled_name virtual function should set RET to the - // mangled name. For a composite type it should append a code for - // the composition and then call do_mangled_name on the components. - this->do_mangled_name(gogo, &ret); - - return ret; -} - -// Default function to export a type. - -void -Type::do_export(Export*) const -{ - go_unreachable(); -} - -// Import a type. - -Type* -Type::import_type(Import* imp) -{ - if (imp->match_c_string("(")) - return Function_type::do_import(imp); - else if (imp->match_c_string("*")) - return Pointer_type::do_import(imp); - else if (imp->match_c_string("struct ")) - return Struct_type::do_import(imp); - else if (imp->match_c_string("[")) - return Array_type::do_import(imp); - else if (imp->match_c_string("map ")) - return Map_type::do_import(imp); - else if (imp->match_c_string("chan ")) - return Channel_type::do_import(imp); - else if (imp->match_c_string("interface")) - return Interface_type::do_import(imp); - else - { - error_at(imp->location(), "import error: expected type"); - return Type::make_error_type(); - } -} - -// A type used to indicate a parsing error. This exists to simplify -// later error detection. - -class Error_type : public Type -{ - public: - Error_type() - : Type(TYPE_ERROR) - { } - - protected: - tree - do_get_tree(Gogo*) - { return error_mark_node; } - - tree - do_get_init_tree(Gogo*, tree, bool) - { return error_mark_node; } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { return Expression::make_error(BUILTINS_LOCATION); } - - void - do_reflection(Gogo*, std::string*) const - { go_assert(saw_errors()); } - - void - do_mangled_name(Gogo*, std::string* ret) const - { ret->push_back('E'); } -}; - -Type* -Type::make_error_type() -{ - static Error_type singleton_error_type; - return &singleton_error_type; -} - -// The void type. - -class Void_type : public Type -{ - public: - Void_type() - : Type(TYPE_VOID) - { } - - protected: - tree - do_get_tree(Gogo*) - { return void_type_node; } - - tree - do_get_init_tree(Gogo*, tree, bool) - { go_unreachable(); } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { go_unreachable(); } - - void - do_reflection(Gogo*, std::string*) const - { } - - void - do_mangled_name(Gogo*, std::string* ret) const - { ret->push_back('v'); } -}; - -Type* -Type::make_void_type() -{ - static Void_type singleton_void_type; - return &singleton_void_type; -} - -// The boolean type. - -class Boolean_type : public Type -{ - public: - Boolean_type() - : Type(TYPE_BOOLEAN) - { } - - protected: - tree - do_get_tree(Gogo*) - { return boolean_type_node; } - - tree - do_get_init_tree(Gogo*, tree type_tree, bool is_clear) - { return is_clear ? NULL : fold_convert(type_tree, boolean_false_node); } - - Expression* - do_type_descriptor(Gogo*, Named_type* name); - - // We should not be asked for the reflection string of a basic type. - void - do_reflection(Gogo*, std::string* ret) const - { ret->append("bool"); } - - void - do_mangled_name(Gogo*, std::string* ret) const - { ret->push_back('b'); } -}; - -// Make the type descriptor. - -Expression* -Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (name != NULL) - return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name); - else - { - Named_object* no = gogo->lookup_global("bool"); - go_assert(no != NULL); - return Type::type_descriptor(gogo, no->type_value()); - } -} - -Type* -Type::make_boolean_type() -{ - static Boolean_type boolean_type; - return &boolean_type; -} - -// The named type "bool". - -static Named_type* named_bool_type; - -// Get the named type "bool". - -Named_type* -Type::lookup_bool_type() -{ - return named_bool_type; -} - -// Make the named type "bool". - -Named_type* -Type::make_named_bool_type() -{ - Type* bool_type = Type::make_boolean_type(); - Named_object* named_object = Named_object::make_type("bool", NULL, - bool_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - named_bool_type = named_type; - return named_type; -} - -// Class Integer_type. - -Integer_type::Named_integer_types Integer_type::named_integer_types; - -// Create a new integer type. Non-abstract integer types always have -// names. - -Named_type* -Integer_type::create_integer_type(const char* name, bool is_unsigned, - int bits, int runtime_type_kind) -{ - Integer_type* integer_type = new Integer_type(false, is_unsigned, bits, - runtime_type_kind); - std::string sname(name); - Named_object* named_object = Named_object::make_type(sname, NULL, - integer_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - std::pair ins = - Integer_type::named_integer_types.insert(std::make_pair(sname, named_type)); - go_assert(ins.second); - return named_type; -} - -// Look up an existing integer type. - -Named_type* -Integer_type::lookup_integer_type(const char* name) -{ - Named_integer_types::const_iterator p = - Integer_type::named_integer_types.find(name); - go_assert(p != Integer_type::named_integer_types.end()); - return p->second; -} - -// Create a new abstract integer type. - -Integer_type* -Integer_type::create_abstract_integer_type() -{ - static Integer_type* abstract_type; - if (abstract_type == NULL) - abstract_type = new Integer_type(true, false, INT_TYPE_SIZE, - RUNTIME_TYPE_KIND_INT); - return abstract_type; -} - -// Integer type compatibility. - -bool -Integer_type::is_identical(const Integer_type* t) const -{ - if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_) - return false; - return this->is_abstract_ == t->is_abstract_; -} - -// Hash code. - -unsigned int -Integer_type::do_hash_for_method(Gogo*) const -{ - return ((this->bits_ << 4) - + ((this->is_unsigned_ ? 1 : 0) << 8) - + ((this->is_abstract_ ? 1 : 0) << 9)); -} - -// Get the tree for an Integer_type. - -tree -Integer_type::do_get_tree(Gogo*) -{ - if (this->is_abstract_) - { - go_assert(saw_errors()); - return error_mark_node; - } - - if (this->is_unsigned_) - { - if (this->bits_ == INT_TYPE_SIZE) - return unsigned_type_node; - else if (this->bits_ == CHAR_TYPE_SIZE) - return unsigned_char_type_node; - else if (this->bits_ == SHORT_TYPE_SIZE) - return short_unsigned_type_node; - else if (this->bits_ == LONG_TYPE_SIZE) - return long_unsigned_type_node; - else if (this->bits_ == LONG_LONG_TYPE_SIZE) - return long_long_unsigned_type_node; - else - return make_unsigned_type(this->bits_); - } - else - { - if (this->bits_ == INT_TYPE_SIZE) - return integer_type_node; - else if (this->bits_ == CHAR_TYPE_SIZE) - return signed_char_type_node; - else if (this->bits_ == SHORT_TYPE_SIZE) - return short_integer_type_node; - else if (this->bits_ == LONG_TYPE_SIZE) - return long_integer_type_node; - else if (this->bits_ == LONG_LONG_TYPE_SIZE) - return long_long_integer_type_node; - else - return make_signed_type(this->bits_); - } -} - -tree -Integer_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - return is_clear ? NULL : build_int_cst(type_tree, 0); -} - -// The type descriptor for an integer type. Integer types are always -// named. - -Expression* -Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - go_assert(name != NULL); - return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name); -} - -// We should not be asked for the reflection string of a basic type. - -void -Integer_type::do_reflection(Gogo*, std::string*) const -{ - go_assert(saw_errors()); -} - -// Mangled name. - -void -Integer_type::do_mangled_name(Gogo*, std::string* ret) const -{ - char buf[100]; - snprintf(buf, sizeof buf, "i%s%s%de", - this->is_abstract_ ? "a" : "", - this->is_unsigned_ ? "u" : "", - this->bits_); - ret->append(buf); -} - -// Make an integer type. - -Named_type* -Type::make_integer_type(const char* name, bool is_unsigned, int bits, - int runtime_type_kind) -{ - return Integer_type::create_integer_type(name, is_unsigned, bits, - runtime_type_kind); -} - -// Make an abstract integer type. - -Integer_type* -Type::make_abstract_integer_type() -{ - return Integer_type::create_abstract_integer_type(); -} - -// Look up an integer type. - -Named_type* -Type::lookup_integer_type(const char* name) -{ - return Integer_type::lookup_integer_type(name); -} - -// Class Float_type. - -Float_type::Named_float_types Float_type::named_float_types; - -// Create a new float type. Non-abstract float types always have -// names. - -Named_type* -Float_type::create_float_type(const char* name, int bits, - int runtime_type_kind) -{ - Float_type* float_type = new Float_type(false, bits, runtime_type_kind); - std::string sname(name); - Named_object* named_object = Named_object::make_type(sname, NULL, float_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - std::pair ins = - Float_type::named_float_types.insert(std::make_pair(sname, named_type)); - go_assert(ins.second); - return named_type; -} - -// Look up an existing float type. - -Named_type* -Float_type::lookup_float_type(const char* name) -{ - Named_float_types::const_iterator p = - Float_type::named_float_types.find(name); - go_assert(p != Float_type::named_float_types.end()); - return p->second; -} - -// Create a new abstract float type. - -Float_type* -Float_type::create_abstract_float_type() -{ - static Float_type* abstract_type; - if (abstract_type == NULL) - abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64); - return abstract_type; -} - -// Whether this type is identical with T. - -bool -Float_type::is_identical(const Float_type* t) const -{ - if (this->bits_ != t->bits_) - return false; - return this->is_abstract_ == t->is_abstract_; -} - -// Hash code. - -unsigned int -Float_type::do_hash_for_method(Gogo*) const -{ - return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8); -} - -// Get a tree without using a Gogo*. - -tree -Float_type::type_tree() const -{ - if (this->bits_ == FLOAT_TYPE_SIZE) - return float_type_node; - else if (this->bits_ == DOUBLE_TYPE_SIZE) - return double_type_node; - else if (this->bits_ == LONG_DOUBLE_TYPE_SIZE) - return long_double_type_node; - else - { - tree ret = make_node(REAL_TYPE); - TYPE_PRECISION(ret) = this->bits_; - layout_type(ret); - return ret; - } -} - -// Get a tree. - -tree -Float_type::do_get_tree(Gogo*) -{ - return this->type_tree(); -} - -tree -Float_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - REAL_VALUE_TYPE r; - real_from_integer(&r, TYPE_MODE(type_tree), 0, 0, 0); - return build_real(type_tree, r); -} - -// The type descriptor for a float type. Float types are always named. - -Expression* -Float_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - go_assert(name != NULL); - return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name); -} - -// We should not be asked for the reflection string of a basic type. - -void -Float_type::do_reflection(Gogo*, std::string*) const -{ - go_assert(saw_errors()); -} - -// Mangled name. - -void -Float_type::do_mangled_name(Gogo*, std::string* ret) const -{ - char buf[100]; - snprintf(buf, sizeof buf, "f%s%de", - this->is_abstract_ ? "a" : "", - this->bits_); - ret->append(buf); -} - -// Make a floating point type. - -Named_type* -Type::make_float_type(const char* name, int bits, int runtime_type_kind) -{ - return Float_type::create_float_type(name, bits, runtime_type_kind); -} - -// Make an abstract float type. - -Float_type* -Type::make_abstract_float_type() -{ - return Float_type::create_abstract_float_type(); -} - -// Look up a float type. - -Named_type* -Type::lookup_float_type(const char* name) -{ - return Float_type::lookup_float_type(name); -} - -// Class Complex_type. - -Complex_type::Named_complex_types Complex_type::named_complex_types; - -// Create a new complex type. Non-abstract complex types always have -// names. - -Named_type* -Complex_type::create_complex_type(const char* name, int bits, - int runtime_type_kind) -{ - Complex_type* complex_type = new Complex_type(false, bits, - runtime_type_kind); - std::string sname(name); - Named_object* named_object = Named_object::make_type(sname, NULL, - complex_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - std::pair ins = - Complex_type::named_complex_types.insert(std::make_pair(sname, - named_type)); - go_assert(ins.second); - return named_type; -} - -// Look up an existing complex type. - -Named_type* -Complex_type::lookup_complex_type(const char* name) -{ - Named_complex_types::const_iterator p = - Complex_type::named_complex_types.find(name); - go_assert(p != Complex_type::named_complex_types.end()); - return p->second; -} - -// Create a new abstract complex type. - -Complex_type* -Complex_type::create_abstract_complex_type() -{ - static Complex_type* abstract_type; - if (abstract_type == NULL) - abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128); - return abstract_type; -} - -// Whether this type is identical with T. - -bool -Complex_type::is_identical(const Complex_type *t) const -{ - if (this->bits_ != t->bits_) - return false; - return this->is_abstract_ == t->is_abstract_; -} - -// Hash code. - -unsigned int -Complex_type::do_hash_for_method(Gogo*) const -{ - return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8); -} - -// Get a tree without using a Gogo*. - -tree -Complex_type::type_tree() const -{ - if (this->bits_ == FLOAT_TYPE_SIZE * 2) - return complex_float_type_node; - else if (this->bits_ == DOUBLE_TYPE_SIZE * 2) - return complex_double_type_node; - else if (this->bits_ == LONG_DOUBLE_TYPE_SIZE * 2) - return complex_long_double_type_node; - else - { - tree ret = make_node(REAL_TYPE); - TYPE_PRECISION(ret) = this->bits_ / 2; - layout_type(ret); - return build_complex_type(ret); - } -} - -// Get a tree. - -tree -Complex_type::do_get_tree(Gogo*) -{ - return this->type_tree(); -} - -// Zero initializer. - -tree -Complex_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - REAL_VALUE_TYPE r; - real_from_integer(&r, TYPE_MODE(TREE_TYPE(type_tree)), 0, 0, 0); - return build_complex(type_tree, build_real(TREE_TYPE(type_tree), r), - build_real(TREE_TYPE(type_tree), r)); -} - -// The type descriptor for a complex type. Complex types are always -// named. - -Expression* -Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - go_assert(name != NULL); - return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name); -} - -// We should not be asked for the reflection string of a basic type. - -void -Complex_type::do_reflection(Gogo*, std::string*) const -{ - go_assert(saw_errors()); -} - -// Mangled name. - -void -Complex_type::do_mangled_name(Gogo*, std::string* ret) const -{ - char buf[100]; - snprintf(buf, sizeof buf, "c%s%de", - this->is_abstract_ ? "a" : "", - this->bits_); - ret->append(buf); -} - -// Make a complex type. - -Named_type* -Type::make_complex_type(const char* name, int bits, int runtime_type_kind) -{ - return Complex_type::create_complex_type(name, bits, runtime_type_kind); -} - -// Make an abstract complex type. - -Complex_type* -Type::make_abstract_complex_type() -{ - return Complex_type::create_abstract_complex_type(); -} - -// Look up a complex type. - -Named_type* -Type::lookup_complex_type(const char* name) -{ - return Complex_type::lookup_complex_type(name); -} - -// Class String_type. - -// Return the tree for String_type. A string is a struct with two -// fields: a pointer to the characters and a length. - -tree -String_type::do_get_tree(Gogo*) -{ - static tree struct_type; - return Gogo::builtin_struct(&struct_type, "__go_string", NULL_TREE, 2, - "__data", - build_pointer_type(unsigned_char_type_node), - "__length", - integer_type_node); -} - -// Return a tree for the length of STRING. - -tree -String_type::length_tree(Gogo*, tree string) -{ - tree string_type = TREE_TYPE(string); - go_assert(TREE_CODE(string_type) == RECORD_TYPE); - tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type)); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)), - "__length") == 0); - return fold_build3(COMPONENT_REF, integer_type_node, string, - length_field, NULL_TREE); -} - -// Return a tree for a pointer to the bytes of STRING. - -tree -String_type::bytes_tree(Gogo*, tree string) -{ - tree string_type = TREE_TYPE(string); - go_assert(TREE_CODE(string_type) == RECORD_TYPE); - tree bytes_field = TYPE_FIELDS(string_type); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)), - "__data") == 0); - return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string, - bytes_field, NULL_TREE); -} - -// We initialize a string to { NULL, 0 }. - -tree -String_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL_TREE; - - go_assert(TREE_CODE(type_tree) == RECORD_TYPE); - - VEC(constructor_elt, gc)* init = VEC_alloc(constructor_elt, gc, 2); - - for (tree field = TYPE_FIELDS(type_tree); - field != NULL_TREE; - field = DECL_CHAIN(field)) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), size_zero_node); - } - - tree ret = build_constructor(type_tree, init); - TREE_CONSTANT(ret) = 1; - return ret; -} - -// The type descriptor for the string type. - -Expression* -String_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (name != NULL) - return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name); - else - { - Named_object* no = gogo->lookup_global("string"); - go_assert(no != NULL); - return Type::type_descriptor(gogo, no->type_value()); - } -} - -// We should not be asked for the reflection string of a basic type. - -void -String_type::do_reflection(Gogo*, std::string* ret) const -{ - ret->append("string"); -} - -// Mangled name of a string type. - -void -String_type::do_mangled_name(Gogo*, std::string* ret) const -{ - ret->push_back('z'); -} - -// Make a string type. - -Type* -Type::make_string_type() -{ - static String_type string_type; - return &string_type; -} - -// The named type "string". - -static Named_type* named_string_type; - -// Get the named type "string". - -Named_type* -Type::lookup_string_type() -{ - return named_string_type; -} - -// Make the named type string. - -Named_type* -Type::make_named_string_type() -{ - Type* string_type = Type::make_string_type(); - Named_object* named_object = Named_object::make_type("string", NULL, - string_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - named_string_type = named_type; - return named_type; -} - -// The sink type. This is the type of the blank identifier _. Any -// type may be assigned to it. - -class Sink_type : public Type -{ - public: - Sink_type() - : Type(TYPE_SINK) - { } - - protected: - tree - do_get_tree(Gogo*) - { go_unreachable(); } - - tree - do_get_init_tree(Gogo*, tree, bool) - { go_unreachable(); } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { go_unreachable(); } - - void - do_reflection(Gogo*, std::string*) const - { go_unreachable(); } - - void - do_mangled_name(Gogo*, std::string*) const - { go_unreachable(); } -}; - -// Make the sink type. - -Type* -Type::make_sink_type() -{ - static Sink_type sink_type; - return &sink_type; -} - -// Class Function_type. - -// Traversal. - -int -Function_type::do_traverse(Traverse* traverse) -{ - if (this->receiver_ != NULL - && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->parameters_ != NULL - && this->parameters_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->results_ != NULL - && this->results_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Returns whether T is a valid redeclaration of this type. If this -// returns false, and REASON is not NULL, *REASON may be set to a -// brief explanation of why it returned false. - -bool -Function_type::is_valid_redeclaration(const Function_type* t, - std::string* reason) const -{ - if (!this->is_identical(t, false, true, reason)) - return false; - - // A redeclaration of a function is required to use the same names - // for the receiver and parameters. - if (this->receiver() != NULL - && this->receiver()->name() != t->receiver()->name() - && this->receiver()->name() != Import::import_marker - && t->receiver()->name() != Import::import_marker) - { - if (reason != NULL) - *reason = "receiver name changed"; - return false; - } - - const Typed_identifier_list* parms1 = this->parameters(); - const Typed_identifier_list* parms2 = t->parameters(); - if (parms1 != NULL) - { - Typed_identifier_list::const_iterator p1 = parms1->begin(); - for (Typed_identifier_list::const_iterator p2 = parms2->begin(); - p2 != parms2->end(); - ++p2, ++p1) - { - if (p1->name() != p2->name() - && p1->name() != Import::import_marker - && p2->name() != Import::import_marker) - { - if (reason != NULL) - *reason = "parameter name changed"; - return false; - } - - // This is called at parse time, so we may have unknown - // types. - Type* t1 = p1->type()->forwarded(); - Type* t2 = p2->type()->forwarded(); - if (t1 != t2 - && t1->forward_declaration_type() != NULL - && (t2->forward_declaration_type() == NULL - || (t1->forward_declaration_type()->named_object() - != t2->forward_declaration_type()->named_object()))) - return false; - } - } - - const Typed_identifier_list* results1 = this->results(); - const Typed_identifier_list* results2 = t->results(); - if (results1 != NULL) - { - Typed_identifier_list::const_iterator res1 = results1->begin(); - for (Typed_identifier_list::const_iterator res2 = results2->begin(); - res2 != results2->end(); - ++res2, ++res1) - { - if (res1->name() != res2->name() - && res1->name() != Import::import_marker - && res2->name() != Import::import_marker) - { - if (reason != NULL) - *reason = "result name changed"; - return false; - } - - // This is called at parse time, so we may have unknown - // types. - Type* t1 = res1->type()->forwarded(); - Type* t2 = res2->type()->forwarded(); - if (t1 != t2 - && t1->forward_declaration_type() != NULL - && (t2->forward_declaration_type() == NULL - || (t1->forward_declaration_type()->named_object() - != t2->forward_declaration_type()->named_object()))) - return false; - } - } - - return true; -} - -// Check whether T is the same as this type. - -bool -Function_type::is_identical(const Function_type* t, bool ignore_receiver, - bool errors_are_identical, - std::string* reason) const -{ - if (!ignore_receiver) - { - const Typed_identifier* r1 = this->receiver(); - const Typed_identifier* r2 = t->receiver(); - if ((r1 != NULL) != (r2 != NULL)) - { - if (reason != NULL) - *reason = _("different receiver types"); - return false; - } - if (r1 != NULL) - { - if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical, - reason)) - { - if (reason != NULL && !reason->empty()) - *reason = "receiver: " + *reason; - return false; - } - } - } - - const Typed_identifier_list* parms1 = this->parameters(); - const Typed_identifier_list* parms2 = t->parameters(); - if ((parms1 != NULL) != (parms2 != NULL)) - { - if (reason != NULL) - *reason = _("different number of parameters"); - return false; - } - if (parms1 != NULL) - { - Typed_identifier_list::const_iterator p1 = parms1->begin(); - for (Typed_identifier_list::const_iterator p2 = parms2->begin(); - p2 != parms2->end(); - ++p2, ++p1) - { - if (p1 == parms1->end()) - { - if (reason != NULL) - *reason = _("different number of parameters"); - return false; - } - - if (!Type::are_identical(p1->type(), p2->type(), - errors_are_identical, NULL)) - { - if (reason != NULL) - *reason = _("different parameter types"); - return false; - } - } - if (p1 != parms1->end()) - { - if (reason != NULL) - *reason = _("different number of parameters"); - return false; - } - } - - if (this->is_varargs() != t->is_varargs()) - { - if (reason != NULL) - *reason = _("different varargs"); - return false; - } - - const Typed_identifier_list* results1 = this->results(); - const Typed_identifier_list* results2 = t->results(); - if ((results1 != NULL) != (results2 != NULL)) - { - if (reason != NULL) - *reason = _("different number of results"); - return false; - } - if (results1 != NULL) - { - Typed_identifier_list::const_iterator res1 = results1->begin(); - for (Typed_identifier_list::const_iterator res2 = results2->begin(); - res2 != results2->end(); - ++res2, ++res1) - { - if (res1 == results1->end()) - { - if (reason != NULL) - *reason = _("different number of results"); - return false; - } - - if (!Type::are_identical(res1->type(), res2->type(), - errors_are_identical, NULL)) - { - if (reason != NULL) - *reason = _("different result types"); - return false; - } - } - if (res1 != results1->end()) - { - if (reason != NULL) - *reason = _("different number of results"); - return false; - } - } - - return true; -} - -// Hash code. - -unsigned int -Function_type::do_hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - // We ignore the receiver type for hash codes, because we need to - // get the same hash code for a method in an interface and a method - // declared for a type. The former will not have a receiver. - if (this->parameters_ != NULL) - { - int shift = 1; - for (Typed_identifier_list::const_iterator p = this->parameters_->begin(); - p != this->parameters_->end(); - ++p, ++shift) - ret += p->type()->hash_for_method(gogo) << shift; - } - if (this->results_ != NULL) - { - int shift = 2; - for (Typed_identifier_list::const_iterator p = this->results_->begin(); - p != this->results_->end(); - ++p, ++shift) - ret += p->type()->hash_for_method(gogo) << shift; - } - if (this->is_varargs_) - ret += 1; - ret <<= 4; - return ret; -} - -// Get the tree for a function type. - -tree -Function_type::do_get_tree(Gogo* gogo) -{ - tree args = NULL_TREE; - tree* pp = &args; - - if (this->receiver_ != NULL) - { - Type* rtype = this->receiver_->type(); - tree ptype = rtype->get_tree(gogo); - if (ptype == error_mark_node) - return error_mark_node; - - // We always pass the address of the receiver parameter, in - // order to make interface calls work with unknown types. - if (rtype->points_to() == NULL) - ptype = build_pointer_type(ptype); - - *pp = tree_cons (NULL_TREE, ptype, NULL_TREE); - pp = &TREE_CHAIN (*pp); - } - - if (this->parameters_ != NULL) - { - for (Typed_identifier_list::const_iterator p = this->parameters_->begin(); - p != this->parameters_->end(); - ++p) - { - tree ptype = p->type()->get_tree(gogo); - if (ptype == error_mark_node) - return error_mark_node; - *pp = tree_cons (NULL_TREE, ptype, NULL_TREE); - pp = &TREE_CHAIN (*pp); - } - } - - // Varargs is handled entirely at the Go level. At the tree level, - // functions are not varargs. - *pp = void_list_node; - - tree result; - if (this->results_ == NULL) - result = void_type_node; - else if (this->results_->size() == 1) - result = this->results_->begin()->type()->get_tree(gogo); - else - { - result = make_node(RECORD_TYPE); - tree field_trees = NULL_TREE; - tree* pp = &field_trees; - for (Typed_identifier_list::const_iterator p = this->results_->begin(); - p != this->results_->end(); - ++p) - { - const std::string name = (p->name().empty() - ? "UNNAMED" - : Gogo::unpack_hidden_name(p->name())); - tree name_tree = get_identifier_with_length(name.data(), - name.length()); - tree field_type_tree = p->type()->get_tree(gogo); - if (field_type_tree == error_mark_node) - return error_mark_node; - tree field = build_decl(this->location_, FIELD_DECL, name_tree, - field_type_tree); - DECL_CONTEXT(field) = result; - *pp = field; - pp = &DECL_CHAIN(field); - } - TYPE_FIELDS(result) = field_trees; - layout_type(result); - } - - if (result == error_mark_node) - return error_mark_node; - - tree fntype = build_function_type(result, args); - if (fntype == error_mark_node) - return fntype; - - return build_pointer_type(fntype); -} - -// Functions are initialized to NULL. - -tree -Function_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - return fold_convert(type_tree, null_pointer_node); -} - -// The type of a function type descriptor. - -Type* -Function_type::make_function_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* bool_type = Type::lookup_bool_type(); - - Type* slice_type = Type::make_array_type(ptdt, NULL); - - Struct_type* s = Type::make_builtin_struct_type(4, - "", tdt, - "dotdotdot", bool_type, - "in", slice_type, - "out", slice_type); - - ret = Type::make_builtin_named_type("FuncType", s); - } - - return ret; -} - -// The type descriptor for a function type. - -Expression* -Function_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* ftdt = Function_type::make_function_type_descriptor_type(); - - const Struct_field_list* fields = ftdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(4); - - Struct_field_list::const_iterator p = fields->begin(); - go_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_FUNC, - name, NULL, true)); - - ++p; - go_assert(p->field_name() == "dotdotdot"); - vals->push_back(Expression::make_boolean(this->is_varargs(), bloc)); - - ++p; - go_assert(p->field_name() == "in"); - vals->push_back(this->type_descriptor_params(p->type(), this->receiver(), - this->parameters())); - - ++p; - go_assert(p->field_name() == "out"); - vals->push_back(this->type_descriptor_params(p->type(), NULL, - this->results())); - - ++p; - go_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(ftdt, vals, bloc); -} - -// Return a composite literal for the parameters or results of a type -// descriptor. - -Expression* -Function_type::type_descriptor_params(Type* params_type, - const Typed_identifier* receiver, - const Typed_identifier_list* params) -{ - source_location bloc = BUILTINS_LOCATION; - - if (receiver == NULL && params == NULL) - return Expression::make_slice_composite_literal(params_type, NULL, bloc); - - Expression_list* vals = new Expression_list(); - vals->reserve((params == NULL ? 0 : params->size()) - + (receiver != NULL ? 1 : 0)); - - if (receiver != NULL) - { - Type* rtype = receiver->type(); - // The receiver is always passed as a pointer. FIXME: Is this - // right? Should that fact affect the type descriptor? - if (rtype->points_to() == NULL) - rtype = Type::make_pointer_type(rtype); - vals->push_back(Expression::make_type_descriptor(rtype, bloc)); - } - - if (params != NULL) - { - for (Typed_identifier_list::const_iterator p = params->begin(); - p != params->end(); - ++p) - vals->push_back(Expression::make_type_descriptor(p->type(), bloc)); - } - - return Expression::make_slice_composite_literal(params_type, vals, bloc); -} - -// The reflection string. - -void -Function_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - // FIXME: Turn this off until we straighten out the type of the - // struct field used in a go statement which calls a method. - // go_assert(this->receiver_ == NULL); - - ret->append("func"); - - if (this->receiver_ != NULL) - { - ret->push_back('('); - this->append_reflection(this->receiver_->type(), gogo, ret); - ret->push_back(')'); - } - - ret->push_back('('); - const Typed_identifier_list* params = this->parameters(); - if (params != NULL) - { - bool is_varargs = this->is_varargs_; - for (Typed_identifier_list::const_iterator p = params->begin(); - p != params->end(); - ++p) - { - if (p != params->begin()) - ret->append(", "); - if (!is_varargs || p + 1 != params->end()) - this->append_reflection(p->type(), gogo, ret); - else - { - ret->append("..."); - this->append_reflection(p->type()->array_type()->element_type(), - gogo, ret); - } - } - } - ret->push_back(')'); - - const Typed_identifier_list* results = this->results(); - if (results != NULL && !results->empty()) - { - if (results->size() == 1) - ret->push_back(' '); - else - ret->append(" ("); - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p) - { - if (p != results->begin()) - ret->append(", "); - this->append_reflection(p->type(), gogo, ret); - } - if (results->size() > 1) - ret->push_back(')'); - } -} - -// Mangled name. - -void -Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('F'); - - if (this->receiver_ != NULL) - { - ret->push_back('m'); - this->append_mangled_name(this->receiver_->type(), gogo, ret); - } - - const Typed_identifier_list* params = this->parameters(); - if (params != NULL) - { - ret->push_back('p'); - for (Typed_identifier_list::const_iterator p = params->begin(); - p != params->end(); - ++p) - this->append_mangled_name(p->type(), gogo, ret); - if (this->is_varargs_) - ret->push_back('V'); - ret->push_back('e'); - } - - const Typed_identifier_list* results = this->results(); - if (results != NULL) - { - ret->push_back('r'); - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p) - this->append_mangled_name(p->type(), gogo, ret); - ret->push_back('e'); - } - - ret->push_back('e'); -} - -// Export a function type. - -void -Function_type::do_export(Export* exp) const -{ - // We don't write out the receiver. The only function types which - // should have a receiver are the ones associated with explicitly - // defined methods. For those the receiver type is written out by - // Function::export_func. - - exp->write_c_string("("); - bool first = true; - if (this->parameters_ != NULL) - { - bool is_varargs = this->is_varargs_; - for (Typed_identifier_list::const_iterator p = - this->parameters_->begin(); - p != this->parameters_->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - if (!is_varargs || p + 1 != this->parameters_->end()) - exp->write_type(p->type()); - else - { - exp->write_c_string("..."); - exp->write_type(p->type()->array_type()->element_type()); - } - } - } - exp->write_c_string(")"); - - const Typed_identifier_list* results = this->results_; - if (results != NULL) - { - exp->write_c_string(" "); - if (results->size() == 1) - exp->write_type(results->begin()->type()); - else - { - first = true; - exp->write_c_string("("); - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - exp->write_type(p->type()); - } - exp->write_c_string(")"); - } - } -} - -// Import a function type. - -Function_type* -Function_type::do_import(Import* imp) -{ - imp->require_c_string("("); - Typed_identifier_list* parameters; - bool is_varargs = false; - if (imp->peek_char() == ')') - parameters = NULL; - else - { - parameters = new Typed_identifier_list(); - while (true) - { - if (imp->match_c_string("...")) - { - imp->advance(3); - is_varargs = true; - } - - Type* ptype = imp->read_type(); - if (is_varargs) - ptype = Type::make_array_type(ptype, NULL); - parameters->push_back(Typed_identifier(Import::import_marker, - ptype, imp->location())); - if (imp->peek_char() != ',') - break; - go_assert(!is_varargs); - imp->require_c_string(", "); - } - } - imp->require_c_string(")"); - - Typed_identifier_list* results; - if (imp->peek_char() != ' ') - results = NULL; - else - { - imp->advance(1); - results = new Typed_identifier_list; - if (imp->peek_char() != '(') - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, rtype, - imp->location())); - } - else - { - imp->advance(1); - while (true) - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, - rtype, imp->location())); - if (imp->peek_char() != ',') - break; - imp->require_c_string(", "); - } - imp->require_c_string(")"); - } - } - - Function_type* ret = Type::make_function_type(NULL, parameters, results, - imp->location()); - if (is_varargs) - ret->set_is_varargs(); - return ret; -} - -// Make a copy of a function type without a receiver. - -Function_type* -Function_type::copy_without_receiver() const -{ - go_assert(this->is_method()); - Function_type *ret = Type::make_function_type(NULL, this->parameters_, - this->results_, - this->location_); - if (this->is_varargs()) - ret->set_is_varargs(); - if (this->is_builtin()) - ret->set_is_builtin(); - return ret; -} - -// Make a copy of a function type with a receiver. - -Function_type* -Function_type::copy_with_receiver(Type* receiver_type) const -{ - go_assert(!this->is_method()); - Typed_identifier* receiver = new Typed_identifier("", receiver_type, - this->location_); - return Type::make_function_type(receiver, this->parameters_, - this->results_, this->location_); -} - -// Make a function type. - -Function_type* -Type::make_function_type(Typed_identifier* receiver, - Typed_identifier_list* parameters, - Typed_identifier_list* results, - source_location location) -{ - return new Function_type(receiver, parameters, results, location); -} - -// Class Pointer_type. - -// Traversal. - -int -Pointer_type::do_traverse(Traverse* traverse) -{ - return Type::traverse(this->to_type_, traverse); -} - -// Hash code. - -unsigned int -Pointer_type::do_hash_for_method(Gogo* gogo) const -{ - return this->to_type_->hash_for_method(gogo) << 4; -} - -// The tree for a pointer type. - -tree -Pointer_type::do_get_tree(Gogo* gogo) -{ - return build_pointer_type(this->to_type_->get_tree(gogo)); -} - -// Initialize a pointer type. - -tree -Pointer_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - return fold_convert(type_tree, null_pointer_node); -} - -// The type of a pointer type descriptor. - -Type* -Pointer_type::make_pointer_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Struct_type* s = Type::make_builtin_struct_type(2, - "", tdt, - "elem", ptdt); - - ret = Type::make_builtin_named_type("PtrType", s); - } - - return ret; -} - -// The type descriptor for a pointer type. - -Expression* -Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (this->is_unsafe_pointer_type()) - { - go_assert(name != NULL); - return this->plain_type_descriptor(gogo, - RUNTIME_TYPE_KIND_UNSAFE_POINTER, - name); - } - else - { - source_location bloc = BUILTINS_LOCATION; - - const Methods* methods; - Type* deref = this->points_to(); - if (deref->named_type() != NULL) - methods = deref->named_type()->methods(); - else if (deref->struct_type() != NULL) - methods = deref->struct_type()->methods(); - else - methods = NULL; - - Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type(); - - const Struct_field_list* fields = ptr_tdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(2); - - Struct_field_list::const_iterator p = fields->begin(); - go_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_PTR, - name, methods, false)); - - ++p; - go_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(deref, bloc)); - - return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc); - } -} - -// Reflection string. - -void -Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->push_back('*'); - this->append_reflection(this->to_type_, gogo, ret); -} - -// Mangled name. - -void -Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('p'); - this->append_mangled_name(this->to_type_, gogo, ret); -} - -// Export. - -void -Pointer_type::do_export(Export* exp) const -{ - exp->write_c_string("*"); - if (this->is_unsafe_pointer_type()) - exp->write_c_string("any"); - else - exp->write_type(this->to_type_); -} - -// Import. - -Pointer_type* -Pointer_type::do_import(Import* imp) -{ - imp->require_c_string("*"); - if (imp->match_c_string("any")) - { - imp->advance(3); - return Type::make_pointer_type(Type::make_void_type()); - } - Type* to = imp->read_type(); - return Type::make_pointer_type(to); -} - -// Make a pointer type. - -Pointer_type* -Type::make_pointer_type(Type* to_type) -{ - typedef Unordered_map(Type*, Pointer_type*) Hashtable; - static Hashtable pointer_types; - Hashtable::const_iterator p = pointer_types.find(to_type); - if (p != pointer_types.end()) - return p->second; - Pointer_type* ret = new Pointer_type(to_type); - pointer_types[to_type] = ret; - return ret; -} - -// The nil type. We use a special type for nil because it is not the -// same as any other type. In C term nil has type void*, but there is -// no such type in Go. - -class Nil_type : public Type -{ - public: - Nil_type() - : Type(TYPE_NIL) - { } - - protected: - tree - do_get_tree(Gogo*) - { return ptr_type_node; } - - tree - do_get_init_tree(Gogo*, tree type_tree, bool is_clear) - { return is_clear ? NULL : fold_convert(type_tree, null_pointer_node); } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { go_unreachable(); } - - void - do_reflection(Gogo*, std::string*) const - { go_unreachable(); } - - void - do_mangled_name(Gogo*, std::string* ret) const - { ret->push_back('n'); } -}; - -// Make the nil type. - -Type* -Type::make_nil_type() -{ - static Nil_type singleton_nil_type; - return &singleton_nil_type; -} - -// The type of a function call which returns multiple values. This is -// really a struct, but we don't want to confuse a function call which -// returns a struct with a function call which returns multiple -// values. - -class Call_multiple_result_type : public Type -{ - public: - Call_multiple_result_type(Call_expression* call) - : Type(TYPE_CALL_MULTIPLE_RESULT), - call_(call) - { } - - protected: - bool - do_has_pointer() const - { - go_assert(saw_errors()); - return false; - } - - tree - do_get_tree(Gogo*); - - tree - do_get_init_tree(Gogo*, tree, bool) - { - go_assert(saw_errors()); - return error_mark_node; - } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { - go_assert(saw_errors()); - return Expression::make_error(UNKNOWN_LOCATION); - } - - void - do_reflection(Gogo*, std::string*) const - { go_assert(saw_errors()); } - - void - do_mangled_name(Gogo*, std::string*) const - { go_assert(saw_errors()); } - - private: - // The expression being called. - Call_expression* call_; -}; - -// Return the tree for a call result. - -tree -Call_multiple_result_type::do_get_tree(Gogo* gogo) -{ - Function_type* fntype = this->call_->get_function_type(); - go_assert(fntype != NULL); - const Typed_identifier_list* results = fntype->results(); - go_assert(results != NULL && results->size() > 1); - tree fntype_tree = fntype->get_tree(gogo); - if (fntype_tree == error_mark_node) - return error_mark_node; - return TREE_TYPE(fntype_tree); -} - -// Make a call result type. - -Type* -Type::make_call_multiple_result_type(Call_expression* call) -{ - return new Call_multiple_result_type(call); -} - -// Class Struct_field. - -// Get the name of a field. - -const std::string& -Struct_field::field_name() const -{ - const std::string& name(this->typed_identifier_.name()); - if (!name.empty()) - return name; - else - { - // This is called during parsing, before anything is lowered, so - // we have to be pretty careful to avoid dereferencing an - // unknown type name. - Type* t = this->typed_identifier_.type(); - Type* dt = t; - if (t->classification() == Type::TYPE_POINTER) - { - // Very ugly. - Pointer_type* ptype = static_cast(t); - dt = ptype->points_to(); - } - if (dt->forward_declaration_type() != NULL) - return dt->forward_declaration_type()->name(); - else if (dt->named_type() != NULL) - return dt->named_type()->name(); - else if (t->is_error_type() || dt->is_error_type()) - { - static const std::string error_string = "*error*"; - return error_string; - } - else - { - // Avoid crashing in the erroneous case where T is named but - // DT is not. - go_assert(t != dt); - if (t->forward_declaration_type() != NULL) - return t->forward_declaration_type()->name(); - else if (t->named_type() != NULL) - return t->named_type()->name(); - else - go_unreachable(); - } - } -} - -// Class Struct_type. - -// Traversal. - -int -Struct_type::do_traverse(Traverse* traverse) -{ - Struct_field_list* fields = this->fields_; - if (fields != NULL) - { - for (Struct_field_list::iterator p = fields->begin(); - p != fields->end(); - ++p) - { - if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - return TRAVERSE_CONTINUE; -} - -// Verify that the struct type is complete and valid. - -bool -Struct_type::do_verify() -{ - Struct_field_list* fields = this->fields_; - if (fields == NULL) - return true; - bool ret = true; - for (Struct_field_list::iterator p = fields->begin(); - p != fields->end(); - ++p) - { - Type* t = p->type(); - if (t->is_undefined()) - { - error_at(p->location(), "struct field type is incomplete"); - p->set_type(Type::make_error_type()); - ret = false; - } - else if (p->is_anonymous()) - { - if (t->named_type() != NULL && t->points_to() != NULL) - { - error_at(p->location(), "embedded type may not be a pointer"); - p->set_type(Type::make_error_type()); - return false; - } - if (t->points_to() != NULL - && t->points_to()->interface_type() != NULL) - { - error_at(p->location(), - "embedded type may not be pointer to interface"); - p->set_type(Type::make_error_type()); - return false; - } - } - } - return ret; -} - -// Whether this contains a pointer. - -bool -Struct_type::do_has_pointer() const -{ - const Struct_field_list* fields = this->fields(); - if (fields == NULL) - return false; - for (Struct_field_list::const_iterator p = fields->begin(); - p != fields->end(); - ++p) - { - if (p->type()->has_pointer()) - return true; - } - return false; -} - -// Whether this type is identical to T. - -bool -Struct_type::is_identical(const Struct_type* t, - bool errors_are_identical) const -{ - const Struct_field_list* fields1 = this->fields(); - const Struct_field_list* fields2 = t->fields(); - if (fields1 == NULL || fields2 == NULL) - return fields1 == fields2; - Struct_field_list::const_iterator pf2 = fields2->begin(); - for (Struct_field_list::const_iterator pf1 = fields1->begin(); - pf1 != fields1->end(); - ++pf1, ++pf2) - { - if (pf2 == fields2->end()) - return false; - if (pf1->field_name() != pf2->field_name()) - return false; - if (pf1->is_anonymous() != pf2->is_anonymous() - || !Type::are_identical(pf1->type(), pf2->type(), - errors_are_identical, NULL)) - return false; - if (!pf1->has_tag()) - { - if (pf2->has_tag()) - return false; - } - else - { - if (!pf2->has_tag()) - return false; - if (pf1->tag() != pf2->tag()) - return false; - } - } - if (pf2 != fields2->end()) - return false; - return true; -} - -// Whether this struct type has any hidden fields. - -bool -Struct_type::struct_has_hidden_fields(const Named_type* within, - std::string* reason) const -{ - const Struct_field_list* fields = this->fields(); - if (fields == NULL) - return false; - const Package* within_package = (within == NULL - ? NULL - : within->named_object()->package()); - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - if (within_package != NULL - && !pf->is_anonymous() - && Gogo::is_hidden_name(pf->field_name())) - { - if (reason != NULL) - { - std::string within_name = within->named_object()->message_name(); - std::string name = Gogo::message_name(pf->field_name()); - size_t bufsize = 200 + within_name.length() + name.length(); - char* buf = new char[bufsize]; - snprintf(buf, bufsize, - _("implicit assignment of %s%s%s hidden field %s%s%s"), - open_quote, within_name.c_str(), close_quote, - open_quote, name.c_str(), close_quote); - reason->assign(buf); - delete[] buf; - } - return true; - } - - if (pf->type()->has_hidden_fields(within, reason)) - return true; - } - - return false; -} - -// Hash code. - -unsigned int -Struct_type::do_hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - if (this->fields() != NULL) - { - for (Struct_field_list::const_iterator pf = this->fields()->begin(); - pf != this->fields()->end(); - ++pf) - ret = (ret << 1) + pf->type()->hash_for_method(gogo); - } - return ret <<= 2; -} - -// Find the local field NAME. - -const Struct_field* -Struct_type::find_local_field(const std::string& name, - unsigned int *pindex) const -{ - const Struct_field_list* fields = this->fields_; - if (fields == NULL) - return NULL; - unsigned int i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++i) - { - if (pf->field_name() == name) - { - if (pindex != NULL) - *pindex = i; - return &*pf; - } - } - return NULL; -} - -// Return an expression for field NAME in STRUCT_EXPR, or NULL. - -Field_reference_expression* -Struct_type::field_reference(Expression* struct_expr, const std::string& name, - source_location location) const -{ - unsigned int depth; - return this->field_reference_depth(struct_expr, name, location, NULL, - &depth); -} - -// Return an expression for a field, along with the depth at which it -// was found. - -Field_reference_expression* -Struct_type::field_reference_depth(Expression* struct_expr, - const std::string& name, - source_location location, - Saw_named_type* saw, - unsigned int* depth) const -{ - const Struct_field_list* fields = this->fields_; - if (fields == NULL) - return NULL; - - // Look for a field with this name. - unsigned int i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++i) - { - if (pf->field_name() == name) - { - *depth = 0; - return Expression::make_field_reference(struct_expr, i, location); - } - } - - // Look for an anonymous field which contains a field with this - // name. - unsigned int found_depth = 0; - Field_reference_expression* ret = NULL; - i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++i) - { - if (!pf->is_anonymous()) - continue; - - Struct_type* st = pf->type()->deref()->struct_type(); - if (st == NULL) - continue; - - Saw_named_type* hold_saw = saw; - Saw_named_type saw_here; - Named_type* nt = pf->type()->named_type(); - if (nt == NULL) - nt = pf->type()->deref()->named_type(); - if (nt != NULL) - { - Saw_named_type* q; - for (q = saw; q != NULL; q = q->next) - { - if (q->nt == nt) - { - // If this is an error, it will be reported - // elsewhere. - break; - } - } - if (q != NULL) - continue; - saw_here.next = saw; - saw_here.nt = nt; - saw = &saw_here; - } - - // Look for a reference using a NULL struct expression. If we - // find one, fill in the struct expression with a reference to - // this field. - unsigned int subdepth; - Field_reference_expression* sub = st->field_reference_depth(NULL, name, - location, - saw, - &subdepth); - - saw = hold_saw; - - if (sub == NULL) - continue; - - if (ret == NULL || subdepth < found_depth) - { - if (ret != NULL) - delete ret; - ret = sub; - found_depth = subdepth; - Expression* here = Expression::make_field_reference(struct_expr, i, - location); - if (pf->type()->points_to() != NULL) - here = Expression::make_unary(OPERATOR_MULT, here, location); - while (sub->expr() != NULL) - { - sub = sub->expr()->deref()->field_reference_expression(); - go_assert(sub != NULL); - } - sub->set_struct_expression(here); - } - else if (subdepth > found_depth) - delete sub; - else - { - // We do not handle ambiguity here--it should be handled by - // Type::bind_field_or_method. - delete sub; - found_depth = 0; - ret = NULL; - } - } - - if (ret != NULL) - *depth = found_depth + 1; - - return ret; -} - -// Return the total number of fields, including embedded fields. - -unsigned int -Struct_type::total_field_count() const -{ - if (this->fields_ == NULL) - return 0; - unsigned int ret = 0; - for (Struct_field_list::const_iterator pf = this->fields_->begin(); - pf != this->fields_->end(); - ++pf) - { - if (!pf->is_anonymous() || pf->type()->deref()->struct_type() == NULL) - ++ret; - else - ret += pf->type()->struct_type()->total_field_count(); - } - return ret; -} - -// Return whether NAME is an unexported field, for better error reporting. - -bool -Struct_type::is_unexported_local_field(Gogo* gogo, - const std::string& name) const -{ - const Struct_field_list* fields = this->fields_; - if (fields != NULL) - { - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - const std::string& field_name(pf->field_name()); - if (Gogo::is_hidden_name(field_name) - && name == Gogo::unpack_hidden_name(field_name) - && gogo->pack_hidden_name(name, false) != field_name) - return true; - } - } - return false; -} - -// Finalize the methods of an unnamed struct. - -void -Struct_type::finalize_methods(Gogo* gogo) -{ - if (this->all_methods_ != NULL) - return; - Type::finalize_methods(gogo, this, this->location_, &this->all_methods_); -} - -// Return the method NAME, or NULL if there isn't one or if it is -// ambiguous. Set *IS_AMBIGUOUS if the method exists but is -// ambiguous. - -Method* -Struct_type::method_function(const std::string& name, bool* is_ambiguous) const -{ - return Type::method_function(this->all_methods_, name, is_ambiguous); -} - -// Get the tree for a struct type. - -tree -Struct_type::do_get_tree(Gogo* gogo) -{ - tree type = make_node(RECORD_TYPE); - return this->fill_in_tree(gogo, type); -} - -// Fill in the fields for a struct type. - -tree -Struct_type::fill_in_tree(Gogo* gogo, tree type) -{ - tree field_trees = NULL_TREE; - tree* pp = &field_trees; - for (Struct_field_list::const_iterator p = this->fields_->begin(); - p != this->fields_->end(); - ++p) - { - std::string name = Gogo::unpack_hidden_name(p->field_name()); - tree name_tree = get_identifier_with_length(name.data(), name.length()); - - tree field_type_tree = p->type()->get_tree(gogo); - if (field_type_tree == error_mark_node) - return error_mark_node; - go_assert(TYPE_SIZE(field_type_tree) != NULL_TREE); - - tree field = build_decl(p->location(), FIELD_DECL, name_tree, - field_type_tree); - DECL_CONTEXT(field) = type; - *pp = field; - pp = &DECL_CHAIN(field); - } - - TYPE_FIELDS(type) = field_trees; - - layout_type(type); - - return type; -} - -// Initialize struct fields. - -tree -Struct_type::do_get_init_tree(Gogo* gogo, tree type_tree, bool is_clear) -{ - if (this->fields_ == NULL || this->fields_->empty()) - { - if (is_clear) - return NULL; - else - { - tree ret = build_constructor(type_tree, - VEC_alloc(constructor_elt, gc, 0)); - TREE_CONSTANT(ret) = 1; - return ret; - } - } - - bool is_constant = true; - bool any_fields_set = false; - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, - this->fields_->size()); - - tree field = TYPE_FIELDS(type_tree); - for (Struct_field_list::const_iterator p = this->fields_->begin(); - p != this->fields_->end(); - ++p, field = DECL_CHAIN(field)) - { - tree value = p->type()->get_init_tree(gogo, is_clear); - if (value == error_mark_node) - return error_mark_node; - go_assert(field != NULL_TREE); - if (value != NULL) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = value; - any_fields_set = true; - if (!TREE_CONSTANT(value)) - is_constant = false; - } - } - go_assert(field == NULL_TREE); - - if (!any_fields_set) - { - go_assert(is_clear); - VEC_free(constructor_elt, gc, init); - return NULL; - } - - tree ret = build_constructor(type_tree, init); - if (is_constant) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// The type of a struct type descriptor. - -Type* -Struct_type::make_struct_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* uintptr_type = Type::lookup_integer_type("uintptr"); - Type* string_type = Type::lookup_string_type(); - Type* pointer_string_type = Type::make_pointer_type(string_type); - - Struct_type* sf = - Type::make_builtin_struct_type(5, - "name", pointer_string_type, - "pkgPath", pointer_string_type, - "typ", ptdt, - "tag", pointer_string_type, - "offset", uintptr_type); - Type* nsf = Type::make_builtin_named_type("structField", sf); - - Type* slice_type = Type::make_array_type(nsf, NULL); - - Struct_type* s = Type::make_builtin_struct_type(2, - "", tdt, - "fields", slice_type); - - ret = Type::make_builtin_named_type("StructType", s); - } - - return ret; -} - -// Build a type descriptor for a struct type. - -Expression* -Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* stdt = Struct_type::make_struct_type_descriptor_type(); - - const Struct_field_list* fields = stdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(2); - - const Methods* methods = this->methods(); - // A named struct should not have methods--the methods should attach - // to the named type. - go_assert(methods == NULL || name == NULL); - - Struct_field_list::const_iterator ps = fields->begin(); - go_assert(ps->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_STRUCT, - name, methods, true)); - - ++ps; - go_assert(ps->field_name() == "fields"); - - Expression_list* elements = new Expression_list(); - elements->reserve(this->fields_->size()); - Type* element_type = ps->type()->array_type()->element_type(); - for (Struct_field_list::const_iterator pf = this->fields_->begin(); - pf != this->fields_->end(); - ++pf) - { - const Struct_field_list* f = element_type->struct_type()->fields(); - - Expression_list* fvals = new Expression_list(); - fvals->reserve(5); - - Struct_field_list::const_iterator q = f->begin(); - go_assert(q->field_name() == "name"); - if (pf->is_anonymous()) - fvals->push_back(Expression::make_nil(bloc)); - else - { - std::string n = Gogo::unpack_hidden_name(pf->field_name()); - Expression* s = Expression::make_string(n, bloc); - fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - - ++q; - go_assert(q->field_name() == "pkgPath"); - if (!Gogo::is_hidden_name(pf->field_name())) - fvals->push_back(Expression::make_nil(bloc)); - else - { - std::string n = Gogo::hidden_name_prefix(pf->field_name()); - Expression* s = Expression::make_string(n, bloc); - fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - - ++q; - go_assert(q->field_name() == "typ"); - fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc)); - - ++q; - go_assert(q->field_name() == "tag"); - if (!pf->has_tag()) - fvals->push_back(Expression::make_nil(bloc)); - else - { - Expression* s = Expression::make_string(pf->tag(), bloc); - fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - - ++q; - go_assert(q->field_name() == "offset"); - fvals->push_back(Expression::make_struct_field_offset(this, &*pf)); - - Expression* v = Expression::make_struct_composite_literal(element_type, - fvals, bloc); - elements->push_back(v); - } - - vals->push_back(Expression::make_slice_composite_literal(ps->type(), - elements, bloc)); - - return Expression::make_struct_composite_literal(stdt, vals, bloc); -} - -// Reflection string. - -void -Struct_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->append("struct { "); - - for (Struct_field_list::const_iterator p = this->fields_->begin(); - p != this->fields_->end(); - ++p) - { - if (p != this->fields_->begin()) - ret->append("; "); - if (p->is_anonymous()) - ret->push_back('?'); - else - ret->append(Gogo::unpack_hidden_name(p->field_name())); - ret->push_back(' '); - this->append_reflection(p->type(), gogo, ret); - - if (p->has_tag()) - { - const std::string& tag(p->tag()); - ret->append(" \""); - for (std::string::const_iterator p = tag.begin(); - p != tag.end(); - ++p) - { - if (*p == '\0') - ret->append("\\x00"); - else if (*p == '\n') - ret->append("\\n"); - else if (*p == '\t') - ret->append("\\t"); - else if (*p == '"') - ret->append("\\\""); - else if (*p == '\\') - ret->append("\\\\"); - else - ret->push_back(*p); - } - ret->push_back('"'); - } - } - - ret->append(" }"); -} - -// Mangled name. - -void -Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('S'); - - const Struct_field_list* fields = this->fields_; - if (fields != NULL) - { - for (Struct_field_list::const_iterator p = fields->begin(); - p != fields->end(); - ++p) - { - if (p->is_anonymous()) - ret->append("0_"); - else - { - std::string n = Gogo::unpack_hidden_name(p->field_name()); - char buf[20]; - snprintf(buf, sizeof buf, "%u_", - static_cast(n.length())); - ret->append(buf); - ret->append(n); - } - this->append_mangled_name(p->type(), gogo, ret); - if (p->has_tag()) - { - const std::string& tag(p->tag()); - std::string out; - for (std::string::const_iterator p = tag.begin(); - p != tag.end(); - ++p) - { - if (ISALNUM(*p) || *p == '_') - out.push_back(*p); - else - { - char buf[20]; - snprintf(buf, sizeof buf, ".%x.", - static_cast(*p)); - out.append(buf); - } - } - char buf[20]; - snprintf(buf, sizeof buf, "T%u_", - static_cast(out.length())); - ret->append(buf); - ret->append(out); - } - } - } - - ret->push_back('e'); -} - -// Export. - -void -Struct_type::do_export(Export* exp) const -{ - exp->write_c_string("struct { "); - const Struct_field_list* fields = this->fields_; - go_assert(fields != NULL); - for (Struct_field_list::const_iterator p = fields->begin(); - p != fields->end(); - ++p) - { - if (p->is_anonymous()) - exp->write_string("? "); - else - { - exp->write_string(p->field_name()); - exp->write_c_string(" "); - } - exp->write_type(p->type()); - - if (p->has_tag()) - { - exp->write_c_string(" "); - Expression* expr = Expression::make_string(p->tag(), - BUILTINS_LOCATION); - expr->export_expression(exp); - delete expr; - } - - exp->write_c_string("; "); - } - exp->write_c_string("}"); -} - -// Import. - -Struct_type* -Struct_type::do_import(Import* imp) -{ - imp->require_c_string("struct { "); - Struct_field_list* fields = new Struct_field_list; - if (imp->peek_char() != '}') - { - while (true) - { - std::string name; - if (imp->match_c_string("? ")) - imp->advance(2); - else - { - name = imp->read_identifier(); - imp->require_c_string(" "); - } - Type* ftype = imp->read_type(); - - Struct_field sf(Typed_identifier(name, ftype, imp->location())); - - if (imp->peek_char() == ' ') - { - imp->advance(1); - Expression* expr = Expression::import_expression(imp); - String_expression* sexpr = expr->string_expression(); - go_assert(sexpr != NULL); - sf.set_tag(sexpr->val()); - delete sexpr; - } - - imp->require_c_string("; "); - fields->push_back(sf); - if (imp->peek_char() == '}') - break; - } - } - imp->require_c_string("}"); - - return Type::make_struct_type(fields, imp->location()); -} - -// Make a struct type. - -Struct_type* -Type::make_struct_type(Struct_field_list* fields, - source_location location) -{ - return new Struct_type(fields, location); -} - -// Class Array_type. - -// Whether two array types are identical. - -bool -Array_type::is_identical(const Array_type* t, bool errors_are_identical) const -{ - if (!Type::are_identical(this->element_type(), t->element_type(), - errors_are_identical, NULL)) - return false; - - Expression* l1 = this->length(); - Expression* l2 = t->length(); - - // Slices of the same element type are identical. - if (l1 == NULL && l2 == NULL) - return true; - - // Arrays of the same element type are identical if they have the - // same length. - if (l1 != NULL && l2 != NULL) - { - if (l1 == l2) - return true; - - // Try to determine the lengths. If we can't, assume the arrays - // are not identical. - bool ret = false; - mpz_t v1; - mpz_init(v1); - Type* type1; - mpz_t v2; - mpz_init(v2); - Type* type2; - if (l1->integer_constant_value(true, v1, &type1) - && l2->integer_constant_value(true, v2, &type2)) - ret = mpz_cmp(v1, v2) == 0; - mpz_clear(v1); - mpz_clear(v2); - return ret; - } - - // Otherwise the arrays are not identical. - return false; -} - -// Traversal. - -int -Array_type::do_traverse(Traverse* traverse) -{ - if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->length_ != NULL - && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Check that the length is valid. - -bool -Array_type::verify_length() -{ - if (this->length_ == NULL) - return true; - - Type_context context(Type::lookup_integer_type("int"), false); - this->length_->determine_type(&context); - - if (!this->length_->is_constant()) - { - error_at(this->length_->location(), "array bound is not constant"); - return false; - } - - mpz_t val; - mpz_init(val); - Type* vt; - if (!this->length_->integer_constant_value(true, val, &vt)) - { - mpfr_t fval; - mpfr_init(fval); - if (!this->length_->float_constant_value(fval, &vt)) - { - if (this->length_->type()->integer_type() != NULL - || this->length_->type()->float_type() != NULL) - error_at(this->length_->location(), - "array bound is not constant"); - else - error_at(this->length_->location(), - "array bound is not numeric"); - mpfr_clear(fval); - mpz_clear(val); - return false; - } - if (!mpfr_integer_p(fval)) - { - error_at(this->length_->location(), - "array bound truncated to integer"); - mpfr_clear(fval); - mpz_clear(val); - return false; - } - mpz_init(val); - mpfr_get_z(val, fval, GMP_RNDN); - mpfr_clear(fval); - } - - if (mpz_sgn(val) < 0) - { - error_at(this->length_->location(), "negative array bound"); - mpz_clear(val); - return false; - } - - Type* int_type = Type::lookup_integer_type("int"); - int tbits = int_type->integer_type()->bits(); - int vbits = mpz_sizeinbase(val, 2); - if (vbits + 1 > tbits) - { - error_at(this->length_->location(), "array bound overflows"); - mpz_clear(val); - return false; - } - - mpz_clear(val); - - return true; -} - -// Verify the type. - -bool -Array_type::do_verify() -{ - if (!this->verify_length()) - { - this->length_ = Expression::make_error(this->length_->location()); - return false; - } - return true; -} - -// Array type hash code. - -unsigned int -Array_type::do_hash_for_method(Gogo* gogo) const -{ - // There is no very convenient way to get a hash code for the - // length. - return this->element_type_->hash_for_method(gogo) + 1; -} - -// See if the expression passed to make is suitable. The first -// argument is required, and gives the length. An optional second -// argument is permitted for the capacity. - -bool -Array_type::do_check_make_expression(Expression_list* args, - source_location location) -{ - go_assert(this->length_ == NULL); - if (args == NULL || args->empty()) - { - error_at(location, "length required when allocating a slice"); - return false; - } - else if (args->size() > 2) - { - error_at(location, "too many expressions passed to make"); - return false; - } - else - { - if (!Type::check_int_value(args->front(), - _("bad length when making slice"), location)) - return false; - - if (args->size() > 1) - { - if (!Type::check_int_value(args->back(), - _("bad capacity when making slice"), - location)) - return false; - } - - return true; - } -} - -// Get a tree for the length of a fixed array. The length may be -// computed using a function call, so we must only evaluate it once. - -tree -Array_type::get_length_tree(Gogo* gogo) -{ - go_assert(this->length_ != NULL); - if (this->length_tree_ == NULL_TREE) - { - mpz_t val; - mpz_init(val); - Type* t; - if (this->length_->integer_constant_value(true, val, &t)) - { - if (t == NULL) - t = Type::lookup_integer_type("int"); - else if (t->is_abstract()) - t = t->make_non_abstract_type(); - tree tt = t->get_tree(gogo); - this->length_tree_ = Expression::integer_constant_tree(val, tt); - mpz_clear(val); - } - else - { - mpz_clear(val); - - // Make up a translation context for the array length - // expression. FIXME: This won't work in general. - Translate_context context(gogo, NULL, NULL, NULL); - tree len = this->length_->get_tree(&context); - if (len != error_mark_node) - { - len = convert_to_integer(integer_type_node, len); - len = save_expr(len); - } - this->length_tree_ = len; - } - } - return this->length_tree_; -} - -// Get a tree for the type of this array. A fixed array is simply -// represented as ARRAY_TYPE with the appropriate index--i.e., it is -// just like an array in C. An open array is a struct with three -// fields: a data pointer, the length, and the capacity. - -tree -Array_type::do_get_tree(Gogo* gogo) -{ - if (this->length_ == NULL) - { - tree struct_type = gogo->slice_type_tree(void_type_node); - return this->fill_in_slice_tree(gogo, struct_type); - } - else - { - tree array_type = make_node(ARRAY_TYPE); - return this->fill_in_array_tree(gogo, array_type); - } -} - -// Fill in the fields for an array type. This is used for named array -// types. - -tree -Array_type::fill_in_array_tree(Gogo* gogo, tree array_type) -{ - go_assert(this->length_ != NULL); - - tree element_type_tree = this->element_type_->get_tree(gogo); - tree length_tree = this->get_length_tree(gogo); - if (element_type_tree == error_mark_node - || length_tree == error_mark_node) - return error_mark_node; - - go_assert(TYPE_SIZE(element_type_tree) != NULL_TREE); - - length_tree = fold_convert(sizetype, length_tree); - - // build_index_type takes the maximum index, which is one less than - // the length. - tree index_type = build_index_type(fold_build2(MINUS_EXPR, sizetype, - length_tree, - size_one_node)); - - TREE_TYPE(array_type) = element_type_tree; - TYPE_DOMAIN(array_type) = index_type; - TYPE_ADDR_SPACE(array_type) = TYPE_ADDR_SPACE(element_type_tree); - layout_type(array_type); - - if (TYPE_STRUCTURAL_EQUALITY_P(element_type_tree) - || TYPE_STRUCTURAL_EQUALITY_P(index_type)) - SET_TYPE_STRUCTURAL_EQUALITY(array_type); - else if (TYPE_CANONICAL(element_type_tree) != element_type_tree - || TYPE_CANONICAL(index_type) != index_type) - TYPE_CANONICAL(array_type) = - build_array_type(TYPE_CANONICAL(element_type_tree), - TYPE_CANONICAL(index_type)); - - return array_type; -} - -// Fill in the fields for a slice type. This is used for named slice -// types. - -tree -Array_type::fill_in_slice_tree(Gogo* gogo, tree struct_type) -{ - go_assert(this->length_ == NULL); - - tree element_type_tree = this->element_type_->get_tree(gogo); - if (element_type_tree == error_mark_node) - return error_mark_node; - tree field = TYPE_FIELDS(struct_type); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0); - go_assert(POINTER_TYPE_P(TREE_TYPE(field)) - && TREE_TYPE(TREE_TYPE(field)) == void_type_node); - TREE_TYPE(field) = build_pointer_type(element_type_tree); - - return struct_type; -} - -// Return an initializer for an array type. - -tree -Array_type::do_get_init_tree(Gogo* gogo, tree type_tree, bool is_clear) -{ - if (this->length_ == NULL) - { - // Open array. - - if (is_clear) - return NULL; - - go_assert(TREE_CODE(type_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - for (tree field = TYPE_FIELDS(type_tree); - field != NULL_TREE; - field = DECL_CHAIN(field)) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, init, - NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), size_zero_node); - } - - tree ret = build_constructor(type_tree, init); - TREE_CONSTANT(ret) = 1; - return ret; - } - else - { - // Fixed array. - - tree value = this->element_type_->get_init_tree(gogo, is_clear); - if (value == NULL) - return NULL; - if (value == error_mark_node) - return error_mark_node; - - tree length_tree = this->get_length_tree(gogo); - if (length_tree == error_mark_node) - return error_mark_node; - - length_tree = fold_convert(sizetype, length_tree); - tree range = build2(RANGE_EXPR, sizetype, size_zero_node, - fold_build2(MINUS_EXPR, sizetype, - length_tree, size_one_node)); - tree ret = build_constructor_single(type_tree, range, value); - if (TREE_CONSTANT(value)) - TREE_CONSTANT(ret) = 1; - return ret; - } -} - -// Handle the builtin make function for a slice. - -tree -Array_type::do_make_expression_tree(Translate_context* context, - Expression_list* args, - source_location location) -{ - go_assert(this->length_ == NULL); - - Gogo* gogo = context->gogo(); - tree type_tree = this->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - - tree values_field = TYPE_FIELDS(type_tree); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(values_field)), - "__values") == 0); - - tree count_field = DECL_CHAIN(values_field); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(count_field)), - "__count") == 0); - - tree element_type_tree = this->element_type_->get_tree(gogo); - if (element_type_tree == error_mark_node) - return error_mark_node; - tree element_size_tree = TYPE_SIZE_UNIT(element_type_tree); - - tree value = this->element_type_->get_init_tree(gogo, true); - if (value == error_mark_node) - return error_mark_node; - - // The first argument is the number of elements, the optional second - // argument is the capacity. - go_assert(args != NULL && args->size() >= 1 && args->size() <= 2); - - tree length_tree = args->front()->get_tree(context); - if (length_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(length_tree)) - length_tree = save_expr(length_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(length_tree))) - length_tree = convert_to_integer(TREE_TYPE(count_field), length_tree); - - tree bad_index = Expression::check_bounds(length_tree, - TREE_TYPE(count_field), - NULL_TREE, location); - - length_tree = fold_convert_loc(location, TREE_TYPE(count_field), length_tree); - tree capacity_tree; - if (args->size() == 1) - capacity_tree = length_tree; - else - { - capacity_tree = args->back()->get_tree(context); - if (capacity_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(capacity_tree)) - capacity_tree = save_expr(capacity_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(capacity_tree))) - capacity_tree = convert_to_integer(TREE_TYPE(count_field), - capacity_tree); - - bad_index = Expression::check_bounds(capacity_tree, - TREE_TYPE(count_field), - bad_index, location); - - tree chktype = (((TYPE_SIZE(TREE_TYPE(capacity_tree)) - > TYPE_SIZE(TREE_TYPE(length_tree))) - || ((TYPE_SIZE(TREE_TYPE(capacity_tree)) - == TYPE_SIZE(TREE_TYPE(length_tree))) - && TYPE_UNSIGNED(TREE_TYPE(capacity_tree)))) - ? TREE_TYPE(capacity_tree) - : TREE_TYPE(length_tree)); - tree chk = fold_build2_loc(location, LT_EXPR, boolean_type_node, - fold_convert_loc(location, chktype, - capacity_tree), - fold_convert_loc(location, chktype, - length_tree)); - if (bad_index == NULL_TREE) - bad_index = chk; - else - bad_index = fold_build2_loc(location, TRUTH_OR_EXPR, boolean_type_node, - bad_index, chk); - - capacity_tree = fold_convert_loc(location, TREE_TYPE(count_field), - capacity_tree); - } - - tree size_tree = fold_build2_loc(location, MULT_EXPR, sizetype, - element_size_tree, - fold_convert_loc(location, sizetype, - capacity_tree)); - - tree chk = fold_build2_loc(location, TRUTH_AND_EXPR, boolean_type_node, - fold_build2_loc(location, GT_EXPR, - boolean_type_node, - fold_convert_loc(location, - sizetype, - capacity_tree), - size_zero_node), - fold_build2_loc(location, LT_EXPR, - boolean_type_node, - size_tree, element_size_tree)); - if (bad_index == NULL_TREE) - bad_index = chk; - else - bad_index = fold_build2_loc(location, TRUTH_OR_EXPR, boolean_type_node, - bad_index, chk); - - tree space = context->gogo()->allocate_memory(this->element_type_, - size_tree, location); - - if (value != NULL_TREE) - space = save_expr(space); - - space = fold_convert(TREE_TYPE(values_field), space); - - if (bad_index != NULL_TREE && bad_index != boolean_false_node) - { - tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_SLICE_OUT_OF_BOUNDS, - location); - space = build2(COMPOUND_EXPR, TREE_TYPE(space), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - space); - } - - tree constructor = gogo->slice_constructor(type_tree, space, length_tree, - capacity_tree); - - if (value == NULL_TREE) - { - // The array contents are zero initialized. - return constructor; - } - - // The elements must be initialized. - - tree max = fold_build2_loc(location, MINUS_EXPR, TREE_TYPE(count_field), - capacity_tree, - fold_convert_loc(location, TREE_TYPE(count_field), - integer_one_node)); - - tree array_type = build_array_type(element_type_tree, - build_index_type(max)); - - tree value_pointer = fold_convert_loc(location, - build_pointer_type(array_type), - space); - - tree range = build2(RANGE_EXPR, sizetype, size_zero_node, max); - tree space_init = build_constructor_single(array_type, range, value); - - return build2(COMPOUND_EXPR, TREE_TYPE(constructor), - build2(MODIFY_EXPR, void_type_node, - build_fold_indirect_ref(value_pointer), - space_init), - constructor); -} - -// Return a tree for a pointer to the values in ARRAY. - -tree -Array_type::value_pointer_tree(Gogo*, tree array) const -{ - tree ret; - if (this->length() != NULL) - { - // Fixed array. - ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))), - build_fold_addr_expr(array)); - } - else - { - // Open array. - tree field = TYPE_FIELDS(TREE_TYPE(array)); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__values") == 0); - ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field, - NULL_TREE); - } - if (TREE_CONSTANT(array)) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Return a tree for the length of the array ARRAY which has this -// type. - -tree -Array_type::length_tree(Gogo* gogo, tree array) -{ - if (this->length_ != NULL) - { - if (TREE_CODE(array) == SAVE_EXPR) - return fold_convert(integer_type_node, this->get_length_tree(gogo)); - else - return omit_one_operand(integer_type_node, - this->get_length_tree(gogo), array); - } - - // This is an open array. We need to read the length field. - - tree type = TREE_TYPE(array); - go_assert(TREE_CODE(type) == RECORD_TYPE); - - tree field = DECL_CHAIN(TYPE_FIELDS(type)); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0); - - tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE); - if (TREE_CONSTANT(array)) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Return a tree for the capacity of the array ARRAY which has this -// type. - -tree -Array_type::capacity_tree(Gogo* gogo, tree array) -{ - if (this->length_ != NULL) - return omit_one_operand(sizetype, this->get_length_tree(gogo), array); - - // This is an open array. We need to read the capacity field. - - tree type = TREE_TYPE(array); - go_assert(TREE_CODE(type) == RECORD_TYPE); - - tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type))); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0); - - return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE); -} - -// Export. - -void -Array_type::do_export(Export* exp) const -{ - exp->write_c_string("["); - if (this->length_ != NULL) - this->length_->export_expression(exp); - exp->write_c_string("] "); - exp->write_type(this->element_type_); -} - -// Import. - -Array_type* -Array_type::do_import(Import* imp) -{ - imp->require_c_string("["); - Expression* length; - if (imp->peek_char() == ']') - length = NULL; - else - length = Expression::import_expression(imp); - imp->require_c_string("] "); - Type* element_type = imp->read_type(); - return Type::make_array_type(element_type, length); -} - -// The type of an array type descriptor. - -Type* -Array_type::make_array_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* uintptr_type = Type::lookup_integer_type("uintptr"); - - Struct_type* sf = - Type::make_builtin_struct_type(3, - "", tdt, - "elem", ptdt, - "len", uintptr_type); - - ret = Type::make_builtin_named_type("ArrayType", sf); - } - - return ret; -} - -// The type of an slice type descriptor. - -Type* -Array_type::make_slice_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Struct_type* sf = - Type::make_builtin_struct_type(2, - "", tdt, - "elem", ptdt); - - ret = Type::make_builtin_named_type("SliceType", sf); - } - - return ret; -} - -// Build a type descriptor for an array/slice type. - -Expression* -Array_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (this->length_ != NULL) - return this->array_type_descriptor(gogo, name); - else - return this->slice_type_descriptor(gogo, name); -} - -// Build a type descriptor for an array type. - -Expression* -Array_type::array_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* atdt = Array_type::make_array_type_descriptor_type(); - - const Struct_field_list* fields = atdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(3); - - Struct_field_list::const_iterator p = fields->begin(); - go_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_ARRAY, - name, NULL, true)); - - ++p; - go_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc)); - - ++p; - go_assert(p->field_name() == "len"); - vals->push_back(Expression::make_cast(p->type(), this->length_, bloc)); - - ++p; - go_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(atdt, vals, bloc); -} - -// Build a type descriptor for a slice type. - -Expression* -Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* stdt = Array_type::make_slice_type_descriptor_type(); - - const Struct_field_list* fields = stdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(2); - - Struct_field_list::const_iterator p = fields->begin(); - go_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_SLICE, - name, NULL, true)); - - ++p; - go_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc)); - - ++p; - go_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(stdt, vals, bloc); -} - -// Reflection string. - -void -Array_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->push_back('['); - if (this->length_ != NULL) - { - mpz_t val; - mpz_init(val); - Type* type; - if (!this->length_->integer_constant_value(true, val, &type)) - error_at(this->length_->location(), - "array length must be integer constant expression"); - else if (mpz_cmp_si(val, 0) < 0) - error_at(this->length_->location(), "array length is negative"); - else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0) - error_at(this->length_->location(), "array length is too large"); - else - { - char buf[50]; - snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val)); - ret->append(buf); - } - mpz_clear(val); - } - ret->push_back(']'); - - this->append_reflection(this->element_type_, gogo, ret); -} - -// Mangled name. - -void -Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('A'); - this->append_mangled_name(this->element_type_, gogo, ret); - if (this->length_ != NULL) - { - mpz_t val; - mpz_init(val); - Type* type; - if (!this->length_->integer_constant_value(true, val, &type)) - error_at(this->length_->location(), - "array length must be integer constant expression"); - else if (mpz_cmp_si(val, 0) < 0) - error_at(this->length_->location(), "array length is negative"); - else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0) - error_at(this->length_->location(), "array size is too large"); - else - { - char buf[50]; - snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val)); - ret->append(buf); - } - mpz_clear(val); - } - ret->push_back('e'); -} - -// Make an array type. - -Array_type* -Type::make_array_type(Type* element_type, Expression* length) -{ - return new Array_type(element_type, length); -} - -// Class Map_type. - -// Traversal. - -int -Map_type::do_traverse(Traverse* traverse) -{ - if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT - || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Check that the map type is OK. - -bool -Map_type::do_verify() -{ - if (this->key_type_->struct_type() != NULL - || this->key_type_->array_type() != NULL) - { - error_at(this->location_, "invalid map key type"); - return false; - } - return true; -} - -// Whether two map types are identical. - -bool -Map_type::is_identical(const Map_type* t, bool errors_are_identical) const -{ - return (Type::are_identical(this->key_type(), t->key_type(), - errors_are_identical, NULL) - && Type::are_identical(this->val_type(), t->val_type(), - errors_are_identical, NULL)); -} - -// Hash code. - -unsigned int -Map_type::do_hash_for_method(Gogo* gogo) const -{ - return (this->key_type_->hash_for_method(gogo) - + this->val_type_->hash_for_method(gogo) - + 2); -} - -// Check that a call to the builtin make function is valid. For a map -// the optional argument is the number of spaces to preallocate for -// values. - -bool -Map_type::do_check_make_expression(Expression_list* args, - source_location location) -{ - if (args != NULL && !args->empty()) - { - if (!Type::check_int_value(args->front(), _("bad size when making map"), - location)) - return false; - else if (args->size() > 1) - { - error_at(location, "too many arguments when making map"); - return false; - } - } - return true; -} - -// Get a tree for a map type. A map type is represented as a pointer -// to a struct. The struct is __go_map in libgo/map.h. - -tree -Map_type::do_get_tree(Gogo* gogo) -{ - static tree type_tree; - if (type_tree == NULL_TREE) - { - tree struct_type = make_node(RECORD_TYPE); - - tree map_descriptor_type = gogo->map_descriptor_type(); - tree const_map_descriptor_type = - build_qualified_type(map_descriptor_type, TYPE_QUAL_CONST); - tree name = get_identifier("__descriptor"); - tree field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name, - build_pointer_type(const_map_descriptor_type)); - DECL_CONTEXT(field) = struct_type; - TYPE_FIELDS(struct_type) = field; - tree last_field = field; - - name = get_identifier("__element_count"); - field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name, sizetype); - DECL_CONTEXT(field) = struct_type; - DECL_CHAIN(last_field) = field; - last_field = field; - - name = get_identifier("__bucket_count"); - field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name, sizetype); - DECL_CONTEXT(field) = struct_type; - DECL_CHAIN(last_field) = field; - last_field = field; - - name = get_identifier("__buckets"); - field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name, - build_pointer_type(ptr_type_node)); - DECL_CONTEXT(field) = struct_type; - DECL_CHAIN(last_field) = field; - - layout_type(struct_type); - - // Give the struct a name for better debugging info. - name = get_identifier("__go_map"); - tree type_decl = build_decl(BUILTINS_LOCATION, TYPE_DECL, name, - struct_type); - DECL_ARTIFICIAL(type_decl) = 1; - TYPE_NAME(struct_type) = type_decl; - go_preserve_from_gc(type_decl); - rest_of_decl_compilation(type_decl, 1, 0); - - type_tree = build_pointer_type(struct_type); - go_preserve_from_gc(type_tree); - } - - return type_tree; -} - -// Initialize a map. - -tree -Map_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - return fold_convert(type_tree, null_pointer_node); -} - -// Return an expression for a newly allocated map. - -tree -Map_type::do_make_expression_tree(Translate_context* context, - Expression_list* args, - source_location location) -{ - tree bad_index = NULL_TREE; - - tree expr_tree; - if (args == NULL || args->empty()) - expr_tree = size_zero_node; - else - { - expr_tree = args->front()->get_tree(context); - if (expr_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(expr_tree)) - expr_tree = save_expr(expr_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(expr_tree))) - expr_tree = convert_to_integer(sizetype, expr_tree); - bad_index = Expression::check_bounds(expr_tree, sizetype, bad_index, - location); - } - - tree map_type = this->get_tree(context->gogo()); - - static tree new_map_fndecl; - tree ret = Gogo::call_builtin(&new_map_fndecl, - location, - "__go_new_map", - 2, - map_type, - TREE_TYPE(TYPE_FIELDS(TREE_TYPE(map_type))), - context->gogo()->map_descriptor(this), - sizetype, - expr_tree); - if (ret == error_mark_node) - return error_mark_node; - // This can panic if the capacity is out of range. - TREE_NOTHROW(new_map_fndecl) = 0; - - if (bad_index == NULL_TREE) - return ret; - else - { - tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_MAP_OUT_OF_BOUNDS, - location); - return build2(COMPOUND_EXPR, TREE_TYPE(ret), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - ret); - } -} - -// The type of a map type descriptor. - -Type* -Map_type::make_map_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Struct_type* sf = - Type::make_builtin_struct_type(3, - "", tdt, - "key", ptdt, - "elem", ptdt); - - ret = Type::make_builtin_named_type("MapType", sf); - } - - return ret; -} - -// Build a type descriptor for a map type. - -Expression* -Map_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* mtdt = Map_type::make_map_type_descriptor_type(); - - const Struct_field_list* fields = mtdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(3); - - Struct_field_list::const_iterator p = fields->begin(); - go_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_MAP, - name, NULL, true)); - - ++p; - go_assert(p->field_name() == "key"); - vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc)); - - ++p; - go_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc)); - - ++p; - go_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(mtdt, vals, bloc); -} - -// Reflection string for a map. - -void -Map_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->append("map["); - this->append_reflection(this->key_type_, gogo, ret); - ret->append("] "); - this->append_reflection(this->val_type_, gogo, ret); -} - -// Mangled name for a map. - -void -Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('M'); - this->append_mangled_name(this->key_type_, gogo, ret); - ret->append("__"); - this->append_mangled_name(this->val_type_, gogo, ret); -} - -// Export a map type. - -void -Map_type::do_export(Export* exp) const -{ - exp->write_c_string("map ["); - exp->write_type(this->key_type_); - exp->write_c_string("] "); - exp->write_type(this->val_type_); -} - -// Import a map type. - -Map_type* -Map_type::do_import(Import* imp) -{ - imp->require_c_string("map ["); - Type* key_type = imp->read_type(); - imp->require_c_string("] "); - Type* val_type = imp->read_type(); - return Type::make_map_type(key_type, val_type, imp->location()); -} - -// Make a map type. - -Map_type* -Type::make_map_type(Type* key_type, Type* val_type, source_location location) -{ - return new Map_type(key_type, val_type, location); -} - -// Class Channel_type. - -// Hash code. - -unsigned int -Channel_type::do_hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - if (this->may_send_) - ret += 1; - if (this->may_receive_) - ret += 2; - if (this->element_type_ != NULL) - ret += this->element_type_->hash_for_method(gogo) << 2; - return ret << 3; -} - -// Whether this type is the same as T. - -bool -Channel_type::is_identical(const Channel_type* t, - bool errors_are_identical) const -{ - if (!Type::are_identical(this->element_type(), t->element_type(), - errors_are_identical, NULL)) - return false; - return (this->may_send_ == t->may_send_ - && this->may_receive_ == t->may_receive_); -} - -// Check whether the parameters for a call to the builtin function -// make are OK for a channel. A channel can take an optional single -// parameter which is the buffer size. - -bool -Channel_type::do_check_make_expression(Expression_list* args, - source_location location) -{ - if (args != NULL && !args->empty()) - { - if (!Type::check_int_value(args->front(), - _("bad buffer size when making channel"), - location)) - return false; - else if (args->size() > 1) - { - error_at(location, "too many arguments when making channel"); - return false; - } - } - return true; -} - -// Return the tree for a channel type. A channel is a pointer to a -// __go_channel struct. The __go_channel struct is defined in -// libgo/runtime/channel.h. - -tree -Channel_type::do_get_tree(Gogo*) -{ - static tree type_tree; - if (type_tree == NULL_TREE) - { - tree ret = make_node(RECORD_TYPE); - TYPE_NAME(ret) = get_identifier("__go_channel"); - TYPE_STUB_DECL(ret) = build_decl(BUILTINS_LOCATION, TYPE_DECL, NULL_TREE, - ret); - type_tree = build_pointer_type(ret); - go_preserve_from_gc(type_tree); - } - return type_tree; -} - -// Initialize a channel variable. - -tree -Channel_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - return fold_convert(type_tree, null_pointer_node); -} - -// Handle the builtin function make for a channel. - -tree -Channel_type::do_make_expression_tree(Translate_context* context, - Expression_list* args, - source_location location) -{ - Gogo* gogo = context->gogo(); - tree channel_type = this->get_tree(gogo); - - tree element_tree = this->element_type_->get_tree(gogo); - tree element_size_tree = size_in_bytes(element_tree); - - tree bad_index = NULL_TREE; - - tree expr_tree; - if (args == NULL || args->empty()) - expr_tree = size_zero_node; - else - { - expr_tree = args->front()->get_tree(context); - if (expr_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(expr_tree)) - expr_tree = save_expr(expr_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(expr_tree))) - expr_tree = convert_to_integer(sizetype, expr_tree); - bad_index = Expression::check_bounds(expr_tree, sizetype, bad_index, - location); - } - - static tree new_channel_fndecl; - tree ret = Gogo::call_builtin(&new_channel_fndecl, - location, - "__go_new_channel", - 2, - channel_type, - sizetype, - element_size_tree, - sizetype, - expr_tree); - if (ret == error_mark_node) - return error_mark_node; - // This can panic if the capacity is out of range. - TREE_NOTHROW(new_channel_fndecl) = 0; - - if (bad_index == NULL_TREE) - return ret; - else - { - tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_CHAN_OUT_OF_BOUNDS, - location); - return build2(COMPOUND_EXPR, TREE_TYPE(ret), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - ret); - } -} - -// Build a type descriptor for a channel type. - -Type* -Channel_type::make_chan_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* uintptr_type = Type::lookup_integer_type("uintptr"); - - Struct_type* sf = - Type::make_builtin_struct_type(3, - "", tdt, - "elem", ptdt, - "dir", uintptr_type); - - ret = Type::make_builtin_named_type("ChanType", sf); - } - - return ret; -} - -// Build a type descriptor for a map type. - -Expression* -Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* ctdt = Channel_type::make_chan_type_descriptor_type(); - - const Struct_field_list* fields = ctdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(3); - - Struct_field_list::const_iterator p = fields->begin(); - go_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_CHAN, - name, NULL, true)); - - ++p; - go_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc)); - - ++p; - go_assert(p->field_name() == "dir"); - // These bits must match the ones in libgo/runtime/go-type.h. - int val = 0; - if (this->may_receive_) - val |= 1; - if (this->may_send_) - val |= 2; - mpz_t iv; - mpz_init_set_ui(iv, val); - vals->push_back(Expression::make_integer(&iv, p->type(), bloc)); - mpz_clear(iv); - - ++p; - go_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(ctdt, vals, bloc); -} - -// Reflection string. - -void -Channel_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - if (!this->may_send_) - ret->append("<-"); - ret->append("chan"); - if (!this->may_receive_) - ret->append("<-"); - ret->push_back(' '); - this->append_reflection(this->element_type_, gogo, ret); -} - -// Mangled name. - -void -Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('C'); - this->append_mangled_name(this->element_type_, gogo, ret); - if (this->may_send_) - ret->push_back('s'); - if (this->may_receive_) - ret->push_back('r'); - ret->push_back('e'); -} - -// Export. - -void -Channel_type::do_export(Export* exp) const -{ - exp->write_c_string("chan "); - if (this->may_send_ && !this->may_receive_) - exp->write_c_string("-< "); - else if (this->may_receive_ && !this->may_send_) - exp->write_c_string("<- "); - exp->write_type(this->element_type_); -} - -// Import. - -Channel_type* -Channel_type::do_import(Import* imp) -{ - imp->require_c_string("chan "); - - bool may_send; - bool may_receive; - if (imp->match_c_string("-< ")) - { - imp->advance(3); - may_send = true; - may_receive = false; - } - else if (imp->match_c_string("<- ")) - { - imp->advance(3); - may_receive = true; - may_send = false; - } - else - { - may_send = true; - may_receive = true; - } - - Type* element_type = imp->read_type(); - - return Type::make_channel_type(may_send, may_receive, element_type); -} - -// Make a new channel type. - -Channel_type* -Type::make_channel_type(bool send, bool receive, Type* element_type) -{ - return new Channel_type(send, receive, element_type); -} - -// Class Interface_type. - -// Traversal. - -int -Interface_type::do_traverse(Traverse* traverse) -{ - if (this->methods_ == NULL) - return TRAVERSE_CONTINUE; - return this->methods_->traverse(traverse); -} - -// Finalize the methods. This handles interface inheritance. - -void -Interface_type::finalize_methods() -{ - if (this->methods_ == NULL) - return; - std::vector seen; - bool is_recursive = false; - size_t from = 0; - size_t to = 0; - while (from < this->methods_->size()) - { - const Typed_identifier* p = &this->methods_->at(from); - if (!p->name().empty()) - { - size_t i; - for (i = 0; i < to; ++i) - { - if (this->methods_->at(i).name() == p->name()) - { - error_at(p->location(), "duplicate method %qs", - Gogo::message_name(p->name()).c_str()); - break; - } - } - if (i == to) - { - if (from != to) - this->methods_->set(to, *p); - ++to; - } - ++from; - continue; - } - - Interface_type* it = p->type()->interface_type(); - if (it == NULL) - { - error_at(p->location(), "interface contains embedded non-interface"); - ++from; - continue; - } - if (it == this) - { - if (!is_recursive) - { - error_at(p->location(), "invalid recursive interface"); - is_recursive = true; - } - ++from; - continue; - } - - Named_type* nt = p->type()->named_type(); - if (nt != NULL) - { - std::vector::const_iterator q; - for (q = seen.begin(); q != seen.end(); ++q) - { - if (*q == nt) - { - error_at(p->location(), "inherited interface loop"); - break; - } - } - if (q != seen.end()) - { - ++from; - continue; - } - seen.push_back(nt); - } - - const Typed_identifier_list* methods = it->methods(); - if (methods == NULL) - { - ++from; - continue; - } - for (Typed_identifier_list::const_iterator q = methods->begin(); - q != methods->end(); - ++q) - { - if (q->name().empty()) - { - if (q->type()->forwarded() == p->type()->forwarded()) - error_at(p->location(), "interface inheritance loop"); - else - { - size_t i; - for (i = from + 1; i < this->methods_->size(); ++i) - { - const Typed_identifier* r = &this->methods_->at(i); - if (r->name().empty() - && r->type()->forwarded() == q->type()->forwarded()) - { - error_at(p->location(), - "inherited interface listed twice"); - break; - } - } - if (i == this->methods_->size()) - this->methods_->push_back(Typed_identifier(q->name(), - q->type(), - p->location())); - } - } - else if (this->find_method(q->name()) == NULL) - this->methods_->push_back(Typed_identifier(q->name(), q->type(), - p->location())); - else - { - if (!is_recursive) - error_at(p->location(), "inherited method %qs is ambiguous", - Gogo::message_name(q->name()).c_str()); - } - } - ++from; - } - if (to == 0) - { - delete this->methods_; - this->methods_ = NULL; - } - else - { - this->methods_->resize(to); - this->methods_->sort_by_name(); - } -} - -// Return the method NAME, or NULL. - -const Typed_identifier* -Interface_type::find_method(const std::string& name) const -{ - if (this->methods_ == NULL) - return NULL; - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - if (p->name() == name) - return &*p; - return NULL; -} - -// Return the method index. - -size_t -Interface_type::method_index(const std::string& name) const -{ - go_assert(this->methods_ != NULL); - size_t ret = 0; - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p, ++ret) - if (p->name() == name) - return ret; - go_unreachable(); -} - -// Return whether NAME is an unexported method, for better error -// reporting. - -bool -Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const -{ - if (this->methods_ == NULL) - return false; - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - const std::string& method_name(p->name()); - if (Gogo::is_hidden_name(method_name) - && name == Gogo::unpack_hidden_name(method_name) - && gogo->pack_hidden_name(name, false) != method_name) - return true; - } - return false; -} - -// Whether this type is identical with T. - -bool -Interface_type::is_identical(const Interface_type* t, - bool errors_are_identical) const -{ - // We require the same methods with the same types. The methods - // have already been sorted. - if (this->methods() == NULL || t->methods() == NULL) - return this->methods() == t->methods(); - - Typed_identifier_list::const_iterator p1 = this->methods()->begin(); - for (Typed_identifier_list::const_iterator p2 = t->methods()->begin(); - p2 != t->methods()->end(); - ++p1, ++p2) - { - if (p1 == this->methods()->end()) - return false; - if (p1->name() != p2->name() - || !Type::are_identical(p1->type(), p2->type(), - errors_are_identical, NULL)) - return false; - } - if (p1 != this->methods()->end()) - return false; - return true; -} - -// Whether we can assign the interface type T to this type. The types -// are known to not be identical. An interface assignment is only -// permitted if T is known to implement all methods in THIS. -// Otherwise a type guard is required. - -bool -Interface_type::is_compatible_for_assign(const Interface_type* t, - std::string* reason) const -{ - if (this->methods() == NULL) - return true; - for (Typed_identifier_list::const_iterator p = this->methods()->begin(); - p != this->methods()->end(); - ++p) - { - const Typed_identifier* m = t->find_method(p->name()); - if (m == NULL) - { - if (reason != NULL) - { - char buf[200]; - snprintf(buf, sizeof buf, - _("need explicit conversion; missing method %s%s%s"), - open_quote, Gogo::message_name(p->name()).c_str(), - close_quote); - reason->assign(buf); - } - return false; - } - - std::string subreason; - if (!Type::are_identical(p->type(), m->type(), true, &subreason)) - { - if (reason != NULL) - { - std::string n = Gogo::message_name(p->name()); - size_t len = 100 + n.length() + subreason.length(); - char* buf = new char[len]; - if (subreason.empty()) - snprintf(buf, len, _("incompatible type for method %s%s%s"), - open_quote, n.c_str(), close_quote); - else - snprintf(buf, len, - _("incompatible type for method %s%s%s (%s)"), - open_quote, n.c_str(), close_quote, - subreason.c_str()); - reason->assign(buf); - delete[] buf; - } - return false; - } - } - - return true; -} - -// Hash code. - -unsigned int -Interface_type::do_hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - if (this->methods_ != NULL) - { - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - ret = Type::hash_string(p->name(), ret); - ret += p->type()->hash_for_method(gogo); - ret <<= 1; - } - } - return ret; -} - -// Return true if T implements the interface. If it does not, and -// REASON is not NULL, set *REASON to a useful error message. - -bool -Interface_type::implements_interface(const Type* t, std::string* reason) const -{ - if (this->methods_ == NULL) - return true; - - bool is_pointer = false; - const Named_type* nt = t->named_type(); - const Struct_type* st = t->struct_type(); - // If we start with a named type, we don't dereference it to find - // methods. - if (nt == NULL) - { - const Type* pt = t->points_to(); - if (pt != NULL) - { - // If T is a pointer to a named type, then we need to look at - // the type to which it points. - is_pointer = true; - nt = pt->named_type(); - st = pt->struct_type(); - } - } - - // If we have a named type, get the methods from it rather than from - // any struct type. - if (nt != NULL) - st = NULL; - - // Only named and struct types have methods. - if (nt == NULL && st == NULL) - { - if (reason != NULL) - { - if (t->points_to() != NULL - && t->points_to()->interface_type() != NULL) - reason->assign(_("pointer to interface type has no methods")); - else - reason->assign(_("type has no methods")); - } - return false; - } - - if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods()) - { - if (reason != NULL) - { - if (t->points_to() != NULL - && t->points_to()->interface_type() != NULL) - reason->assign(_("pointer to interface type has no methods")); - else - reason->assign(_("type has no methods")); - } - return false; - } - - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - bool is_ambiguous = false; - Method* m = (nt != NULL - ? nt->method_function(p->name(), &is_ambiguous) - : st->method_function(p->name(), &is_ambiguous)); - if (m == NULL) - { - if (reason != NULL) - { - std::string n = Gogo::message_name(p->name()); - size_t len = n.length() + 100; - char* buf = new char[len]; - if (is_ambiguous) - snprintf(buf, len, _("ambiguous method %s%s%s"), - open_quote, n.c_str(), close_quote); - else - snprintf(buf, len, _("missing method %s%s%s"), - open_quote, n.c_str(), close_quote); - reason->assign(buf); - delete[] buf; - } - return false; - } - - Function_type *p_fn_type = p->type()->function_type(); - Function_type* m_fn_type = m->type()->function_type(); - go_assert(p_fn_type != NULL && m_fn_type != NULL); - std::string subreason; - if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason)) - { - if (reason != NULL) - { - std::string n = Gogo::message_name(p->name()); - size_t len = 100 + n.length() + subreason.length(); - char* buf = new char[len]; - if (subreason.empty()) - snprintf(buf, len, _("incompatible type for method %s%s%s"), - open_quote, n.c_str(), close_quote); - else - snprintf(buf, len, - _("incompatible type for method %s%s%s (%s)"), - open_quote, n.c_str(), close_quote, - subreason.c_str()); - reason->assign(buf); - delete[] buf; - } - return false; - } - - if (!is_pointer && !m->is_value_method()) - { - if (reason != NULL) - { - std::string n = Gogo::message_name(p->name()); - size_t len = 100 + n.length(); - char* buf = new char[len]; - snprintf(buf, len, _("method %s%s%s requires a pointer"), - open_quote, n.c_str(), close_quote); - reason->assign(buf); - delete[] buf; - } - return false; - } - } - - return true; -} - -// Return a tree for an interface type. An interface is a pointer to -// a struct. The struct has three fields. The first field is a -// pointer to the type descriptor for the dynamic type of the object. -// The second field is a pointer to a table of methods for the -// interface to be used with the object. The third field is the value -// of the object itself. - -tree -Interface_type::do_get_tree(Gogo* gogo) -{ - if (this->methods_ == NULL) - return Interface_type::empty_type_tree(gogo); - else - { - tree t = Interface_type::non_empty_type_tree(this->location_); - return this->fill_in_tree(gogo, t); - } -} - -// Return a singleton struct for an empty interface type. We use the -// same type for all empty interfaces. This lets us assign them to -// each other directly without triggering GIMPLE type errors. - -tree -Interface_type::empty_type_tree(Gogo* gogo) -{ - static tree empty_interface; - if (empty_interface != NULL_TREE) - return empty_interface; - - tree dtype = Type::make_type_descriptor_type()->get_tree(gogo); - dtype = build_pointer_type(build_qualified_type(dtype, TYPE_QUAL_CONST)); - return Gogo::builtin_struct(&empty_interface, "__go_empty_interface", - NULL_TREE, 2, - "__type_descriptor", - dtype, - "__object", - ptr_type_node); -} - -// Return a new struct for a non-empty interface type. The correct -// values are filled in by fill_in_tree. - -tree -Interface_type::non_empty_type_tree(source_location location) -{ - tree ret = make_node(RECORD_TYPE); - - tree field_trees = NULL_TREE; - tree* pp = &field_trees; - - tree name_tree = get_identifier("__methods"); - tree field = build_decl(location, FIELD_DECL, name_tree, ptr_type_node); - DECL_CONTEXT(field) = ret; - *pp = field; - pp = &DECL_CHAIN(field); - - name_tree = get_identifier("__object"); - field = build_decl(location, FIELD_DECL, name_tree, ptr_type_node); - DECL_CONTEXT(field) = ret; - *pp = field; - - TYPE_FIELDS(ret) = field_trees; - - layout_type(ret); - - return ret; -} - -// Fill in the tree for an interface type. This is used for named -// interface types. - -tree -Interface_type::fill_in_tree(Gogo* gogo, tree type) -{ - go_assert(this->methods_ != NULL); - - // Build the type of the table of methods. - - tree method_table = make_node(RECORD_TYPE); - - // The first field is a pointer to the type descriptor. - tree name_tree = get_identifier("__type_descriptor"); - tree dtype = Type::make_type_descriptor_type()->get_tree(gogo); - dtype = build_pointer_type(build_qualified_type(dtype, TYPE_QUAL_CONST)); - tree field = build_decl(this->location_, FIELD_DECL, name_tree, dtype); - DECL_CONTEXT(field) = method_table; - TYPE_FIELDS(method_table) = field; - - std::string last_name = ""; - tree* pp = &DECL_CHAIN(field); - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - std::string name = Gogo::unpack_hidden_name(p->name()); - name_tree = get_identifier_with_length(name.data(), name.length()); - tree field_type = p->type()->get_tree(gogo); - if (field_type == error_mark_node) - return error_mark_node; - field = build_decl(this->location_, FIELD_DECL, name_tree, field_type); - DECL_CONTEXT(field) = method_table; - *pp = field; - pp = &DECL_CHAIN(field); - // Sanity check: the names should be sorted. - go_assert(p->name() > last_name); - last_name = p->name(); - } - layout_type(method_table); - - // Update the type of the __methods field from a generic pointer to - // a pointer to the method table. - field = TYPE_FIELDS(type); - go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0); - - TREE_TYPE(field) = build_pointer_type(method_table); - - return type; -} - -// Initialization value. - -tree -Interface_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - for (tree field = TYPE_FIELDS(type_tree); - field != NULL_TREE; - field = DECL_CHAIN(field)) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), null_pointer_node); - } - - tree ret = build_constructor(type_tree, init); - TREE_CONSTANT(ret) = 1; - return ret; -} - -// The type of an interface type descriptor. - -Type* -Interface_type::make_interface_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* string_type = Type::lookup_string_type(); - Type* pointer_string_type = Type::make_pointer_type(string_type); - - Struct_type* sm = - Type::make_builtin_struct_type(3, - "name", pointer_string_type, - "pkgPath", pointer_string_type, - "typ", ptdt); - - Type* nsm = Type::make_builtin_named_type("imethod", sm); - - Type* slice_nsm = Type::make_array_type(nsm, NULL); - - Struct_type* s = Type::make_builtin_struct_type(2, - "", tdt, - "methods", slice_nsm); - - ret = Type::make_builtin_named_type("InterfaceType", s); - } - - return ret; -} - -// Build a type descriptor for an interface type. - -Expression* -Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* itdt = Interface_type::make_interface_type_descriptor_type(); - - const Struct_field_list* ifields = itdt->struct_type()->fields(); - - Expression_list* ivals = new Expression_list(); - ivals->reserve(2); - - Struct_field_list::const_iterator pif = ifields->begin(); - go_assert(pif->field_name() == "commonType"); - ivals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_INTERFACE, - name, NULL, true)); - - ++pif; - go_assert(pif->field_name() == "methods"); - - Expression_list* methods = new Expression_list(); - if (this->methods_ != NULL && !this->methods_->empty()) - { - Type* elemtype = pif->type()->array_type()->element_type(); - - methods->reserve(this->methods_->size()); - for (Typed_identifier_list::const_iterator pm = this->methods_->begin(); - pm != this->methods_->end(); - ++pm) - { - const Struct_field_list* mfields = elemtype->struct_type()->fields(); - - Expression_list* mvals = new Expression_list(); - mvals->reserve(3); - - Struct_field_list::const_iterator pmf = mfields->begin(); - go_assert(pmf->field_name() == "name"); - std::string s = Gogo::unpack_hidden_name(pm->name()); - Expression* e = Expression::make_string(s, bloc); - mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc)); - - ++pmf; - go_assert(pmf->field_name() == "pkgPath"); - if (!Gogo::is_hidden_name(pm->name())) - mvals->push_back(Expression::make_nil(bloc)); - else - { - s = Gogo::hidden_name_prefix(pm->name()); - e = Expression::make_string(s, bloc); - mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc)); - } - - ++pmf; - go_assert(pmf->field_name() == "typ"); - mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc)); - - ++pmf; - go_assert(pmf == mfields->end()); - - e = Expression::make_struct_composite_literal(elemtype, mvals, - bloc); - methods->push_back(e); - } - } - - ivals->push_back(Expression::make_slice_composite_literal(pif->type(), - methods, bloc)); - - ++pif; - go_assert(pif == ifields->end()); - - return Expression::make_struct_composite_literal(itdt, ivals, bloc); -} - -// Reflection string. - -void -Interface_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->append("interface {"); - if (this->methods_ != NULL) - { - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - if (p != this->methods_->begin()) - ret->append(";"); - ret->push_back(' '); - ret->append(Gogo::unpack_hidden_name(p->name())); - std::string sub = p->type()->reflection(gogo); - go_assert(sub.compare(0, 4, "func") == 0); - sub = sub.substr(4); - ret->append(sub); - } - } - ret->append(" }"); -} - -// Mangled name. - -void -Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('I'); - - const Typed_identifier_list* methods = this->methods_; - if (methods != NULL) - { - for (Typed_identifier_list::const_iterator p = methods->begin(); - p != methods->end(); - ++p) - { - std::string n = Gogo::unpack_hidden_name(p->name()); - char buf[20]; - snprintf(buf, sizeof buf, "%u_", - static_cast(n.length())); - ret->append(buf); - ret->append(n); - this->append_mangled_name(p->type(), gogo, ret); - } - } - - ret->push_back('e'); -} - -// Export. - -void -Interface_type::do_export(Export* exp) const -{ - exp->write_c_string("interface { "); - - const Typed_identifier_list* methods = this->methods_; - if (methods != NULL) - { - for (Typed_identifier_list::const_iterator pm = methods->begin(); - pm != methods->end(); - ++pm) - { - exp->write_string(pm->name()); - exp->write_c_string(" ("); - - const Function_type* fntype = pm->type()->function_type(); - - bool first = true; - const Typed_identifier_list* parameters = fntype->parameters(); - if (parameters != NULL) - { - bool is_varargs = fntype->is_varargs(); - for (Typed_identifier_list::const_iterator pp = - parameters->begin(); - pp != parameters->end(); - ++pp) - { - if (first) - first = false; - else - exp->write_c_string(", "); - if (!is_varargs || pp + 1 != parameters->end()) - exp->write_type(pp->type()); - else - { - exp->write_c_string("..."); - Type *pptype = pp->type(); - exp->write_type(pptype->array_type()->element_type()); - } - } - } - - exp->write_c_string(")"); - - const Typed_identifier_list* results = fntype->results(); - if (results != NULL) - { - exp->write_c_string(" "); - if (results->size() == 1) - exp->write_type(results->begin()->type()); - else - { - first = true; - exp->write_c_string("("); - for (Typed_identifier_list::const_iterator p = - results->begin(); - p != results->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - exp->write_type(p->type()); - } - exp->write_c_string(")"); - } - } - - exp->write_c_string("; "); - } - } - - exp->write_c_string("}"); -} - -// Import an interface type. - -Interface_type* -Interface_type::do_import(Import* imp) -{ - imp->require_c_string("interface { "); - - Typed_identifier_list* methods = new Typed_identifier_list; - while (imp->peek_char() != '}') - { - std::string name = imp->read_identifier(); - imp->require_c_string(" ("); - - Typed_identifier_list* parameters; - bool is_varargs = false; - if (imp->peek_char() == ')') - parameters = NULL; - else - { - parameters = new Typed_identifier_list; - while (true) - { - if (imp->match_c_string("...")) - { - imp->advance(3); - is_varargs = true; - } - - Type* ptype = imp->read_type(); - if (is_varargs) - ptype = Type::make_array_type(ptype, NULL); - parameters->push_back(Typed_identifier(Import::import_marker, - ptype, imp->location())); - if (imp->peek_char() != ',') - break; - go_assert(!is_varargs); - imp->require_c_string(", "); - } - } - imp->require_c_string(")"); - - Typed_identifier_list* results; - if (imp->peek_char() != ' ') - results = NULL; - else - { - results = new Typed_identifier_list; - imp->advance(1); - if (imp->peek_char() != '(') - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, - rtype, imp->location())); - } - else - { - imp->advance(1); - while (true) - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, - rtype, imp->location())); - if (imp->peek_char() != ',') - break; - imp->require_c_string(", "); - } - imp->require_c_string(")"); - } - } - - Function_type* fntype = Type::make_function_type(NULL, parameters, - results, - imp->location()); - if (is_varargs) - fntype->set_is_varargs(); - methods->push_back(Typed_identifier(name, fntype, imp->location())); - - imp->require_c_string("; "); - } - - imp->require_c_string("}"); - - if (methods->empty()) - { - delete methods; - methods = NULL; - } - - return Type::make_interface_type(methods, imp->location()); -} - -// Make an interface type. - -Interface_type* -Type::make_interface_type(Typed_identifier_list* methods, - source_location location) -{ - return new Interface_type(methods, location); -} - -// Class Method. - -// Bind a method to an object. - -Expression* -Method::bind_method(Expression* expr, source_location location) const -{ - if (this->stub_ == NULL) - { - // When there is no stub object, the binding is determined by - // the child class. - return this->do_bind_method(expr, location); - } - - Expression* func = Expression::make_func_reference(this->stub_, NULL, - location); - return Expression::make_bound_method(expr, func, location); -} - -// Return the named object associated with a method. This may only be -// called after methods are finalized. - -Named_object* -Method::named_object() const -{ - if (this->stub_ != NULL) - return this->stub_; - return this->do_named_object(); -} - -// Class Named_method. - -// The type of the method. - -Function_type* -Named_method::do_type() const -{ - if (this->named_object_->is_function()) - return this->named_object_->func_value()->type(); - else if (this->named_object_->is_function_declaration()) - return this->named_object_->func_declaration_value()->type(); - else - go_unreachable(); -} - -// Return the location of the method receiver. - -source_location -Named_method::do_receiver_location() const -{ - return this->do_type()->receiver()->location(); -} - -// Bind a method to an object. - -Expression* -Named_method::do_bind_method(Expression* expr, source_location location) const -{ - Expression* func = Expression::make_func_reference(this->named_object_, NULL, - location); - Bound_method_expression* bme = Expression::make_bound_method(expr, func, - location); - // If this is not a local method, and it does not use a stub, then - // the real method expects a different type. We need to cast the - // first argument. - if (this->depth() > 0 && !this->needs_stub_method()) - { - Function_type* ftype = this->do_type(); - go_assert(ftype->is_method()); - Type* frtype = ftype->receiver()->type(); - bme->set_first_argument_type(frtype); - } - return bme; -} - -// Class Interface_method. - -// Bind a method to an object. - -Expression* -Interface_method::do_bind_method(Expression* expr, - source_location location) const -{ - return Expression::make_interface_field_reference(expr, this->name_, - location); -} - -// Class Methods. - -// Insert a new method. Return true if it was inserted, false -// otherwise. - -bool -Methods::insert(const std::string& name, Method* m) -{ - std::pair ins = - this->methods_.insert(std::make_pair(name, m)); - if (ins.second) - return true; - else - { - Method* old_method = ins.first->second; - if (m->depth() < old_method->depth()) - { - delete old_method; - ins.first->second = m; - return true; - } - else - { - if (m->depth() == old_method->depth()) - old_method->set_is_ambiguous(); - return false; - } - } -} - -// Return the number of unambiguous methods. - -size_t -Methods::count() const -{ - size_t ret = 0; - for (Method_map::const_iterator p = this->methods_.begin(); - p != this->methods_.end(); - ++p) - if (!p->second->is_ambiguous()) - ++ret; - return ret; -} - -// Class Named_type. - -// Return the name of the type. - -const std::string& -Named_type::name() const -{ - return this->named_object_->name(); -} - -// Return the name of the type to use in an error message. - -std::string -Named_type::message_name() const -{ - return this->named_object_->message_name(); -} - -// Return the base type for this type. We have to be careful about -// circular type definitions, which are invalid but may be seen here. - -Type* -Named_type::named_base() -{ - if (this->seen_ > 0) - return this; - ++this->seen_; - Type* ret = this->type_->base(); - --this->seen_; - return ret; -} - -const Type* -Named_type::named_base() const -{ - if (this->seen_ > 0) - return this; - ++this->seen_; - const Type* ret = this->type_->base(); - --this->seen_; - return ret; -} - -// Return whether this is an error type. We have to be careful about -// circular type definitions, which are invalid but may be seen here. - -bool -Named_type::is_named_error_type() const -{ - if (this->seen_ > 0) - return false; - ++this->seen_; - bool ret = this->type_->is_error_type(); - --this->seen_; - return ret; -} - -// Add a method to this type. - -Named_object* -Named_type::add_method(const std::string& name, Function* function) -{ - if (this->local_methods_ == NULL) - this->local_methods_ = new Bindings(NULL); - return this->local_methods_->add_function(name, NULL, function); -} - -// Add a method declaration to this type. - -Named_object* -Named_type::add_method_declaration(const std::string& name, Package* package, - Function_type* type, - source_location location) -{ - if (this->local_methods_ == NULL) - this->local_methods_ = new Bindings(NULL); - return this->local_methods_->add_function_declaration(name, package, type, - location); -} - -// Add an existing method to this type. - -void -Named_type::add_existing_method(Named_object* no) -{ - if (this->local_methods_ == NULL) - this->local_methods_ = new Bindings(NULL); - this->local_methods_->add_named_object(no); -} - -// Look for a local method NAME, and returns its named object, or NULL -// if not there. - -Named_object* -Named_type::find_local_method(const std::string& name) const -{ - if (this->local_methods_ == NULL) - return NULL; - return this->local_methods_->lookup(name); -} - -// Return whether NAME is an unexported field or method, for better -// error reporting. - -bool -Named_type::is_unexported_local_method(Gogo* gogo, - const std::string& name) const -{ - Bindings* methods = this->local_methods_; - if (methods != NULL) - { - for (Bindings::const_declarations_iterator p = - methods->begin_declarations(); - p != methods->end_declarations(); - ++p) - { - if (Gogo::is_hidden_name(p->first) - && name == Gogo::unpack_hidden_name(p->first) - && gogo->pack_hidden_name(name, false) != p->first) - return true; - } - } - return false; -} - -// Build the complete list of methods for this type, which means -// recursively including all methods for anonymous fields. Create all -// stub methods. - -void -Named_type::finalize_methods(Gogo* gogo) -{ - if (this->all_methods_ != NULL) - return; - - if (this->local_methods_ != NULL - && (this->points_to() != NULL || this->interface_type() != NULL)) - { - const Bindings* lm = this->local_methods_; - for (Bindings::const_declarations_iterator p = lm->begin_declarations(); - p != lm->end_declarations(); - ++p) - error_at(p->second->location(), - "invalid pointer or interface receiver type"); - delete this->local_methods_; - this->local_methods_ = NULL; - return; - } - - Type::finalize_methods(gogo, this, this->location_, &this->all_methods_); -} - -// Return the method NAME, or NULL if there isn't one or if it is -// ambiguous. Set *IS_AMBIGUOUS if the method exists but is -// ambiguous. - -Method* -Named_type::method_function(const std::string& name, bool* is_ambiguous) const -{ - return Type::method_function(this->all_methods_, name, is_ambiguous); -} - -// Return a pointer to the interface method table for this type for -// the interface INTERFACE. IS_POINTER is true if this is for a -// pointer to THIS. - -tree -Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface, - bool is_pointer) -{ - go_assert(!interface->is_empty()); - - Interface_method_tables** pimt = (is_pointer - ? &this->interface_method_tables_ - : &this->pointer_interface_method_tables_); - - if (*pimt == NULL) - *pimt = new Interface_method_tables(5); - - std::pair val(interface, NULL_TREE); - std::pair ins = (*pimt)->insert(val); - - if (ins.second) - { - // This is a new entry in the hash table. - go_assert(ins.first->second == NULL_TREE); - ins.first->second = gogo->interface_method_table_for_type(interface, - this, - is_pointer); - } - - tree decl = ins.first->second; - if (decl == error_mark_node) - return error_mark_node; - go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL); - return build_fold_addr_expr(decl); -} - -// Return whether a named type has any hidden fields. - -bool -Named_type::named_type_has_hidden_fields(std::string* reason) const -{ - if (this->seen_ > 0) - return false; - ++this->seen_; - bool ret = this->type_->has_hidden_fields(this, reason); - --this->seen_; - return ret; -} - -// Look for a use of a complete type within another type. This is -// used to check that we don't try to use a type within itself. - -class Find_type_use : public Traverse -{ - public: - Find_type_use(Named_type* find_type) - : Traverse(traverse_types), - find_type_(find_type), found_(false) - { } - - // Whether we found the type. - bool - found() const - { return this->found_; } - - protected: - int - type(Type*); - - private: - // The type we are looking for. - Named_type* find_type_; - // Whether we found the type. - bool found_; -}; - -// Check for FIND_TYPE in TYPE. - -int -Find_type_use::type(Type* type) -{ - if (type->named_type() != NULL && this->find_type_ == type->named_type()) - { - this->found_ = true; - return TRAVERSE_EXIT; - } - - // It's OK if we see a reference to the type in any type which is - // essentially a pointer: a pointer, a slice, a function, a map, or - // a channel. - if (type->points_to() != NULL - || type->is_open_array_type() - || type->function_type() != NULL - || type->map_type() != NULL - || type->channel_type() != NULL) - return TRAVERSE_SKIP_COMPONENTS; - - // For an interface, a reference to the type in a method type should - // be ignored, but we have to consider direct inheritance. When - // this is called, there may be cases of direct inheritance - // represented as a method with no name. - if (type->interface_type() != NULL) - { - const Typed_identifier_list* methods = type->interface_type()->methods(); - if (methods != NULL) - { - for (Typed_identifier_list::const_iterator p = methods->begin(); - p != methods->end(); - ++p) - { - if (p->name().empty()) - { - if (Type::traverse(p->type(), this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - } - return TRAVERSE_SKIP_COMPONENTS; - } - - // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need - // to convert TYPE to the backend representation before we convert - // FIND_TYPE_. - if (type->named_type() != NULL) - { - switch (type->base()->classification()) - { - case Type::TYPE_ERROR: - case Type::TYPE_BOOLEAN: - case Type::TYPE_INTEGER: - case Type::TYPE_FLOAT: - case Type::TYPE_COMPLEX: - case Type::TYPE_STRING: - case Type::TYPE_NIL: - break; - - case Type::TYPE_ARRAY: - case Type::TYPE_STRUCT: - this->find_type_->add_dependency(type->named_type()); - break; - - case Type::TYPE_VOID: - case Type::TYPE_SINK: - case Type::TYPE_FUNCTION: - case Type::TYPE_POINTER: - case Type::TYPE_CALL_MULTIPLE_RESULT: - case Type::TYPE_MAP: - case Type::TYPE_CHANNEL: - case Type::TYPE_INTERFACE: - case Type::TYPE_NAMED: - case Type::TYPE_FORWARD: - default: - go_unreachable(); - } - } - - return TRAVERSE_CONTINUE; -} - -// Verify that a named type does not refer to itself. - -bool -Named_type::do_verify() -{ - Find_type_use find(this); - Type::traverse(this->type_, &find); - if (find.found()) - { - error_at(this->location_, "invalid recursive type %qs", - this->message_name().c_str()); - this->is_error_ = true; - return false; - } - - // Check whether any of the local methods overloads an existing - // struct field or interface method. We don't need to check the - // list of methods against itself: that is handled by the Bindings - // code. - if (this->local_methods_ != NULL) - { - Struct_type* st = this->type_->struct_type(); - bool found_dup = false; - if (st != NULL) - { - for (Bindings::const_declarations_iterator p = - this->local_methods_->begin_declarations(); - p != this->local_methods_->end_declarations(); - ++p) - { - const std::string& name(p->first); - if (st != NULL && st->find_local_field(name, NULL) != NULL) - { - error_at(p->second->location(), - "method %qs redeclares struct field name", - Gogo::message_name(name).c_str()); - found_dup = true; - } - } - } - if (found_dup) - return false; - } - - return true; -} - -// Return whether this type is or contains a pointer. - -bool -Named_type::do_has_pointer() const -{ - if (this->seen_ > 0) - return false; - ++this->seen_; - bool ret = this->type_->has_pointer(); - --this->seen_; - return ret; -} - -// Return a hash code. This is used for method lookup. We simply -// hash on the name itself. - -unsigned int -Named_type::do_hash_for_method(Gogo* gogo) const -{ - const std::string& name(this->named_object()->name()); - unsigned int ret = Type::hash_string(name, 0); - - // GOGO will be NULL here when called from Type_hash_identical. - // That is OK because that is only used for internal hash tables - // where we are going to be comparing named types for equality. In - // other cases, which are cases where the runtime is going to - // compare hash codes to see if the types are the same, we need to - // include the package prefix and name in the hash. - if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin()) - { - const Package* package = this->named_object()->package(); - if (package == NULL) - { - ret = Type::hash_string(gogo->unique_prefix(), ret); - ret = Type::hash_string(gogo->package_name(), ret); - } - else - { - ret = Type::hash_string(package->unique_prefix(), ret); - ret = Type::hash_string(package->name(), ret); - } - } - - return ret; -} - -// Convert a named type to the backend representation. In order to -// get dependencies right, we fill in a dummy structure for this type, -// then convert all the dependencies, then complete this type. When -// this function is complete, the size of the type is known. - -void -Named_type::convert(Gogo* gogo) -{ - if (this->is_error_ || this->is_converted_) - return; - - this->create_placeholder(gogo); - - // Convert all the dependencies. If they refer indirectly back to - // this type, they will pick up the intermediate tree we just - // created. - for (std::vector::const_iterator p = this->dependencies_.begin(); - p != this->dependencies_.end(); - ++p) - (*p)->convert(gogo); - - // Complete this type. - tree t = this->named_tree_; - Type* base = this->type_->base(); - switch (base->classification()) - { - case TYPE_VOID: - case TYPE_BOOLEAN: - case TYPE_INTEGER: - case TYPE_FLOAT: - case TYPE_COMPLEX: - case TYPE_STRING: - case TYPE_NIL: - break; - - case TYPE_MAP: - case TYPE_CHANNEL: - break; - - case TYPE_FUNCTION: - case TYPE_POINTER: - // The size of these types is already correct. - break; - - case TYPE_STRUCT: - t = base->struct_type()->fill_in_tree(gogo, t); - break; - - case TYPE_ARRAY: - if (!base->is_open_array_type()) - t = base->array_type()->fill_in_array_tree(gogo, t); - break; - - case TYPE_INTERFACE: - if (!base->interface_type()->is_empty()) - t = base->interface_type()->fill_in_tree(gogo, t); - break; - - case TYPE_ERROR: - return; - - default: - case TYPE_SINK: - case TYPE_CALL_MULTIPLE_RESULT: - case TYPE_NAMED: - case TYPE_FORWARD: - go_unreachable(); - } - - this->named_tree_ = t; - - if (t == error_mark_node) - this->is_error_ = true; - else - go_assert(TYPE_SIZE(t) != NULL_TREE); - - this->is_converted_ = true; -} - -// Create the placeholder for a named type. This is the first step in -// converting to the backend representation. - -void -Named_type::create_placeholder(Gogo* gogo) -{ - if (this->is_error_) - this->named_tree_ = error_mark_node; - - if (this->named_tree_ != NULL_TREE) - return; - - // Create the structure for this type. Note that because we call - // base() here, we don't attempt to represent a named type defined - // as another named type. Instead both named types will point to - // different base representations. - Type* base = this->type_->base(); - tree t; - switch (base->classification()) - { - case TYPE_ERROR: - this->is_error_ = true; - this->named_tree_ = error_mark_node; - return; - - case TYPE_VOID: - case TYPE_BOOLEAN: - case TYPE_INTEGER: - case TYPE_FLOAT: - case TYPE_COMPLEX: - case TYPE_STRING: - case TYPE_NIL: - // These are simple basic types, we can just create them - // directly. - t = Type::get_named_type_tree(gogo, base); - if (t == error_mark_node) - { - this->is_error_ = true; - this->named_tree_ = error_mark_node; - return; - } - t = build_variant_type_copy(t); - break; - - case TYPE_MAP: - case TYPE_CHANNEL: - // All maps and channels have the same type in GENERIC. - t = Type::get_named_type_tree(gogo, base); - if (t == error_mark_node) - { - this->is_error_ = true; - this->named_tree_ = error_mark_node; - return; - } - t = build_variant_type_copy(t); - break; - - case TYPE_FUNCTION: - case TYPE_POINTER: - t = build_variant_type_copy(ptr_type_node); - break; - - case TYPE_STRUCT: - t = make_node(RECORD_TYPE); - break; - - case TYPE_ARRAY: - if (base->is_open_array_type()) - t = gogo->slice_type_tree(void_type_node); - else - t = make_node(ARRAY_TYPE); - break; - - case TYPE_INTERFACE: - if (base->interface_type()->is_empty()) - { - t = Interface_type::empty_type_tree(gogo); - t = build_variant_type_copy(t); - } - else - { - source_location loc = base->interface_type()->location(); - t = Interface_type::non_empty_type_tree(loc); - } - break; - - default: - case TYPE_SINK: - case TYPE_CALL_MULTIPLE_RESULT: - case TYPE_NAMED: - case TYPE_FORWARD: - go_unreachable(); - } - - // Create the named type. - - tree id = this->named_object_->get_id(gogo); - tree decl = build_decl(this->location_, TYPE_DECL, id, t); - TYPE_NAME(t) = decl; - - this->named_tree_ = t; -} - -// Get a tree for a named type. - -tree -Named_type::do_get_tree(Gogo* gogo) -{ - if (this->is_error_) - return error_mark_node; - - tree t = this->named_tree_; - - // FIXME: GOGO can be NULL when called from go_type_for_size, which - // is only used for basic types. - if (gogo == NULL || !gogo->named_types_are_converted()) - { - // We have not completed converting named types. NAMED_TREE_ is - // a placeholder and we shouldn't do anything further. - if (t != NULL_TREE) - return t; - - // We don't build dependencies for types whose sizes do not - // change or are not relevant, so we may see them here while - // converting types. - this->create_placeholder(gogo); - t = this->named_tree_; - go_assert(t != NULL_TREE); - return t; - } - - // We are not converting types. This should only be called if the - // type has already been converted. - if (!this->is_converted_) - { - go_assert(saw_errors()); - return error_mark_node; - } - - go_assert(t != NULL_TREE && TYPE_SIZE(t) != NULL_TREE); - - // Complete the tree. - Type* base = this->type_->base(); - tree t1; - switch (base->classification()) - { - case TYPE_ERROR: - return error_mark_node; - - case TYPE_VOID: - case TYPE_BOOLEAN: - case TYPE_INTEGER: - case TYPE_FLOAT: - case TYPE_COMPLEX: - case TYPE_STRING: - case TYPE_NIL: - case TYPE_MAP: - case TYPE_CHANNEL: - case TYPE_STRUCT: - case TYPE_INTERFACE: - return t; - - case TYPE_FUNCTION: - // Don't build a circular data structure. GENERIC can't handle - // it. - if (this->seen_ > 0) - { - this->is_circular_ = true; - return ptr_type_node; - } - ++this->seen_; - t1 = Type::get_named_type_tree(gogo, base); - --this->seen_; - if (t1 == error_mark_node) - return error_mark_node; - if (this->is_circular_) - t1 = ptr_type_node; - go_assert(t != NULL_TREE && TREE_CODE(t) == POINTER_TYPE); - go_assert(TREE_CODE(t1) == POINTER_TYPE); - TREE_TYPE(t) = TREE_TYPE(t1); - return t; - - case TYPE_POINTER: - // Don't build a circular data structure. GENERIC can't handle - // it. - if (this->seen_ > 0) - { - this->is_circular_ = true; - return ptr_type_node; - } - ++this->seen_; - t1 = Type::get_named_type_tree(gogo, base); - --this->seen_; - if (t1 == error_mark_node) - return error_mark_node; - if (this->is_circular_) - t1 = ptr_type_node; - go_assert(t != NULL_TREE && TREE_CODE(t) == POINTER_TYPE); - go_assert(TREE_CODE(t1) == POINTER_TYPE); - TREE_TYPE(t) = TREE_TYPE(t1); - return t; - - case TYPE_ARRAY: - if (base->is_open_array_type()) - { - if (this->seen_ > 0) - return t; - else - { - ++this->seen_; - t = base->array_type()->fill_in_slice_tree(gogo, t); - --this->seen_; - } - } - return t; - - default: - case TYPE_SINK: - case TYPE_CALL_MULTIPLE_RESULT: - case TYPE_NAMED: - case TYPE_FORWARD: - go_unreachable(); - } - - go_unreachable(); -} - -// Build a type descriptor for a named type. - -Expression* -Named_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - // If NAME is not NULL, then we don't really want the type - // descriptor for this type; we want the descriptor for the - // underlying type, giving it the name NAME. - return this->named_type_descriptor(gogo, this->type_, - name == NULL ? this : name); -} - -// Add to the reflection string. This is used mostly for the name of -// the type used in a type descriptor, not for actual reflection -// strings. - -void -Named_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - if (this->location() != BUILTINS_LOCATION) - { - const Package* package = this->named_object_->package(); - if (package != NULL) - ret->append(package->name()); - else - ret->append(gogo->package_name()); - ret->push_back('.'); - } - if (this->in_function_ != NULL) - { - ret->append(Gogo::unpack_hidden_name(this->in_function_->name())); - ret->push_back('$'); - } - ret->append(Gogo::unpack_hidden_name(this->named_object_->name())); -} - -// Get the mangled name. - -void -Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - Named_object* no = this->named_object_; - std::string name; - if (this->location() == BUILTINS_LOCATION) - go_assert(this->in_function_ == NULL); - else - { - const std::string& unique_prefix(no->package() == NULL - ? gogo->unique_prefix() - : no->package()->unique_prefix()); - const std::string& package_name(no->package() == NULL - ? gogo->package_name() - : no->package()->name()); - name = unique_prefix; - name.append(1, '.'); - name.append(package_name); - name.append(1, '.'); - if (this->in_function_ != NULL) - { - name.append(Gogo::unpack_hidden_name(this->in_function_->name())); - name.append(1, '$'); - } - } - name.append(Gogo::unpack_hidden_name(no->name())); - char buf[20]; - snprintf(buf, sizeof buf, "N%u_", static_cast(name.length())); - ret->append(buf); - ret->append(name); -} - -// Export the type. This is called to export a global type. - -void -Named_type::export_named_type(Export* exp, const std::string&) const -{ - // We don't need to write the name of the type here, because it will - // be written by Export::write_type anyhow. - exp->write_c_string("type "); - exp->write_type(this); - exp->write_c_string(";\n"); -} - -// Import a named type. - -void -Named_type::import_named_type(Import* imp, Named_type** ptype) -{ - imp->require_c_string("type "); - Type *type = imp->read_type(); - *ptype = type->named_type(); - go_assert(*ptype != NULL); - imp->require_c_string(";\n"); -} - -// Export the type when it is referenced by another type. In this -// case Export::export_type will already have issued the name. - -void -Named_type::do_export(Export* exp) const -{ - exp->write_type(this->type_); - - // To save space, we only export the methods directly attached to - // this type. - Bindings* methods = this->local_methods_; - if (methods == NULL) - return; - - exp->write_c_string("\n"); - for (Bindings::const_definitions_iterator p = methods->begin_definitions(); - p != methods->end_definitions(); - ++p) - { - exp->write_c_string(" "); - (*p)->export_named_object(exp); - } - - for (Bindings::const_declarations_iterator p = methods->begin_declarations(); - p != methods->end_declarations(); - ++p) - { - if (p->second->is_function_declaration()) - { - exp->write_c_string(" "); - p->second->export_named_object(exp); - } - } -} - -// Make a named type. - -Named_type* -Type::make_named_type(Named_object* named_object, Type* type, - source_location location) -{ - return new Named_type(named_object, type, location); -} - -// Finalize the methods for TYPE. It will be a named type or a struct -// type. This sets *ALL_METHODS to the list of methods, and builds -// all required stubs. - -void -Type::finalize_methods(Gogo* gogo, const Type* type, source_location location, - Methods** all_methods) -{ - *all_methods = NULL; - Types_seen types_seen; - Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen, - all_methods); - Type::build_stub_methods(gogo, type, *all_methods, location); -} - -// Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to -// build up the struct field indexes as we go. DEPTH is the depth of -// the field within TYPE. IS_EMBEDDED_POINTER is true if we are -// adding these methods for an anonymous field with pointer type. -// NEEDS_STUB_METHOD is true if we need to use a stub method which -// calls the real method. TYPES_SEEN is used to avoid infinite -// recursion. - -void -Type::add_methods_for_type(const Type* type, - const Method::Field_indexes* field_indexes, - unsigned int depth, - bool is_embedded_pointer, - bool needs_stub_method, - Types_seen* types_seen, - Methods** methods) -{ - // Pointer types may not have methods. - if (type->points_to() != NULL) - return; - - const Named_type* nt = type->named_type(); - if (nt != NULL) - { - std::pair ins = types_seen->insert(nt); - if (!ins.second) - return; - } - - if (nt != NULL) - Type::add_local_methods_for_type(nt, field_indexes, depth, - is_embedded_pointer, needs_stub_method, - methods); - - Type::add_embedded_methods_for_type(type, field_indexes, depth, - is_embedded_pointer, needs_stub_method, - types_seen, methods); - - // If we are called with depth > 0, then we are looking at an - // anonymous field of a struct. If such a field has interface type, - // then we need to add the interface methods. We don't want to add - // them when depth == 0, because we will already handle them - // following the usual rules for an interface type. - if (depth > 0) - Type::add_interface_methods_for_type(type, field_indexes, depth, methods); -} - -// Add the local methods for the named type NT to *METHODS. The -// parameters are as for add_methods_to_type. - -void -Type::add_local_methods_for_type(const Named_type* nt, - const Method::Field_indexes* field_indexes, - unsigned int depth, - bool is_embedded_pointer, - bool needs_stub_method, - Methods** methods) -{ - const Bindings* local_methods = nt->local_methods(); - if (local_methods == NULL) - return; - - if (*methods == NULL) - *methods = new Methods(); - - for (Bindings::const_declarations_iterator p = - local_methods->begin_declarations(); - p != local_methods->end_declarations(); - ++p) - { - Named_object* no = p->second; - bool is_value_method = (is_embedded_pointer - || !Type::method_expects_pointer(no)); - Method* m = new Named_method(no, field_indexes, depth, is_value_method, - (needs_stub_method - || (depth > 0 && is_value_method))); - if (!(*methods)->insert(no->name(), m)) - delete m; - } -} - -// Add the embedded methods for TYPE to *METHODS. These are the -// methods attached to anonymous fields. The parameters are as for -// add_methods_to_type. - -void -Type::add_embedded_methods_for_type(const Type* type, - const Method::Field_indexes* field_indexes, - unsigned int depth, - bool is_embedded_pointer, - bool needs_stub_method, - Types_seen* types_seen, - Methods** methods) -{ - // Look for anonymous fields in TYPE. TYPE has fields if it is a - // struct. - const Struct_type* st = type->struct_type(); - if (st == NULL) - return; - - const Struct_field_list* fields = st->fields(); - if (fields == NULL) - return; - - unsigned int i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++i) - { - if (!pf->is_anonymous()) - continue; - - Type* ftype = pf->type(); - bool is_pointer = false; - if (ftype->points_to() != NULL) - { - ftype = ftype->points_to(); - is_pointer = true; - } - Named_type* fnt = ftype->named_type(); - if (fnt == NULL) - { - // This is an error, but it will be diagnosed elsewhere. - continue; - } - - Method::Field_indexes* sub_field_indexes = new Method::Field_indexes(); - sub_field_indexes->next = field_indexes; - sub_field_indexes->field_index = i; - - Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1, - (is_embedded_pointer || is_pointer), - (needs_stub_method - || is_pointer - || i > 0), - types_seen, - methods); - } -} - -// If TYPE is an interface type, then add its method to *METHODS. -// This is for interface methods attached to an anonymous field. The -// parameters are as for add_methods_for_type. - -void -Type::add_interface_methods_for_type(const Type* type, - const Method::Field_indexes* field_indexes, - unsigned int depth, - Methods** methods) -{ - const Interface_type* it = type->interface_type(); - if (it == NULL) - return; - - const Typed_identifier_list* imethods = it->methods(); - if (imethods == NULL) - return; - - if (*methods == NULL) - *methods = new Methods(); - - for (Typed_identifier_list::const_iterator pm = imethods->begin(); - pm != imethods->end(); - ++pm) - { - Function_type* fntype = pm->type()->function_type(); - if (fntype == NULL) - { - // This is an error, but it should be reported elsewhere - // when we look at the methods for IT. - continue; - } - go_assert(!fntype->is_method()); - fntype = fntype->copy_with_receiver(const_cast(type)); - Method* m = new Interface_method(pm->name(), pm->location(), fntype, - field_indexes, depth); - if (!(*methods)->insert(pm->name(), m)) - delete m; - } -} - -// Build stub methods for TYPE as needed. METHODS is the set of -// methods for the type. A stub method may be needed when a type -// inherits a method from an anonymous field. When we need the -// address of the method, as in a type descriptor, we need to build a -// little stub which does the required field dereferences and jumps to -// the real method. LOCATION is the location of the type definition. - -void -Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods, - source_location location) -{ - if (methods == NULL) - return; - for (Methods::const_iterator p = methods->begin(); - p != methods->end(); - ++p) - { - Method* m = p->second; - if (m->is_ambiguous() || !m->needs_stub_method()) - continue; - - const std::string& name(p->first); - - // Build a stub method. - - const Function_type* fntype = m->type(); - - static unsigned int counter; - char buf[100]; - snprintf(buf, sizeof buf, "$this%u", counter); - ++counter; - - Type* receiver_type = const_cast(type); - if (!m->is_value_method()) - receiver_type = Type::make_pointer_type(receiver_type); - source_location receiver_location = m->receiver_location(); - Typed_identifier* receiver = new Typed_identifier(buf, receiver_type, - receiver_location); - - const Typed_identifier_list* fnparams = fntype->parameters(); - Typed_identifier_list* stub_params; - if (fnparams == NULL || fnparams->empty()) - stub_params = NULL; - else - { - // We give each stub parameter a unique name. - stub_params = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator pp = fnparams->begin(); - pp != fnparams->end(); - ++pp) - { - char pbuf[100]; - snprintf(pbuf, sizeof pbuf, "$p%u", counter); - stub_params->push_back(Typed_identifier(pbuf, pp->type(), - pp->location())); - ++counter; - } - } - - const Typed_identifier_list* fnresults = fntype->results(); - Typed_identifier_list* stub_results; - if (fnresults == NULL || fnresults->empty()) - stub_results = NULL; - else - { - // We create the result parameters without any names, since - // we won't refer to them. - stub_results = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator pr = fnresults->begin(); - pr != fnresults->end(); - ++pr) - stub_results->push_back(Typed_identifier("", pr->type(), - pr->location())); - } - - Function_type* stub_type = Type::make_function_type(receiver, - stub_params, - stub_results, - fntype->location()); - if (fntype->is_varargs()) - stub_type->set_is_varargs(); - - // We only create the function in the package which creates the - // type. - const Package* package; - if (type->named_type() == NULL) - package = NULL; - else - package = type->named_type()->named_object()->package(); - Named_object* stub; - if (package != NULL) - stub = Named_object::make_function_declaration(name, package, - stub_type, location); - else - { - stub = gogo->start_function(name, stub_type, false, - fntype->location()); - Type::build_one_stub_method(gogo, m, buf, stub_params, - fntype->is_varargs(), location); - gogo->finish_function(fntype->location()); - } - - m->set_stub_object(stub); - } -} - -// Build a stub method which adjusts the receiver as required to call -// METHOD. RECEIVER_NAME is the name we used for the receiver. -// PARAMS is the list of function parameters. - -void -Type::build_one_stub_method(Gogo* gogo, Method* method, - const char* receiver_name, - const Typed_identifier_list* params, - bool is_varargs, - source_location location) -{ - Named_object* receiver_object = gogo->lookup(receiver_name, NULL); - go_assert(receiver_object != NULL); - - Expression* expr = Expression::make_var_reference(receiver_object, location); - expr = Type::apply_field_indexes(expr, method->field_indexes(), location); - if (expr->type()->points_to() == NULL) - expr = Expression::make_unary(OPERATOR_AND, expr, location); - - Expression_list* arguments; - if (params == NULL || params->empty()) - arguments = NULL; - else - { - arguments = new Expression_list(); - for (Typed_identifier_list::const_iterator p = params->begin(); - p != params->end(); - ++p) - { - Named_object* param = gogo->lookup(p->name(), NULL); - go_assert(param != NULL); - Expression* param_ref = Expression::make_var_reference(param, - location); - arguments->push_back(param_ref); - } - } - - Expression* func = method->bind_method(expr, location); - go_assert(func != NULL); - Call_expression* call = Expression::make_call(func, arguments, is_varargs, - location); - size_t count = call->result_count(); - if (count == 0) - gogo->add_statement(Statement::make_statement(call)); - else - { - Expression_list* retvals = new Expression_list(); - if (count <= 1) - retvals->push_back(call); - else - { - for (size_t i = 0; i < count; ++i) - retvals->push_back(Expression::make_call_result(call, i)); - } - Statement* retstat = Statement::make_return_statement(retvals, location); - gogo->add_statement(retstat); - } -} - -// Apply FIELD_INDEXES to EXPR. The field indexes have to be applied -// in reverse order. - -Expression* -Type::apply_field_indexes(Expression* expr, - const Method::Field_indexes* field_indexes, - source_location location) -{ - if (field_indexes == NULL) - return expr; - expr = Type::apply_field_indexes(expr, field_indexes->next, location); - Struct_type* stype = expr->type()->deref()->struct_type(); - go_assert(stype != NULL - && field_indexes->field_index < stype->field_count()); - if (expr->type()->struct_type() == NULL) - { - go_assert(expr->type()->points_to() != NULL); - expr = Expression::make_unary(OPERATOR_MULT, expr, location); - go_assert(expr->type()->struct_type() == stype); - } - return Expression::make_field_reference(expr, field_indexes->field_index, - location); -} - -// Return whether NO is a method for which the receiver is a pointer. - -bool -Type::method_expects_pointer(const Named_object* no) -{ - const Function_type *fntype; - if (no->is_function()) - fntype = no->func_value()->type(); - else if (no->is_function_declaration()) - fntype = no->func_declaration_value()->type(); - else - go_unreachable(); - return fntype->receiver()->type()->points_to() != NULL; -} - -// Given a set of methods for a type, METHODS, return the method NAME, -// or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS -// is not NULL, then set *IS_AMBIGUOUS to true if the method exists -// but is ambiguous (and return NULL). - -Method* -Type::method_function(const Methods* methods, const std::string& name, - bool* is_ambiguous) -{ - if (is_ambiguous != NULL) - *is_ambiguous = false; - if (methods == NULL) - return NULL; - Methods::const_iterator p = methods->find(name); - if (p == methods->end()) - return NULL; - Method* m = p->second; - if (m->is_ambiguous()) - { - if (is_ambiguous != NULL) - *is_ambiguous = true; - return NULL; - } - return m; -} - -// Look for field or method NAME for TYPE. Return an Expression for -// the field or method bound to EXPR. If there is no such field or -// method, give an appropriate error and return an error expression. - -Expression* -Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr, - const std::string& name, - source_location location) -{ - if (type->deref()->is_error_type()) - return Expression::make_error(location); - - const Named_type* nt = type->deref()->named_type(); - const Struct_type* st = type->deref()->struct_type(); - const Interface_type* it = type->interface_type(); - - // If this is a pointer to a pointer, then it is possible that the - // pointed-to type has methods. - if (nt == NULL - && st == NULL - && it == NULL - && type->points_to() != NULL - && type->points_to()->points_to() != NULL) - { - expr = Expression::make_unary(OPERATOR_MULT, expr, location); - type = type->points_to(); - if (type->deref()->is_error_type()) - return Expression::make_error(location); - nt = type->points_to()->named_type(); - st = type->points_to()->struct_type(); - } - - bool receiver_can_be_pointer = (expr->type()->points_to() != NULL - || expr->is_addressable()); - std::vector seen; - bool is_method = false; - bool found_pointer_method = false; - std::string ambig1; - std::string ambig2; - if (Type::find_field_or_method(type, name, receiver_can_be_pointer, - &seen, NULL, &is_method, - &found_pointer_method, &ambig1, &ambig2)) - { - Expression* ret; - if (!is_method) - { - go_assert(st != NULL); - if (type->struct_type() == NULL) - { - go_assert(type->points_to() != NULL); - expr = Expression::make_unary(OPERATOR_MULT, expr, - location); - go_assert(expr->type()->struct_type() == st); - } - ret = st->field_reference(expr, name, location); - } - else if (it != NULL && it->find_method(name) != NULL) - ret = Expression::make_interface_field_reference(expr, name, - location); - else - { - Method* m; - if (nt != NULL) - m = nt->method_function(name, NULL); - else if (st != NULL) - m = st->method_function(name, NULL); - else - go_unreachable(); - go_assert(m != NULL); - if (!m->is_value_method() && expr->type()->points_to() == NULL) - expr = Expression::make_unary(OPERATOR_AND, expr, location); - ret = m->bind_method(expr, location); - } - go_assert(ret != NULL); - return ret; - } - else - { - if (!ambig1.empty()) - error_at(location, "%qs is ambiguous via %qs and %qs", - Gogo::message_name(name).c_str(), - Gogo::message_name(ambig1).c_str(), - Gogo::message_name(ambig2).c_str()); - else if (found_pointer_method) - error_at(location, "method requires a pointer"); - else if (nt == NULL && st == NULL && it == NULL) - error_at(location, - ("reference to field %qs in object which " - "has no fields or methods"), - Gogo::message_name(name).c_str()); - else - { - bool is_unexported; - if (!Gogo::is_hidden_name(name)) - is_unexported = false; - else - { - std::string unpacked = Gogo::unpack_hidden_name(name); - seen.clear(); - is_unexported = Type::is_unexported_field_or_method(gogo, type, - unpacked, - &seen); - } - if (is_unexported) - error_at(location, "reference to unexported field or method %qs", - Gogo::message_name(name).c_str()); - else - error_at(location, "reference to undefined field or method %qs", - Gogo::message_name(name).c_str()); - } - return Expression::make_error(location); - } -} - -// Look in TYPE for a field or method named NAME, return true if one -// is found. This looks through embedded anonymous fields and handles -// ambiguity. If a method is found, sets *IS_METHOD to true; -// otherwise, if a field is found, set it to false. If -// RECEIVER_CAN_BE_POINTER is false, then the receiver is a value -// whose address can not be taken. SEEN is used to avoid infinite -// recursion on invalid types. - -// When returning false, this sets *FOUND_POINTER_METHOD if we found a -// method we couldn't use because it requires a pointer. LEVEL is -// used for recursive calls, and can be NULL for a non-recursive call. -// When this function returns false because it finds that the name is -// ambiguous, it will store a path to the ambiguous names in *AMBIG1 -// and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2 -// will be unchanged. - -// This function just returns whether or not there is a field or -// method, and whether it is a field or method. It doesn't build an -// expression to refer to it. If it is a method, we then look in the -// list of all methods for the type. If it is a field, the search has -// to be done again, looking only for fields, and building up the -// expression as we go. - -bool -Type::find_field_or_method(const Type* type, - const std::string& name, - bool receiver_can_be_pointer, - std::vector* seen, - int* level, - bool* is_method, - bool* found_pointer_method, - std::string* ambig1, - std::string* ambig2) -{ - // Named types can have locally defined methods. - const Named_type* nt = type->named_type(); - if (nt == NULL && type->points_to() != NULL) - nt = type->points_to()->named_type(); - if (nt != NULL) - { - Named_object* no = nt->find_local_method(name); - if (no != NULL) - { - if (receiver_can_be_pointer || !Type::method_expects_pointer(no)) - { - *is_method = true; - return true; - } - - // Record that we have found a pointer method in order to - // give a better error message if we don't find anything - // else. - *found_pointer_method = true; - } - - for (std::vector::const_iterator p = seen->begin(); - p != seen->end(); - ++p) - { - if (*p == nt) - { - // We've already seen this type when searching for methods. - return false; - } - } - } - - // Interface types can have methods. - const Interface_type* it = type->interface_type(); - if (it != NULL && it->find_method(name) != NULL) - { - *is_method = true; - return true; - } - - // Struct types can have fields. They can also inherit fields and - // methods from anonymous fields. - const Struct_type* st = type->deref()->struct_type(); - if (st == NULL) - return false; - const Struct_field_list* fields = st->fields(); - if (fields == NULL) - return false; - - if (nt != NULL) - seen->push_back(nt); - - int found_level = 0; - bool found_is_method = false; - std::string found_ambig1; - std::string found_ambig2; - const Struct_field* found_parent = NULL; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - if (pf->field_name() == name) - { - *is_method = false; - if (nt != NULL) - seen->pop_back(); - return true; - } - - if (!pf->is_anonymous()) - continue; - - if (pf->type()->deref()->is_error_type() - || pf->type()->deref()->is_undefined()) - continue; - - Named_type* fnt = pf->type()->named_type(); - if (fnt == NULL) - fnt = pf->type()->deref()->named_type(); - go_assert(fnt != NULL); - - int sublevel = level == NULL ? 1 : *level + 1; - bool sub_is_method; - std::string subambig1; - std::string subambig2; - bool subfound = Type::find_field_or_method(fnt, - name, - receiver_can_be_pointer, - seen, - &sublevel, - &sub_is_method, - found_pointer_method, - &subambig1, - &subambig2); - if (!subfound) - { - if (!subambig1.empty()) - { - // The name was found via this field, but is ambiguous. - // if the ambiguity is lower or at the same level as - // anything else we have already found, then we want to - // pass the ambiguity back to the caller. - if (found_level == 0 || sublevel <= found_level) - { - found_ambig1 = pf->field_name() + '.' + subambig1; - found_ambig2 = pf->field_name() + '.' + subambig2; - found_level = sublevel; - } - } - } - else - { - // The name was found via this field. Use the level to see - // if we want to use this one, or whether it introduces an - // ambiguity. - if (found_level == 0 || sublevel < found_level) - { - found_level = sublevel; - found_is_method = sub_is_method; - found_ambig1.clear(); - found_ambig2.clear(); - found_parent = &*pf; - } - else if (sublevel > found_level) - ; - else if (found_ambig1.empty()) - { - // We found an ambiguity. - go_assert(found_parent != NULL); - found_ambig1 = found_parent->field_name(); - found_ambig2 = pf->field_name(); - } - else - { - // We found an ambiguity, but we already know of one. - // Just report the earlier one. - } - } - } - - // Here if we didn't find anything FOUND_LEVEL is 0. If we found - // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and - // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL - // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty. - - if (nt != NULL) - seen->pop_back(); - - if (found_level == 0) - return false; - else if (!found_ambig1.empty()) - { - go_assert(!found_ambig1.empty()); - ambig1->assign(found_ambig1); - ambig2->assign(found_ambig2); - if (level != NULL) - *level = found_level; - return false; - } - else - { - if (level != NULL) - *level = found_level; - *is_method = found_is_method; - return true; - } -} - -// Return whether NAME is an unexported field or method for TYPE. - -bool -Type::is_unexported_field_or_method(Gogo* gogo, const Type* type, - const std::string& name, - std::vector* seen) -{ - const Named_type* nt = type->named_type(); - if (nt == NULL) - nt = type->deref()->named_type(); - if (nt != NULL) - { - if (nt->is_unexported_local_method(gogo, name)) - return true; - - for (std::vector::const_iterator p = seen->begin(); - p != seen->end(); - ++p) - { - if (*p == nt) - { - // We've already seen this type. - return false; - } - } - } - - const Interface_type* it = type->interface_type(); - if (it != NULL && it->is_unexported_method(gogo, name)) - return true; - - type = type->deref(); - - const Struct_type* st = type->struct_type(); - if (st != NULL && st->is_unexported_local_field(gogo, name)) - return true; - - if (st == NULL) - return false; - - const Struct_field_list* fields = st->fields(); - if (fields == NULL) - return false; - - if (nt != NULL) - seen->push_back(nt); - - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - if (pf->is_anonymous() - && !pf->type()->deref()->is_error_type() - && !pf->type()->deref()->is_undefined()) - { - Named_type* subtype = pf->type()->named_type(); - if (subtype == NULL) - subtype = pf->type()->deref()->named_type(); - if (subtype == NULL) - { - // This is an error, but it will be diagnosed elsewhere. - continue; - } - if (Type::is_unexported_field_or_method(gogo, subtype, name, seen)) - { - if (nt != NULL) - seen->pop_back(); - return true; - } - } - } - - if (nt != NULL) - seen->pop_back(); - - return false; -} - -// Class Forward_declaration. - -Forward_declaration_type::Forward_declaration_type(Named_object* named_object) - : Type(TYPE_FORWARD), - named_object_(named_object->resolve()), warned_(false) -{ - go_assert(this->named_object_->is_unknown() - || this->named_object_->is_type_declaration()); -} - -// Return the named object. - -Named_object* -Forward_declaration_type::named_object() -{ - return this->named_object_->resolve(); -} - -const Named_object* -Forward_declaration_type::named_object() const -{ - return this->named_object_->resolve(); -} - -// Return the name of the forward declared type. - -const std::string& -Forward_declaration_type::name() const -{ - return this->named_object()->name(); -} - -// Warn about a use of a type which has been declared but not defined. - -void -Forward_declaration_type::warn() const -{ - Named_object* no = this->named_object_->resolve(); - if (no->is_unknown()) - { - // The name was not defined anywhere. - if (!this->warned_) - { - error_at(this->named_object_->location(), - "use of undefined type %qs", - no->message_name().c_str()); - this->warned_ = true; - } - } - else if (no->is_type_declaration()) - { - // The name was seen as a type, but the type was never defined. - if (no->type_declaration_value()->using_type()) - { - error_at(this->named_object_->location(), - "use of undefined type %qs", - no->message_name().c_str()); - this->warned_ = true; - } - } - else - { - // The name was defined, but not as a type. - if (!this->warned_) - { - error_at(this->named_object_->location(), "expected type"); - this->warned_ = true; - } - } -} - -// Get the base type of a declaration. This gives an error if the -// type has not yet been defined. - -Type* -Forward_declaration_type::real_type() -{ - if (this->is_defined()) - return this->named_object()->type_value(); - else - { - this->warn(); - return Type::make_error_type(); - } -} - -const Type* -Forward_declaration_type::real_type() const -{ - if (this->is_defined()) - return this->named_object()->type_value(); - else - { - this->warn(); - return Type::make_error_type(); - } -} - -// Return whether the base type is defined. - -bool -Forward_declaration_type::is_defined() const -{ - return this->named_object()->is_type(); -} - -// Add a method. This is used when methods are defined before the -// type. - -Named_object* -Forward_declaration_type::add_method(const std::string& name, - Function* function) -{ - Named_object* no = this->named_object(); - if (no->is_unknown()) - no->declare_as_type(); - return no->type_declaration_value()->add_method(name, function); -} - -// Add a method declaration. This is used when methods are declared -// before the type. - -Named_object* -Forward_declaration_type::add_method_declaration(const std::string& name, - Function_type* type, - source_location location) -{ - Named_object* no = this->named_object(); - if (no->is_unknown()) - no->declare_as_type(); - Type_declaration* td = no->type_declaration_value(); - return td->add_method_declaration(name, type, location); -} - -// Traversal. - -int -Forward_declaration_type::do_traverse(Traverse* traverse) -{ - if (this->is_defined() - && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Get a tree for the type. - -tree -Forward_declaration_type::do_get_tree(Gogo* gogo) -{ - if (this->is_defined()) - return Type::get_named_type_tree(gogo, this->real_type()); - - if (this->warned_) - return error_mark_node; - - // We represent an undefined type as a struct with no fields. That - // should work fine for the middle-end, since the same case can - // arise in C. - Named_object* no = this->named_object(); - tree type_tree = make_node(RECORD_TYPE); - tree id = no->get_id(gogo); - tree decl = build_decl(no->location(), TYPE_DECL, id, type_tree); - TYPE_NAME(type_tree) = decl; - layout_type(type_tree); - return type_tree; -} - -// Build a type descriptor for a forwarded type. - -Expression* -Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (!this->is_defined()) - return Expression::make_nil(BUILTINS_LOCATION); - else - { - Type* t = this->real_type(); - if (name != NULL) - return this->named_type_descriptor(gogo, t, name); - else - return Expression::make_type_descriptor(t, BUILTINS_LOCATION); - } -} - -// The reflection string. - -void -Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - this->append_reflection(this->real_type(), gogo, ret); -} - -// The mangled name. - -void -Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - if (this->is_defined()) - this->append_mangled_name(this->real_type(), gogo, ret); - else - { - const Named_object* no = this->named_object(); - std::string name; - if (no->package() == NULL) - name = gogo->package_name(); - else - name = no->package()->name(); - name += '.'; - name += Gogo::unpack_hidden_name(no->name()); - char buf[20]; - snprintf(buf, sizeof buf, "N%u_", - static_cast(name.length())); - ret->append(buf); - ret->append(name); - } -} - -// Export a forward declaration. This can happen when a defined type -// refers to a type which is only declared (and is presumably defined -// in some other file in the same package). - -void -Forward_declaration_type::do_export(Export*) const -{ - // If there is a base type, that should be exported instead of this. - go_assert(!this->is_defined()); - - // We don't output anything. -} - -// Make a forward declaration. - -Type* -Type::make_forward_declaration(Named_object* named_object) -{ - return new Forward_declaration_type(named_object); -} - -// Class Typed_identifier_list. - -// Sort the entries by name. - -struct Typed_identifier_list_sort -{ - public: - bool - operator()(const Typed_identifier& t1, const Typed_identifier& t2) const - { return t1.name() < t2.name(); } -}; - -void -Typed_identifier_list::sort_by_name() -{ - std::sort(this->entries_.begin(), this->entries_.end(), - Typed_identifier_list_sort()); -} - -// Traverse types. - -int -Typed_identifier_list::traverse(Traverse* traverse) -{ - for (Typed_identifier_list::const_iterator p = this->begin(); - p != this->end(); - ++p) - { - if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Copy the list. - -Typed_identifier_list* -Typed_identifier_list::copy() const -{ - Typed_identifier_list* ret = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator p = this->begin(); - p != this->end(); - ++p) - ret->push_back(Typed_identifier(p->name(), p->type(), p->location())); - return ret; -} diff --git a/gcc/go/gofrontend/types.cc.working b/gcc/go/gofrontend/types.cc.working deleted file mode 100644 index 2eecafd89d6..00000000000 --- a/gcc/go/gofrontend/types.cc.working +++ /dev/null @@ -1,8656 +0,0 @@ -// types.cc -- Go frontend types. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include - -#ifndef ENABLE_BUILD_WITH_CXX -extern "C" -{ -#endif - -#include "toplev.h" -#include "intl.h" -#include "tree.h" -#include "gimple.h" -#include "real.h" -#include "convert.h" - -#ifndef ENABLE_BUILD_WITH_CXX -} -#endif - -#include "go-c.h" -#include "gogo.h" -#include "operator.h" -#include "expressions.h" -#include "statements.h" -#include "export.h" -#include "import.h" -#include "types.h" - -// Class Type. - -Type::Type(Type_classification classification) - : classification_(classification), tree_(NULL_TREE), - type_descriptor_decl_(NULL_TREE) -{ -} - -Type::~Type() -{ -} - -// Get the base type for a type--skip names and forward declarations. - -Type* -Type::base() -{ - switch (this->classification_) - { - case TYPE_NAMED: - return this->named_type()->named_base(); - case TYPE_FORWARD: - return this->forward_declaration_type()->real_type()->base(); - default: - return this; - } -} - -const Type* -Type::base() const -{ - switch (this->classification_) - { - case TYPE_NAMED: - return this->named_type()->named_base(); - case TYPE_FORWARD: - return this->forward_declaration_type()->real_type()->base(); - default: - return this; - } -} - -// Skip defined forward declarations. - -Type* -Type::forwarded() -{ - Type* t = this; - Forward_declaration_type* ftype = t->forward_declaration_type(); - while (ftype != NULL && ftype->is_defined()) - { - t = ftype->real_type(); - ftype = t->forward_declaration_type(); - } - return t; -} - -const Type* -Type::forwarded() const -{ - const Type* t = this; - const Forward_declaration_type* ftype = t->forward_declaration_type(); - while (ftype != NULL && ftype->is_defined()) - { - t = ftype->real_type(); - ftype = t->forward_declaration_type(); - } - return t; -} - -// If this is a named type, return it. Otherwise, return NULL. - -Named_type* -Type::named_type() -{ - return this->forwarded()->convert_no_base(); -} - -const Named_type* -Type::named_type() const -{ - return this->forwarded()->convert_no_base(); -} - -// Return true if this type is not defined. - -bool -Type::is_undefined() const -{ - return this->forwarded()->forward_declaration_type() != NULL; -} - -// Return true if this is a basic type: a type which is not composed -// of other types, and is not void. - -bool -Type::is_basic_type() const -{ - switch (this->classification_) - { - case TYPE_INTEGER: - case TYPE_FLOAT: - case TYPE_COMPLEX: - case TYPE_BOOLEAN: - case TYPE_STRING: - case TYPE_NIL: - return true; - - case TYPE_ERROR: - case TYPE_VOID: - case TYPE_FUNCTION: - case TYPE_POINTER: - case TYPE_STRUCT: - case TYPE_ARRAY: - case TYPE_MAP: - case TYPE_CHANNEL: - case TYPE_INTERFACE: - return false; - - case TYPE_NAMED: - case TYPE_FORWARD: - return this->base()->is_basic_type(); - - default: - gcc_unreachable(); - } -} - -// Return true if this is an abstract type. - -bool -Type::is_abstract() const -{ - switch (this->classification()) - { - case TYPE_INTEGER: - return this->integer_type()->is_abstract(); - case TYPE_FLOAT: - return this->float_type()->is_abstract(); - case TYPE_COMPLEX: - return this->complex_type()->is_abstract(); - case TYPE_STRING: - return this->is_abstract_string_type(); - case TYPE_BOOLEAN: - return this->is_abstract_boolean_type(); - default: - return false; - } -} - -// Return a non-abstract version of an abstract type. - -Type* -Type::make_non_abstract_type() -{ - gcc_assert(this->is_abstract()); - switch (this->classification()) - { - case TYPE_INTEGER: - return Type::lookup_integer_type("int"); - case TYPE_FLOAT: - return Type::lookup_float_type("float64"); - case TYPE_COMPLEX: - return Type::lookup_complex_type("complex128"); - case TYPE_STRING: - return Type::lookup_string_type(); - case TYPE_BOOLEAN: - return Type::lookup_bool_type(); - default: - gcc_unreachable(); - } -} - -// Return true if this is an error type. Don't give an error if we -// try to dereference an undefined forwarding type, as this is called -// in the parser when the type may legitimately be undefined. - -bool -Type::is_error_type() const -{ - const Type* t = this->forwarded(); - // Note that we return false for an undefined forward type. - switch (t->classification_) - { - case TYPE_ERROR: - return true; - case TYPE_NAMED: - return t->named_type()->is_named_error_type(); - default: - return false; - } -} - -// If this is a pointer type, return the type to which it points. -// Otherwise, return NULL. - -Type* -Type::points_to() const -{ - const Pointer_type* ptype = this->convert(); - return ptype == NULL ? NULL : ptype->points_to(); -} - -// Return whether this is an open array type. - -bool -Type::is_open_array_type() const -{ - return this->array_type() != NULL && this->array_type()->length() == NULL; -} - -// Return whether this is the predeclared constant nil being used as a -// type. - -bool -Type::is_nil_constant_as_type() const -{ - const Type* t = this->forwarded(); - if (t->forward_declaration_type() != NULL) - { - const Named_object* no = t->forward_declaration_type()->named_object(); - if (no->is_unknown()) - no = no->unknown_value()->real_named_object(); - if (no != NULL - && no->is_const() - && no->const_value()->expr()->is_nil_expression()) - return true; - } - return false; -} - -// Traverse a type. - -int -Type::traverse(Type* type, Traverse* traverse) -{ - gcc_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0 - || (traverse->traverse_mask() - & Traverse::traverse_expressions) != 0); - if (traverse->remember_type(type)) - { - // We have already traversed this type. - return TRAVERSE_CONTINUE; - } - if ((traverse->traverse_mask() & Traverse::traverse_types) != 0) - { - int t = traverse->type(type); - if (t == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - else if (t == TRAVERSE_SKIP_COMPONENTS) - return TRAVERSE_CONTINUE; - } - // An array type has an expression which we need to traverse if - // traverse_expressions is set. - if (type->do_traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Default implementation for do_traverse for child class. - -int -Type::do_traverse(Traverse*) -{ - return TRAVERSE_CONTINUE; -} - -// Return whether two types are identical. If ERRORS_ARE_IDENTICAL, -// then return true for all erroneous types; this is used to avoid -// cascading errors. If REASON is not NULL, optionally set *REASON to -// the reason the types are not identical. - -bool -Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical, - std::string* reason) -{ - if (t1 == NULL || t2 == NULL) - { - // Something is wrong. - return errors_are_identical ? true : t1 == t2; - } - - // Skip defined forward declarations. - t1 = t1->forwarded(); - t2 = t2->forwarded(); - - if (t1 == t2) - return true; - - // An undefined forward declaration is an error. - if (t1->forward_declaration_type() != NULL - || t2->forward_declaration_type() != NULL) - return errors_are_identical; - - // Avoid cascading errors with error types. - if (t1->is_error_type() || t2->is_error_type()) - { - if (errors_are_identical) - return true; - return t1->is_error_type() && t2->is_error_type(); - } - - // Get a good reason for the sink type. Note that the sink type on - // the left hand side of an assignment is handled in are_assignable. - if (t1->is_sink_type() || t2->is_sink_type()) - { - if (reason != NULL) - *reason = "invalid use of _"; - return false; - } - - // A named type is only identical to itself. - if (t1->named_type() != NULL || t2->named_type() != NULL) - return false; - - // Check type shapes. - if (t1->classification() != t2->classification()) - return false; - - switch (t1->classification()) - { - case TYPE_VOID: - case TYPE_BOOLEAN: - case TYPE_STRING: - case TYPE_NIL: - // These types are always identical. - return true; - - case TYPE_INTEGER: - return t1->integer_type()->is_identical(t2->integer_type()); - - case TYPE_FLOAT: - return t1->float_type()->is_identical(t2->float_type()); - - case TYPE_COMPLEX: - return t1->complex_type()->is_identical(t2->complex_type()); - - case TYPE_FUNCTION: - return t1->function_type()->is_identical(t2->function_type(), - false, - errors_are_identical, - reason); - - case TYPE_POINTER: - return Type::are_identical(t1->points_to(), t2->points_to(), - errors_are_identical, reason); - - case TYPE_STRUCT: - return t1->struct_type()->is_identical(t2->struct_type(), - errors_are_identical); - - case TYPE_ARRAY: - return t1->array_type()->is_identical(t2->array_type(), - errors_are_identical); - - case TYPE_MAP: - return t1->map_type()->is_identical(t2->map_type(), - errors_are_identical); - - case TYPE_CHANNEL: - return t1->channel_type()->is_identical(t2->channel_type(), - errors_are_identical); - - case TYPE_INTERFACE: - return t1->interface_type()->is_identical(t2->interface_type(), - errors_are_identical); - - case TYPE_CALL_MULTIPLE_RESULT: - if (reason != NULL) - *reason = "invalid use of multiple value function call"; - return false; - - default: - gcc_unreachable(); - } -} - -// Return true if it's OK to have a binary operation with types LHS -// and RHS. This is not used for shifts or comparisons. - -bool -Type::are_compatible_for_binop(const Type* lhs, const Type* rhs) -{ - if (Type::are_identical(lhs, rhs, true, NULL)) - return true; - - // A constant of abstract bool type may be mixed with any bool type. - if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type()) - || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type())) - return true; - - // A constant of abstract string type may be mixed with any string - // type. - if ((rhs->is_abstract_string_type() && lhs->is_string_type()) - || (lhs->is_abstract_string_type() && rhs->is_string_type())) - return true; - - lhs = lhs->base(); - rhs = rhs->base(); - - // A constant of abstract integer, float, or complex type may be - // mixed with an integer, float, or complex type. - if ((rhs->is_abstract() - && (rhs->integer_type() != NULL - || rhs->float_type() != NULL - || rhs->complex_type() != NULL) - && (lhs->integer_type() != NULL - || lhs->float_type() != NULL - || lhs->complex_type() != NULL)) - || (lhs->is_abstract() - && (lhs->integer_type() != NULL - || lhs->float_type() != NULL - || lhs->complex_type() != NULL) - && (rhs->integer_type() != NULL - || rhs->float_type() != NULL - || rhs->complex_type() != NULL))) - return true; - - // The nil type may be compared to a pointer, an interface type, a - // slice type, a channel type, a map type, or a function type. - if (lhs->is_nil_type() - && (rhs->points_to() != NULL - || rhs->interface_type() != NULL - || rhs->is_open_array_type() - || rhs->map_type() != NULL - || rhs->channel_type() != NULL - || rhs->function_type() != NULL)) - return true; - if (rhs->is_nil_type() - && (lhs->points_to() != NULL - || lhs->interface_type() != NULL - || lhs->is_open_array_type() - || lhs->map_type() != NULL - || lhs->channel_type() != NULL - || lhs->function_type() != NULL)) - return true; - - return false; -} - -// Return true if a value with type RHS may be assigned to a variable -// with type LHS. If REASON is not NULL, set *REASON to the reason -// the types are not assignable. - -bool -Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason) -{ - // Do some checks first. Make sure the types are defined. - if (rhs != NULL - && rhs->forwarded()->forward_declaration_type() == NULL - && rhs->is_void_type()) - { - if (reason != NULL) - *reason = "non-value used as value"; - return false; - } - - if (lhs != NULL && lhs->forwarded()->forward_declaration_type() == NULL) - { - // Any value may be assigned to the blank identifier. - if (lhs->is_sink_type()) - return true; - - // All fields of a struct must be exported, or the assignment - // must be in the same package. - if (rhs != NULL && rhs->forwarded()->forward_declaration_type() == NULL) - { - if (lhs->has_hidden_fields(NULL, reason) - || rhs->has_hidden_fields(NULL, reason)) - return false; - } - } - - // Identical types are assignable. - if (Type::are_identical(lhs, rhs, true, reason)) - return true; - - // The types are assignable if they have identical underlying types - // and either LHS or RHS is not a named type. - if (((lhs->named_type() != NULL && rhs->named_type() == NULL) - || (rhs->named_type() != NULL && lhs->named_type() == NULL)) - && Type::are_identical(lhs->base(), rhs->base(), true, reason)) - return true; - - // The types are assignable if LHS is an interface type and RHS - // implements the required methods. - const Interface_type* lhs_interface_type = lhs->interface_type(); - if (lhs_interface_type != NULL) - { - if (lhs_interface_type->implements_interface(rhs, reason)) - return true; - const Interface_type* rhs_interface_type = rhs->interface_type(); - if (rhs_interface_type != NULL - && lhs_interface_type->is_compatible_for_assign(rhs_interface_type, - reason)) - return true; - } - - // The type are assignable if RHS is a bidirectional channel type, - // LHS is a channel type, they have identical element types, and - // either LHS or RHS is not a named type. - if (lhs->channel_type() != NULL - && rhs->channel_type() != NULL - && rhs->channel_type()->may_send() - && rhs->channel_type()->may_receive() - && (lhs->named_type() == NULL || rhs->named_type() == NULL) - && Type::are_identical(lhs->channel_type()->element_type(), - rhs->channel_type()->element_type(), - true, - reason)) - return true; - - // The nil type may be assigned to a pointer, function, slice, map, - // channel, or interface type. - if (rhs->is_nil_type() - && (lhs->points_to() != NULL - || lhs->function_type() != NULL - || lhs->is_open_array_type() - || lhs->map_type() != NULL - || lhs->channel_type() != NULL - || lhs->interface_type() != NULL)) - return true; - - // An untyped numeric constant may be assigned to a numeric type if - // it is representable in that type. - if ((rhs->is_abstract() - && (rhs->integer_type() != NULL - || rhs->float_type() != NULL - || rhs->complex_type() != NULL)) - && (lhs->integer_type() != NULL - || lhs->float_type() != NULL - || lhs->complex_type() != NULL)) - return true; - - // Give some better error messages. - if (reason != NULL && reason->empty()) - { - if (rhs->interface_type() != NULL) - reason->assign(_("need explicit conversion")); - else if (rhs->is_call_multiple_result_type()) - reason->assign(_("multiple value function call in " - "single value context")); - else if (lhs->named_type() != NULL && rhs->named_type() != NULL) - { - size_t len = (lhs->named_type()->name().length() - + rhs->named_type()->name().length() - + 100); - char* buf = new char[len]; - snprintf(buf, len, _("cannot use type %s as type %s"), - rhs->named_type()->message_name().c_str(), - lhs->named_type()->message_name().c_str()); - reason->assign(buf); - delete[] buf; - } - } - - return false; -} - -// Return true if a value with type RHS may be converted to type LHS. -// If REASON is not NULL, set *REASON to the reason the types are not -// convertible. - -bool -Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason) -{ - // The types are convertible if they are assignable. - if (Type::are_assignable(lhs, rhs, reason)) - return true; - - // The types are convertible if they have identical underlying - // types. - if ((lhs->named_type() != NULL || rhs->named_type() != NULL) - && Type::are_identical(lhs->base(), rhs->base(), true, reason)) - return true; - - // The types are convertible if they are both unnamed pointer types - // and their pointer base types have identical underlying types. - if (lhs->named_type() == NULL - && rhs->named_type() == NULL - && lhs->points_to() != NULL - && rhs->points_to() != NULL - && (lhs->points_to()->named_type() != NULL - || rhs->points_to()->named_type() != NULL) - && Type::are_identical(lhs->points_to()->base(), - rhs->points_to()->base(), - true, - reason)) - return true; - - // Integer and floating point types are convertible to each other. - if ((lhs->integer_type() != NULL || lhs->float_type() != NULL) - && (rhs->integer_type() != NULL || rhs->float_type() != NULL)) - return true; - - // Complex types are convertible to each other. - if (lhs->complex_type() != NULL && rhs->complex_type() != NULL) - return true; - - // An integer, or []byte, or []int, may be converted to a string. - if (lhs->is_string_type()) - { - if (rhs->integer_type() != NULL) - return true; - if (rhs->is_open_array_type() && rhs->named_type() == NULL) - { - const Type* e = rhs->array_type()->element_type()->forwarded(); - if (e->integer_type() != NULL - && (e == Type::lookup_integer_type("uint8") - || e == Type::lookup_integer_type("int"))) - return true; - } - } - - // A string may be converted to []byte or []int. - if (rhs->is_string_type() - && lhs->is_open_array_type() - && lhs->named_type() == NULL) - { - const Type* e = lhs->array_type()->element_type()->forwarded(); - if (e->integer_type() != NULL - && (e == Type::lookup_integer_type("uint8") - || e == Type::lookup_integer_type("int"))) - return true; - } - - // An unsafe.Pointer type may be converted to any pointer type or to - // uintptr, and vice-versa. - if (lhs->is_unsafe_pointer_type() - && (rhs->points_to() != NULL - || (rhs->integer_type() != NULL - && rhs->forwarded() == Type::lookup_integer_type("uintptr")))) - return true; - if (rhs->is_unsafe_pointer_type() - && (lhs->points_to() != NULL - || (lhs->integer_type() != NULL - && lhs->forwarded() == Type::lookup_integer_type("uintptr")))) - return true; - - // Give a better error message. - if (reason != NULL) - { - if (reason->empty()) - *reason = "invalid type conversion"; - else - { - std::string s = "invalid type conversion ("; - s += *reason; - s += ')'; - *reason = s; - } - } - - return false; -} - -// Return whether this type has any hidden fields. This is only a -// possibility for a few types. - -bool -Type::has_hidden_fields(const Named_type* within, std::string* reason) const -{ - switch (this->forwarded()->classification_) - { - case TYPE_NAMED: - return this->named_type()->named_type_has_hidden_fields(reason); - case TYPE_STRUCT: - return this->struct_type()->struct_has_hidden_fields(within, reason); - case TYPE_ARRAY: - return this->array_type()->array_has_hidden_fields(within, reason); - default: - return false; - } -} - -// Return a hash code for the type to be used for method lookup. - -unsigned int -Type::hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - if (this->classification_ != TYPE_FORWARD) - ret += this->classification_; - return ret + this->do_hash_for_method(gogo); -} - -// Default implementation of do_hash_for_method. This is appropriate -// for types with no subfields. - -unsigned int -Type::do_hash_for_method(Gogo*) const -{ - return 0; -} - -// Return a hash code for a string, given a starting hash. - -unsigned int -Type::hash_string(const std::string& s, unsigned int h) -{ - const char* p = s.data(); - size_t len = s.length(); - for (; len > 0; --len) - { - h ^= *p++; - h*= 16777619; - } - return h; -} - -// Default check for the expression passed to make. Any type which -// may be used with make implements its own version of this. - -bool -Type::do_check_make_expression(Expression_list*, source_location) -{ - gcc_unreachable(); -} - -// Return whether an expression has an integer value. Report an error -// if not. This is used when handling calls to the predeclared make -// function. - -bool -Type::check_int_value(Expression* e, const char* errmsg, - source_location location) -{ - if (e->type()->integer_type() != NULL) - return true; - - // Check for a floating point constant with integer value. - mpfr_t fval; - mpfr_init(fval); - - Type* dummy; - if (e->float_constant_value(fval, &dummy) && mpfr_integer_p(fval)) - { - mpz_t ival; - mpz_init(ival); - - bool ok = false; - - mpfr_clear_overflow(); - mpfr_clear_erangeflag(); - mpfr_get_z(ival, fval, GMP_RNDN); - if (!mpfr_overflow_p() - && !mpfr_erangeflag_p() - && mpz_sgn(ival) >= 0) - { - Named_type* ntype = Type::lookup_integer_type("int"); - Integer_type* inttype = ntype->integer_type(); - mpz_t max; - mpz_init_set_ui(max, 1); - mpz_mul_2exp(max, max, inttype->bits() - 1); - ok = mpz_cmp(ival, max) < 0; - mpz_clear(max); - } - mpz_clear(ival); - - if (ok) - { - mpfr_clear(fval); - return true; - } - } - - mpfr_clear(fval); - - error_at(location, "%s", errmsg); - return false; -} - -// A hash table mapping unnamed types to trees. - -Type::Type_trees Type::type_trees; - -// Return a tree representing this type. - -tree -Type::get_tree(Gogo* gogo) -{ - if (this->tree_ != NULL) - return this->tree_; - - if (this->forward_declaration_type() != NULL - || this->named_type() != NULL) - return this->get_tree_without_hash(gogo); - - if (this->is_error_type()) - return error_mark_node; - - // To avoid confusing GIMPLE, we need to translate all identical Go - // types to the same GIMPLE type. We use a hash table to do that. - // There is no need to use the hash table for named types, as named - // types are only identical to themselves. - - std::pair val(this, NULL); - std::pair ins = - Type::type_trees.insert(val); - if (!ins.second && ins.first->second != NULL_TREE) - { - if (gogo != NULL && gogo->named_types_are_converted()) - this->tree_ = ins.first->second; - return ins.first->second; - } - - tree t = this->get_tree_without_hash(gogo); - - if (ins.first->second == NULL_TREE) - ins.first->second = t; - else - { - // We have already created a tree for this type. This can - // happen when an unnamed type is defined using a named type - // which in turns uses an identical unnamed type. Use the tree - // we created earlier and ignore the one we just built. - t = ins.first->second; - if (gogo == NULL || !gogo->named_types_are_converted()) - return t; - this->tree_ = t; - } - - return t; -} - -// Return a tree for a type without looking in the hash table for -// identical types. This is used for named types, since there is no -// point to looking in the hash table for them. - -tree -Type::get_tree_without_hash(Gogo* gogo) -{ - if (this->tree_ == NULL_TREE) - { - tree t = this->do_get_tree(gogo); - - // For a recursive function or pointer type, we will temporarily - // return ptr_type_node during the recursion. We don't want to - // record that for a forwarding type, as it may confuse us - // later. - if (t == ptr_type_node && this->forward_declaration_type() != NULL) - return t; - - if (gogo == NULL || !gogo->named_types_are_converted()) - return t; - - this->tree_ = t; - go_preserve_from_gc(t); - } - - return this->tree_; -} - -// Return a tree representing a zero initialization for this type. - -tree -Type::get_init_tree(Gogo* gogo, bool is_clear) -{ - tree type_tree = this->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - return this->do_get_init_tree(gogo, type_tree, is_clear); -} - -// Any type which supports the builtin make function must implement -// this. - -tree -Type::do_make_expression_tree(Translate_context*, Expression_list*, - source_location) -{ - gcc_unreachable(); -} - -// Return a pointer to the type descriptor for this type. - -tree -Type::type_descriptor_pointer(Gogo* gogo) -{ - Type* t = this->forwarded(); - if (t->type_descriptor_decl_ == NULL_TREE) - { - Expression* e = t->do_type_descriptor(gogo, NULL); - gogo->build_type_descriptor_decl(t, e, &t->type_descriptor_decl_); - gcc_assert(t->type_descriptor_decl_ != NULL_TREE - && (t->type_descriptor_decl_ == error_mark_node - || DECL_P(t->type_descriptor_decl_))); - } - if (t->type_descriptor_decl_ == error_mark_node) - return error_mark_node; - return build_fold_addr_expr(t->type_descriptor_decl_); -} - -// Return a composite literal for a type descriptor. - -Expression* -Type::type_descriptor(Gogo* gogo, Type* type) -{ - return type->do_type_descriptor(gogo, NULL); -} - -// Return a composite literal for a type descriptor with a name. - -Expression* -Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name) -{ - gcc_assert(name != NULL && type->named_type() != name); - return type->do_type_descriptor(gogo, name); -} - -// Make a builtin struct type from a list of fields. The fields are -// pairs of a name and a type. - -Struct_type* -Type::make_builtin_struct_type(int nfields, ...) -{ - va_list ap; - va_start(ap, nfields); - - source_location bloc = BUILTINS_LOCATION; - Struct_field_list* sfl = new Struct_field_list(); - for (int i = 0; i < nfields; i++) - { - const char* field_name = va_arg(ap, const char *); - Type* type = va_arg(ap, Type*); - sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc))); - } - - va_end(ap); - - return Type::make_struct_type(sfl, bloc); -} - -// A list of builtin named types. - -std::vector Type::named_builtin_types; - -// Make a builtin named type. - -Named_type* -Type::make_builtin_named_type(const char* name, Type* type) -{ - source_location bloc = BUILTINS_LOCATION; - Named_object* no = Named_object::make_type(name, NULL, type, bloc); - Named_type* ret = no->type_value(); - Type::named_builtin_types.push_back(ret); - return ret; -} - -// Convert the named builtin types. - -void -Type::convert_builtin_named_types(Gogo* gogo) -{ - for (std::vector::const_iterator p = - Type::named_builtin_types.begin(); - p != Type::named_builtin_types.end(); - ++p) - { - bool r = (*p)->verify(); - gcc_assert(r); - (*p)->convert(gogo); - } -} - -// Return the type of a type descriptor. We should really tie this to -// runtime.Type rather than copying it. This must match commonType in -// libgo/go/runtime/type.go. - -Type* -Type::make_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - source_location bloc = BUILTINS_LOCATION; - - Type* uint8_type = Type::lookup_integer_type("uint8"); - Type* uint32_type = Type::lookup_integer_type("uint32"); - Type* uintptr_type = Type::lookup_integer_type("uintptr"); - Type* string_type = Type::lookup_string_type(); - Type* pointer_string_type = Type::make_pointer_type(string_type); - - // This is an unnamed version of unsafe.Pointer. Perhaps we - // should use the named version instead, although that would - // require us to create the unsafe package if it has not been - // imported. It probably doesn't matter. - Type* void_type = Type::make_void_type(); - Type* unsafe_pointer_type = Type::make_pointer_type(void_type); - - // Forward declaration for the type descriptor type. - Named_object* named_type_descriptor_type = - Named_object::make_type_declaration("commonType", NULL, bloc); - Type* ft = Type::make_forward_declaration(named_type_descriptor_type); - Type* pointer_type_descriptor_type = Type::make_pointer_type(ft); - - // The type of a method on a concrete type. - Struct_type* method_type = - Type::make_builtin_struct_type(5, - "name", pointer_string_type, - "pkgPath", pointer_string_type, - "mtyp", pointer_type_descriptor_type, - "typ", pointer_type_descriptor_type, - "tfn", unsafe_pointer_type); - Named_type* named_method_type = - Type::make_builtin_named_type("method", method_type); - - // Information for types with a name or methods. - Type* slice_named_method_type = - Type::make_array_type(named_method_type, NULL); - Struct_type* uncommon_type = - Type::make_builtin_struct_type(3, - "name", pointer_string_type, - "pkgPath", pointer_string_type, - "methods", slice_named_method_type); - Named_type* named_uncommon_type = - Type::make_builtin_named_type("uncommonType", uncommon_type); - - Type* pointer_uncommon_type = - Type::make_pointer_type(named_uncommon_type); - - // The type descriptor type. - - Typed_identifier_list* params = new Typed_identifier_list(); - params->push_back(Typed_identifier("", unsafe_pointer_type, bloc)); - params->push_back(Typed_identifier("", uintptr_type, bloc)); - - Typed_identifier_list* results = new Typed_identifier_list(); - results->push_back(Typed_identifier("", uintptr_type, bloc)); - - Type* hashfn_type = Type::make_function_type(NULL, params, results, bloc); - - params = new Typed_identifier_list(); - params->push_back(Typed_identifier("", unsafe_pointer_type, bloc)); - params->push_back(Typed_identifier("", unsafe_pointer_type, bloc)); - params->push_back(Typed_identifier("", uintptr_type, bloc)); - - results = new Typed_identifier_list(); - results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc)); - - Type* equalfn_type = Type::make_function_type(NULL, params, results, - bloc); - - Struct_type* type_descriptor_type = - Type::make_builtin_struct_type(10, - "Kind", uint8_type, - "align", uint8_type, - "fieldAlign", uint8_type, - "size", uintptr_type, - "hash", uint32_type, - "hashfn", hashfn_type, - "equalfn", equalfn_type, - "string", pointer_string_type, - "", pointer_uncommon_type, - "ptrToThis", - pointer_type_descriptor_type); - - Named_type* named = Type::make_builtin_named_type("commonType", - type_descriptor_type); - - named_type_descriptor_type->set_type_value(named); - - ret = named; - } - - return ret; -} - -// Make the type of a pointer to a type descriptor as represented in -// Go. - -Type* -Type::make_type_descriptor_ptr_type() -{ - static Type* ret; - if (ret == NULL) - ret = Type::make_pointer_type(Type::make_type_descriptor_type()); - return ret; -} - -// Return the names of runtime functions which compute a hash code for -// this type and which compare whether two values of this type are -// equal. - -void -Type::type_functions(const char** hash_fn, const char** equal_fn) const -{ - switch (this->base()->classification()) - { - case Type::TYPE_ERROR: - case Type::TYPE_VOID: - case Type::TYPE_NIL: - // These types can not be hashed or compared. - *hash_fn = "__go_type_hash_error"; - *equal_fn = "__go_type_equal_error"; - break; - - case Type::TYPE_BOOLEAN: - case Type::TYPE_INTEGER: - case Type::TYPE_FLOAT: - case Type::TYPE_COMPLEX: - case Type::TYPE_POINTER: - case Type::TYPE_FUNCTION: - case Type::TYPE_MAP: - case Type::TYPE_CHANNEL: - *hash_fn = "__go_type_hash_identity"; - *equal_fn = "__go_type_equal_identity"; - break; - - case Type::TYPE_STRING: - *hash_fn = "__go_type_hash_string"; - *equal_fn = "__go_type_equal_string"; - break; - - case Type::TYPE_STRUCT: - case Type::TYPE_ARRAY: - // These types can not be hashed or compared. - *hash_fn = "__go_type_hash_error"; - *equal_fn = "__go_type_equal_error"; - break; - - case Type::TYPE_INTERFACE: - if (this->interface_type()->is_empty()) - { - *hash_fn = "__go_type_hash_empty_interface"; - *equal_fn = "__go_type_equal_empty_interface"; - } - else - { - *hash_fn = "__go_type_hash_interface"; - *equal_fn = "__go_type_equal_interface"; - } - break; - - case Type::TYPE_NAMED: - case Type::TYPE_FORWARD: - gcc_unreachable(); - - default: - gcc_unreachable(); - } -} - -// Return a composite literal for the type descriptor for a plain type -// of kind RUNTIME_TYPE_KIND named NAME. - -Expression* -Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind, - Named_type* name, const Methods* methods, - bool only_value_methods) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* td_type = Type::make_type_descriptor_type(); - const Struct_field_list* fields = td_type->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(9); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "Kind"); - mpz_t iv; - mpz_init_set_ui(iv, runtime_type_kind); - vals->push_back(Expression::make_integer(&iv, p->type(), bloc)); - - ++p; - gcc_assert(p->field_name() == "align"); - Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT; - vals->push_back(Expression::make_type_info(this, type_info)); - - ++p; - gcc_assert(p->field_name() == "fieldAlign"); - type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT; - vals->push_back(Expression::make_type_info(this, type_info)); - - ++p; - gcc_assert(p->field_name() == "size"); - type_info = Expression::TYPE_INFO_SIZE; - vals->push_back(Expression::make_type_info(this, type_info)); - - ++p; - gcc_assert(p->field_name() == "hash"); - mpz_set_ui(iv, this->hash_for_method(gogo)); - vals->push_back(Expression::make_integer(&iv, p->type(), bloc)); - - const char* hash_fn; - const char* equal_fn; - this->type_functions(&hash_fn, &equal_fn); - - ++p; - gcc_assert(p->field_name() == "hashfn"); - Function_type* fntype = p->type()->function_type(); - Named_object* no = Named_object::make_function_declaration(hash_fn, NULL, - fntype, - bloc); - no->func_declaration_value()->set_asm_name(hash_fn); - vals->push_back(Expression::make_func_reference(no, NULL, bloc)); - - ++p; - gcc_assert(p->field_name() == "equalfn"); - fntype = p->type()->function_type(); - no = Named_object::make_function_declaration(equal_fn, NULL, fntype, bloc); - no->func_declaration_value()->set_asm_name(equal_fn); - vals->push_back(Expression::make_func_reference(no, NULL, bloc)); - - ++p; - gcc_assert(p->field_name() == "string"); - Expression* s = Expression::make_string((name != NULL - ? name->reflection(gogo) - : this->reflection(gogo)), - bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - - ++p; - gcc_assert(p->field_name() == "uncommonType"); - if (name == NULL && methods == NULL) - vals->push_back(Expression::make_nil(bloc)); - else - { - if (methods == NULL) - methods = name->methods(); - vals->push_back(this->uncommon_type_constructor(gogo, - p->type()->deref(), - name, methods, - only_value_methods)); - } - - ++p; - gcc_assert(p->field_name() == "ptrToThis"); - if (name == NULL) - vals->push_back(Expression::make_nil(bloc)); - else - { - Type* pt = Type::make_pointer_type(name); - vals->push_back(Expression::make_type_descriptor(pt, bloc)); - } - - ++p; - gcc_assert(p == fields->end()); - - mpz_clear(iv); - - return Expression::make_struct_composite_literal(td_type, vals, bloc); -} - -// Return a composite literal for the uncommon type information for -// this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type -// struct. If name is not NULL, it is the name of the type. If -// METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS -// is true if only value methods should be included. At least one of -// NAME and METHODS must not be NULL. - -Expression* -Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type, - Named_type* name, const Methods* methods, - bool only_value_methods) const -{ - source_location bloc = BUILTINS_LOCATION; - - const Struct_field_list* fields = uncommon_type->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(3); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "name"); - - ++p; - gcc_assert(p->field_name() == "pkgPath"); - - if (name == NULL) - { - vals->push_back(Expression::make_nil(bloc)); - vals->push_back(Expression::make_nil(bloc)); - } - else - { - Named_object* no = name->named_object(); - std::string n = Gogo::unpack_hidden_name(no->name()); - Expression* s = Expression::make_string(n, bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - - if (name->is_builtin()) - vals->push_back(Expression::make_nil(bloc)); - else - { - const Package* package = no->package(); - const std::string& unique_prefix(package == NULL - ? gogo->unique_prefix() - : package->unique_prefix()); - const std::string& package_name(package == NULL - ? gogo->package_name() - : package->name()); - n.assign(unique_prefix); - n.append(1, '.'); - n.append(package_name); - if (name->in_function() != NULL) - { - n.append(1, '.'); - n.append(Gogo::unpack_hidden_name(name->in_function()->name())); - } - s = Expression::make_string(n, bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - } - - ++p; - gcc_assert(p->field_name() == "methods"); - vals->push_back(this->methods_constructor(gogo, p->type(), methods, - only_value_methods)); - - ++p; - gcc_assert(p == fields->end()); - - Expression* r = Expression::make_struct_composite_literal(uncommon_type, - vals, bloc); - return Expression::make_unary(OPERATOR_AND, r, bloc); -} - -// Sort methods by name. - -class Sort_methods -{ - public: - bool - operator()(const std::pair& m1, - const std::pair& m2) const - { return m1.first < m2.first; } -}; - -// Return a composite literal for the type method table for this type. -// METHODS_TYPE is the type of the table, and is a slice type. -// METHODS is the list of methods. If ONLY_VALUE_METHODS is true, -// then only value methods are used. - -Expression* -Type::methods_constructor(Gogo* gogo, Type* methods_type, - const Methods* methods, - bool only_value_methods) const -{ - source_location bloc = BUILTINS_LOCATION; - - std::vector > smethods; - if (methods != NULL) - { - smethods.reserve(methods->count()); - for (Methods::const_iterator p = methods->begin(); - p != methods->end(); - ++p) - { - if (p->second->is_ambiguous()) - continue; - if (only_value_methods && !p->second->is_value_method()) - continue; - smethods.push_back(std::make_pair(p->first, p->second)); - } - } - - if (smethods.empty()) - return Expression::make_slice_composite_literal(methods_type, NULL, bloc); - - std::sort(smethods.begin(), smethods.end(), Sort_methods()); - - Type* method_type = methods_type->array_type()->element_type(); - - Expression_list* vals = new Expression_list(); - vals->reserve(smethods.size()); - for (std::vector >::const_iterator p - = smethods.begin(); - p != smethods.end(); - ++p) - vals->push_back(this->method_constructor(gogo, method_type, p->first, - p->second)); - - return Expression::make_slice_composite_literal(methods_type, vals, bloc); -} - -// Return a composite literal for a single method. METHOD_TYPE is the -// type of the entry. METHOD_NAME is the name of the method and M is -// the method information. - -Expression* -Type::method_constructor(Gogo*, Type* method_type, - const std::string& method_name, - const Method* m) const -{ - source_location bloc = BUILTINS_LOCATION; - - const Struct_field_list* fields = method_type->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(5); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "name"); - const std::string n = Gogo::unpack_hidden_name(method_name); - Expression* s = Expression::make_string(n, bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - - ++p; - gcc_assert(p->field_name() == "pkgPath"); - if (!Gogo::is_hidden_name(method_name)) - vals->push_back(Expression::make_nil(bloc)); - else - { - s = Expression::make_string(Gogo::hidden_name_prefix(method_name), bloc); - vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - - Named_object* no = (m->needs_stub_method() - ? m->stub_object() - : m->named_object()); - - Function_type* mtype; - if (no->is_function()) - mtype = no->func_value()->type(); - else - mtype = no->func_declaration_value()->type(); - gcc_assert(mtype->is_method()); - Type* nonmethod_type = mtype->copy_without_receiver(); - - ++p; - gcc_assert(p->field_name() == "mtyp"); - vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc)); - - ++p; - gcc_assert(p->field_name() == "typ"); - vals->push_back(Expression::make_type_descriptor(mtype, bloc)); - - ++p; - gcc_assert(p->field_name() == "tfn"); - vals->push_back(Expression::make_func_reference(no, NULL, bloc)); - - ++p; - gcc_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(method_type, vals, bloc); -} - -// Return a composite literal for the type descriptor of a plain type. -// RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not -// NULL, it is the name to use as well as the list of methods. - -Expression* -Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind, - Named_type* name) -{ - return this->type_descriptor_constructor(gogo, runtime_type_kind, - name, NULL, true); -} - -// Return the type reflection string for this type. - -std::string -Type::reflection(Gogo* gogo) const -{ - std::string ret; - - // The do_reflection virtual function should set RET to the - // reflection string. - this->do_reflection(gogo, &ret); - - return ret; -} - -// Return a mangled name for the type. - -std::string -Type::mangled_name(Gogo* gogo) const -{ - std::string ret; - - // The do_mangled_name virtual function should set RET to the - // mangled name. For a composite type it should append a code for - // the composition and then call do_mangled_name on the components. - this->do_mangled_name(gogo, &ret); - - return ret; -} - -// Default function to export a type. - -void -Type::do_export(Export*) const -{ - gcc_unreachable(); -} - -// Import a type. - -Type* -Type::import_type(Import* imp) -{ - if (imp->match_c_string("(")) - return Function_type::do_import(imp); - else if (imp->match_c_string("*")) - return Pointer_type::do_import(imp); - else if (imp->match_c_string("struct ")) - return Struct_type::do_import(imp); - else if (imp->match_c_string("[")) - return Array_type::do_import(imp); - else if (imp->match_c_string("map ")) - return Map_type::do_import(imp); - else if (imp->match_c_string("chan ")) - return Channel_type::do_import(imp); - else if (imp->match_c_string("interface")) - return Interface_type::do_import(imp); - else - { - error_at(imp->location(), "import error: expected type"); - return Type::make_error_type(); - } -} - -// A type used to indicate a parsing error. This exists to simplify -// later error detection. - -class Error_type : public Type -{ - public: - Error_type() - : Type(TYPE_ERROR) - { } - - protected: - tree - do_get_tree(Gogo*) - { return error_mark_node; } - - tree - do_get_init_tree(Gogo*, tree, bool) - { return error_mark_node; } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { return Expression::make_error(BUILTINS_LOCATION); } - - void - do_reflection(Gogo*, std::string*) const - { gcc_assert(saw_errors()); } - - void - do_mangled_name(Gogo*, std::string* ret) const - { ret->push_back('E'); } -}; - -Type* -Type::make_error_type() -{ - static Error_type singleton_error_type; - return &singleton_error_type; -} - -// The void type. - -class Void_type : public Type -{ - public: - Void_type() - : Type(TYPE_VOID) - { } - - protected: - tree - do_get_tree(Gogo*) - { return void_type_node; } - - tree - do_get_init_tree(Gogo*, tree, bool) - { gcc_unreachable(); } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { gcc_unreachable(); } - - void - do_reflection(Gogo*, std::string*) const - { } - - void - do_mangled_name(Gogo*, std::string* ret) const - { ret->push_back('v'); } -}; - -Type* -Type::make_void_type() -{ - static Void_type singleton_void_type; - return &singleton_void_type; -} - -// The boolean type. - -class Boolean_type : public Type -{ - public: - Boolean_type() - : Type(TYPE_BOOLEAN) - { } - - protected: - tree - do_get_tree(Gogo*) - { return boolean_type_node; } - - tree - do_get_init_tree(Gogo*, tree type_tree, bool is_clear) - { return is_clear ? NULL : fold_convert(type_tree, boolean_false_node); } - - Expression* - do_type_descriptor(Gogo*, Named_type* name); - - // We should not be asked for the reflection string of a basic type. - void - do_reflection(Gogo*, std::string* ret) const - { ret->append("bool"); } - - void - do_mangled_name(Gogo*, std::string* ret) const - { ret->push_back('b'); } -}; - -// Make the type descriptor. - -Expression* -Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (name != NULL) - return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name); - else - { - Named_object* no = gogo->lookup_global("bool"); - gcc_assert(no != NULL); - return Type::type_descriptor(gogo, no->type_value()); - } -} - -Type* -Type::make_boolean_type() -{ - static Boolean_type boolean_type; - return &boolean_type; -} - -// The named type "bool". - -static Named_type* named_bool_type; - -// Get the named type "bool". - -Named_type* -Type::lookup_bool_type() -{ - return named_bool_type; -} - -// Make the named type "bool". - -Named_type* -Type::make_named_bool_type() -{ - Type* bool_type = Type::make_boolean_type(); - Named_object* named_object = Named_object::make_type("bool", NULL, - bool_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - named_bool_type = named_type; - return named_type; -} - -// Class Integer_type. - -Integer_type::Named_integer_types Integer_type::named_integer_types; - -// Create a new integer type. Non-abstract integer types always have -// names. - -Named_type* -Integer_type::create_integer_type(const char* name, bool is_unsigned, - int bits, int runtime_type_kind) -{ - Integer_type* integer_type = new Integer_type(false, is_unsigned, bits, - runtime_type_kind); - std::string sname(name); - Named_object* named_object = Named_object::make_type(sname, NULL, - integer_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - std::pair ins = - Integer_type::named_integer_types.insert(std::make_pair(sname, named_type)); - gcc_assert(ins.second); - return named_type; -} - -// Look up an existing integer type. - -Named_type* -Integer_type::lookup_integer_type(const char* name) -{ - Named_integer_types::const_iterator p = - Integer_type::named_integer_types.find(name); - gcc_assert(p != Integer_type::named_integer_types.end()); - return p->second; -} - -// Create a new abstract integer type. - -Integer_type* -Integer_type::create_abstract_integer_type() -{ - static Integer_type* abstract_type; - if (abstract_type == NULL) - abstract_type = new Integer_type(true, false, INT_TYPE_SIZE, - RUNTIME_TYPE_KIND_INT); - return abstract_type; -} - -// Integer type compatibility. - -bool -Integer_type::is_identical(const Integer_type* t) const -{ - if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_) - return false; - return this->is_abstract_ == t->is_abstract_; -} - -// Hash code. - -unsigned int -Integer_type::do_hash_for_method(Gogo*) const -{ - return ((this->bits_ << 4) - + ((this->is_unsigned_ ? 1 : 0) << 8) - + ((this->is_abstract_ ? 1 : 0) << 9)); -} - -// Get the tree for an Integer_type. - -tree -Integer_type::do_get_tree(Gogo*) -{ - if (this->is_abstract_) - { - gcc_assert(saw_errors()); - return error_mark_node; - } - - if (this->is_unsigned_) - { - if (this->bits_ == INT_TYPE_SIZE) - return unsigned_type_node; - else if (this->bits_ == CHAR_TYPE_SIZE) - return unsigned_char_type_node; - else if (this->bits_ == SHORT_TYPE_SIZE) - return short_unsigned_type_node; - else if (this->bits_ == LONG_TYPE_SIZE) - return long_unsigned_type_node; - else if (this->bits_ == LONG_LONG_TYPE_SIZE) - return long_long_unsigned_type_node; - else - return make_unsigned_type(this->bits_); - } - else - { - if (this->bits_ == INT_TYPE_SIZE) - return integer_type_node; - else if (this->bits_ == CHAR_TYPE_SIZE) - return signed_char_type_node; - else if (this->bits_ == SHORT_TYPE_SIZE) - return short_integer_type_node; - else if (this->bits_ == LONG_TYPE_SIZE) - return long_integer_type_node; - else if (this->bits_ == LONG_LONG_TYPE_SIZE) - return long_long_integer_type_node; - else - return make_signed_type(this->bits_); - } -} - -tree -Integer_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - return is_clear ? NULL : build_int_cst(type_tree, 0); -} - -// The type descriptor for an integer type. Integer types are always -// named. - -Expression* -Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - gcc_assert(name != NULL); - return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name); -} - -// We should not be asked for the reflection string of a basic type. - -void -Integer_type::do_reflection(Gogo*, std::string*) const -{ - gcc_assert(saw_errors()); -} - -// Mangled name. - -void -Integer_type::do_mangled_name(Gogo*, std::string* ret) const -{ - char buf[100]; - snprintf(buf, sizeof buf, "i%s%s%de", - this->is_abstract_ ? "a" : "", - this->is_unsigned_ ? "u" : "", - this->bits_); - ret->append(buf); -} - -// Make an integer type. - -Named_type* -Type::make_integer_type(const char* name, bool is_unsigned, int bits, - int runtime_type_kind) -{ - return Integer_type::create_integer_type(name, is_unsigned, bits, - runtime_type_kind); -} - -// Make an abstract integer type. - -Integer_type* -Type::make_abstract_integer_type() -{ - return Integer_type::create_abstract_integer_type(); -} - -// Look up an integer type. - -Named_type* -Type::lookup_integer_type(const char* name) -{ - return Integer_type::lookup_integer_type(name); -} - -// Class Float_type. - -Float_type::Named_float_types Float_type::named_float_types; - -// Create a new float type. Non-abstract float types always have -// names. - -Named_type* -Float_type::create_float_type(const char* name, int bits, - int runtime_type_kind) -{ - Float_type* float_type = new Float_type(false, bits, runtime_type_kind); - std::string sname(name); - Named_object* named_object = Named_object::make_type(sname, NULL, float_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - std::pair ins = - Float_type::named_float_types.insert(std::make_pair(sname, named_type)); - gcc_assert(ins.second); - return named_type; -} - -// Look up an existing float type. - -Named_type* -Float_type::lookup_float_type(const char* name) -{ - Named_float_types::const_iterator p = - Float_type::named_float_types.find(name); - gcc_assert(p != Float_type::named_float_types.end()); - return p->second; -} - -// Create a new abstract float type. - -Float_type* -Float_type::create_abstract_float_type() -{ - static Float_type* abstract_type; - if (abstract_type == NULL) - abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64); - return abstract_type; -} - -// Whether this type is identical with T. - -bool -Float_type::is_identical(const Float_type* t) const -{ - if (this->bits_ != t->bits_) - return false; - return this->is_abstract_ == t->is_abstract_; -} - -// Hash code. - -unsigned int -Float_type::do_hash_for_method(Gogo*) const -{ - return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8); -} - -// Get a tree without using a Gogo*. - -tree -Float_type::type_tree() const -{ - if (this->bits_ == FLOAT_TYPE_SIZE) - return float_type_node; - else if (this->bits_ == DOUBLE_TYPE_SIZE) - return double_type_node; - else if (this->bits_ == LONG_DOUBLE_TYPE_SIZE) - return long_double_type_node; - else - { - tree ret = make_node(REAL_TYPE); - TYPE_PRECISION(ret) = this->bits_; - layout_type(ret); - return ret; - } -} - -// Get a tree. - -tree -Float_type::do_get_tree(Gogo*) -{ - return this->type_tree(); -} - -tree -Float_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - REAL_VALUE_TYPE r; - real_from_integer(&r, TYPE_MODE(type_tree), 0, 0, 0); - return build_real(type_tree, r); -} - -// The type descriptor for a float type. Float types are always named. - -Expression* -Float_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - gcc_assert(name != NULL); - return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name); -} - -// We should not be asked for the reflection string of a basic type. - -void -Float_type::do_reflection(Gogo*, std::string*) const -{ - gcc_assert(saw_errors()); -} - -// Mangled name. - -void -Float_type::do_mangled_name(Gogo*, std::string* ret) const -{ - char buf[100]; - snprintf(buf, sizeof buf, "f%s%de", - this->is_abstract_ ? "a" : "", - this->bits_); - ret->append(buf); -} - -// Make a floating point type. - -Named_type* -Type::make_float_type(const char* name, int bits, int runtime_type_kind) -{ - return Float_type::create_float_type(name, bits, runtime_type_kind); -} - -// Make an abstract float type. - -Float_type* -Type::make_abstract_float_type() -{ - return Float_type::create_abstract_float_type(); -} - -// Look up a float type. - -Named_type* -Type::lookup_float_type(const char* name) -{ - return Float_type::lookup_float_type(name); -} - -// Class Complex_type. - -Complex_type::Named_complex_types Complex_type::named_complex_types; - -// Create a new complex type. Non-abstract complex types always have -// names. - -Named_type* -Complex_type::create_complex_type(const char* name, int bits, - int runtime_type_kind) -{ - Complex_type* complex_type = new Complex_type(false, bits, - runtime_type_kind); - std::string sname(name); - Named_object* named_object = Named_object::make_type(sname, NULL, - complex_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - std::pair ins = - Complex_type::named_complex_types.insert(std::make_pair(sname, - named_type)); - gcc_assert(ins.second); - return named_type; -} - -// Look up an existing complex type. - -Named_type* -Complex_type::lookup_complex_type(const char* name) -{ - Named_complex_types::const_iterator p = - Complex_type::named_complex_types.find(name); - gcc_assert(p != Complex_type::named_complex_types.end()); - return p->second; -} - -// Create a new abstract complex type. - -Complex_type* -Complex_type::create_abstract_complex_type() -{ - static Complex_type* abstract_type; - if (abstract_type == NULL) - abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128); - return abstract_type; -} - -// Whether this type is identical with T. - -bool -Complex_type::is_identical(const Complex_type *t) const -{ - if (this->bits_ != t->bits_) - return false; - return this->is_abstract_ == t->is_abstract_; -} - -// Hash code. - -unsigned int -Complex_type::do_hash_for_method(Gogo*) const -{ - return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8); -} - -// Get a tree without using a Gogo*. - -tree -Complex_type::type_tree() const -{ - if (this->bits_ == FLOAT_TYPE_SIZE * 2) - return complex_float_type_node; - else if (this->bits_ == DOUBLE_TYPE_SIZE * 2) - return complex_double_type_node; - else if (this->bits_ == LONG_DOUBLE_TYPE_SIZE * 2) - return complex_long_double_type_node; - else - { - tree ret = make_node(REAL_TYPE); - TYPE_PRECISION(ret) = this->bits_ / 2; - layout_type(ret); - return build_complex_type(ret); - } -} - -// Get a tree. - -tree -Complex_type::do_get_tree(Gogo*) -{ - return this->type_tree(); -} - -// Zero initializer. - -tree -Complex_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - REAL_VALUE_TYPE r; - real_from_integer(&r, TYPE_MODE(TREE_TYPE(type_tree)), 0, 0, 0); - return build_complex(type_tree, build_real(TREE_TYPE(type_tree), r), - build_real(TREE_TYPE(type_tree), r)); -} - -// The type descriptor for a complex type. Complex types are always -// named. - -Expression* -Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - gcc_assert(name != NULL); - return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name); -} - -// We should not be asked for the reflection string of a basic type. - -void -Complex_type::do_reflection(Gogo*, std::string*) const -{ - gcc_assert(saw_errors()); -} - -// Mangled name. - -void -Complex_type::do_mangled_name(Gogo*, std::string* ret) const -{ - char buf[100]; - snprintf(buf, sizeof buf, "c%s%de", - this->is_abstract_ ? "a" : "", - this->bits_); - ret->append(buf); -} - -// Make a complex type. - -Named_type* -Type::make_complex_type(const char* name, int bits, int runtime_type_kind) -{ - return Complex_type::create_complex_type(name, bits, runtime_type_kind); -} - -// Make an abstract complex type. - -Complex_type* -Type::make_abstract_complex_type() -{ - return Complex_type::create_abstract_complex_type(); -} - -// Look up a complex type. - -Named_type* -Type::lookup_complex_type(const char* name) -{ - return Complex_type::lookup_complex_type(name); -} - -// Class String_type. - -// Return the tree for String_type. A string is a struct with two -// fields: a pointer to the characters and a length. - -tree -String_type::do_get_tree(Gogo*) -{ - static tree struct_type; - return Gogo::builtin_struct(&struct_type, "__go_string", NULL_TREE, 2, - "__data", - build_pointer_type(unsigned_char_type_node), - "__length", - integer_type_node); -} - -// Return a tree for the length of STRING. - -tree -String_type::length_tree(Gogo*, tree string) -{ - tree string_type = TREE_TYPE(string); - gcc_assert(TREE_CODE(string_type) == RECORD_TYPE); - tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)), - "__length") == 0); - return fold_build3(COMPONENT_REF, integer_type_node, string, - length_field, NULL_TREE); -} - -// Return a tree for a pointer to the bytes of STRING. - -tree -String_type::bytes_tree(Gogo*, tree string) -{ - tree string_type = TREE_TYPE(string); - gcc_assert(TREE_CODE(string_type) == RECORD_TYPE); - tree bytes_field = TYPE_FIELDS(string_type); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)), - "__data") == 0); - return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string, - bytes_field, NULL_TREE); -} - -// We initialize a string to { NULL, 0 }. - -tree -String_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL_TREE; - - gcc_assert(TREE_CODE(type_tree) == RECORD_TYPE); - - VEC(constructor_elt, gc)* init = VEC_alloc(constructor_elt, gc, 2); - - for (tree field = TYPE_FIELDS(type_tree); - field != NULL_TREE; - field = DECL_CHAIN(field)) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), size_zero_node); - } - - tree ret = build_constructor(type_tree, init); - TREE_CONSTANT(ret) = 1; - return ret; -} - -// The type descriptor for the string type. - -Expression* -String_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (name != NULL) - return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name); - else - { - Named_object* no = gogo->lookup_global("string"); - gcc_assert(no != NULL); - return Type::type_descriptor(gogo, no->type_value()); - } -} - -// We should not be asked for the reflection string of a basic type. - -void -String_type::do_reflection(Gogo*, std::string* ret) const -{ - ret->append("string"); -} - -// Mangled name of a string type. - -void -String_type::do_mangled_name(Gogo*, std::string* ret) const -{ - ret->push_back('z'); -} - -// Make a string type. - -Type* -Type::make_string_type() -{ - static String_type string_type; - return &string_type; -} - -// The named type "string". - -static Named_type* named_string_type; - -// Get the named type "string". - -Named_type* -Type::lookup_string_type() -{ - return named_string_type; -} - -// Make the named type string. - -Named_type* -Type::make_named_string_type() -{ - Type* string_type = Type::make_string_type(); - Named_object* named_object = Named_object::make_type("string", NULL, - string_type, - BUILTINS_LOCATION); - Named_type* named_type = named_object->type_value(); - named_string_type = named_type; - return named_type; -} - -// The sink type. This is the type of the blank identifier _. Any -// type may be assigned to it. - -class Sink_type : public Type -{ - public: - Sink_type() - : Type(TYPE_SINK) - { } - - protected: - tree - do_get_tree(Gogo*) - { gcc_unreachable(); } - - tree - do_get_init_tree(Gogo*, tree, bool) - { gcc_unreachable(); } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { gcc_unreachable(); } - - void - do_reflection(Gogo*, std::string*) const - { gcc_unreachable(); } - - void - do_mangled_name(Gogo*, std::string*) const - { gcc_unreachable(); } -}; - -// Make the sink type. - -Type* -Type::make_sink_type() -{ - static Sink_type sink_type; - return &sink_type; -} - -// Class Function_type. - -// Traversal. - -int -Function_type::do_traverse(Traverse* traverse) -{ - if (this->receiver_ != NULL - && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->parameters_ != NULL - && this->parameters_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->results_ != NULL - && this->results_->traverse(traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Returns whether T is a valid redeclaration of this type. If this -// returns false, and REASON is not NULL, *REASON may be set to a -// brief explanation of why it returned false. - -bool -Function_type::is_valid_redeclaration(const Function_type* t, - std::string* reason) const -{ - if (!this->is_identical(t, false, true, reason)) - return false; - - // A redeclaration of a function is required to use the same names - // for the receiver and parameters. - if (this->receiver() != NULL - && this->receiver()->name() != t->receiver()->name() - && this->receiver()->name() != Import::import_marker - && t->receiver()->name() != Import::import_marker) - { - if (reason != NULL) - *reason = "receiver name changed"; - return false; - } - - const Typed_identifier_list* parms1 = this->parameters(); - const Typed_identifier_list* parms2 = t->parameters(); - if (parms1 != NULL) - { - Typed_identifier_list::const_iterator p1 = parms1->begin(); - for (Typed_identifier_list::const_iterator p2 = parms2->begin(); - p2 != parms2->end(); - ++p2, ++p1) - { - if (p1->name() != p2->name() - && p1->name() != Import::import_marker - && p2->name() != Import::import_marker) - { - if (reason != NULL) - *reason = "parameter name changed"; - return false; - } - - // This is called at parse time, so we may have unknown - // types. - Type* t1 = p1->type()->forwarded(); - Type* t2 = p2->type()->forwarded(); - if (t1 != t2 - && t1->forward_declaration_type() != NULL - && (t2->forward_declaration_type() == NULL - || (t1->forward_declaration_type()->named_object() - != t2->forward_declaration_type()->named_object()))) - return false; - } - } - - const Typed_identifier_list* results1 = this->results(); - const Typed_identifier_list* results2 = t->results(); - if (results1 != NULL) - { - Typed_identifier_list::const_iterator res1 = results1->begin(); - for (Typed_identifier_list::const_iterator res2 = results2->begin(); - res2 != results2->end(); - ++res2, ++res1) - { - if (res1->name() != res2->name() - && res1->name() != Import::import_marker - && res2->name() != Import::import_marker) - { - if (reason != NULL) - *reason = "result name changed"; - return false; - } - - // This is called at parse time, so we may have unknown - // types. - Type* t1 = res1->type()->forwarded(); - Type* t2 = res2->type()->forwarded(); - if (t1 != t2 - && t1->forward_declaration_type() != NULL - && (t2->forward_declaration_type() == NULL - || (t1->forward_declaration_type()->named_object() - != t2->forward_declaration_type()->named_object()))) - return false; - } - } - - return true; -} - -// Check whether T is the same as this type. - -bool -Function_type::is_identical(const Function_type* t, bool ignore_receiver, - bool errors_are_identical, - std::string* reason) const -{ - if (!ignore_receiver) - { - const Typed_identifier* r1 = this->receiver(); - const Typed_identifier* r2 = t->receiver(); - if ((r1 != NULL) != (r2 != NULL)) - { - if (reason != NULL) - *reason = _("different receiver types"); - return false; - } - if (r1 != NULL) - { - if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical, - reason)) - { - if (reason != NULL && !reason->empty()) - *reason = "receiver: " + *reason; - return false; - } - } - } - - const Typed_identifier_list* parms1 = this->parameters(); - const Typed_identifier_list* parms2 = t->parameters(); - if ((parms1 != NULL) != (parms2 != NULL)) - { - if (reason != NULL) - *reason = _("different number of parameters"); - return false; - } - if (parms1 != NULL) - { - Typed_identifier_list::const_iterator p1 = parms1->begin(); - for (Typed_identifier_list::const_iterator p2 = parms2->begin(); - p2 != parms2->end(); - ++p2, ++p1) - { - if (p1 == parms1->end()) - { - if (reason != NULL) - *reason = _("different number of parameters"); - return false; - } - - if (!Type::are_identical(p1->type(), p2->type(), - errors_are_identical, NULL)) - { - if (reason != NULL) - *reason = _("different parameter types"); - return false; - } - } - if (p1 != parms1->end()) - { - if (reason != NULL) - *reason = _("different number of parameters"); - return false; - } - } - - if (this->is_varargs() != t->is_varargs()) - { - if (reason != NULL) - *reason = _("different varargs"); - return false; - } - - const Typed_identifier_list* results1 = this->results(); - const Typed_identifier_list* results2 = t->results(); - if ((results1 != NULL) != (results2 != NULL)) - { - if (reason != NULL) - *reason = _("different number of results"); - return false; - } - if (results1 != NULL) - { - Typed_identifier_list::const_iterator res1 = results1->begin(); - for (Typed_identifier_list::const_iterator res2 = results2->begin(); - res2 != results2->end(); - ++res2, ++res1) - { - if (res1 == results1->end()) - { - if (reason != NULL) - *reason = _("different number of results"); - return false; - } - - if (!Type::are_identical(res1->type(), res2->type(), - errors_are_identical, NULL)) - { - if (reason != NULL) - *reason = _("different result types"); - return false; - } - } - if (res1 != results1->end()) - { - if (reason != NULL) - *reason = _("different number of results"); - return false; - } - } - - return true; -} - -// Hash code. - -unsigned int -Function_type::do_hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - // We ignore the receiver type for hash codes, because we need to - // get the same hash code for a method in an interface and a method - // declared for a type. The former will not have a receiver. - if (this->parameters_ != NULL) - { - int shift = 1; - for (Typed_identifier_list::const_iterator p = this->parameters_->begin(); - p != this->parameters_->end(); - ++p, ++shift) - ret += p->type()->hash_for_method(gogo) << shift; - } - if (this->results_ != NULL) - { - int shift = 2; - for (Typed_identifier_list::const_iterator p = this->results_->begin(); - p != this->results_->end(); - ++p, ++shift) - ret += p->type()->hash_for_method(gogo) << shift; - } - if (this->is_varargs_) - ret += 1; - ret <<= 4; - return ret; -} - -// Get the tree for a function type. - -tree -Function_type::do_get_tree(Gogo* gogo) -{ - tree args = NULL_TREE; - tree* pp = &args; - - if (this->receiver_ != NULL) - { - Type* rtype = this->receiver_->type(); - tree ptype = rtype->get_tree(gogo); - if (ptype == error_mark_node) - return error_mark_node; - - // We always pass the address of the receiver parameter, in - // order to make interface calls work with unknown types. - if (rtype->points_to() == NULL) - ptype = build_pointer_type(ptype); - - *pp = tree_cons (NULL_TREE, ptype, NULL_TREE); - pp = &TREE_CHAIN (*pp); - } - - if (this->parameters_ != NULL) - { - for (Typed_identifier_list::const_iterator p = this->parameters_->begin(); - p != this->parameters_->end(); - ++p) - { - tree ptype = p->type()->get_tree(gogo); - if (ptype == error_mark_node) - return error_mark_node; - *pp = tree_cons (NULL_TREE, ptype, NULL_TREE); - pp = &TREE_CHAIN (*pp); - } - } - - // Varargs is handled entirely at the Go level. At the tree level, - // functions are not varargs. - *pp = void_list_node; - - tree result; - if (this->results_ == NULL) - result = void_type_node; - else if (this->results_->size() == 1) - result = this->results_->begin()->type()->get_tree(gogo); - else - { - result = make_node(RECORD_TYPE); - tree field_trees = NULL_TREE; - tree* pp = &field_trees; - for (Typed_identifier_list::const_iterator p = this->results_->begin(); - p != this->results_->end(); - ++p) - { - const std::string name = (p->name().empty() - ? "UNNAMED" - : Gogo::unpack_hidden_name(p->name())); - tree name_tree = get_identifier_with_length(name.data(), - name.length()); - tree field_type_tree = p->type()->get_tree(gogo); - if (field_type_tree == error_mark_node) - return error_mark_node; - tree field = build_decl(this->location_, FIELD_DECL, name_tree, - field_type_tree); - DECL_CONTEXT(field) = result; - *pp = field; - pp = &DECL_CHAIN(field); - } - TYPE_FIELDS(result) = field_trees; - layout_type(result); - } - - if (result == error_mark_node) - return error_mark_node; - - tree fntype = build_function_type(result, args); - if (fntype == error_mark_node) - return fntype; - - return build_pointer_type(fntype); -} - -// Functions are initialized to NULL. - -tree -Function_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - return fold_convert(type_tree, null_pointer_node); -} - -// The type of a function type descriptor. - -Type* -Function_type::make_function_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* bool_type = Type::lookup_bool_type(); - - Type* slice_type = Type::make_array_type(ptdt, NULL); - - Struct_type* s = Type::make_builtin_struct_type(4, - "", tdt, - "dotdotdot", bool_type, - "in", slice_type, - "out", slice_type); - - ret = Type::make_builtin_named_type("FuncType", s); - } - - return ret; -} - -// The type descriptor for a function type. - -Expression* -Function_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* ftdt = Function_type::make_function_type_descriptor_type(); - - const Struct_field_list* fields = ftdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(4); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_FUNC, - name, NULL, true)); - - ++p; - gcc_assert(p->field_name() == "dotdotdot"); - vals->push_back(Expression::make_boolean(this->is_varargs(), bloc)); - - ++p; - gcc_assert(p->field_name() == "in"); - vals->push_back(this->type_descriptor_params(p->type(), this->receiver(), - this->parameters())); - - ++p; - gcc_assert(p->field_name() == "out"); - vals->push_back(this->type_descriptor_params(p->type(), NULL, - this->results())); - - ++p; - gcc_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(ftdt, vals, bloc); -} - -// Return a composite literal for the parameters or results of a type -// descriptor. - -Expression* -Function_type::type_descriptor_params(Type* params_type, - const Typed_identifier* receiver, - const Typed_identifier_list* params) -{ - source_location bloc = BUILTINS_LOCATION; - - if (receiver == NULL && params == NULL) - return Expression::make_slice_composite_literal(params_type, NULL, bloc); - - Expression_list* vals = new Expression_list(); - vals->reserve((params == NULL ? 0 : params->size()) - + (receiver != NULL ? 1 : 0)); - - if (receiver != NULL) - { - Type* rtype = receiver->type(); - // The receiver is always passed as a pointer. FIXME: Is this - // right? Should that fact affect the type descriptor? - if (rtype->points_to() == NULL) - rtype = Type::make_pointer_type(rtype); - vals->push_back(Expression::make_type_descriptor(rtype, bloc)); - } - - if (params != NULL) - { - for (Typed_identifier_list::const_iterator p = params->begin(); - p != params->end(); - ++p) - vals->push_back(Expression::make_type_descriptor(p->type(), bloc)); - } - - return Expression::make_slice_composite_literal(params_type, vals, bloc); -} - -// The reflection string. - -void -Function_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - // FIXME: Turn this off until we straighten out the type of the - // struct field used in a go statement which calls a method. - // gcc_assert(this->receiver_ == NULL); - - ret->append("func"); - - if (this->receiver_ != NULL) - { - ret->push_back('('); - this->append_reflection(this->receiver_->type(), gogo, ret); - ret->push_back(')'); - } - - ret->push_back('('); - const Typed_identifier_list* params = this->parameters(); - if (params != NULL) - { - bool is_varargs = this->is_varargs_; - for (Typed_identifier_list::const_iterator p = params->begin(); - p != params->end(); - ++p) - { - if (p != params->begin()) - ret->append(", "); - if (!is_varargs || p + 1 != params->end()) - this->append_reflection(p->type(), gogo, ret); - else - { - ret->append("..."); - this->append_reflection(p->type()->array_type()->element_type(), - gogo, ret); - } - } - } - ret->push_back(')'); - - const Typed_identifier_list* results = this->results(); - if (results != NULL && !results->empty()) - { - if (results->size() == 1) - ret->push_back(' '); - else - ret->append(" ("); - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p) - { - if (p != results->begin()) - ret->append(", "); - this->append_reflection(p->type(), gogo, ret); - } - if (results->size() > 1) - ret->push_back(')'); - } -} - -// Mangled name. - -void -Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('F'); - - if (this->receiver_ != NULL) - { - ret->push_back('m'); - this->append_mangled_name(this->receiver_->type(), gogo, ret); - } - - const Typed_identifier_list* params = this->parameters(); - if (params != NULL) - { - ret->push_back('p'); - for (Typed_identifier_list::const_iterator p = params->begin(); - p != params->end(); - ++p) - this->append_mangled_name(p->type(), gogo, ret); - if (this->is_varargs_) - ret->push_back('V'); - ret->push_back('e'); - } - - const Typed_identifier_list* results = this->results(); - if (results != NULL) - { - ret->push_back('r'); - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p) - this->append_mangled_name(p->type(), gogo, ret); - ret->push_back('e'); - } - - ret->push_back('e'); -} - -// Export a function type. - -void -Function_type::do_export(Export* exp) const -{ - // We don't write out the receiver. The only function types which - // should have a receiver are the ones associated with explicitly - // defined methods. For those the receiver type is written out by - // Function::export_func. - - exp->write_c_string("("); - bool first = true; - if (this->parameters_ != NULL) - { - bool is_varargs = this->is_varargs_; - for (Typed_identifier_list::const_iterator p = - this->parameters_->begin(); - p != this->parameters_->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - if (!is_varargs || p + 1 != this->parameters_->end()) - exp->write_type(p->type()); - else - { - exp->write_c_string("..."); - exp->write_type(p->type()->array_type()->element_type()); - } - } - } - exp->write_c_string(")"); - - const Typed_identifier_list* results = this->results_; - if (results != NULL) - { - exp->write_c_string(" "); - if (results->size() == 1) - exp->write_type(results->begin()->type()); - else - { - first = true; - exp->write_c_string("("); - for (Typed_identifier_list::const_iterator p = results->begin(); - p != results->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - exp->write_type(p->type()); - } - exp->write_c_string(")"); - } - } -} - -// Import a function type. - -Function_type* -Function_type::do_import(Import* imp) -{ - imp->require_c_string("("); - Typed_identifier_list* parameters; - bool is_varargs = false; - if (imp->peek_char() == ')') - parameters = NULL; - else - { - parameters = new Typed_identifier_list(); - while (true) - { - if (imp->match_c_string("...")) - { - imp->advance(3); - is_varargs = true; - } - - Type* ptype = imp->read_type(); - if (is_varargs) - ptype = Type::make_array_type(ptype, NULL); - parameters->push_back(Typed_identifier(Import::import_marker, - ptype, imp->location())); - if (imp->peek_char() != ',') - break; - gcc_assert(!is_varargs); - imp->require_c_string(", "); - } - } - imp->require_c_string(")"); - - Typed_identifier_list* results; - if (imp->peek_char() != ' ') - results = NULL; - else - { - imp->advance(1); - results = new Typed_identifier_list; - if (imp->peek_char() != '(') - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, rtype, - imp->location())); - } - else - { - imp->advance(1); - while (true) - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, - rtype, imp->location())); - if (imp->peek_char() != ',') - break; - imp->require_c_string(", "); - } - imp->require_c_string(")"); - } - } - - Function_type* ret = Type::make_function_type(NULL, parameters, results, - imp->location()); - if (is_varargs) - ret->set_is_varargs(); - return ret; -} - -// Make a copy of a function type without a receiver. - -Function_type* -Function_type::copy_without_receiver() const -{ - gcc_assert(this->is_method()); - Function_type *ret = Type::make_function_type(NULL, this->parameters_, - this->results_, - this->location_); - if (this->is_varargs()) - ret->set_is_varargs(); - if (this->is_builtin()) - ret->set_is_builtin(); - return ret; -} - -// Make a copy of a function type with a receiver. - -Function_type* -Function_type::copy_with_receiver(Type* receiver_type) const -{ - gcc_assert(!this->is_method()); - Typed_identifier* receiver = new Typed_identifier("", receiver_type, - this->location_); - return Type::make_function_type(receiver, this->parameters_, - this->results_, this->location_); -} - -// Make a function type. - -Function_type* -Type::make_function_type(Typed_identifier* receiver, - Typed_identifier_list* parameters, - Typed_identifier_list* results, - source_location location) -{ - return new Function_type(receiver, parameters, results, location); -} - -// Class Pointer_type. - -// Traversal. - -int -Pointer_type::do_traverse(Traverse* traverse) -{ - return Type::traverse(this->to_type_, traverse); -} - -// Hash code. - -unsigned int -Pointer_type::do_hash_for_method(Gogo* gogo) const -{ - return this->to_type_->hash_for_method(gogo) << 4; -} - -// The tree for a pointer type. - -tree -Pointer_type::do_get_tree(Gogo* gogo) -{ - return build_pointer_type(this->to_type_->get_tree(gogo)); -} - -// Initialize a pointer type. - -tree -Pointer_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - return fold_convert(type_tree, null_pointer_node); -} - -// The type of a pointer type descriptor. - -Type* -Pointer_type::make_pointer_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Struct_type* s = Type::make_builtin_struct_type(2, - "", tdt, - "elem", ptdt); - - ret = Type::make_builtin_named_type("PtrType", s); - } - - return ret; -} - -// The type descriptor for a pointer type. - -Expression* -Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (this->is_unsafe_pointer_type()) - { - gcc_assert(name != NULL); - return this->plain_type_descriptor(gogo, - RUNTIME_TYPE_KIND_UNSAFE_POINTER, - name); - } - else - { - source_location bloc = BUILTINS_LOCATION; - - const Methods* methods; - Type* deref = this->points_to(); - if (deref->named_type() != NULL) - methods = deref->named_type()->methods(); - else if (deref->struct_type() != NULL) - methods = deref->struct_type()->methods(); - else - methods = NULL; - - Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type(); - - const Struct_field_list* fields = ptr_tdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(2); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_PTR, - name, methods, false)); - - ++p; - gcc_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(deref, bloc)); - - return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc); - } -} - -// Reflection string. - -void -Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->push_back('*'); - this->append_reflection(this->to_type_, gogo, ret); -} - -// Mangled name. - -void -Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('p'); - this->append_mangled_name(this->to_type_, gogo, ret); -} - -// Export. - -void -Pointer_type::do_export(Export* exp) const -{ - exp->write_c_string("*"); - if (this->is_unsafe_pointer_type()) - exp->write_c_string("any"); - else - exp->write_type(this->to_type_); -} - -// Import. - -Pointer_type* -Pointer_type::do_import(Import* imp) -{ - imp->require_c_string("*"); - if (imp->match_c_string("any")) - { - imp->advance(3); - return Type::make_pointer_type(Type::make_void_type()); - } - Type* to = imp->read_type(); - return Type::make_pointer_type(to); -} - -// Make a pointer type. - -Pointer_type* -Type::make_pointer_type(Type* to_type) -{ - typedef Unordered_map(Type*, Pointer_type*) Hashtable; - static Hashtable pointer_types; - Hashtable::const_iterator p = pointer_types.find(to_type); - if (p != pointer_types.end()) - return p->second; - Pointer_type* ret = new Pointer_type(to_type); - pointer_types[to_type] = ret; - return ret; -} - -// The nil type. We use a special type for nil because it is not the -// same as any other type. In C term nil has type void*, but there is -// no such type in Go. - -class Nil_type : public Type -{ - public: - Nil_type() - : Type(TYPE_NIL) - { } - - protected: - tree - do_get_tree(Gogo*) - { return ptr_type_node; } - - tree - do_get_init_tree(Gogo*, tree type_tree, bool is_clear) - { return is_clear ? NULL : fold_convert(type_tree, null_pointer_node); } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { gcc_unreachable(); } - - void - do_reflection(Gogo*, std::string*) const - { gcc_unreachable(); } - - void - do_mangled_name(Gogo*, std::string* ret) const - { ret->push_back('n'); } -}; - -// Make the nil type. - -Type* -Type::make_nil_type() -{ - static Nil_type singleton_nil_type; - return &singleton_nil_type; -} - -// The type of a function call which returns multiple values. This is -// really a struct, but we don't want to confuse a function call which -// returns a struct with a function call which returns multiple -// values. - -class Call_multiple_result_type : public Type -{ - public: - Call_multiple_result_type(Call_expression* call) - : Type(TYPE_CALL_MULTIPLE_RESULT), - call_(call) - { } - - protected: - bool - do_has_pointer() const - { - gcc_assert(saw_errors()); - return false; - } - - tree - do_get_tree(Gogo*); - - tree - do_get_init_tree(Gogo*, tree, bool) - { - gcc_assert(saw_errors()); - return error_mark_node; - } - - Expression* - do_type_descriptor(Gogo*, Named_type*) - { - gcc_assert(saw_errors()); - return Expression::make_error(UNKNOWN_LOCATION); - } - - void - do_reflection(Gogo*, std::string*) const - { gcc_assert(saw_errors()); } - - void - do_mangled_name(Gogo*, std::string*) const - { gcc_assert(saw_errors()); } - - private: - // The expression being called. - Call_expression* call_; -}; - -// Return the tree for a call result. - -tree -Call_multiple_result_type::do_get_tree(Gogo* gogo) -{ - Function_type* fntype = this->call_->get_function_type(); - gcc_assert(fntype != NULL); - const Typed_identifier_list* results = fntype->results(); - gcc_assert(results != NULL && results->size() > 1); - tree fntype_tree = fntype->get_tree(gogo); - if (fntype_tree == error_mark_node) - return error_mark_node; - return TREE_TYPE(fntype_tree); -} - -// Make a call result type. - -Type* -Type::make_call_multiple_result_type(Call_expression* call) -{ - return new Call_multiple_result_type(call); -} - -// Class Struct_field. - -// Get the name of a field. - -const std::string& -Struct_field::field_name() const -{ - const std::string& name(this->typed_identifier_.name()); - if (!name.empty()) - return name; - else - { - // This is called during parsing, before anything is lowered, so - // we have to be pretty careful to avoid dereferencing an - // unknown type name. - Type* t = this->typed_identifier_.type(); - Type* dt = t; - if (t->classification() == Type::TYPE_POINTER) - { - // Very ugly. - Pointer_type* ptype = static_cast(t); - dt = ptype->points_to(); - } - if (dt->forward_declaration_type() != NULL) - return dt->forward_declaration_type()->name(); - else if (dt->named_type() != NULL) - return dt->named_type()->name(); - else if (t->is_error_type() || dt->is_error_type()) - { - static const std::string error_string = "*error*"; - return error_string; - } - else - { - // Avoid crashing in the erroneous case where T is named but - // DT is not. - gcc_assert(t != dt); - if (t->forward_declaration_type() != NULL) - return t->forward_declaration_type()->name(); - else if (t->named_type() != NULL) - return t->named_type()->name(); - else - gcc_unreachable(); - } - } -} - -// Class Struct_type. - -// Traversal. - -int -Struct_type::do_traverse(Traverse* traverse) -{ - Struct_field_list* fields = this->fields_; - if (fields != NULL) - { - for (Struct_field_list::iterator p = fields->begin(); - p != fields->end(); - ++p) - { - if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - return TRAVERSE_CONTINUE; -} - -// Verify that the struct type is complete and valid. - -bool -Struct_type::do_verify() -{ - Struct_field_list* fields = this->fields_; - if (fields == NULL) - return true; - bool ret = true; - for (Struct_field_list::iterator p = fields->begin(); - p != fields->end(); - ++p) - { - Type* t = p->type(); - if (t->is_undefined()) - { - error_at(p->location(), "struct field type is incomplete"); - p->set_type(Type::make_error_type()); - ret = false; - } - else if (p->is_anonymous()) - { - if (t->named_type() != NULL && t->points_to() != NULL) - { - error_at(p->location(), "embedded type may not be a pointer"); - p->set_type(Type::make_error_type()); - return false; - } - } - } - return ret; -} - -// Whether this contains a pointer. - -bool -Struct_type::do_has_pointer() const -{ - const Struct_field_list* fields = this->fields(); - if (fields == NULL) - return false; - for (Struct_field_list::const_iterator p = fields->begin(); - p != fields->end(); - ++p) - { - if (p->type()->has_pointer()) - return true; - } - return false; -} - -// Whether this type is identical to T. - -bool -Struct_type::is_identical(const Struct_type* t, - bool errors_are_identical) const -{ - const Struct_field_list* fields1 = this->fields(); - const Struct_field_list* fields2 = t->fields(); - if (fields1 == NULL || fields2 == NULL) - return fields1 == fields2; - Struct_field_list::const_iterator pf2 = fields2->begin(); - for (Struct_field_list::const_iterator pf1 = fields1->begin(); - pf1 != fields1->end(); - ++pf1, ++pf2) - { - if (pf2 == fields2->end()) - return false; - if (pf1->field_name() != pf2->field_name()) - return false; - if (pf1->is_anonymous() != pf2->is_anonymous() - || !Type::are_identical(pf1->type(), pf2->type(), - errors_are_identical, NULL)) - return false; - if (!pf1->has_tag()) - { - if (pf2->has_tag()) - return false; - } - else - { - if (!pf2->has_tag()) - return false; - if (pf1->tag() != pf2->tag()) - return false; - } - } - if (pf2 != fields2->end()) - return false; - return true; -} - -// Whether this struct type has any hidden fields. - -bool -Struct_type::struct_has_hidden_fields(const Named_type* within, - std::string* reason) const -{ - const Struct_field_list* fields = this->fields(); - if (fields == NULL) - return false; - const Package* within_package = (within == NULL - ? NULL - : within->named_object()->package()); - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - if (within_package != NULL - && !pf->is_anonymous() - && Gogo::is_hidden_name(pf->field_name())) - { - if (reason != NULL) - { - std::string within_name = within->named_object()->message_name(); - std::string name = Gogo::message_name(pf->field_name()); - size_t bufsize = 200 + within_name.length() + name.length(); - char* buf = new char[bufsize]; - snprintf(buf, bufsize, - _("implicit assignment of %s%s%s hidden field %s%s%s"), - open_quote, within_name.c_str(), close_quote, - open_quote, name.c_str(), close_quote); - reason->assign(buf); - delete[] buf; - } - return true; - } - - if (pf->type()->has_hidden_fields(within, reason)) - return true; - } - - return false; -} - -// Hash code. - -unsigned int -Struct_type::do_hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - if (this->fields() != NULL) - { - for (Struct_field_list::const_iterator pf = this->fields()->begin(); - pf != this->fields()->end(); - ++pf) - ret = (ret << 1) + pf->type()->hash_for_method(gogo); - } - return ret <<= 2; -} - -// Find the local field NAME. - -const Struct_field* -Struct_type::find_local_field(const std::string& name, - unsigned int *pindex) const -{ - const Struct_field_list* fields = this->fields_; - if (fields == NULL) - return NULL; - unsigned int i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++i) - { - if (pf->field_name() == name) - { - if (pindex != NULL) - *pindex = i; - return &*pf; - } - } - return NULL; -} - -// Return an expression for field NAME in STRUCT_EXPR, or NULL. - -Field_reference_expression* -Struct_type::field_reference(Expression* struct_expr, const std::string& name, - source_location location) const -{ - unsigned int depth; - return this->field_reference_depth(struct_expr, name, location, NULL, - &depth); -} - -// Return an expression for a field, along with the depth at which it -// was found. - -Field_reference_expression* -Struct_type::field_reference_depth(Expression* struct_expr, - const std::string& name, - source_location location, - Saw_named_type* saw, - unsigned int* depth) const -{ - const Struct_field_list* fields = this->fields_; - if (fields == NULL) - return NULL; - - // Look for a field with this name. - unsigned int i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++i) - { - if (pf->field_name() == name) - { - *depth = 0; - return Expression::make_field_reference(struct_expr, i, location); - } - } - - // Look for an anonymous field which contains a field with this - // name. - unsigned int found_depth = 0; - Field_reference_expression* ret = NULL; - i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++i) - { - if (!pf->is_anonymous()) - continue; - - Struct_type* st = pf->type()->deref()->struct_type(); - if (st == NULL) - continue; - - Saw_named_type* hold_saw = saw; - Saw_named_type saw_here; - Named_type* nt = pf->type()->named_type(); - if (nt == NULL) - nt = pf->type()->deref()->named_type(); - if (nt != NULL) - { - Saw_named_type* q; - for (q = saw; q != NULL; q = q->next) - { - if (q->nt == nt) - { - // If this is an error, it will be reported - // elsewhere. - break; - } - } - if (q != NULL) - continue; - saw_here.next = saw; - saw_here.nt = nt; - saw = &saw_here; - } - - // Look for a reference using a NULL struct expression. If we - // find one, fill in the struct expression with a reference to - // this field. - unsigned int subdepth; - Field_reference_expression* sub = st->field_reference_depth(NULL, name, - location, - saw, - &subdepth); - - saw = hold_saw; - - if (sub == NULL) - continue; - - if (ret == NULL || subdepth < found_depth) - { - if (ret != NULL) - delete ret; - ret = sub; - found_depth = subdepth; - Expression* here = Expression::make_field_reference(struct_expr, i, - location); - if (pf->type()->points_to() != NULL) - here = Expression::make_unary(OPERATOR_MULT, here, location); - while (sub->expr() != NULL) - { - sub = sub->expr()->deref()->field_reference_expression(); - gcc_assert(sub != NULL); - } - sub->set_struct_expression(here); - } - else if (subdepth > found_depth) - delete sub; - else - { - // We do not handle ambiguity here--it should be handled by - // Type::bind_field_or_method. - delete sub; - found_depth = 0; - ret = NULL; - } - } - - if (ret != NULL) - *depth = found_depth + 1; - - return ret; -} - -// Return the total number of fields, including embedded fields. - -unsigned int -Struct_type::total_field_count() const -{ - if (this->fields_ == NULL) - return 0; - unsigned int ret = 0; - for (Struct_field_list::const_iterator pf = this->fields_->begin(); - pf != this->fields_->end(); - ++pf) - { - if (!pf->is_anonymous() || pf->type()->deref()->struct_type() == NULL) - ++ret; - else - ret += pf->type()->struct_type()->total_field_count(); - } - return ret; -} - -// Return whether NAME is an unexported field, for better error reporting. - -bool -Struct_type::is_unexported_local_field(Gogo* gogo, - const std::string& name) const -{ - const Struct_field_list* fields = this->fields_; - if (fields != NULL) - { - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - const std::string& field_name(pf->field_name()); - if (Gogo::is_hidden_name(field_name) - && name == Gogo::unpack_hidden_name(field_name) - && gogo->pack_hidden_name(name, false) != field_name) - return true; - } - } - return false; -} - -// Finalize the methods of an unnamed struct. - -void -Struct_type::finalize_methods(Gogo* gogo) -{ - if (this->all_methods_ != NULL) - return; - Type::finalize_methods(gogo, this, this->location_, &this->all_methods_); -} - -// Return the method NAME, or NULL if there isn't one or if it is -// ambiguous. Set *IS_AMBIGUOUS if the method exists but is -// ambiguous. - -Method* -Struct_type::method_function(const std::string& name, bool* is_ambiguous) const -{ - return Type::method_function(this->all_methods_, name, is_ambiguous); -} - -// Get the tree for a struct type. - -tree -Struct_type::do_get_tree(Gogo* gogo) -{ - tree type = make_node(RECORD_TYPE); - return this->fill_in_tree(gogo, type); -} - -// Fill in the fields for a struct type. - -tree -Struct_type::fill_in_tree(Gogo* gogo, tree type) -{ - tree field_trees = NULL_TREE; - tree* pp = &field_trees; - for (Struct_field_list::const_iterator p = this->fields_->begin(); - p != this->fields_->end(); - ++p) - { - std::string name = Gogo::unpack_hidden_name(p->field_name()); - tree name_tree = get_identifier_with_length(name.data(), name.length()); - - tree field_type_tree = p->type()->get_tree(gogo); - if (field_type_tree == error_mark_node) - return error_mark_node; - gcc_assert(TYPE_SIZE(field_type_tree) != NULL_TREE); - - tree field = build_decl(p->location(), FIELD_DECL, name_tree, - field_type_tree); - DECL_CONTEXT(field) = type; - *pp = field; - pp = &DECL_CHAIN(field); - } - - TYPE_FIELDS(type) = field_trees; - - layout_type(type); - - return type; -} - -// Initialize struct fields. - -tree -Struct_type::do_get_init_tree(Gogo* gogo, tree type_tree, bool is_clear) -{ - if (this->fields_ == NULL || this->fields_->empty()) - { - if (is_clear) - return NULL; - else - { - tree ret = build_constructor(type_tree, - VEC_alloc(constructor_elt, gc, 0)); - TREE_CONSTANT(ret) = 1; - return ret; - } - } - - bool is_constant = true; - bool any_fields_set = false; - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, - this->fields_->size()); - - tree field = TYPE_FIELDS(type_tree); - for (Struct_field_list::const_iterator p = this->fields_->begin(); - p != this->fields_->end(); - ++p, field = DECL_CHAIN(field)) - { - tree value = p->type()->get_init_tree(gogo, is_clear); - if (value == error_mark_node) - return error_mark_node; - gcc_assert(field != NULL_TREE); - if (value != NULL) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = value; - any_fields_set = true; - if (!TREE_CONSTANT(value)) - is_constant = false; - } - } - gcc_assert(field == NULL_TREE); - - if (!any_fields_set) - { - gcc_assert(is_clear); - VEC_free(constructor_elt, gc, init); - return NULL; - } - - tree ret = build_constructor(type_tree, init); - if (is_constant) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// The type of a struct type descriptor. - -Type* -Struct_type::make_struct_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* uintptr_type = Type::lookup_integer_type("uintptr"); - Type* string_type = Type::lookup_string_type(); - Type* pointer_string_type = Type::make_pointer_type(string_type); - - Struct_type* sf = - Type::make_builtin_struct_type(5, - "name", pointer_string_type, - "pkgPath", pointer_string_type, - "typ", ptdt, - "tag", pointer_string_type, - "offset", uintptr_type); - Type* nsf = Type::make_builtin_named_type("structField", sf); - - Type* slice_type = Type::make_array_type(nsf, NULL); - - Struct_type* s = Type::make_builtin_struct_type(2, - "", tdt, - "fields", slice_type); - - ret = Type::make_builtin_named_type("StructType", s); - } - - return ret; -} - -// Build a type descriptor for a struct type. - -Expression* -Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* stdt = Struct_type::make_struct_type_descriptor_type(); - - const Struct_field_list* fields = stdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(2); - - const Methods* methods = this->methods(); - // A named struct should not have methods--the methods should attach - // to the named type. - gcc_assert(methods == NULL || name == NULL); - - Struct_field_list::const_iterator ps = fields->begin(); - gcc_assert(ps->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_STRUCT, - name, methods, true)); - - ++ps; - gcc_assert(ps->field_name() == "fields"); - - Expression_list* elements = new Expression_list(); - elements->reserve(this->fields_->size()); - Type* element_type = ps->type()->array_type()->element_type(); - for (Struct_field_list::const_iterator pf = this->fields_->begin(); - pf != this->fields_->end(); - ++pf) - { - const Struct_field_list* f = element_type->struct_type()->fields(); - - Expression_list* fvals = new Expression_list(); - fvals->reserve(5); - - Struct_field_list::const_iterator q = f->begin(); - gcc_assert(q->field_name() == "name"); - if (pf->is_anonymous()) - fvals->push_back(Expression::make_nil(bloc)); - else - { - std::string n = Gogo::unpack_hidden_name(pf->field_name()); - Expression* s = Expression::make_string(n, bloc); - fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - - ++q; - gcc_assert(q->field_name() == "pkgPath"); - if (!Gogo::is_hidden_name(pf->field_name())) - fvals->push_back(Expression::make_nil(bloc)); - else - { - std::string n = Gogo::hidden_name_prefix(pf->field_name()); - Expression* s = Expression::make_string(n, bloc); - fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - - ++q; - gcc_assert(q->field_name() == "typ"); - fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc)); - - ++q; - gcc_assert(q->field_name() == "tag"); - if (!pf->has_tag()) - fvals->push_back(Expression::make_nil(bloc)); - else - { - Expression* s = Expression::make_string(pf->tag(), bloc); - fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc)); - } - - ++q; - gcc_assert(q->field_name() == "offset"); - fvals->push_back(Expression::make_struct_field_offset(this, &*pf)); - - Expression* v = Expression::make_struct_composite_literal(element_type, - fvals, bloc); - elements->push_back(v); - } - - vals->push_back(Expression::make_slice_composite_literal(ps->type(), - elements, bloc)); - - return Expression::make_struct_composite_literal(stdt, vals, bloc); -} - -// Reflection string. - -void -Struct_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->append("struct { "); - - for (Struct_field_list::const_iterator p = this->fields_->begin(); - p != this->fields_->end(); - ++p) - { - if (p != this->fields_->begin()) - ret->append("; "); - if (p->is_anonymous()) - ret->push_back('?'); - else - ret->append(Gogo::unpack_hidden_name(p->field_name())); - ret->push_back(' '); - this->append_reflection(p->type(), gogo, ret); - - if (p->has_tag()) - { - const std::string& tag(p->tag()); - ret->append(" \""); - for (std::string::const_iterator p = tag.begin(); - p != tag.end(); - ++p) - { - if (*p == '\0') - ret->append("\\x00"); - else if (*p == '\n') - ret->append("\\n"); - else if (*p == '\t') - ret->append("\\t"); - else if (*p == '"') - ret->append("\\\""); - else if (*p == '\\') - ret->append("\\\\"); - else - ret->push_back(*p); - } - ret->push_back('"'); - } - } - - ret->append(" }"); -} - -// Mangled name. - -void -Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('S'); - - const Struct_field_list* fields = this->fields_; - if (fields != NULL) - { - for (Struct_field_list::const_iterator p = fields->begin(); - p != fields->end(); - ++p) - { - if (p->is_anonymous()) - ret->append("0_"); - else - { - std::string n = Gogo::unpack_hidden_name(p->field_name()); - char buf[20]; - snprintf(buf, sizeof buf, "%u_", - static_cast(n.length())); - ret->append(buf); - ret->append(n); - } - this->append_mangled_name(p->type(), gogo, ret); - if (p->has_tag()) - { - const std::string& tag(p->tag()); - std::string out; - for (std::string::const_iterator p = tag.begin(); - p != tag.end(); - ++p) - { - if (ISALNUM(*p) || *p == '_') - out.push_back(*p); - else - { - char buf[20]; - snprintf(buf, sizeof buf, ".%x.", - static_cast(*p)); - out.append(buf); - } - } - char buf[20]; - snprintf(buf, sizeof buf, "T%u_", - static_cast(out.length())); - ret->append(buf); - ret->append(out); - } - } - } - - ret->push_back('e'); -} - -// Export. - -void -Struct_type::do_export(Export* exp) const -{ - exp->write_c_string("struct { "); - const Struct_field_list* fields = this->fields_; - gcc_assert(fields != NULL); - for (Struct_field_list::const_iterator p = fields->begin(); - p != fields->end(); - ++p) - { - if (p->is_anonymous()) - exp->write_string("? "); - else - { - exp->write_string(p->field_name()); - exp->write_c_string(" "); - } - exp->write_type(p->type()); - - if (p->has_tag()) - { - exp->write_c_string(" "); - Expression* expr = Expression::make_string(p->tag(), - BUILTINS_LOCATION); - expr->export_expression(exp); - delete expr; - } - - exp->write_c_string("; "); - } - exp->write_c_string("}"); -} - -// Import. - -Struct_type* -Struct_type::do_import(Import* imp) -{ - imp->require_c_string("struct { "); - Struct_field_list* fields = new Struct_field_list; - if (imp->peek_char() != '}') - { - while (true) - { - std::string name; - if (imp->match_c_string("? ")) - imp->advance(2); - else - { - name = imp->read_identifier(); - imp->require_c_string(" "); - } - Type* ftype = imp->read_type(); - - Struct_field sf(Typed_identifier(name, ftype, imp->location())); - - if (imp->peek_char() == ' ') - { - imp->advance(1); - Expression* expr = Expression::import_expression(imp); - String_expression* sexpr = expr->string_expression(); - gcc_assert(sexpr != NULL); - sf.set_tag(sexpr->val()); - delete sexpr; - } - - imp->require_c_string("; "); - fields->push_back(sf); - if (imp->peek_char() == '}') - break; - } - } - imp->require_c_string("}"); - - return Type::make_struct_type(fields, imp->location()); -} - -// Make a struct type. - -Struct_type* -Type::make_struct_type(Struct_field_list* fields, - source_location location) -{ - return new Struct_type(fields, location); -} - -// Class Array_type. - -// Whether two array types are identical. - -bool -Array_type::is_identical(const Array_type* t, bool errors_are_identical) const -{ - if (!Type::are_identical(this->element_type(), t->element_type(), - errors_are_identical, NULL)) - return false; - - Expression* l1 = this->length(); - Expression* l2 = t->length(); - - // Slices of the same element type are identical. - if (l1 == NULL && l2 == NULL) - return true; - - // Arrays of the same element type are identical if they have the - // same length. - if (l1 != NULL && l2 != NULL) - { - if (l1 == l2) - return true; - - // Try to determine the lengths. If we can't, assume the arrays - // are not identical. - bool ret = false; - mpz_t v1; - mpz_init(v1); - Type* type1; - mpz_t v2; - mpz_init(v2); - Type* type2; - if (l1->integer_constant_value(true, v1, &type1) - && l2->integer_constant_value(true, v2, &type2)) - ret = mpz_cmp(v1, v2) == 0; - mpz_clear(v1); - mpz_clear(v2); - return ret; - } - - // Otherwise the arrays are not identical. - return false; -} - -// Traversal. - -int -Array_type::do_traverse(Traverse* traverse) -{ - if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - if (this->length_ != NULL - && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Check that the length is valid. - -bool -Array_type::verify_length() -{ - if (this->length_ == NULL) - return true; - - Type_context context(Type::lookup_integer_type("int"), false); - this->length_->determine_type(&context); - - if (!this->length_->is_constant()) - { - error_at(this->length_->location(), "array bound is not constant"); - return false; - } - - mpz_t val; - mpz_init(val); - Type* vt; - if (!this->length_->integer_constant_value(true, val, &vt)) - { - mpfr_t fval; - mpfr_init(fval); - if (!this->length_->float_constant_value(fval, &vt)) - { - if (this->length_->type()->integer_type() != NULL - || this->length_->type()->float_type() != NULL) - error_at(this->length_->location(), - "array bound is not constant"); - else - error_at(this->length_->location(), - "array bound is not numeric"); - mpfr_clear(fval); - mpz_clear(val); - return false; - } - if (!mpfr_integer_p(fval)) - { - error_at(this->length_->location(), - "array bound truncated to integer"); - mpfr_clear(fval); - mpz_clear(val); - return false; - } - mpz_init(val); - mpfr_get_z(val, fval, GMP_RNDN); - mpfr_clear(fval); - } - - if (mpz_sgn(val) < 0) - { - error_at(this->length_->location(), "negative array bound"); - mpz_clear(val); - return false; - } - - Type* int_type = Type::lookup_integer_type("int"); - int tbits = int_type->integer_type()->bits(); - int vbits = mpz_sizeinbase(val, 2); - if (vbits + 1 > tbits) - { - error_at(this->length_->location(), "array bound overflows"); - mpz_clear(val); - return false; - } - - mpz_clear(val); - - return true; -} - -// Verify the type. - -bool -Array_type::do_verify() -{ - if (!this->verify_length()) - { - this->length_ = Expression::make_error(this->length_->location()); - return false; - } - return true; -} - -// Array type hash code. - -unsigned int -Array_type::do_hash_for_method(Gogo* gogo) const -{ - // There is no very convenient way to get a hash code for the - // length. - return this->element_type_->hash_for_method(gogo) + 1; -} - -// See if the expression passed to make is suitable. The first -// argument is required, and gives the length. An optional second -// argument is permitted for the capacity. - -bool -Array_type::do_check_make_expression(Expression_list* args, - source_location location) -{ - gcc_assert(this->length_ == NULL); - if (args == NULL || args->empty()) - { - error_at(location, "length required when allocating a slice"); - return false; - } - else if (args->size() > 2) - { - error_at(location, "too many expressions passed to make"); - return false; - } - else - { - if (!Type::check_int_value(args->front(), - _("bad length when making slice"), location)) - return false; - - if (args->size() > 1) - { - if (!Type::check_int_value(args->back(), - _("bad capacity when making slice"), - location)) - return false; - } - - return true; - } -} - -// Get a tree for the length of a fixed array. The length may be -// computed using a function call, so we must only evaluate it once. - -tree -Array_type::get_length_tree(Gogo* gogo) -{ - gcc_assert(this->length_ != NULL); - if (this->length_tree_ == NULL_TREE) - { - mpz_t val; - mpz_init(val); - Type* t; - if (this->length_->integer_constant_value(true, val, &t)) - { - if (t == NULL) - t = Type::lookup_integer_type("int"); - else if (t->is_abstract()) - t = t->make_non_abstract_type(); - tree tt = t->get_tree(gogo); - this->length_tree_ = Expression::integer_constant_tree(val, tt); - mpz_clear(val); - } - else - { - mpz_clear(val); - - // Make up a translation context for the array length - // expression. FIXME: This won't work in general. - Translate_context context(gogo, NULL, NULL, NULL_TREE); - tree len = this->length_->get_tree(&context); - if (len != error_mark_node) - { - len = convert_to_integer(integer_type_node, len); - len = save_expr(len); - } - this->length_tree_ = len; - } - } - return this->length_tree_; -} - -// Get a tree for the type of this array. A fixed array is simply -// represented as ARRAY_TYPE with the appropriate index--i.e., it is -// just like an array in C. An open array is a struct with three -// fields: a data pointer, the length, and the capacity. - -tree -Array_type::do_get_tree(Gogo* gogo) -{ - if (this->length_ == NULL) - { - tree struct_type = gogo->slice_type_tree(void_type_node); - return this->fill_in_slice_tree(gogo, struct_type); - } - else - { - tree array_type = make_node(ARRAY_TYPE); - return this->fill_in_array_tree(gogo, array_type); - } -} - -// Fill in the fields for an array type. This is used for named array -// types. - -tree -Array_type::fill_in_array_tree(Gogo* gogo, tree array_type) -{ - gcc_assert(this->length_ != NULL); - - tree element_type_tree = this->element_type_->get_tree(gogo); - tree length_tree = this->get_length_tree(gogo); - if (element_type_tree == error_mark_node - || length_tree == error_mark_node) - return error_mark_node; - - gcc_assert(TYPE_SIZE(element_type_tree) != NULL_TREE); - - length_tree = fold_convert(sizetype, length_tree); - - // build_index_type takes the maximum index, which is one less than - // the length. - tree index_type = build_index_type(fold_build2(MINUS_EXPR, sizetype, - length_tree, - size_one_node)); - - TREE_TYPE(array_type) = element_type_tree; - TYPE_DOMAIN(array_type) = index_type; - TYPE_ADDR_SPACE(array_type) = TYPE_ADDR_SPACE(element_type_tree); - layout_type(array_type); - - if (TYPE_STRUCTURAL_EQUALITY_P(element_type_tree) - || TYPE_STRUCTURAL_EQUALITY_P(index_type)) - SET_TYPE_STRUCTURAL_EQUALITY(array_type); - else if (TYPE_CANONICAL(element_type_tree) != element_type_tree - || TYPE_CANONICAL(index_type) != index_type) - TYPE_CANONICAL(array_type) = - build_array_type(TYPE_CANONICAL(element_type_tree), - TYPE_CANONICAL(index_type)); - - return array_type; -} - -// Fill in the fields for a slice type. This is used for named slice -// types. - -tree -Array_type::fill_in_slice_tree(Gogo* gogo, tree struct_type) -{ - gcc_assert(this->length_ == NULL); - - tree element_type_tree = this->element_type_->get_tree(gogo); - if (element_type_tree == error_mark_node) - return error_mark_node; - tree field = TYPE_FIELDS(struct_type); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0); - gcc_assert(POINTER_TYPE_P(TREE_TYPE(field)) - && TREE_TYPE(TREE_TYPE(field)) == void_type_node); - TREE_TYPE(field) = build_pointer_type(element_type_tree); - - return struct_type; -} - -// Return an initializer for an array type. - -tree -Array_type::do_get_init_tree(Gogo* gogo, tree type_tree, bool is_clear) -{ - if (this->length_ == NULL) - { - // Open array. - - if (is_clear) - return NULL; - - gcc_assert(TREE_CODE(type_tree) == RECORD_TYPE); - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3); - - for (tree field = TYPE_FIELDS(type_tree); - field != NULL_TREE; - field = DECL_CHAIN(field)) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, init, - NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), size_zero_node); - } - - tree ret = build_constructor(type_tree, init); - TREE_CONSTANT(ret) = 1; - return ret; - } - else - { - // Fixed array. - - tree value = this->element_type_->get_init_tree(gogo, is_clear); - if (value == NULL) - return NULL; - if (value == error_mark_node) - return error_mark_node; - - tree length_tree = this->get_length_tree(gogo); - if (length_tree == error_mark_node) - return error_mark_node; - - length_tree = fold_convert(sizetype, length_tree); - tree range = build2(RANGE_EXPR, sizetype, size_zero_node, - fold_build2(MINUS_EXPR, sizetype, - length_tree, size_one_node)); - tree ret = build_constructor_single(type_tree, range, value); - if (TREE_CONSTANT(value)) - TREE_CONSTANT(ret) = 1; - return ret; - } -} - -// Handle the builtin make function for a slice. - -tree -Array_type::do_make_expression_tree(Translate_context* context, - Expression_list* args, - source_location location) -{ - gcc_assert(this->length_ == NULL); - - Gogo* gogo = context->gogo(); - tree type_tree = this->get_tree(gogo); - if (type_tree == error_mark_node) - return error_mark_node; - - tree values_field = TYPE_FIELDS(type_tree); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(values_field)), - "__values") == 0); - - tree count_field = DECL_CHAIN(values_field); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(count_field)), - "__count") == 0); - - tree element_type_tree = this->element_type_->get_tree(gogo); - if (element_type_tree == error_mark_node) - return error_mark_node; - tree element_size_tree = TYPE_SIZE_UNIT(element_type_tree); - - tree value = this->element_type_->get_init_tree(gogo, true); - if (value == error_mark_node) - return error_mark_node; - - // The first argument is the number of elements, the optional second - // argument is the capacity. - gcc_assert(args != NULL && args->size() >= 1 && args->size() <= 2); - - tree length_tree = args->front()->get_tree(context); - if (length_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(length_tree)) - length_tree = save_expr(length_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(length_tree))) - length_tree = convert_to_integer(TREE_TYPE(count_field), length_tree); - - tree bad_index = Expression::check_bounds(length_tree, - TREE_TYPE(count_field), - NULL_TREE, location); - - length_tree = fold_convert_loc(location, TREE_TYPE(count_field), length_tree); - tree capacity_tree; - if (args->size() == 1) - capacity_tree = length_tree; - else - { - capacity_tree = args->back()->get_tree(context); - if (capacity_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(capacity_tree)) - capacity_tree = save_expr(capacity_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(capacity_tree))) - capacity_tree = convert_to_integer(TREE_TYPE(count_field), - capacity_tree); - - bad_index = Expression::check_bounds(capacity_tree, - TREE_TYPE(count_field), - bad_index, location); - - tree chktype = (((TYPE_SIZE(TREE_TYPE(capacity_tree)) - > TYPE_SIZE(TREE_TYPE(length_tree))) - || ((TYPE_SIZE(TREE_TYPE(capacity_tree)) - == TYPE_SIZE(TREE_TYPE(length_tree))) - && TYPE_UNSIGNED(TREE_TYPE(capacity_tree)))) - ? TREE_TYPE(capacity_tree) - : TREE_TYPE(length_tree)); - tree chk = fold_build2_loc(location, LT_EXPR, boolean_type_node, - fold_convert_loc(location, chktype, - capacity_tree), - fold_convert_loc(location, chktype, - length_tree)); - if (bad_index == NULL_TREE) - bad_index = chk; - else - bad_index = fold_build2_loc(location, TRUTH_OR_EXPR, boolean_type_node, - bad_index, chk); - - capacity_tree = fold_convert_loc(location, TREE_TYPE(count_field), - capacity_tree); - } - - tree size_tree = fold_build2_loc(location, MULT_EXPR, sizetype, - element_size_tree, - fold_convert_loc(location, sizetype, - capacity_tree)); - - tree chk = fold_build2_loc(location, TRUTH_AND_EXPR, boolean_type_node, - fold_build2_loc(location, GT_EXPR, - boolean_type_node, - fold_convert_loc(location, - sizetype, - capacity_tree), - size_zero_node), - fold_build2_loc(location, LT_EXPR, - boolean_type_node, - size_tree, element_size_tree)); - if (bad_index == NULL_TREE) - bad_index = chk; - else - bad_index = fold_build2_loc(location, TRUTH_OR_EXPR, boolean_type_node, - bad_index, chk); - - tree space = context->gogo()->allocate_memory(this->element_type_, - size_tree, location); - - if (value != NULL_TREE) - space = save_expr(space); - - space = fold_convert(TREE_TYPE(values_field), space); - - if (bad_index != NULL_TREE && bad_index != boolean_false_node) - { - tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_SLICE_OUT_OF_BOUNDS, - location); - space = build2(COMPOUND_EXPR, TREE_TYPE(space), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - space); - } - - tree constructor = gogo->slice_constructor(type_tree, space, length_tree, - capacity_tree); - - if (value == NULL_TREE) - { - // The array contents are zero initialized. - return constructor; - } - - // The elements must be initialized. - - tree max = fold_build2_loc(location, MINUS_EXPR, TREE_TYPE(count_field), - capacity_tree, - fold_convert_loc(location, TREE_TYPE(count_field), - integer_one_node)); - - tree array_type = build_array_type(element_type_tree, - build_index_type(max)); - - tree value_pointer = fold_convert_loc(location, - build_pointer_type(array_type), - space); - - tree range = build2(RANGE_EXPR, sizetype, size_zero_node, max); - tree space_init = build_constructor_single(array_type, range, value); - - return build2(COMPOUND_EXPR, TREE_TYPE(constructor), - build2(MODIFY_EXPR, void_type_node, - build_fold_indirect_ref(value_pointer), - space_init), - constructor); -} - -// Return a tree for a pointer to the values in ARRAY. - -tree -Array_type::value_pointer_tree(Gogo*, tree array) const -{ - tree ret; - if (this->length() != NULL) - { - // Fixed array. - ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))), - build_fold_addr_expr(array)); - } - else - { - // Open array. - tree field = TYPE_FIELDS(TREE_TYPE(array)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), - "__values") == 0); - ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field, - NULL_TREE); - } - if (TREE_CONSTANT(array)) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Return a tree for the length of the array ARRAY which has this -// type. - -tree -Array_type::length_tree(Gogo* gogo, tree array) -{ - if (this->length_ != NULL) - { - if (TREE_CODE(array) == SAVE_EXPR) - return fold_convert(integer_type_node, this->get_length_tree(gogo)); - else - return omit_one_operand(integer_type_node, - this->get_length_tree(gogo), array); - } - - // This is an open array. We need to read the length field. - - tree type = TREE_TYPE(array); - gcc_assert(TREE_CODE(type) == RECORD_TYPE); - - tree field = DECL_CHAIN(TYPE_FIELDS(type)); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0); - - tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE); - if (TREE_CONSTANT(array)) - TREE_CONSTANT(ret) = 1; - return ret; -} - -// Return a tree for the capacity of the array ARRAY which has this -// type. - -tree -Array_type::capacity_tree(Gogo* gogo, tree array) -{ - if (this->length_ != NULL) - return omit_one_operand(sizetype, this->get_length_tree(gogo), array); - - // This is an open array. We need to read the capacity field. - - tree type = TREE_TYPE(array); - gcc_assert(TREE_CODE(type) == RECORD_TYPE); - - tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type))); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0); - - return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE); -} - -// Export. - -void -Array_type::do_export(Export* exp) const -{ - exp->write_c_string("["); - if (this->length_ != NULL) - this->length_->export_expression(exp); - exp->write_c_string("] "); - exp->write_type(this->element_type_); -} - -// Import. - -Array_type* -Array_type::do_import(Import* imp) -{ - imp->require_c_string("["); - Expression* length; - if (imp->peek_char() == ']') - length = NULL; - else - length = Expression::import_expression(imp); - imp->require_c_string("] "); - Type* element_type = imp->read_type(); - return Type::make_array_type(element_type, length); -} - -// The type of an array type descriptor. - -Type* -Array_type::make_array_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* uintptr_type = Type::lookup_integer_type("uintptr"); - - Struct_type* sf = - Type::make_builtin_struct_type(3, - "", tdt, - "elem", ptdt, - "len", uintptr_type); - - ret = Type::make_builtin_named_type("ArrayType", sf); - } - - return ret; -} - -// The type of an slice type descriptor. - -Type* -Array_type::make_slice_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Struct_type* sf = - Type::make_builtin_struct_type(2, - "", tdt, - "elem", ptdt); - - ret = Type::make_builtin_named_type("SliceType", sf); - } - - return ret; -} - -// Build a type descriptor for an array/slice type. - -Expression* -Array_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (this->length_ != NULL) - return this->array_type_descriptor(gogo, name); - else - return this->slice_type_descriptor(gogo, name); -} - -// Build a type descriptor for an array type. - -Expression* -Array_type::array_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* atdt = Array_type::make_array_type_descriptor_type(); - - const Struct_field_list* fields = atdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(3); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_ARRAY, - name, NULL, true)); - - ++p; - gcc_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc)); - - ++p; - gcc_assert(p->field_name() == "len"); - vals->push_back(Expression::make_cast(p->type(), this->length_, bloc)); - - ++p; - gcc_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(atdt, vals, bloc); -} - -// Build a type descriptor for a slice type. - -Expression* -Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* stdt = Array_type::make_slice_type_descriptor_type(); - - const Struct_field_list* fields = stdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(2); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_SLICE, - name, NULL, true)); - - ++p; - gcc_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc)); - - ++p; - gcc_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(stdt, vals, bloc); -} - -// Reflection string. - -void -Array_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->push_back('['); - if (this->length_ != NULL) - { - mpz_t val; - mpz_init(val); - Type* type; - if (!this->length_->integer_constant_value(true, val, &type)) - error_at(this->length_->location(), - "array length must be integer constant expression"); - else if (mpz_cmp_si(val, 0) < 0) - error_at(this->length_->location(), "array length is negative"); - else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0) - error_at(this->length_->location(), "array length is too large"); - else - { - char buf[50]; - snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val)); - ret->append(buf); - } - mpz_clear(val); - } - ret->push_back(']'); - - this->append_reflection(this->element_type_, gogo, ret); -} - -// Mangled name. - -void -Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('A'); - this->append_mangled_name(this->element_type_, gogo, ret); - if (this->length_ != NULL) - { - mpz_t val; - mpz_init(val); - Type* type; - if (!this->length_->integer_constant_value(true, val, &type)) - error_at(this->length_->location(), - "array length must be integer constant expression"); - else if (mpz_cmp_si(val, 0) < 0) - error_at(this->length_->location(), "array length is negative"); - else if (mpz_cmp_ui(val, mpz_get_ui(val)) != 0) - error_at(this->length_->location(), "array size is too large"); - else - { - char buf[50]; - snprintf(buf, sizeof buf, "%lu", mpz_get_ui(val)); - ret->append(buf); - } - mpz_clear(val); - } - ret->push_back('e'); -} - -// Make an array type. - -Array_type* -Type::make_array_type(Type* element_type, Expression* length) -{ - return new Array_type(element_type, length); -} - -// Class Map_type. - -// Traversal. - -int -Map_type::do_traverse(Traverse* traverse) -{ - if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT - || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Check that the map type is OK. - -bool -Map_type::do_verify() -{ - if (this->key_type_->struct_type() != NULL - || this->key_type_->array_type() != NULL) - { - error_at(this->location_, "invalid map key type"); - return false; - } - return true; -} - -// Whether two map types are identical. - -bool -Map_type::is_identical(const Map_type* t, bool errors_are_identical) const -{ - return (Type::are_identical(this->key_type(), t->key_type(), - errors_are_identical, NULL) - && Type::are_identical(this->val_type(), t->val_type(), - errors_are_identical, NULL)); -} - -// Hash code. - -unsigned int -Map_type::do_hash_for_method(Gogo* gogo) const -{ - return (this->key_type_->hash_for_method(gogo) - + this->val_type_->hash_for_method(gogo) - + 2); -} - -// Check that a call to the builtin make function is valid. For a map -// the optional argument is the number of spaces to preallocate for -// values. - -bool -Map_type::do_check_make_expression(Expression_list* args, - source_location location) -{ - if (args != NULL && !args->empty()) - { - if (!Type::check_int_value(args->front(), _("bad size when making map"), - location)) - return false; - else if (args->size() > 1) - { - error_at(location, "too many arguments when making map"); - return false; - } - } - return true; -} - -// Get a tree for a map type. A map type is represented as a pointer -// to a struct. The struct is __go_map in libgo/map.h. - -tree -Map_type::do_get_tree(Gogo* gogo) -{ - static tree type_tree; - if (type_tree == NULL_TREE) - { - tree struct_type = make_node(RECORD_TYPE); - - tree map_descriptor_type = gogo->map_descriptor_type(); - tree const_map_descriptor_type = - build_qualified_type(map_descriptor_type, TYPE_QUAL_CONST); - tree name = get_identifier("__descriptor"); - tree field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name, - build_pointer_type(const_map_descriptor_type)); - DECL_CONTEXT(field) = struct_type; - TYPE_FIELDS(struct_type) = field; - tree last_field = field; - - name = get_identifier("__element_count"); - field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name, sizetype); - DECL_CONTEXT(field) = struct_type; - DECL_CHAIN(last_field) = field; - last_field = field; - - name = get_identifier("__bucket_count"); - field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name, sizetype); - DECL_CONTEXT(field) = struct_type; - DECL_CHAIN(last_field) = field; - last_field = field; - - name = get_identifier("__buckets"); - field = build_decl(BUILTINS_LOCATION, FIELD_DECL, name, - build_pointer_type(ptr_type_node)); - DECL_CONTEXT(field) = struct_type; - DECL_CHAIN(last_field) = field; - - layout_type(struct_type); - - // Give the struct a name for better debugging info. - name = get_identifier("__go_map"); - tree type_decl = build_decl(BUILTINS_LOCATION, TYPE_DECL, name, - struct_type); - DECL_ARTIFICIAL(type_decl) = 1; - TYPE_NAME(struct_type) = type_decl; - go_preserve_from_gc(type_decl); - rest_of_decl_compilation(type_decl, 1, 0); - - type_tree = build_pointer_type(struct_type); - go_preserve_from_gc(type_tree); - } - - return type_tree; -} - -// Initialize a map. - -tree -Map_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - return fold_convert(type_tree, null_pointer_node); -} - -// Return an expression for a newly allocated map. - -tree -Map_type::do_make_expression_tree(Translate_context* context, - Expression_list* args, - source_location location) -{ - tree bad_index = NULL_TREE; - - tree expr_tree; - if (args == NULL || args->empty()) - expr_tree = size_zero_node; - else - { - expr_tree = args->front()->get_tree(context); - if (expr_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(expr_tree)) - expr_tree = save_expr(expr_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(expr_tree))) - expr_tree = convert_to_integer(sizetype, expr_tree); - bad_index = Expression::check_bounds(expr_tree, sizetype, bad_index, - location); - } - - tree map_type = this->get_tree(context->gogo()); - - static tree new_map_fndecl; - tree ret = Gogo::call_builtin(&new_map_fndecl, - location, - "__go_new_map", - 2, - map_type, - TREE_TYPE(TYPE_FIELDS(TREE_TYPE(map_type))), - context->gogo()->map_descriptor(this), - sizetype, - expr_tree); - if (ret == error_mark_node) - return error_mark_node; - // This can panic if the capacity is out of range. - TREE_NOTHROW(new_map_fndecl) = 0; - - if (bad_index == NULL_TREE) - return ret; - else - { - tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_MAP_OUT_OF_BOUNDS, - location); - return build2(COMPOUND_EXPR, TREE_TYPE(ret), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - ret); - } -} - -// The type of a map type descriptor. - -Type* -Map_type::make_map_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Struct_type* sf = - Type::make_builtin_struct_type(3, - "", tdt, - "key", ptdt, - "elem", ptdt); - - ret = Type::make_builtin_named_type("MapType", sf); - } - - return ret; -} - -// Build a type descriptor for a map type. - -Expression* -Map_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* mtdt = Map_type::make_map_type_descriptor_type(); - - const Struct_field_list* fields = mtdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(3); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_MAP, - name, NULL, true)); - - ++p; - gcc_assert(p->field_name() == "key"); - vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc)); - - ++p; - gcc_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc)); - - ++p; - gcc_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(mtdt, vals, bloc); -} - -// Reflection string for a map. - -void -Map_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->append("map["); - this->append_reflection(this->key_type_, gogo, ret); - ret->append("] "); - this->append_reflection(this->val_type_, gogo, ret); -} - -// Mangled name for a map. - -void -Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('M'); - this->append_mangled_name(this->key_type_, gogo, ret); - ret->append("__"); - this->append_mangled_name(this->val_type_, gogo, ret); -} - -// Export a map type. - -void -Map_type::do_export(Export* exp) const -{ - exp->write_c_string("map ["); - exp->write_type(this->key_type_); - exp->write_c_string("] "); - exp->write_type(this->val_type_); -} - -// Import a map type. - -Map_type* -Map_type::do_import(Import* imp) -{ - imp->require_c_string("map ["); - Type* key_type = imp->read_type(); - imp->require_c_string("] "); - Type* val_type = imp->read_type(); - return Type::make_map_type(key_type, val_type, imp->location()); -} - -// Make a map type. - -Map_type* -Type::make_map_type(Type* key_type, Type* val_type, source_location location) -{ - return new Map_type(key_type, val_type, location); -} - -// Class Channel_type. - -// Hash code. - -unsigned int -Channel_type::do_hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - if (this->may_send_) - ret += 1; - if (this->may_receive_) - ret += 2; - if (this->element_type_ != NULL) - ret += this->element_type_->hash_for_method(gogo) << 2; - return ret << 3; -} - -// Whether this type is the same as T. - -bool -Channel_type::is_identical(const Channel_type* t, - bool errors_are_identical) const -{ - if (!Type::are_identical(this->element_type(), t->element_type(), - errors_are_identical, NULL)) - return false; - return (this->may_send_ == t->may_send_ - && this->may_receive_ == t->may_receive_); -} - -// Check whether the parameters for a call to the builtin function -// make are OK for a channel. A channel can take an optional single -// parameter which is the buffer size. - -bool -Channel_type::do_check_make_expression(Expression_list* args, - source_location location) -{ - if (args != NULL && !args->empty()) - { - if (!Type::check_int_value(args->front(), - _("bad buffer size when making channel"), - location)) - return false; - else if (args->size() > 1) - { - error_at(location, "too many arguments when making channel"); - return false; - } - } - return true; -} - -// Return the tree for a channel type. A channel is a pointer to a -// __go_channel struct. The __go_channel struct is defined in -// libgo/runtime/channel.h. - -tree -Channel_type::do_get_tree(Gogo*) -{ - static tree type_tree; - if (type_tree == NULL_TREE) - { - tree ret = make_node(RECORD_TYPE); - TYPE_NAME(ret) = get_identifier("__go_channel"); - TYPE_STUB_DECL(ret) = build_decl(BUILTINS_LOCATION, TYPE_DECL, NULL_TREE, - ret); - type_tree = build_pointer_type(ret); - go_preserve_from_gc(type_tree); - } - return type_tree; -} - -// Initialize a channel variable. - -tree -Channel_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - return fold_convert(type_tree, null_pointer_node); -} - -// Handle the builtin function make for a channel. - -tree -Channel_type::do_make_expression_tree(Translate_context* context, - Expression_list* args, - source_location location) -{ - Gogo* gogo = context->gogo(); - tree channel_type = this->get_tree(gogo); - - tree element_tree = this->element_type_->get_tree(gogo); - tree element_size_tree = size_in_bytes(element_tree); - - tree bad_index = NULL_TREE; - - tree expr_tree; - if (args == NULL || args->empty()) - expr_tree = size_zero_node; - else - { - expr_tree = args->front()->get_tree(context); - if (expr_tree == error_mark_node) - return error_mark_node; - if (!DECL_P(expr_tree)) - expr_tree = save_expr(expr_tree); - if (!INTEGRAL_TYPE_P(TREE_TYPE(expr_tree))) - expr_tree = convert_to_integer(sizetype, expr_tree); - bad_index = Expression::check_bounds(expr_tree, sizetype, bad_index, - location); - } - - static tree new_channel_fndecl; - tree ret = Gogo::call_builtin(&new_channel_fndecl, - location, - "__go_new_channel", - 2, - channel_type, - sizetype, - element_size_tree, - sizetype, - expr_tree); - if (ret == error_mark_node) - return error_mark_node; - // This can panic if the capacity is out of range. - TREE_NOTHROW(new_channel_fndecl) = 0; - - if (bad_index == NULL_TREE) - return ret; - else - { - tree crash = Gogo::runtime_error(RUNTIME_ERROR_MAKE_CHAN_OUT_OF_BOUNDS, - location); - return build2(COMPOUND_EXPR, TREE_TYPE(ret), - build3(COND_EXPR, void_type_node, - bad_index, crash, NULL_TREE), - ret); - } -} - -// Build a type descriptor for a channel type. - -Type* -Channel_type::make_chan_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* uintptr_type = Type::lookup_integer_type("uintptr"); - - Struct_type* sf = - Type::make_builtin_struct_type(3, - "", tdt, - "elem", ptdt, - "dir", uintptr_type); - - ret = Type::make_builtin_named_type("ChanType", sf); - } - - return ret; -} - -// Build a type descriptor for a map type. - -Expression* -Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* ctdt = Channel_type::make_chan_type_descriptor_type(); - - const Struct_field_list* fields = ctdt->struct_type()->fields(); - - Expression_list* vals = new Expression_list(); - vals->reserve(3); - - Struct_field_list::const_iterator p = fields->begin(); - gcc_assert(p->field_name() == "commonType"); - vals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_CHAN, - name, NULL, true)); - - ++p; - gcc_assert(p->field_name() == "elem"); - vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc)); - - ++p; - gcc_assert(p->field_name() == "dir"); - // These bits must match the ones in libgo/runtime/go-type.h. - int val = 0; - if (this->may_receive_) - val |= 1; - if (this->may_send_) - val |= 2; - mpz_t iv; - mpz_init_set_ui(iv, val); - vals->push_back(Expression::make_integer(&iv, p->type(), bloc)); - mpz_clear(iv); - - ++p; - gcc_assert(p == fields->end()); - - return Expression::make_struct_composite_literal(ctdt, vals, bloc); -} - -// Reflection string. - -void -Channel_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - if (!this->may_send_) - ret->append("<-"); - ret->append("chan"); - if (!this->may_receive_) - ret->append("<-"); - ret->push_back(' '); - this->append_reflection(this->element_type_, gogo, ret); -} - -// Mangled name. - -void -Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('C'); - this->append_mangled_name(this->element_type_, gogo, ret); - if (this->may_send_) - ret->push_back('s'); - if (this->may_receive_) - ret->push_back('r'); - ret->push_back('e'); -} - -// Export. - -void -Channel_type::do_export(Export* exp) const -{ - exp->write_c_string("chan "); - if (this->may_send_ && !this->may_receive_) - exp->write_c_string("-< "); - else if (this->may_receive_ && !this->may_send_) - exp->write_c_string("<- "); - exp->write_type(this->element_type_); -} - -// Import. - -Channel_type* -Channel_type::do_import(Import* imp) -{ - imp->require_c_string("chan "); - - bool may_send; - bool may_receive; - if (imp->match_c_string("-< ")) - { - imp->advance(3); - may_send = true; - may_receive = false; - } - else if (imp->match_c_string("<- ")) - { - imp->advance(3); - may_receive = true; - may_send = false; - } - else - { - may_send = true; - may_receive = true; - } - - Type* element_type = imp->read_type(); - - return Type::make_channel_type(may_send, may_receive, element_type); -} - -// Make a new channel type. - -Channel_type* -Type::make_channel_type(bool send, bool receive, Type* element_type) -{ - return new Channel_type(send, receive, element_type); -} - -// Class Interface_type. - -// Traversal. - -int -Interface_type::do_traverse(Traverse* traverse) -{ - if (this->methods_ == NULL) - return TRAVERSE_CONTINUE; - return this->methods_->traverse(traverse); -} - -// Finalize the methods. This handles interface inheritance. - -void -Interface_type::finalize_methods() -{ - if (this->methods_ == NULL) - return; - std::vector seen; - bool is_recursive = false; - size_t from = 0; - size_t to = 0; - while (from < this->methods_->size()) - { - const Typed_identifier* p = &this->methods_->at(from); - if (!p->name().empty()) - { - size_t i; - for (i = 0; i < to; ++i) - { - if (this->methods_->at(i).name() == p->name()) - { - error_at(p->location(), "duplicate method %qs", - Gogo::message_name(p->name()).c_str()); - break; - } - } - if (i == to) - { - if (from != to) - this->methods_->set(to, *p); - ++to; - } - ++from; - continue; - } - - Interface_type* it = p->type()->interface_type(); - if (it == NULL) - { - error_at(p->location(), "interface contains embedded non-interface"); - ++from; - continue; - } - if (it == this) - { - if (!is_recursive) - { - error_at(p->location(), "invalid recursive interface"); - is_recursive = true; - } - ++from; - continue; - } - - Named_type* nt = p->type()->named_type(); - if (nt != NULL) - { - std::vector::const_iterator q; - for (q = seen.begin(); q != seen.end(); ++q) - { - if (*q == nt) - { - error_at(p->location(), "inherited interface loop"); - break; - } - } - if (q != seen.end()) - { - ++from; - continue; - } - seen.push_back(nt); - } - - const Typed_identifier_list* methods = it->methods(); - if (methods == NULL) - { - ++from; - continue; - } - for (Typed_identifier_list::const_iterator q = methods->begin(); - q != methods->end(); - ++q) - { - if (q->name().empty()) - { - if (q->type()->forwarded() == p->type()->forwarded()) - error_at(p->location(), "interface inheritance loop"); - else - { - size_t i; - for (i = from + 1; i < this->methods_->size(); ++i) - { - const Typed_identifier* r = &this->methods_->at(i); - if (r->name().empty() - && r->type()->forwarded() == q->type()->forwarded()) - { - error_at(p->location(), - "inherited interface listed twice"); - break; - } - } - if (i == this->methods_->size()) - this->methods_->push_back(Typed_identifier(q->name(), - q->type(), - p->location())); - } - } - else if (this->find_method(q->name()) == NULL) - this->methods_->push_back(Typed_identifier(q->name(), q->type(), - p->location())); - else - { - if (!is_recursive) - error_at(p->location(), "inherited method %qs is ambiguous", - Gogo::message_name(q->name()).c_str()); - } - } - ++from; - } - if (to == 0) - { - delete this->methods_; - this->methods_ = NULL; - } - else - { - this->methods_->resize(to); - this->methods_->sort_by_name(); - } -} - -// Return the method NAME, or NULL. - -const Typed_identifier* -Interface_type::find_method(const std::string& name) const -{ - if (this->methods_ == NULL) - return NULL; - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - if (p->name() == name) - return &*p; - return NULL; -} - -// Return the method index. - -size_t -Interface_type::method_index(const std::string& name) const -{ - gcc_assert(this->methods_ != NULL); - size_t ret = 0; - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p, ++ret) - if (p->name() == name) - return ret; - gcc_unreachable(); -} - -// Return whether NAME is an unexported method, for better error -// reporting. - -bool -Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const -{ - if (this->methods_ == NULL) - return false; - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - const std::string& method_name(p->name()); - if (Gogo::is_hidden_name(method_name) - && name == Gogo::unpack_hidden_name(method_name) - && gogo->pack_hidden_name(name, false) != method_name) - return true; - } - return false; -} - -// Whether this type is identical with T. - -bool -Interface_type::is_identical(const Interface_type* t, - bool errors_are_identical) const -{ - // We require the same methods with the same types. The methods - // have already been sorted. - if (this->methods() == NULL || t->methods() == NULL) - return this->methods() == t->methods(); - - Typed_identifier_list::const_iterator p1 = this->methods()->begin(); - for (Typed_identifier_list::const_iterator p2 = t->methods()->begin(); - p2 != t->methods()->end(); - ++p1, ++p2) - { - if (p1 == this->methods()->end()) - return false; - if (p1->name() != p2->name() - || !Type::are_identical(p1->type(), p2->type(), - errors_are_identical, NULL)) - return false; - } - if (p1 != this->methods()->end()) - return false; - return true; -} - -// Whether we can assign the interface type T to this type. The types -// are known to not be identical. An interface assignment is only -// permitted if T is known to implement all methods in THIS. -// Otherwise a type guard is required. - -bool -Interface_type::is_compatible_for_assign(const Interface_type* t, - std::string* reason) const -{ - if (this->methods() == NULL) - return true; - for (Typed_identifier_list::const_iterator p = this->methods()->begin(); - p != this->methods()->end(); - ++p) - { - const Typed_identifier* m = t->find_method(p->name()); - if (m == NULL) - { - if (reason != NULL) - { - char buf[200]; - snprintf(buf, sizeof buf, - _("need explicit conversion; missing method %s%s%s"), - open_quote, Gogo::message_name(p->name()).c_str(), - close_quote); - reason->assign(buf); - } - return false; - } - - std::string subreason; - if (!Type::are_identical(p->type(), m->type(), true, &subreason)) - { - if (reason != NULL) - { - std::string n = Gogo::message_name(p->name()); - size_t len = 100 + n.length() + subreason.length(); - char* buf = new char[len]; - if (subreason.empty()) - snprintf(buf, len, _("incompatible type for method %s%s%s"), - open_quote, n.c_str(), close_quote); - else - snprintf(buf, len, - _("incompatible type for method %s%s%s (%s)"), - open_quote, n.c_str(), close_quote, - subreason.c_str()); - reason->assign(buf); - delete[] buf; - } - return false; - } - } - - return true; -} - -// Hash code. - -unsigned int -Interface_type::do_hash_for_method(Gogo* gogo) const -{ - unsigned int ret = 0; - if (this->methods_ != NULL) - { - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - ret = Type::hash_string(p->name(), ret); - ret += p->type()->hash_for_method(gogo); - ret <<= 1; - } - } - return ret; -} - -// Return true if T implements the interface. If it does not, and -// REASON is not NULL, set *REASON to a useful error message. - -bool -Interface_type::implements_interface(const Type* t, std::string* reason) const -{ - if (this->methods_ == NULL) - return true; - - bool is_pointer = false; - const Named_type* nt = t->named_type(); - const Struct_type* st = t->struct_type(); - // If we start with a named type, we don't dereference it to find - // methods. - if (nt == NULL) - { - const Type* pt = t->points_to(); - if (pt != NULL) - { - // If T is a pointer to a named type, then we need to look at - // the type to which it points. - is_pointer = true; - nt = pt->named_type(); - st = pt->struct_type(); - } - } - - // If we have a named type, get the methods from it rather than from - // any struct type. - if (nt != NULL) - st = NULL; - - // Only named and struct types have methods. - if (nt == NULL && st == NULL) - { - if (reason != NULL) - { - if (t->points_to() != NULL - && t->points_to()->interface_type() != NULL) - reason->assign(_("pointer to interface type has no methods")); - else - reason->assign(_("type has no methods")); - } - return false; - } - - if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods()) - { - if (reason != NULL) - { - if (t->points_to() != NULL - && t->points_to()->interface_type() != NULL) - reason->assign(_("pointer to interface type has no methods")); - else - reason->assign(_("type has no methods")); - } - return false; - } - - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - bool is_ambiguous = false; - Method* m = (nt != NULL - ? nt->method_function(p->name(), &is_ambiguous) - : st->method_function(p->name(), &is_ambiguous)); - if (m == NULL) - { - if (reason != NULL) - { - std::string n = Gogo::message_name(p->name()); - size_t len = n.length() + 100; - char* buf = new char[len]; - if (is_ambiguous) - snprintf(buf, len, _("ambiguous method %s%s%s"), - open_quote, n.c_str(), close_quote); - else - snprintf(buf, len, _("missing method %s%s%s"), - open_quote, n.c_str(), close_quote); - reason->assign(buf); - delete[] buf; - } - return false; - } - - Function_type *p_fn_type = p->type()->function_type(); - Function_type* m_fn_type = m->type()->function_type(); - gcc_assert(p_fn_type != NULL && m_fn_type != NULL); - std::string subreason; - if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason)) - { - if (reason != NULL) - { - std::string n = Gogo::message_name(p->name()); - size_t len = 100 + n.length() + subreason.length(); - char* buf = new char[len]; - if (subreason.empty()) - snprintf(buf, len, _("incompatible type for method %s%s%s"), - open_quote, n.c_str(), close_quote); - else - snprintf(buf, len, - _("incompatible type for method %s%s%s (%s)"), - open_quote, n.c_str(), close_quote, - subreason.c_str()); - reason->assign(buf); - delete[] buf; - } - return false; - } - - if (!is_pointer && !m->is_value_method()) - { - if (reason != NULL) - { - std::string n = Gogo::message_name(p->name()); - size_t len = 100 + n.length(); - char* buf = new char[len]; - snprintf(buf, len, _("method %s%s%s requires a pointer"), - open_quote, n.c_str(), close_quote); - reason->assign(buf); - delete[] buf; - } - return false; - } - } - - return true; -} - -// Return a tree for an interface type. An interface is a pointer to -// a struct. The struct has three fields. The first field is a -// pointer to the type descriptor for the dynamic type of the object. -// The second field is a pointer to a table of methods for the -// interface to be used with the object. The third field is the value -// of the object itself. - -tree -Interface_type::do_get_tree(Gogo* gogo) -{ - if (this->methods_ == NULL) - return Interface_type::empty_type_tree(gogo); - else - { - tree t = Interface_type::non_empty_type_tree(this->location_); - return this->fill_in_tree(gogo, t); - } -} - -// Return a singleton struct for an empty interface type. We use the -// same type for all empty interfaces. This lets us assign them to -// each other directly without triggering GIMPLE type errors. - -tree -Interface_type::empty_type_tree(Gogo* gogo) -{ - static tree empty_interface; - if (empty_interface != NULL_TREE) - return empty_interface; - - tree dtype = Type::make_type_descriptor_type()->get_tree(gogo); - dtype = build_pointer_type(build_qualified_type(dtype, TYPE_QUAL_CONST)); - return Gogo::builtin_struct(&empty_interface, "__go_empty_interface", - NULL_TREE, 2, - "__type_descriptor", - dtype, - "__object", - ptr_type_node); -} - -// Return a new struct for a non-empty interface type. The correct -// values are filled in by fill_in_tree. - -tree -Interface_type::non_empty_type_tree(source_location location) -{ - tree ret = make_node(RECORD_TYPE); - - tree field_trees = NULL_TREE; - tree* pp = &field_trees; - - tree name_tree = get_identifier("__methods"); - tree field = build_decl(location, FIELD_DECL, name_tree, ptr_type_node); - DECL_CONTEXT(field) = ret; - *pp = field; - pp = &DECL_CHAIN(field); - - name_tree = get_identifier("__object"); - field = build_decl(location, FIELD_DECL, name_tree, ptr_type_node); - DECL_CONTEXT(field) = ret; - *pp = field; - - TYPE_FIELDS(ret) = field_trees; - - layout_type(ret); - - return ret; -} - -// Fill in the tree for an interface type. This is used for named -// interface types. - -tree -Interface_type::fill_in_tree(Gogo* gogo, tree type) -{ - gcc_assert(this->methods_ != NULL); - - // Build the type of the table of methods. - - tree method_table = make_node(RECORD_TYPE); - - // The first field is a pointer to the type descriptor. - tree name_tree = get_identifier("__type_descriptor"); - tree dtype = Type::make_type_descriptor_type()->get_tree(gogo); - dtype = build_pointer_type(build_qualified_type(dtype, TYPE_QUAL_CONST)); - tree field = build_decl(this->location_, FIELD_DECL, name_tree, dtype); - DECL_CONTEXT(field) = method_table; - TYPE_FIELDS(method_table) = field; - - std::string last_name = ""; - tree* pp = &DECL_CHAIN(field); - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - std::string name = Gogo::unpack_hidden_name(p->name()); - name_tree = get_identifier_with_length(name.data(), name.length()); - tree field_type = p->type()->get_tree(gogo); - if (field_type == error_mark_node) - return error_mark_node; - field = build_decl(this->location_, FIELD_DECL, name_tree, field_type); - DECL_CONTEXT(field) = method_table; - *pp = field; - pp = &DECL_CHAIN(field); - // Sanity check: the names should be sorted. - gcc_assert(p->name() > last_name); - last_name = p->name(); - } - layout_type(method_table); - - // Update the type of the __methods field from a generic pointer to - // a pointer to the method table. - field = TYPE_FIELDS(type); - gcc_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0); - - TREE_TYPE(field) = build_pointer_type(method_table); - - return type; -} - -// Initialization value. - -tree -Interface_type::do_get_init_tree(Gogo*, tree type_tree, bool is_clear) -{ - if (is_clear) - return NULL; - - VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2); - for (tree field = TYPE_FIELDS(type_tree); - field != NULL_TREE; - field = DECL_CHAIN(field)) - { - constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL); - elt->index = field; - elt->value = fold_convert(TREE_TYPE(field), null_pointer_node); - } - - tree ret = build_constructor(type_tree, init); - TREE_CONSTANT(ret) = 1; - return ret; -} - -// The type of an interface type descriptor. - -Type* -Interface_type::make_interface_type_descriptor_type() -{ - static Type* ret; - if (ret == NULL) - { - Type* tdt = Type::make_type_descriptor_type(); - Type* ptdt = Type::make_type_descriptor_ptr_type(); - - Type* string_type = Type::lookup_string_type(); - Type* pointer_string_type = Type::make_pointer_type(string_type); - - Struct_type* sm = - Type::make_builtin_struct_type(3, - "name", pointer_string_type, - "pkgPath", pointer_string_type, - "typ", ptdt); - - Type* nsm = Type::make_builtin_named_type("imethod", sm); - - Type* slice_nsm = Type::make_array_type(nsm, NULL); - - Struct_type* s = Type::make_builtin_struct_type(2, - "", tdt, - "methods", slice_nsm); - - ret = Type::make_builtin_named_type("InterfaceType", s); - } - - return ret; -} - -// Build a type descriptor for an interface type. - -Expression* -Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - source_location bloc = BUILTINS_LOCATION; - - Type* itdt = Interface_type::make_interface_type_descriptor_type(); - - const Struct_field_list* ifields = itdt->struct_type()->fields(); - - Expression_list* ivals = new Expression_list(); - ivals->reserve(2); - - Struct_field_list::const_iterator pif = ifields->begin(); - gcc_assert(pif->field_name() == "commonType"); - ivals->push_back(this->type_descriptor_constructor(gogo, - RUNTIME_TYPE_KIND_INTERFACE, - name, NULL, true)); - - ++pif; - gcc_assert(pif->field_name() == "methods"); - - Expression_list* methods = new Expression_list(); - if (this->methods_ != NULL && !this->methods_->empty()) - { - Type* elemtype = pif->type()->array_type()->element_type(); - - methods->reserve(this->methods_->size()); - for (Typed_identifier_list::const_iterator pm = this->methods_->begin(); - pm != this->methods_->end(); - ++pm) - { - const Struct_field_list* mfields = elemtype->struct_type()->fields(); - - Expression_list* mvals = new Expression_list(); - mvals->reserve(3); - - Struct_field_list::const_iterator pmf = mfields->begin(); - gcc_assert(pmf->field_name() == "name"); - std::string s = Gogo::unpack_hidden_name(pm->name()); - Expression* e = Expression::make_string(s, bloc); - mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc)); - - ++pmf; - gcc_assert(pmf->field_name() == "pkgPath"); - if (!Gogo::is_hidden_name(pm->name())) - mvals->push_back(Expression::make_nil(bloc)); - else - { - s = Gogo::hidden_name_prefix(pm->name()); - e = Expression::make_string(s, bloc); - mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc)); - } - - ++pmf; - gcc_assert(pmf->field_name() == "typ"); - mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc)); - - ++pmf; - gcc_assert(pmf == mfields->end()); - - e = Expression::make_struct_composite_literal(elemtype, mvals, - bloc); - methods->push_back(e); - } - } - - ivals->push_back(Expression::make_slice_composite_literal(pif->type(), - methods, bloc)); - - ++pif; - gcc_assert(pif == ifields->end()); - - return Expression::make_struct_composite_literal(itdt, ivals, bloc); -} - -// Reflection string. - -void -Interface_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - ret->append("interface {"); - if (this->methods_ != NULL) - { - for (Typed_identifier_list::const_iterator p = this->methods_->begin(); - p != this->methods_->end(); - ++p) - { - if (p != this->methods_->begin()) - ret->append(";"); - ret->push_back(' '); - ret->append(Gogo::unpack_hidden_name(p->name())); - std::string sub = p->type()->reflection(gogo); - gcc_assert(sub.compare(0, 4, "func") == 0); - sub = sub.substr(4); - ret->append(sub); - } - } - ret->append(" }"); -} - -// Mangled name. - -void -Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - ret->push_back('I'); - - const Typed_identifier_list* methods = this->methods_; - if (methods != NULL) - { - for (Typed_identifier_list::const_iterator p = methods->begin(); - p != methods->end(); - ++p) - { - std::string n = Gogo::unpack_hidden_name(p->name()); - char buf[20]; - snprintf(buf, sizeof buf, "%u_", - static_cast(n.length())); - ret->append(buf); - ret->append(n); - this->append_mangled_name(p->type(), gogo, ret); - } - } - - ret->push_back('e'); -} - -// Export. - -void -Interface_type::do_export(Export* exp) const -{ - exp->write_c_string("interface { "); - - const Typed_identifier_list* methods = this->methods_; - if (methods != NULL) - { - for (Typed_identifier_list::const_iterator pm = methods->begin(); - pm != methods->end(); - ++pm) - { - exp->write_string(pm->name()); - exp->write_c_string(" ("); - - const Function_type* fntype = pm->type()->function_type(); - - bool first = true; - const Typed_identifier_list* parameters = fntype->parameters(); - if (parameters != NULL) - { - bool is_varargs = fntype->is_varargs(); - for (Typed_identifier_list::const_iterator pp = - parameters->begin(); - pp != parameters->end(); - ++pp) - { - if (first) - first = false; - else - exp->write_c_string(", "); - if (!is_varargs || pp + 1 != parameters->end()) - exp->write_type(pp->type()); - else - { - exp->write_c_string("..."); - Type *pptype = pp->type(); - exp->write_type(pptype->array_type()->element_type()); - } - } - } - - exp->write_c_string(")"); - - const Typed_identifier_list* results = fntype->results(); - if (results != NULL) - { - exp->write_c_string(" "); - if (results->size() == 1) - exp->write_type(results->begin()->type()); - else - { - first = true; - exp->write_c_string("("); - for (Typed_identifier_list::const_iterator p = - results->begin(); - p != results->end(); - ++p) - { - if (first) - first = false; - else - exp->write_c_string(", "); - exp->write_type(p->type()); - } - exp->write_c_string(")"); - } - } - - exp->write_c_string("; "); - } - } - - exp->write_c_string("}"); -} - -// Import an interface type. - -Interface_type* -Interface_type::do_import(Import* imp) -{ - imp->require_c_string("interface { "); - - Typed_identifier_list* methods = new Typed_identifier_list; - while (imp->peek_char() != '}') - { - std::string name = imp->read_identifier(); - imp->require_c_string(" ("); - - Typed_identifier_list* parameters; - bool is_varargs = false; - if (imp->peek_char() == ')') - parameters = NULL; - else - { - parameters = new Typed_identifier_list; - while (true) - { - if (imp->match_c_string("...")) - { - imp->advance(3); - is_varargs = true; - } - - Type* ptype = imp->read_type(); - if (is_varargs) - ptype = Type::make_array_type(ptype, NULL); - parameters->push_back(Typed_identifier(Import::import_marker, - ptype, imp->location())); - if (imp->peek_char() != ',') - break; - gcc_assert(!is_varargs); - imp->require_c_string(", "); - } - } - imp->require_c_string(")"); - - Typed_identifier_list* results; - if (imp->peek_char() != ' ') - results = NULL; - else - { - results = new Typed_identifier_list; - imp->advance(1); - if (imp->peek_char() != '(') - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, - rtype, imp->location())); - } - else - { - imp->advance(1); - while (true) - { - Type* rtype = imp->read_type(); - results->push_back(Typed_identifier(Import::import_marker, - rtype, imp->location())); - if (imp->peek_char() != ',') - break; - imp->require_c_string(", "); - } - imp->require_c_string(")"); - } - } - - Function_type* fntype = Type::make_function_type(NULL, parameters, - results, - imp->location()); - if (is_varargs) - fntype->set_is_varargs(); - methods->push_back(Typed_identifier(name, fntype, imp->location())); - - imp->require_c_string("; "); - } - - imp->require_c_string("}"); - - if (methods->empty()) - { - delete methods; - methods = NULL; - } - - return Type::make_interface_type(methods, imp->location()); -} - -// Make an interface type. - -Interface_type* -Type::make_interface_type(Typed_identifier_list* methods, - source_location location) -{ - return new Interface_type(methods, location); -} - -// Class Method. - -// Bind a method to an object. - -Expression* -Method::bind_method(Expression* expr, source_location location) const -{ - if (this->stub_ == NULL) - { - // When there is no stub object, the binding is determined by - // the child class. - return this->do_bind_method(expr, location); - } - - Expression* func = Expression::make_func_reference(this->stub_, NULL, - location); - return Expression::make_bound_method(expr, func, location); -} - -// Return the named object associated with a method. This may only be -// called after methods are finalized. - -Named_object* -Method::named_object() const -{ - if (this->stub_ != NULL) - return this->stub_; - return this->do_named_object(); -} - -// Class Named_method. - -// The type of the method. - -Function_type* -Named_method::do_type() const -{ - if (this->named_object_->is_function()) - return this->named_object_->func_value()->type(); - else if (this->named_object_->is_function_declaration()) - return this->named_object_->func_declaration_value()->type(); - else - gcc_unreachable(); -} - -// Return the location of the method receiver. - -source_location -Named_method::do_receiver_location() const -{ - return this->do_type()->receiver()->location(); -} - -// Bind a method to an object. - -Expression* -Named_method::do_bind_method(Expression* expr, source_location location) const -{ - Expression* func = Expression::make_func_reference(this->named_object_, NULL, - location); - Bound_method_expression* bme = Expression::make_bound_method(expr, func, - location); - // If this is not a local method, and it does not use a stub, then - // the real method expects a different type. We need to cast the - // first argument. - if (this->depth() > 0 && !this->needs_stub_method()) - { - Function_type* ftype = this->do_type(); - gcc_assert(ftype->is_method()); - Type* frtype = ftype->receiver()->type(); - bme->set_first_argument_type(frtype); - } - return bme; -} - -// Class Interface_method. - -// Bind a method to an object. - -Expression* -Interface_method::do_bind_method(Expression* expr, - source_location location) const -{ - return Expression::make_interface_field_reference(expr, this->name_, - location); -} - -// Class Methods. - -// Insert a new method. Return true if it was inserted, false -// otherwise. - -bool -Methods::insert(const std::string& name, Method* m) -{ - std::pair ins = - this->methods_.insert(std::make_pair(name, m)); - if (ins.second) - return true; - else - { - Method* old_method = ins.first->second; - if (m->depth() < old_method->depth()) - { - delete old_method; - ins.first->second = m; - return true; - } - else - { - if (m->depth() == old_method->depth()) - old_method->set_is_ambiguous(); - return false; - } - } -} - -// Return the number of unambiguous methods. - -size_t -Methods::count() const -{ - size_t ret = 0; - for (Method_map::const_iterator p = this->methods_.begin(); - p != this->methods_.end(); - ++p) - if (!p->second->is_ambiguous()) - ++ret; - return ret; -} - -// Class Named_type. - -// Return the name of the type. - -const std::string& -Named_type::name() const -{ - return this->named_object_->name(); -} - -// Return the name of the type to use in an error message. - -std::string -Named_type::message_name() const -{ - return this->named_object_->message_name(); -} - -// Return the base type for this type. We have to be careful about -// circular type definitions, which are invalid but may be seen here. - -Type* -Named_type::named_base() -{ - if (this->seen_ > 0) - return this; - ++this->seen_; - Type* ret = this->type_->base(); - --this->seen_; - return ret; -} - -const Type* -Named_type::named_base() const -{ - if (this->seen_ > 0) - return this; - ++this->seen_; - const Type* ret = this->type_->base(); - --this->seen_; - return ret; -} - -// Return whether this is an error type. We have to be careful about -// circular type definitions, which are invalid but may be seen here. - -bool -Named_type::is_named_error_type() const -{ - if (this->seen_ > 0) - return false; - ++this->seen_; - bool ret = this->type_->is_error_type(); - --this->seen_; - return ret; -} - -// Add a method to this type. - -Named_object* -Named_type::add_method(const std::string& name, Function* function) -{ - if (this->local_methods_ == NULL) - this->local_methods_ = new Bindings(NULL); - return this->local_methods_->add_function(name, NULL, function); -} - -// Add a method declaration to this type. - -Named_object* -Named_type::add_method_declaration(const std::string& name, Package* package, - Function_type* type, - source_location location) -{ - if (this->local_methods_ == NULL) - this->local_methods_ = new Bindings(NULL); - return this->local_methods_->add_function_declaration(name, package, type, - location); -} - -// Add an existing method to this type. - -void -Named_type::add_existing_method(Named_object* no) -{ - if (this->local_methods_ == NULL) - this->local_methods_ = new Bindings(NULL); - this->local_methods_->add_named_object(no); -} - -// Look for a local method NAME, and returns its named object, or NULL -// if not there. - -Named_object* -Named_type::find_local_method(const std::string& name) const -{ - if (this->local_methods_ == NULL) - return NULL; - return this->local_methods_->lookup(name); -} - -// Return whether NAME is an unexported field or method, for better -// error reporting. - -bool -Named_type::is_unexported_local_method(Gogo* gogo, - const std::string& name) const -{ - Bindings* methods = this->local_methods_; - if (methods != NULL) - { - for (Bindings::const_declarations_iterator p = - methods->begin_declarations(); - p != methods->end_declarations(); - ++p) - { - if (Gogo::is_hidden_name(p->first) - && name == Gogo::unpack_hidden_name(p->first) - && gogo->pack_hidden_name(name, false) != p->first) - return true; - } - } - return false; -} - -// Build the complete list of methods for this type, which means -// recursively including all methods for anonymous fields. Create all -// stub methods. - -void -Named_type::finalize_methods(Gogo* gogo) -{ - if (this->all_methods_ != NULL) - return; - - if (this->local_methods_ != NULL - && (this->points_to() != NULL || this->interface_type() != NULL)) - { - const Bindings* lm = this->local_methods_; - for (Bindings::const_declarations_iterator p = lm->begin_declarations(); - p != lm->end_declarations(); - ++p) - error_at(p->second->location(), - "invalid pointer or interface receiver type"); - delete this->local_methods_; - this->local_methods_ = NULL; - return; - } - - Type::finalize_methods(gogo, this, this->location_, &this->all_methods_); -} - -// Return the method NAME, or NULL if there isn't one or if it is -// ambiguous. Set *IS_AMBIGUOUS if the method exists but is -// ambiguous. - -Method* -Named_type::method_function(const std::string& name, bool* is_ambiguous) const -{ - return Type::method_function(this->all_methods_, name, is_ambiguous); -} - -// Return a pointer to the interface method table for this type for -// the interface INTERFACE. IS_POINTER is true if this is for a -// pointer to THIS. - -tree -Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface, - bool is_pointer) -{ - gcc_assert(!interface->is_empty()); - - Interface_method_tables** pimt = (is_pointer - ? &this->interface_method_tables_ - : &this->pointer_interface_method_tables_); - - if (*pimt == NULL) - *pimt = new Interface_method_tables(5); - - std::pair val(interface, NULL_TREE); - std::pair ins = (*pimt)->insert(val); - - if (ins.second) - { - // This is a new entry in the hash table. - gcc_assert(ins.first->second == NULL_TREE); - ins.first->second = gogo->interface_method_table_for_type(interface, - this, - is_pointer); - } - - tree decl = ins.first->second; - if (decl == error_mark_node) - return error_mark_node; - gcc_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL); - return build_fold_addr_expr(decl); -} - -// Return whether a named type has any hidden fields. - -bool -Named_type::named_type_has_hidden_fields(std::string* reason) const -{ - if (this->seen_ > 0) - return false; - ++this->seen_; - bool ret = this->type_->has_hidden_fields(this, reason); - --this->seen_; - return ret; -} - -// Look for a use of a complete type within another type. This is -// used to check that we don't try to use a type within itself. - -class Find_type_use : public Traverse -{ - public: - Find_type_use(Named_type* find_type) - : Traverse(traverse_types), - find_type_(find_type), found_(false) - { } - - // Whether we found the type. - bool - found() const - { return this->found_; } - - protected: - int - type(Type*); - - private: - // The type we are looking for. - Named_type* find_type_; - // Whether we found the type. - bool found_; -}; - -// Check for FIND_TYPE in TYPE. - -int -Find_type_use::type(Type* type) -{ - if (type->named_type() != NULL && this->find_type_ == type->named_type()) - { - this->found_ = true; - return TRAVERSE_EXIT; - } - - // It's OK if we see a reference to the type in any type which is - // essentially a pointer: a pointer, a slice, a function, a map, or - // a channel. - if (type->points_to() != NULL - || type->is_open_array_type() - || type->function_type() != NULL - || type->map_type() != NULL - || type->channel_type() != NULL) - return TRAVERSE_SKIP_COMPONENTS; - - // For an interface, a reference to the type in a method type should - // be ignored, but we have to consider direct inheritance. When - // this is called, there may be cases of direct inheritance - // represented as a method with no name. - if (type->interface_type() != NULL) - { - const Typed_identifier_list* methods = type->interface_type()->methods(); - if (methods != NULL) - { - for (Typed_identifier_list::const_iterator p = methods->begin(); - p != methods->end(); - ++p) - { - if (p->name().empty()) - { - if (Type::traverse(p->type(), this) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - } - } - return TRAVERSE_SKIP_COMPONENTS; - } - - // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need - // to convert TYPE to the backend representation before we convert - // FIND_TYPE_. - if (type->named_type() != NULL) - { - switch (type->base()->classification()) - { - case Type::TYPE_ERROR: - case Type::TYPE_BOOLEAN: - case Type::TYPE_INTEGER: - case Type::TYPE_FLOAT: - case Type::TYPE_COMPLEX: - case Type::TYPE_STRING: - case Type::TYPE_NIL: - break; - - case Type::TYPE_ARRAY: - case Type::TYPE_STRUCT: - this->find_type_->add_dependency(type->named_type()); - break; - - case Type::TYPE_VOID: - case Type::TYPE_SINK: - case Type::TYPE_FUNCTION: - case Type::TYPE_POINTER: - case Type::TYPE_CALL_MULTIPLE_RESULT: - case Type::TYPE_MAP: - case Type::TYPE_CHANNEL: - case Type::TYPE_INTERFACE: - case Type::TYPE_NAMED: - case Type::TYPE_FORWARD: - default: - gcc_unreachable(); - } - } - - return TRAVERSE_CONTINUE; -} - -// Verify that a named type does not refer to itself. - -bool -Named_type::do_verify() -{ - Find_type_use find(this); - Type::traverse(this->type_, &find); - if (find.found()) - { - error_at(this->location_, "invalid recursive type %qs", - this->message_name().c_str()); - this->is_error_ = true; - return false; - } - - // Check whether any of the local methods overloads an existing - // struct field or interface method. We don't need to check the - // list of methods against itself: that is handled by the Bindings - // code. - if (this->local_methods_ != NULL) - { - Struct_type* st = this->type_->struct_type(); - Interface_type* it = this->type_->interface_type(); - bool found_dup = false; - if (st != NULL || it != NULL) - { - for (Bindings::const_declarations_iterator p = - this->local_methods_->begin_declarations(); - p != this->local_methods_->end_declarations(); - ++p) - { - const std::string& name(p->first); - if (st != NULL && st->find_local_field(name, NULL) != NULL) - { - error_at(p->second->location(), - "method %qs redeclares struct field name", - Gogo::message_name(name).c_str()); - found_dup = true; - } - if (it != NULL && it->find_method(name) != NULL) - { - error_at(p->second->location(), - "method %qs redeclares interface method name", - Gogo::message_name(name).c_str()); - found_dup = true; - } - } - } - if (found_dup) - return false; - } - - return true; -} - -// Return whether this type is or contains a pointer. - -bool -Named_type::do_has_pointer() const -{ - if (this->seen_ > 0) - return false; - ++this->seen_; - bool ret = this->type_->has_pointer(); - --this->seen_; - return ret; -} - -// Return a hash code. This is used for method lookup. We simply -// hash on the name itself. - -unsigned int -Named_type::do_hash_for_method(Gogo* gogo) const -{ - const std::string& name(this->named_object()->name()); - unsigned int ret = Type::hash_string(name, 0); - - // GOGO will be NULL here when called from Type_hash_identical. - // That is OK because that is only used for internal hash tables - // where we are going to be comparing named types for equality. In - // other cases, which are cases where the runtime is going to - // compare hash codes to see if the types are the same, we need to - // include the package prefix and name in the hash. - if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin()) - { - const Package* package = this->named_object()->package(); - if (package == NULL) - { - ret = Type::hash_string(gogo->unique_prefix(), ret); - ret = Type::hash_string(gogo->package_name(), ret); - } - else - { - ret = Type::hash_string(package->unique_prefix(), ret); - ret = Type::hash_string(package->name(), ret); - } - } - - return ret; -} - -// Convert a named type to the backend representation. In order to -// get dependencies right, we fill in a dummy structure for this type, -// then convert all the dependencies, then complete this type. When -// this function is complete, the size of the type is known. - -void -Named_type::convert(Gogo* gogo) -{ - if (this->is_error_ || this->is_converted_) - return; - - this->create_placeholder(gogo); - - // Convert all the dependencies. If they refer indirectly back to - // this type, they will pick up the intermediate tree we just - // created. - for (std::vector::const_iterator p = this->dependencies_.begin(); - p != this->dependencies_.end(); - ++p) - (*p)->convert(gogo); - - // Complete this type. - tree t = this->named_tree_; - Type* base = this->type_->base(); - switch (base->classification()) - { - case TYPE_VOID: - case TYPE_BOOLEAN: - case TYPE_INTEGER: - case TYPE_FLOAT: - case TYPE_COMPLEX: - case TYPE_STRING: - case TYPE_NIL: - break; - - case TYPE_MAP: - case TYPE_CHANNEL: - break; - - case TYPE_FUNCTION: - case TYPE_POINTER: - // The size of these types is already correct. - break; - - case TYPE_STRUCT: - t = base->struct_type()->fill_in_tree(gogo, t); - break; - - case TYPE_ARRAY: - if (!base->is_open_array_type()) - t = base->array_type()->fill_in_array_tree(gogo, t); - break; - - case TYPE_INTERFACE: - if (!base->interface_type()->is_empty()) - t = base->interface_type()->fill_in_tree(gogo, t); - break; - - case TYPE_ERROR: - return; - - default: - case TYPE_SINK: - case TYPE_CALL_MULTIPLE_RESULT: - case TYPE_NAMED: - case TYPE_FORWARD: - gcc_unreachable(); - } - - this->named_tree_ = t; - - if (t == error_mark_node) - this->is_error_ = true; - else - gcc_assert(TYPE_SIZE(t) != NULL_TREE); - - this->is_converted_ = true; -} - -// Create the placeholder for a named type. This is the first step in -// converting to the backend representation. - -void -Named_type::create_placeholder(Gogo* gogo) -{ - if (this->is_error_) - this->named_tree_ = error_mark_node; - - if (this->named_tree_ != NULL_TREE) - return; - - // Create the structure for this type. Note that because we call - // base() here, we don't attempt to represent a named type defined - // as another named type. Instead both named types will point to - // different base representations. - Type* base = this->type_->base(); - tree t; - switch (base->classification()) - { - case TYPE_ERROR: - this->is_error_ = true; - this->named_tree_ = error_mark_node; - return; - - case TYPE_VOID: - case TYPE_BOOLEAN: - case TYPE_INTEGER: - case TYPE_FLOAT: - case TYPE_COMPLEX: - case TYPE_STRING: - case TYPE_NIL: - // These are simple basic types, we can just create them - // directly. - t = Type::get_named_type_tree(gogo, base); - if (t == error_mark_node) - { - this->is_error_ = true; - this->named_tree_ = error_mark_node; - return; - } - t = build_variant_type_copy(t); - break; - - case TYPE_MAP: - case TYPE_CHANNEL: - // All maps and channels have the same type in GENERIC. - t = Type::get_named_type_tree(gogo, base); - if (t == error_mark_node) - { - this->is_error_ = true; - this->named_tree_ = error_mark_node; - return; - } - t = build_variant_type_copy(t); - break; - - case TYPE_FUNCTION: - case TYPE_POINTER: - t = build_variant_type_copy(ptr_type_node); - break; - - case TYPE_STRUCT: - t = make_node(RECORD_TYPE); - break; - - case TYPE_ARRAY: - if (base->is_open_array_type()) - t = gogo->slice_type_tree(void_type_node); - else - t = make_node(ARRAY_TYPE); - break; - - case TYPE_INTERFACE: - if (base->interface_type()->is_empty()) - { - t = Interface_type::empty_type_tree(gogo); - t = build_variant_type_copy(t); - } - else - { - source_location loc = base->interface_type()->location(); - t = Interface_type::non_empty_type_tree(loc); - } - break; - - default: - case TYPE_SINK: - case TYPE_CALL_MULTIPLE_RESULT: - case TYPE_NAMED: - case TYPE_FORWARD: - gcc_unreachable(); - } - - // Create the named type. - - tree id = this->named_object_->get_id(gogo); - tree decl = build_decl(this->location_, TYPE_DECL, id, t); - TYPE_NAME(t) = decl; - - this->named_tree_ = t; -} - -// Get a tree for a named type. - -tree -Named_type::do_get_tree(Gogo* gogo) -{ - if (this->is_error_) - return error_mark_node; - - tree t = this->named_tree_; - - // FIXME: GOGO can be NULL when called from go_type_for_size, which - // is only used for basic types. - if (gogo == NULL || !gogo->named_types_are_converted()) - { - // We have not completed converting named types. NAMED_TREE_ is - // a placeholder and we shouldn't do anything further. - if (t != NULL_TREE) - return t; - - // We don't build dependencies for types whose sizes do not - // change or are not relevant, so we may see them here while - // converting types. - this->create_placeholder(gogo); - t = this->named_tree_; - gcc_assert(t != NULL_TREE); - return t; - } - - // We are not converting types. This should only be called if the - // type has already been converted. - if (!this->is_converted_) - { - gcc_assert(saw_errors()); - return error_mark_node; - } - - gcc_assert(t != NULL_TREE && TYPE_SIZE(t) != NULL_TREE); - - // Complete the tree. - Type* base = this->type_->base(); - tree t1; - switch (base->classification()) - { - case TYPE_ERROR: - return error_mark_node; - - case TYPE_VOID: - case TYPE_BOOLEAN: - case TYPE_INTEGER: - case TYPE_FLOAT: - case TYPE_COMPLEX: - case TYPE_STRING: - case TYPE_NIL: - case TYPE_MAP: - case TYPE_CHANNEL: - case TYPE_STRUCT: - case TYPE_INTERFACE: - return t; - - case TYPE_FUNCTION: - // Don't build a circular data structure. GENERIC can't handle - // it. - if (this->seen_ > 0) - { - this->is_circular_ = true; - return ptr_type_node; - } - ++this->seen_; - t1 = Type::get_named_type_tree(gogo, base); - --this->seen_; - if (t1 == error_mark_node) - return error_mark_node; - if (this->is_circular_) - t1 = ptr_type_node; - gcc_assert(t != NULL_TREE && TREE_CODE(t) == POINTER_TYPE); - gcc_assert(TREE_CODE(t1) == POINTER_TYPE); - TREE_TYPE(t) = TREE_TYPE(t1); - return t; - - case TYPE_POINTER: - // Don't build a circular data structure. GENERIC can't handle - // it. - if (this->seen_ > 0) - { - this->is_circular_ = true; - return ptr_type_node; - } - ++this->seen_; - t1 = Type::get_named_type_tree(gogo, base); - --this->seen_; - if (t1 == error_mark_node) - return error_mark_node; - if (this->is_circular_) - t1 = ptr_type_node; - gcc_assert(t != NULL_TREE && TREE_CODE(t) == POINTER_TYPE); - gcc_assert(TREE_CODE(t1) == POINTER_TYPE); - TREE_TYPE(t) = TREE_TYPE(t1); - return t; - - case TYPE_ARRAY: - if (base->is_open_array_type()) - { - if (this->seen_ > 0) - return t; - else - { - ++this->seen_; - t = base->array_type()->fill_in_slice_tree(gogo, t); - --this->seen_; - } - } - return t; - - default: - case TYPE_SINK: - case TYPE_CALL_MULTIPLE_RESULT: - case TYPE_NAMED: - case TYPE_FORWARD: - gcc_unreachable(); - } - - gcc_unreachable(); -} - -// Build a type descriptor for a named type. - -Expression* -Named_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - // If NAME is not NULL, then we don't really want the type - // descriptor for this type; we want the descriptor for the - // underlying type, giving it the name NAME. - return this->named_type_descriptor(gogo, this->type_, - name == NULL ? this : name); -} - -// Add to the reflection string. This is used mostly for the name of -// the type used in a type descriptor, not for actual reflection -// strings. - -void -Named_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - if (this->location() != BUILTINS_LOCATION) - { - const Package* package = this->named_object_->package(); - if (package != NULL) - ret->append(package->name()); - else - ret->append(gogo->package_name()); - ret->push_back('.'); - } - if (this->in_function_ != NULL) - { - ret->append(Gogo::unpack_hidden_name(this->in_function_->name())); - ret->push_back('$'); - } - ret->append(Gogo::unpack_hidden_name(this->named_object_->name())); -} - -// Get the mangled name. - -void -Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - Named_object* no = this->named_object_; - std::string name; - if (this->location() == BUILTINS_LOCATION) - gcc_assert(this->in_function_ == NULL); - else - { - const std::string& unique_prefix(no->package() == NULL - ? gogo->unique_prefix() - : no->package()->unique_prefix()); - const std::string& package_name(no->package() == NULL - ? gogo->package_name() - : no->package()->name()); - name = unique_prefix; - name.append(1, '.'); - name.append(package_name); - name.append(1, '.'); - if (this->in_function_ != NULL) - { - name.append(Gogo::unpack_hidden_name(this->in_function_->name())); - name.append(1, '$'); - } - } - name.append(Gogo::unpack_hidden_name(no->name())); - char buf[20]; - snprintf(buf, sizeof buf, "N%u_", static_cast(name.length())); - ret->append(buf); - ret->append(name); -} - -// Export the type. This is called to export a global type. - -void -Named_type::export_named_type(Export* exp, const std::string&) const -{ - // We don't need to write the name of the type here, because it will - // be written by Export::write_type anyhow. - exp->write_c_string("type "); - exp->write_type(this); - exp->write_c_string(";\n"); -} - -// Import a named type. - -void -Named_type::import_named_type(Import* imp, Named_type** ptype) -{ - imp->require_c_string("type "); - Type *type = imp->read_type(); - *ptype = type->named_type(); - gcc_assert(*ptype != NULL); - imp->require_c_string(";\n"); -} - -// Export the type when it is referenced by another type. In this -// case Export::export_type will already have issued the name. - -void -Named_type::do_export(Export* exp) const -{ - exp->write_type(this->type_); - - // To save space, we only export the methods directly attached to - // this type. - Bindings* methods = this->local_methods_; - if (methods == NULL) - return; - - exp->write_c_string("\n"); - for (Bindings::const_definitions_iterator p = methods->begin_definitions(); - p != methods->end_definitions(); - ++p) - { - exp->write_c_string(" "); - (*p)->export_named_object(exp); - } - - for (Bindings::const_declarations_iterator p = methods->begin_declarations(); - p != methods->end_declarations(); - ++p) - { - if (p->second->is_function_declaration()) - { - exp->write_c_string(" "); - p->second->export_named_object(exp); - } - } -} - -// Make a named type. - -Named_type* -Type::make_named_type(Named_object* named_object, Type* type, - source_location location) -{ - return new Named_type(named_object, type, location); -} - -// Finalize the methods for TYPE. It will be a named type or a struct -// type. This sets *ALL_METHODS to the list of methods, and builds -// all required stubs. - -void -Type::finalize_methods(Gogo* gogo, const Type* type, source_location location, - Methods** all_methods) -{ - *all_methods = NULL; - Types_seen types_seen; - Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen, - all_methods); - Type::build_stub_methods(gogo, type, *all_methods, location); -} - -// Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to -// build up the struct field indexes as we go. DEPTH is the depth of -// the field within TYPE. IS_EMBEDDED_POINTER is true if we are -// adding these methods for an anonymous field with pointer type. -// NEEDS_STUB_METHOD is true if we need to use a stub method which -// calls the real method. TYPES_SEEN is used to avoid infinite -// recursion. - -void -Type::add_methods_for_type(const Type* type, - const Method::Field_indexes* field_indexes, - unsigned int depth, - bool is_embedded_pointer, - bool needs_stub_method, - Types_seen* types_seen, - Methods** methods) -{ - // Pointer types may not have methods. - if (type->points_to() != NULL) - return; - - const Named_type* nt = type->named_type(); - if (nt != NULL) - { - std::pair ins = types_seen->insert(nt); - if (!ins.second) - return; - } - - if (nt != NULL) - Type::add_local_methods_for_type(nt, field_indexes, depth, - is_embedded_pointer, needs_stub_method, - methods); - - Type::add_embedded_methods_for_type(type, field_indexes, depth, - is_embedded_pointer, needs_stub_method, - types_seen, methods); - - // If we are called with depth > 0, then we are looking at an - // anonymous field of a struct. If such a field has interface type, - // then we need to add the interface methods. We don't want to add - // them when depth == 0, because we will already handle them - // following the usual rules for an interface type. - if (depth > 0) - Type::add_interface_methods_for_type(type, field_indexes, depth, methods); -} - -// Add the local methods for the named type NT to *METHODS. The -// parameters are as for add_methods_to_type. - -void -Type::add_local_methods_for_type(const Named_type* nt, - const Method::Field_indexes* field_indexes, - unsigned int depth, - bool is_embedded_pointer, - bool needs_stub_method, - Methods** methods) -{ - const Bindings* local_methods = nt->local_methods(); - if (local_methods == NULL) - return; - - if (*methods == NULL) - *methods = new Methods(); - - for (Bindings::const_declarations_iterator p = - local_methods->begin_declarations(); - p != local_methods->end_declarations(); - ++p) - { - Named_object* no = p->second; - bool is_value_method = (is_embedded_pointer - || !Type::method_expects_pointer(no)); - Method* m = new Named_method(no, field_indexes, depth, is_value_method, - (needs_stub_method - || (depth > 0 && is_value_method))); - if (!(*methods)->insert(no->name(), m)) - delete m; - } -} - -// Add the embedded methods for TYPE to *METHODS. These are the -// methods attached to anonymous fields. The parameters are as for -// add_methods_to_type. - -void -Type::add_embedded_methods_for_type(const Type* type, - const Method::Field_indexes* field_indexes, - unsigned int depth, - bool is_embedded_pointer, - bool needs_stub_method, - Types_seen* types_seen, - Methods** methods) -{ - // Look for anonymous fields in TYPE. TYPE has fields if it is a - // struct. - const Struct_type* st = type->struct_type(); - if (st == NULL) - return; - - const Struct_field_list* fields = st->fields(); - if (fields == NULL) - return; - - unsigned int i = 0; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf, ++i) - { - if (!pf->is_anonymous()) - continue; - - Type* ftype = pf->type(); - bool is_pointer = false; - if (ftype->points_to() != NULL) - { - ftype = ftype->points_to(); - is_pointer = true; - } - Named_type* fnt = ftype->named_type(); - if (fnt == NULL) - { - // This is an error, but it will be diagnosed elsewhere. - continue; - } - - Method::Field_indexes* sub_field_indexes = new Method::Field_indexes(); - sub_field_indexes->next = field_indexes; - sub_field_indexes->field_index = i; - - Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1, - (is_embedded_pointer || is_pointer), - (needs_stub_method - || is_pointer - || i > 0), - types_seen, - methods); - } -} - -// If TYPE is an interface type, then add its method to *METHODS. -// This is for interface methods attached to an anonymous field. The -// parameters are as for add_methods_for_type. - -void -Type::add_interface_methods_for_type(const Type* type, - const Method::Field_indexes* field_indexes, - unsigned int depth, - Methods** methods) -{ - const Interface_type* it = type->interface_type(); - if (it == NULL) - return; - - const Typed_identifier_list* imethods = it->methods(); - if (imethods == NULL) - return; - - if (*methods == NULL) - *methods = new Methods(); - - for (Typed_identifier_list::const_iterator pm = imethods->begin(); - pm != imethods->end(); - ++pm) - { - Function_type* fntype = pm->type()->function_type(); - if (fntype == NULL) - { - // This is an error, but it should be reported elsewhere - // when we look at the methods for IT. - continue; - } - gcc_assert(!fntype->is_method()); - fntype = fntype->copy_with_receiver(const_cast(type)); - Method* m = new Interface_method(pm->name(), pm->location(), fntype, - field_indexes, depth); - if (!(*methods)->insert(pm->name(), m)) - delete m; - } -} - -// Build stub methods for TYPE as needed. METHODS is the set of -// methods for the type. A stub method may be needed when a type -// inherits a method from an anonymous field. When we need the -// address of the method, as in a type descriptor, we need to build a -// little stub which does the required field dereferences and jumps to -// the real method. LOCATION is the location of the type definition. - -void -Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods, - source_location location) -{ - if (methods == NULL) - return; - for (Methods::const_iterator p = methods->begin(); - p != methods->end(); - ++p) - { - Method* m = p->second; - if (m->is_ambiguous() || !m->needs_stub_method()) - continue; - - const std::string& name(p->first); - - // Build a stub method. - - const Function_type* fntype = m->type(); - - static unsigned int counter; - char buf[100]; - snprintf(buf, sizeof buf, "$this%u", counter); - ++counter; - - Type* receiver_type = const_cast(type); - if (!m->is_value_method()) - receiver_type = Type::make_pointer_type(receiver_type); - source_location receiver_location = m->receiver_location(); - Typed_identifier* receiver = new Typed_identifier(buf, receiver_type, - receiver_location); - - const Typed_identifier_list* fnparams = fntype->parameters(); - Typed_identifier_list* stub_params; - if (fnparams == NULL || fnparams->empty()) - stub_params = NULL; - else - { - // We give each stub parameter a unique name. - stub_params = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator pp = fnparams->begin(); - pp != fnparams->end(); - ++pp) - { - char pbuf[100]; - snprintf(pbuf, sizeof pbuf, "$p%u", counter); - stub_params->push_back(Typed_identifier(pbuf, pp->type(), - pp->location())); - ++counter; - } - } - - const Typed_identifier_list* fnresults = fntype->results(); - Typed_identifier_list* stub_results; - if (fnresults == NULL || fnresults->empty()) - stub_results = NULL; - else - { - // We create the result parameters without any names, since - // we won't refer to them. - stub_results = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator pr = fnresults->begin(); - pr != fnresults->end(); - ++pr) - stub_results->push_back(Typed_identifier("", pr->type(), - pr->location())); - } - - Function_type* stub_type = Type::make_function_type(receiver, - stub_params, - stub_results, - fntype->location()); - if (fntype->is_varargs()) - stub_type->set_is_varargs(); - - // We only create the function in the package which creates the - // type. - const Package* package; - if (type->named_type() == NULL) - package = NULL; - else - package = type->named_type()->named_object()->package(); - Named_object* stub; - if (package != NULL) - stub = Named_object::make_function_declaration(name, package, - stub_type, location); - else - { - stub = gogo->start_function(name, stub_type, false, - fntype->location()); - Type::build_one_stub_method(gogo, m, buf, stub_params, - fntype->is_varargs(), location); - gogo->finish_function(fntype->location()); - } - - m->set_stub_object(stub); - } -} - -// Build a stub method which adjusts the receiver as required to call -// METHOD. RECEIVER_NAME is the name we used for the receiver. -// PARAMS is the list of function parameters. - -void -Type::build_one_stub_method(Gogo* gogo, Method* method, - const char* receiver_name, - const Typed_identifier_list* params, - bool is_varargs, - source_location location) -{ - Named_object* receiver_object = gogo->lookup(receiver_name, NULL); - gcc_assert(receiver_object != NULL); - - Expression* expr = Expression::make_var_reference(receiver_object, location); - expr = Type::apply_field_indexes(expr, method->field_indexes(), location); - if (expr->type()->points_to() == NULL) - expr = Expression::make_unary(OPERATOR_AND, expr, location); - - Expression_list* arguments; - if (params == NULL || params->empty()) - arguments = NULL; - else - { - arguments = new Expression_list(); - for (Typed_identifier_list::const_iterator p = params->begin(); - p != params->end(); - ++p) - { - Named_object* param = gogo->lookup(p->name(), NULL); - gcc_assert(param != NULL); - Expression* param_ref = Expression::make_var_reference(param, - location); - arguments->push_back(param_ref); - } - } - - Expression* func = method->bind_method(expr, location); - gcc_assert(func != NULL); - Call_expression* call = Expression::make_call(func, arguments, is_varargs, - location); - size_t count = call->result_count(); - if (count == 0) - gogo->add_statement(Statement::make_statement(call)); - else - { - Expression_list* retvals = new Expression_list(); - if (count <= 1) - retvals->push_back(call); - else - { - for (size_t i = 0; i < count; ++i) - retvals->push_back(Expression::make_call_result(call, i)); - } - const Function* function = gogo->current_function()->func_value(); - const Typed_identifier_list* results = function->type()->results(); - Statement* retstat = Statement::make_return_statement(results, retvals, - location); - gogo->add_statement(retstat); - } -} - -// Apply FIELD_INDEXES to EXPR. The field indexes have to be applied -// in reverse order. - -Expression* -Type::apply_field_indexes(Expression* expr, - const Method::Field_indexes* field_indexes, - source_location location) -{ - if (field_indexes == NULL) - return expr; - expr = Type::apply_field_indexes(expr, field_indexes->next, location); - Struct_type* stype = expr->type()->deref()->struct_type(); - gcc_assert(stype != NULL - && field_indexes->field_index < stype->field_count()); - if (expr->type()->struct_type() == NULL) - { - gcc_assert(expr->type()->points_to() != NULL); - expr = Expression::make_unary(OPERATOR_MULT, expr, location); - gcc_assert(expr->type()->struct_type() == stype); - } - return Expression::make_field_reference(expr, field_indexes->field_index, - location); -} - -// Return whether NO is a method for which the receiver is a pointer. - -bool -Type::method_expects_pointer(const Named_object* no) -{ - const Function_type *fntype; - if (no->is_function()) - fntype = no->func_value()->type(); - else if (no->is_function_declaration()) - fntype = no->func_declaration_value()->type(); - else - gcc_unreachable(); - return fntype->receiver()->type()->points_to() != NULL; -} - -// Given a set of methods for a type, METHODS, return the method NAME, -// or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS -// is not NULL, then set *IS_AMBIGUOUS to true if the method exists -// but is ambiguous (and return NULL). - -Method* -Type::method_function(const Methods* methods, const std::string& name, - bool* is_ambiguous) -{ - if (is_ambiguous != NULL) - *is_ambiguous = false; - if (methods == NULL) - return NULL; - Methods::const_iterator p = methods->find(name); - if (p == methods->end()) - return NULL; - Method* m = p->second; - if (m->is_ambiguous()) - { - if (is_ambiguous != NULL) - *is_ambiguous = true; - return NULL; - } - return m; -} - -// Look for field or method NAME for TYPE. Return an Expression for -// the field or method bound to EXPR. If there is no such field or -// method, give an appropriate error and return an error expression. - -Expression* -Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr, - const std::string& name, - source_location location) -{ - if (type->deref()->is_error_type()) - return Expression::make_error(location); - - const Named_type* nt = type->deref()->named_type(); - const Struct_type* st = type->deref()->struct_type(); - const Interface_type* it = type->deref()->interface_type(); - - // If this is a pointer to a pointer, then it is possible that the - // pointed-to type has methods. - if (nt == NULL - && st == NULL - && it == NULL - && type->points_to() != NULL - && type->points_to()->points_to() != NULL) - { - expr = Expression::make_unary(OPERATOR_MULT, expr, location); - type = type->points_to(); - if (type->deref()->is_error_type()) - return Expression::make_error(location); - nt = type->points_to()->named_type(); - st = type->points_to()->struct_type(); - it = type->points_to()->interface_type(); - } - - bool receiver_can_be_pointer = (expr->type()->points_to() != NULL - || expr->is_addressable()); - std::vector seen; - bool is_method = false; - bool found_pointer_method = false; - std::string ambig1; - std::string ambig2; - if (Type::find_field_or_method(type, name, receiver_can_be_pointer, - &seen, NULL, &is_method, - &found_pointer_method, &ambig1, &ambig2)) - { - Expression* ret; - if (!is_method) - { - gcc_assert(st != NULL); - if (type->struct_type() == NULL) - { - gcc_assert(type->points_to() != NULL); - expr = Expression::make_unary(OPERATOR_MULT, expr, - location); - gcc_assert(expr->type()->struct_type() == st); - } - ret = st->field_reference(expr, name, location); - } - else if (it != NULL && it->find_method(name) != NULL) - ret = Expression::make_interface_field_reference(expr, name, - location); - else - { - Method* m; - if (nt != NULL) - m = nt->method_function(name, NULL); - else if (st != NULL) - m = st->method_function(name, NULL); - else - gcc_unreachable(); - gcc_assert(m != NULL); - if (!m->is_value_method() && expr->type()->points_to() == NULL) - expr = Expression::make_unary(OPERATOR_AND, expr, location); - ret = m->bind_method(expr, location); - } - gcc_assert(ret != NULL); - return ret; - } - else - { - if (!ambig1.empty()) - error_at(location, "%qs is ambiguous via %qs and %qs", - Gogo::message_name(name).c_str(), - Gogo::message_name(ambig1).c_str(), - Gogo::message_name(ambig2).c_str()); - else if (found_pointer_method) - error_at(location, "method requires a pointer"); - else if (nt == NULL && st == NULL && it == NULL) - error_at(location, - ("reference to field %qs in object which " - "has no fields or methods"), - Gogo::message_name(name).c_str()); - else - { - bool is_unexported; - if (!Gogo::is_hidden_name(name)) - is_unexported = false; - else - { - std::string unpacked = Gogo::unpack_hidden_name(name); - seen.clear(); - is_unexported = Type::is_unexported_field_or_method(gogo, type, - unpacked, - &seen); - } - if (is_unexported) - error_at(location, "reference to unexported field or method %qs", - Gogo::message_name(name).c_str()); - else - error_at(location, "reference to undefined field or method %qs", - Gogo::message_name(name).c_str()); - } - return Expression::make_error(location); - } -} - -// Look in TYPE for a field or method named NAME, return true if one -// is found. This looks through embedded anonymous fields and handles -// ambiguity. If a method is found, sets *IS_METHOD to true; -// otherwise, if a field is found, set it to false. If -// RECEIVER_CAN_BE_POINTER is false, then the receiver is a value -// whose address can not be taken. SEEN is used to avoid infinite -// recursion on invalid types. - -// When returning false, this sets *FOUND_POINTER_METHOD if we found a -// method we couldn't use because it requires a pointer. LEVEL is -// used for recursive calls, and can be NULL for a non-recursive call. -// When this function returns false because it finds that the name is -// ambiguous, it will store a path to the ambiguous names in *AMBIG1 -// and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2 -// will be unchanged. - -// This function just returns whether or not there is a field or -// method, and whether it is a field or method. It doesn't build an -// expression to refer to it. If it is a method, we then look in the -// list of all methods for the type. If it is a field, the search has -// to be done again, looking only for fields, and building up the -// expression as we go. - -bool -Type::find_field_or_method(const Type* type, - const std::string& name, - bool receiver_can_be_pointer, - std::vector* seen, - int* level, - bool* is_method, - bool* found_pointer_method, - std::string* ambig1, - std::string* ambig2) -{ - // Named types can have locally defined methods. - const Named_type* nt = type->named_type(); - if (nt == NULL && type->points_to() != NULL) - nt = type->points_to()->named_type(); - if (nt != NULL) - { - Named_object* no = nt->find_local_method(name); - if (no != NULL) - { - if (receiver_can_be_pointer || !Type::method_expects_pointer(no)) - { - *is_method = true; - return true; - } - - // Record that we have found a pointer method in order to - // give a better error message if we don't find anything - // else. - *found_pointer_method = true; - } - - for (std::vector::const_iterator p = seen->begin(); - p != seen->end(); - ++p) - { - if (*p == nt) - { - // We've already seen this type when searching for methods. - return false; - } - } - } - - // Interface types can have methods. - const Interface_type* it = type->deref()->interface_type(); - if (it != NULL && it->find_method(name) != NULL) - { - *is_method = true; - return true; - } - - // Struct types can have fields. They can also inherit fields and - // methods from anonymous fields. - const Struct_type* st = type->deref()->struct_type(); - if (st == NULL) - return false; - const Struct_field_list* fields = st->fields(); - if (fields == NULL) - return false; - - if (nt != NULL) - seen->push_back(nt); - - int found_level = 0; - bool found_is_method = false; - std::string found_ambig1; - std::string found_ambig2; - const Struct_field* found_parent = NULL; - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - if (pf->field_name() == name) - { - *is_method = false; - if (nt != NULL) - seen->pop_back(); - return true; - } - - if (!pf->is_anonymous()) - continue; - - if (pf->type()->deref()->is_error_type() - || pf->type()->deref()->is_undefined()) - continue; - - Named_type* fnt = pf->type()->named_type(); - if (fnt == NULL) - fnt = pf->type()->deref()->named_type(); - gcc_assert(fnt != NULL); - - int sublevel = level == NULL ? 1 : *level + 1; - bool sub_is_method; - std::string subambig1; - std::string subambig2; - bool subfound = Type::find_field_or_method(fnt, - name, - receiver_can_be_pointer, - seen, - &sublevel, - &sub_is_method, - found_pointer_method, - &subambig1, - &subambig2); - if (!subfound) - { - if (!subambig1.empty()) - { - // The name was found via this field, but is ambiguous. - // if the ambiguity is lower or at the same level as - // anything else we have already found, then we want to - // pass the ambiguity back to the caller. - if (found_level == 0 || sublevel <= found_level) - { - found_ambig1 = pf->field_name() + '.' + subambig1; - found_ambig2 = pf->field_name() + '.' + subambig2; - found_level = sublevel; - } - } - } - else - { - // The name was found via this field. Use the level to see - // if we want to use this one, or whether it introduces an - // ambiguity. - if (found_level == 0 || sublevel < found_level) - { - found_level = sublevel; - found_is_method = sub_is_method; - found_ambig1.clear(); - found_ambig2.clear(); - found_parent = &*pf; - } - else if (sublevel > found_level) - ; - else if (found_ambig1.empty()) - { - // We found an ambiguity. - gcc_assert(found_parent != NULL); - found_ambig1 = found_parent->field_name(); - found_ambig2 = pf->field_name(); - } - else - { - // We found an ambiguity, but we already know of one. - // Just report the earlier one. - } - } - } - - // Here if we didn't find anything FOUND_LEVEL is 0. If we found - // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and - // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL - // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty. - - if (nt != NULL) - seen->pop_back(); - - if (found_level == 0) - return false; - else if (!found_ambig1.empty()) - { - gcc_assert(!found_ambig1.empty()); - ambig1->assign(found_ambig1); - ambig2->assign(found_ambig2); - if (level != NULL) - *level = found_level; - return false; - } - else - { - if (level != NULL) - *level = found_level; - *is_method = found_is_method; - return true; - } -} - -// Return whether NAME is an unexported field or method for TYPE. - -bool -Type::is_unexported_field_or_method(Gogo* gogo, const Type* type, - const std::string& name, - std::vector* seen) -{ - const Named_type* nt = type->named_type(); - if (nt == NULL) - nt = type->deref()->named_type(); - if (nt != NULL) - { - if (nt->is_unexported_local_method(gogo, name)) - return true; - - for (std::vector::const_iterator p = seen->begin(); - p != seen->end(); - ++p) - { - if (*p == nt) - { - // We've already seen this type. - return false; - } - } - } - - type = type->deref(); - - const Interface_type* it = type->interface_type(); - if (it != NULL && it->is_unexported_method(gogo, name)) - return true; - - const Struct_type* st = type->struct_type(); - if (st != NULL && st->is_unexported_local_field(gogo, name)) - return true; - - if (st == NULL) - return false; - - const Struct_field_list* fields = st->fields(); - if (fields == NULL) - return false; - - if (nt != NULL) - seen->push_back(nt); - - for (Struct_field_list::const_iterator pf = fields->begin(); - pf != fields->end(); - ++pf) - { - if (pf->is_anonymous() - && !pf->type()->deref()->is_error_type() - && !pf->type()->deref()->is_undefined()) - { - Named_type* subtype = pf->type()->named_type(); - if (subtype == NULL) - subtype = pf->type()->deref()->named_type(); - if (subtype == NULL) - { - // This is an error, but it will be diagnosed elsewhere. - continue; - } - if (Type::is_unexported_field_or_method(gogo, subtype, name, seen)) - { - if (nt != NULL) - seen->pop_back(); - return true; - } - } - } - - if (nt != NULL) - seen->pop_back(); - - return false; -} - -// Class Forward_declaration. - -Forward_declaration_type::Forward_declaration_type(Named_object* named_object) - : Type(TYPE_FORWARD), - named_object_(named_object->resolve()), warned_(false) -{ - gcc_assert(this->named_object_->is_unknown() - || this->named_object_->is_type_declaration()); -} - -// Return the named object. - -Named_object* -Forward_declaration_type::named_object() -{ - return this->named_object_->resolve(); -} - -const Named_object* -Forward_declaration_type::named_object() const -{ - return this->named_object_->resolve(); -} - -// Return the name of the forward declared type. - -const std::string& -Forward_declaration_type::name() const -{ - return this->named_object()->name(); -} - -// Warn about a use of a type which has been declared but not defined. - -void -Forward_declaration_type::warn() const -{ - Named_object* no = this->named_object_->resolve(); - if (no->is_unknown()) - { - // The name was not defined anywhere. - if (!this->warned_) - { - error_at(this->named_object_->location(), - "use of undefined type %qs", - no->message_name().c_str()); - this->warned_ = true; - } - } - else if (no->is_type_declaration()) - { - // The name was seen as a type, but the type was never defined. - if (no->type_declaration_value()->using_type()) - { - error_at(this->named_object_->location(), - "use of undefined type %qs", - no->message_name().c_str()); - this->warned_ = true; - } - } - else - { - // The name was defined, but not as a type. - if (!this->warned_) - { - error_at(this->named_object_->location(), "expected type"); - this->warned_ = true; - } - } -} - -// Get the base type of a declaration. This gives an error if the -// type has not yet been defined. - -Type* -Forward_declaration_type::real_type() -{ - if (this->is_defined()) - return this->named_object()->type_value(); - else - { - this->warn(); - return Type::make_error_type(); - } -} - -const Type* -Forward_declaration_type::real_type() const -{ - if (this->is_defined()) - return this->named_object()->type_value(); - else - { - this->warn(); - return Type::make_error_type(); - } -} - -// Return whether the base type is defined. - -bool -Forward_declaration_type::is_defined() const -{ - return this->named_object()->is_type(); -} - -// Add a method. This is used when methods are defined before the -// type. - -Named_object* -Forward_declaration_type::add_method(const std::string& name, - Function* function) -{ - Named_object* no = this->named_object(); - if (no->is_unknown()) - no->declare_as_type(); - return no->type_declaration_value()->add_method(name, function); -} - -// Add a method declaration. This is used when methods are declared -// before the type. - -Named_object* -Forward_declaration_type::add_method_declaration(const std::string& name, - Function_type* type, - source_location location) -{ - Named_object* no = this->named_object(); - if (no->is_unknown()) - no->declare_as_type(); - Type_declaration* td = no->type_declaration_value(); - return td->add_method_declaration(name, type, location); -} - -// Traversal. - -int -Forward_declaration_type::do_traverse(Traverse* traverse) -{ - if (this->is_defined() - && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - return TRAVERSE_CONTINUE; -} - -// Get a tree for the type. - -tree -Forward_declaration_type::do_get_tree(Gogo* gogo) -{ - if (this->is_defined()) - return Type::get_named_type_tree(gogo, this->real_type()); - - if (this->warned_) - return error_mark_node; - - // We represent an undefined type as a struct with no fields. That - // should work fine for the middle-end, since the same case can - // arise in C. - Named_object* no = this->named_object(); - tree type_tree = make_node(RECORD_TYPE); - tree id = no->get_id(gogo); - tree decl = build_decl(no->location(), TYPE_DECL, id, type_tree); - TYPE_NAME(type_tree) = decl; - layout_type(type_tree); - return type_tree; -} - -// Build a type descriptor for a forwarded type. - -Expression* -Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name) -{ - if (!this->is_defined()) - return Expression::make_nil(BUILTINS_LOCATION); - else - { - Type* t = this->real_type(); - if (name != NULL) - return this->named_type_descriptor(gogo, t, name); - else - return Expression::make_type_descriptor(t, BUILTINS_LOCATION); - } -} - -// The reflection string. - -void -Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const -{ - this->append_reflection(this->real_type(), gogo, ret); -} - -// The mangled name. - -void -Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const -{ - if (this->is_defined()) - this->append_mangled_name(this->real_type(), gogo, ret); - else - { - const Named_object* no = this->named_object(); - std::string name; - if (no->package() == NULL) - name = gogo->package_name(); - else - name = no->package()->name(); - name += '.'; - name += Gogo::unpack_hidden_name(no->name()); - char buf[20]; - snprintf(buf, sizeof buf, "N%u_", - static_cast(name.length())); - ret->append(buf); - ret->append(name); - } -} - -// Export a forward declaration. This can happen when a defined type -// refers to a type which is only declared (and is presumably defined -// in some other file in the same package). - -void -Forward_declaration_type::do_export(Export*) const -{ - // If there is a base type, that should be exported instead of this. - gcc_assert(!this->is_defined()); - - // We don't output anything. -} - -// Make a forward declaration. - -Type* -Type::make_forward_declaration(Named_object* named_object) -{ - return new Forward_declaration_type(named_object); -} - -// Class Typed_identifier_list. - -// Sort the entries by name. - -struct Typed_identifier_list_sort -{ - public: - bool - operator()(const Typed_identifier& t1, const Typed_identifier& t2) const - { return t1.name() < t2.name(); } -}; - -void -Typed_identifier_list::sort_by_name() -{ - std::sort(this->entries_.begin(), this->entries_.end(), - Typed_identifier_list_sort()); -} - -// Traverse types. - -int -Typed_identifier_list::traverse(Traverse* traverse) -{ - for (Typed_identifier_list::const_iterator p = this->begin(); - p != this->end(); - ++p) - { - if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT) - return TRAVERSE_EXIT; - } - return TRAVERSE_CONTINUE; -} - -// Copy the list. - -Typed_identifier_list* -Typed_identifier_list::copy() const -{ - Typed_identifier_list* ret = new Typed_identifier_list(); - for (Typed_identifier_list::const_iterator p = this->begin(); - p != this->end(); - ++p) - ret->push_back(Typed_identifier(p->name(), p->type(), p->location())); - return ret; -} diff --git a/gcc/go/gofrontend/unsafe.cc.merge-left.r167407 b/gcc/go/gofrontend/unsafe.cc.merge-left.r167407 deleted file mode 100644 index 51d812b3d8f..00000000000 --- a/gcc/go/gofrontend/unsafe.cc.merge-left.r167407 +++ /dev/null @@ -1,134 +0,0 @@ -// unsafe.cc -- Go frontend builtin unsafe package. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include "types.h" -#include "gogo.h" - -// Set up the builtin unsafe package. This should probably be driven -// by a table. - -void -Gogo::import_unsafe(const std::string& local_name, bool is_local_name_exported, - source_location location) -{ - location_t bloc = BUILTINS_LOCATION; - - bool add_to_globals; - Package* package = this->add_imported_package("unsafe", local_name, - is_local_name_exported, - "libgo_unsafe", - location, &add_to_globals); - package->set_is_imported(); - - Bindings* bindings = package->bindings(); - - // The type may have already been created by an import. - Named_object* no = package->bindings()->lookup("Pointer"); - if (no == NULL) - { - Type* type = Type::make_pointer_type(Type::make_void_type()); - no = bindings->add_type("Pointer", package, type, UNKNOWN_LOCATION); - } - else - { - gcc_assert(no->package() == package); - gcc_assert(no->is_type()); - gcc_assert(no->type_value()->is_unsafe_pointer_type()); - no->type_value()->set_is_visible(); - } - Named_type* pointer_type = no->type_value(); - if (add_to_globals) - this->add_named_type(pointer_type); - - Type* int_type = this->lookup_global("int")->type_value(); - - // Sizeof. - Typed_identifier_list* results = new Typed_identifier_list; - results->push_back(Typed_identifier("", int_type, bloc)); - Function_type* fntype = Type::make_function_type(NULL, NULL, results, bloc); - fntype->set_is_builtin(); - no = bindings->add_function_declaration("Sizeof", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Offsetof. - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", int_type, bloc)); - fntype = Type::make_function_type(NULL, NULL, results, bloc); - fntype->set_is_varargs(); - fntype->set_is_builtin(); - no = bindings->add_function_declaration("Offsetof", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Alignof. - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", int_type, bloc)); - fntype = Type::make_function_type(NULL, NULL, results, bloc); - fntype->set_is_varargs(); - fntype->set_is_builtin(); - no = bindings->add_function_declaration("Alignof", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Typeof. - Type* empty_interface = Type::make_interface_type(NULL, bloc); - Typed_identifier_list* parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("i", empty_interface, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", empty_interface, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("Typeof", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Reflect. - parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("it", empty_interface, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", empty_interface, bloc)); - results->push_back(Typed_identifier("", pointer_type, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("Reflect", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Unreflect. - parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("typ", empty_interface, bloc)); - parameters->push_back(Typed_identifier("addr", pointer_type, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", empty_interface, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("Unreflect", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // New. - parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("typ", empty_interface, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", pointer_type, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("New", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // NewArray. - parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("typ", empty_interface, bloc)); - parameters->push_back(Typed_identifier("n", int_type, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", pointer_type, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("NewArray", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - this->imported_unsafe_ = true; -} diff --git a/gcc/go/gofrontend/unsafe.cc.merge-right.r172891 b/gcc/go/gofrontend/unsafe.cc.merge-right.r172891 deleted file mode 100644 index 80b367cc46d..00000000000 --- a/gcc/go/gofrontend/unsafe.cc.merge-right.r172891 +++ /dev/null @@ -1,146 +0,0 @@ -// unsafe.cc -- Go frontend builtin unsafe package. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include "go-c.h" -#include "types.h" -#include "gogo.h" - -// Set up the builtin unsafe package. This should probably be driven -// by a table. - -void -Gogo::import_unsafe(const std::string& local_name, bool is_local_name_exported, - source_location location) -{ - location_t bloc = BUILTINS_LOCATION; - - bool add_to_globals; - Package* package = this->add_imported_package("unsafe", local_name, - is_local_name_exported, - "libgo_unsafe", - location, &add_to_globals); - - if (package == NULL) - { - go_assert(saw_errors()); - return; - } - - package->set_is_imported(); - - Bindings* bindings = package->bindings(); - - // The type may have already been created by an import. - Named_object* no = package->bindings()->lookup("Pointer"); - if (no == NULL) - { - Type* type = Type::make_pointer_type(Type::make_void_type()); - no = bindings->add_type("Pointer", package, type, UNKNOWN_LOCATION); - } - else - { - go_assert(no->package() == package); - go_assert(no->is_type()); - go_assert(no->type_value()->is_unsafe_pointer_type()); - no->type_value()->set_is_visible(); - } - Named_type* pointer_type = no->type_value(); - if (add_to_globals) - this->add_named_type(pointer_type); - - Type* int_type = this->lookup_global("int")->type_value(); - - // Sizeof. - Typed_identifier_list* results = new Typed_identifier_list; - results->push_back(Typed_identifier("", int_type, bloc)); - Function_type* fntype = Type::make_function_type(NULL, NULL, results, bloc); - fntype->set_is_builtin(); - no = bindings->add_function_declaration("Sizeof", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Offsetof. - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", int_type, bloc)); - fntype = Type::make_function_type(NULL, NULL, results, bloc); - fntype->set_is_varargs(); - fntype->set_is_builtin(); - no = bindings->add_function_declaration("Offsetof", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Alignof. - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", int_type, bloc)); - fntype = Type::make_function_type(NULL, NULL, results, bloc); - fntype->set_is_varargs(); - fntype->set_is_builtin(); - no = bindings->add_function_declaration("Alignof", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Typeof. - Type* empty_interface = Type::make_interface_type(NULL, bloc); - Typed_identifier_list* parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("i", empty_interface, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", empty_interface, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("Typeof", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Reflect. - parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("it", empty_interface, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", empty_interface, bloc)); - results->push_back(Typed_identifier("", pointer_type, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("Reflect", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Unreflect. - parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("typ", empty_interface, bloc)); - parameters->push_back(Typed_identifier("addr", pointer_type, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", empty_interface, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("Unreflect", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // New. - parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("typ", empty_interface, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", pointer_type, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("New", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // NewArray. - parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("typ", empty_interface, bloc)); - parameters->push_back(Typed_identifier("n", int_type, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", pointer_type, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("NewArray", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - if (!this->imported_unsafe_) - { - go_imported_unsafe(); - this->imported_unsafe_ = true; - } -} diff --git a/gcc/go/gofrontend/unsafe.cc.working b/gcc/go/gofrontend/unsafe.cc.working deleted file mode 100644 index 9d51b4d9424..00000000000 --- a/gcc/go/gofrontend/unsafe.cc.working +++ /dev/null @@ -1,146 +0,0 @@ -// unsafe.cc -- Go frontend builtin unsafe package. - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "go-system.h" - -#include "go-c.h" -#include "types.h" -#include "gogo.h" - -// Set up the builtin unsafe package. This should probably be driven -// by a table. - -void -Gogo::import_unsafe(const std::string& local_name, bool is_local_name_exported, - source_location location) -{ - location_t bloc = BUILTINS_LOCATION; - - bool add_to_globals; - Package* package = this->add_imported_package("unsafe", local_name, - is_local_name_exported, - "libgo_unsafe", - location, &add_to_globals); - - if (package == NULL) - { - gcc_assert(saw_errors()); - return; - } - - package->set_is_imported(); - - Bindings* bindings = package->bindings(); - - // The type may have already been created by an import. - Named_object* no = package->bindings()->lookup("Pointer"); - if (no == NULL) - { - Type* type = Type::make_pointer_type(Type::make_void_type()); - no = bindings->add_type("Pointer", package, type, UNKNOWN_LOCATION); - } - else - { - gcc_assert(no->package() == package); - gcc_assert(no->is_type()); - gcc_assert(no->type_value()->is_unsafe_pointer_type()); - no->type_value()->set_is_visible(); - } - Named_type* pointer_type = no->type_value(); - if (add_to_globals) - this->add_named_type(pointer_type); - - Type* int_type = this->lookup_global("int")->type_value(); - - // Sizeof. - Typed_identifier_list* results = new Typed_identifier_list; - results->push_back(Typed_identifier("", int_type, bloc)); - Function_type* fntype = Type::make_function_type(NULL, NULL, results, bloc); - fntype->set_is_builtin(); - no = bindings->add_function_declaration("Sizeof", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Offsetof. - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", int_type, bloc)); - fntype = Type::make_function_type(NULL, NULL, results, bloc); - fntype->set_is_varargs(); - fntype->set_is_builtin(); - no = bindings->add_function_declaration("Offsetof", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Alignof. - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", int_type, bloc)); - fntype = Type::make_function_type(NULL, NULL, results, bloc); - fntype->set_is_varargs(); - fntype->set_is_builtin(); - no = bindings->add_function_declaration("Alignof", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Typeof. - Type* empty_interface = Type::make_interface_type(NULL, bloc); - Typed_identifier_list* parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("i", empty_interface, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", empty_interface, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("Typeof", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Reflect. - parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("it", empty_interface, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", empty_interface, bloc)); - results->push_back(Typed_identifier("", pointer_type, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("Reflect", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // Unreflect. - parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("typ", empty_interface, bloc)); - parameters->push_back(Typed_identifier("addr", pointer_type, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", empty_interface, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("Unreflect", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // New. - parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("typ", empty_interface, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", pointer_type, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("New", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - // NewArray. - parameters = new Typed_identifier_list; - parameters->push_back(Typed_identifier("typ", empty_interface, bloc)); - parameters->push_back(Typed_identifier("n", int_type, bloc)); - results = new Typed_identifier_list; - results->push_back(Typed_identifier("", pointer_type, bloc)); - fntype = Type::make_function_type(NULL, parameters, results, bloc); - no = bindings->add_function_declaration("NewArray", package, fntype, bloc); - if (add_to_globals) - this->add_named_object(no); - - if (!this->imported_unsafe_) - { - go_imported_unsafe(); - this->imported_unsafe_ = true; - } -} -- 2.30.2