1 // gogo.cc -- Go frontend parsed representation.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
13 #include "statements.h"
14 #include "expressions.h"
24 Gogo::Gogo(Backend* backend, int int_type_size, int pointer_size)
28 globals_(new Bindings(NULL)),
30 imported_unsafe_(false),
32 map_descriptors_(NULL),
33 type_descriptor_decls_(NULL),
39 unique_prefix_specified_(false),
41 named_types_are_converted_(false)
43 const source_location loc = BUILTINS_LOCATION;
45 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
46 RUNTIME_TYPE_KIND_UINT8);
47 this->add_named_type(uint8_type);
48 this->add_named_type(Type::make_integer_type("uint16", true, 16,
49 RUNTIME_TYPE_KIND_UINT16));
50 this->add_named_type(Type::make_integer_type("uint32", true, 32,
51 RUNTIME_TYPE_KIND_UINT32));
52 this->add_named_type(Type::make_integer_type("uint64", true, 64,
53 RUNTIME_TYPE_KIND_UINT64));
55 this->add_named_type(Type::make_integer_type("int8", false, 8,
56 RUNTIME_TYPE_KIND_INT8));
57 this->add_named_type(Type::make_integer_type("int16", false, 16,
58 RUNTIME_TYPE_KIND_INT16));
59 this->add_named_type(Type::make_integer_type("int32", false, 32,
60 RUNTIME_TYPE_KIND_INT32));
61 this->add_named_type(Type::make_integer_type("int64", false, 64,
62 RUNTIME_TYPE_KIND_INT64));
64 this->add_named_type(Type::make_float_type("float32", 32,
65 RUNTIME_TYPE_KIND_FLOAT32));
66 this->add_named_type(Type::make_float_type("float64", 64,
67 RUNTIME_TYPE_KIND_FLOAT64));
69 this->add_named_type(Type::make_complex_type("complex64", 64,
70 RUNTIME_TYPE_KIND_COMPLEX64));
71 this->add_named_type(Type::make_complex_type("complex128", 128,
72 RUNTIME_TYPE_KIND_COMPLEX128));
74 if (int_type_size < 32)
76 this->add_named_type(Type::make_integer_type("uint", true,
78 RUNTIME_TYPE_KIND_UINT));
79 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
80 RUNTIME_TYPE_KIND_INT);
81 this->add_named_type(int_type);
83 // "byte" is an alias for "uint8". Construct a Named_object which
84 // points to UINT8_TYPE. Note that this breaks the normal pairing
85 // in which a Named_object points to a Named_type which points back
86 // to the same Named_object.
87 Named_object* byte_type = this->declare_type("byte", loc);
88 byte_type->set_type_value(uint8_type);
90 this->add_named_type(Type::make_integer_type("uintptr", true,
92 RUNTIME_TYPE_KIND_UINTPTR));
94 this->add_named_type(Type::make_named_bool_type());
96 this->add_named_type(Type::make_named_string_type());
98 this->globals_->add_constant(Typed_identifier("true",
99 Type::make_boolean_type(),
102 Expression::make_boolean(true, loc),
104 this->globals_->add_constant(Typed_identifier("false",
105 Type::make_boolean_type(),
108 Expression::make_boolean(false, loc),
111 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
114 Expression::make_nil(loc),
117 Type* abstract_int_type = Type::make_abstract_integer_type();
118 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
121 Expression::make_iota(),
124 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
125 new_type->set_is_varargs();
126 new_type->set_is_builtin();
127 this->globals_->add_function_declaration("new", NULL, new_type, loc);
129 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
130 make_type->set_is_varargs();
131 make_type->set_is_builtin();
132 this->globals_->add_function_declaration("make", NULL, make_type, loc);
134 Typed_identifier_list* len_result = new Typed_identifier_list();
135 len_result->push_back(Typed_identifier("", int_type, loc));
136 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
138 len_type->set_is_builtin();
139 this->globals_->add_function_declaration("len", NULL, len_type, loc);
141 Typed_identifier_list* cap_result = new Typed_identifier_list();
142 cap_result->push_back(Typed_identifier("", int_type, loc));
143 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
145 cap_type->set_is_builtin();
146 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
148 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
149 print_type->set_is_varargs();
150 print_type->set_is_builtin();
151 this->globals_->add_function_declaration("print", NULL, print_type, loc);
153 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
154 print_type->set_is_varargs();
155 print_type->set_is_builtin();
156 this->globals_->add_function_declaration("println", NULL, print_type, loc);
158 Type *empty = Type::make_interface_type(NULL, loc);
159 Typed_identifier_list* panic_parms = new Typed_identifier_list();
160 panic_parms->push_back(Typed_identifier("e", empty, loc));
161 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
163 panic_type->set_is_builtin();
164 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
166 Typed_identifier_list* recover_result = new Typed_identifier_list();
167 recover_result->push_back(Typed_identifier("", empty, loc));
168 Function_type* recover_type = Type::make_function_type(NULL, NULL,
171 recover_type->set_is_builtin();
172 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
174 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
175 close_type->set_is_varargs();
176 close_type->set_is_builtin();
177 this->globals_->add_function_declaration("close", NULL, close_type, loc);
179 Typed_identifier_list* copy_result = new Typed_identifier_list();
180 copy_result->push_back(Typed_identifier("", int_type, loc));
181 Function_type* copy_type = Type::make_function_type(NULL, NULL,
183 copy_type->set_is_varargs();
184 copy_type->set_is_builtin();
185 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
187 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
188 append_type->set_is_varargs();
189 append_type->set_is_builtin();
190 this->globals_->add_function_declaration("append", NULL, append_type, loc);
192 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
193 complex_type->set_is_varargs();
194 complex_type->set_is_builtin();
195 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
197 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
198 real_type->set_is_varargs();
199 real_type->set_is_builtin();
200 this->globals_->add_function_declaration("real", NULL, real_type, loc);
202 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
203 imag_type->set_is_varargs();
204 imag_type->set_is_builtin();
205 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
208 // Munge name for use in an error message.
211 Gogo::message_name(const std::string& name)
213 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
216 // Get the package name.
219 Gogo::package_name() const
221 go_assert(this->package_ != NULL);
222 return this->package_->name();
225 // Set the package name.
228 Gogo::set_package_name(const std::string& package_name,
229 source_location location)
231 if (this->package_ != NULL && this->package_->name() != package_name)
233 error_at(location, "expected package %<%s%>",
234 Gogo::message_name(this->package_->name()).c_str());
238 // If the user did not specify a unique prefix, we always use "go".
239 // This in effect requires that the package name be unique.
240 if (this->unique_prefix_.empty())
241 this->unique_prefix_ = "go";
243 this->package_ = this->register_package(package_name, this->unique_prefix_,
246 // We used to permit people to qualify symbols with the current
247 // package name (e.g., P.x), but we no longer do.
248 // this->globals_->add_package(package_name, this->package_);
250 if (this->is_main_package())
252 // Declare "main" as a function which takes no parameters and
254 this->declare_function("main",
255 Type::make_function_type(NULL, NULL, NULL,
261 // Return whether this is the "main" package. This is not true if
262 // -fgo-prefix was used.
265 Gogo::is_main_package() const
267 return this->package_name() == "main" && !this->unique_prefix_specified_;
273 Gogo::import_package(const std::string& filename,
274 const std::string& local_name,
275 bool is_local_name_exported,
276 source_location location)
278 if (filename == "unsafe")
280 this->import_unsafe(local_name, is_local_name_exported, location);
284 Imports::const_iterator p = this->imports_.find(filename);
285 if (p != this->imports_.end())
287 Package* package = p->second;
288 package->set_location(location);
289 package->set_is_imported();
290 std::string ln = local_name;
291 bool is_ln_exported = is_local_name_exported;
294 ln = package->name();
295 is_ln_exported = Lex::is_exported_name(ln);
299 Bindings* bindings = package->bindings();
300 for (Bindings::const_declarations_iterator p =
301 bindings->begin_declarations();
302 p != bindings->end_declarations();
304 this->add_named_object(p->second);
307 package->set_uses_sink_alias();
310 ln = this->pack_hidden_name(ln, is_ln_exported);
311 this->package_->bindings()->add_package(ln, package);
316 Import::Stream* stream = Import::open_package(filename, location);
319 error_at(location, "import file %qs not found", filename.c_str());
323 Import imp(stream, location);
324 imp.register_builtin_types(this);
325 Package* package = imp.import(this, local_name, is_local_name_exported);
328 if (package->name() == this->package_name()
329 && package->unique_prefix() == this->unique_prefix())
331 ("imported package uses same package name and prefix "
332 "as package being compiled (see -fgo-prefix option)"));
334 this->imports_.insert(std::make_pair(filename, package));
335 package->set_is_imported();
341 // Add an import control function for an imported package to the list.
344 Gogo::add_import_init_fn(const std::string& package_name,
345 const std::string& init_name, int prio)
347 for (std::set<Import_init>::const_iterator p =
348 this->imported_init_fns_.begin();
349 p != this->imported_init_fns_.end();
352 if (p->init_name() == init_name
353 && (p->package_name() != package_name || p->priority() != prio))
355 error("duplicate package initialization name %qs",
356 Gogo::message_name(init_name).c_str());
357 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
358 Gogo::message_name(p->package_name()).c_str(),
360 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
361 Gogo::message_name(package_name).c_str(), prio);
366 this->imported_init_fns_.insert(Import_init(package_name, init_name,
370 // Return whether we are at the global binding level.
373 Gogo::in_global_scope() const
375 return this->functions_.empty();
378 // Return the current binding contour.
381 Gogo::current_bindings()
383 if (!this->functions_.empty())
384 return this->functions_.back().blocks.back()->bindings();
385 else if (this->package_ != NULL)
386 return this->package_->bindings();
388 return this->globals_;
392 Gogo::current_bindings() const
394 if (!this->functions_.empty())
395 return this->functions_.back().blocks.back()->bindings();
396 else if (this->package_ != NULL)
397 return this->package_->bindings();
399 return this->globals_;
402 // Return the current block.
405 Gogo::current_block()
407 if (this->functions_.empty())
410 return this->functions_.back().blocks.back();
413 // Look up a name in the current binding contour. If PFUNCTION is not
414 // NULL, set it to the function in which the name is defined, or NULL
415 // if the name is defined in global scope.
418 Gogo::lookup(const std::string& name, Named_object** pfunction) const
420 if (pfunction != NULL)
423 if (Gogo::is_sink_name(name))
424 return Named_object::make_sink();
426 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
427 p != this->functions_.rend();
430 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
433 if (pfunction != NULL)
434 *pfunction = p->function;
439 if (this->package_ != NULL)
441 Named_object* ret = this->package_->bindings()->lookup(name);
444 if (ret->package() != NULL)
445 ret->package()->set_used();
450 // We do not look in the global namespace. If we did, the global
451 // namespace would effectively hide names which were defined in
452 // package scope which we have not yet seen. Instead,
453 // define_global_names is called after parsing is over to connect
454 // undefined names at package scope with names defined at global
460 // Look up a name in the current block, without searching enclosing
464 Gogo::lookup_in_block(const std::string& name) const
466 go_assert(!this->functions_.empty());
467 go_assert(!this->functions_.back().blocks.empty());
468 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
471 // Look up a name in the global namespace.
474 Gogo::lookup_global(const char* name) const
476 return this->globals_->lookup(name);
479 // Add an imported package.
482 Gogo::add_imported_package(const std::string& real_name,
483 const std::string& alias_arg,
484 bool is_alias_exported,
485 const std::string& unique_prefix,
486 source_location location,
487 bool* padd_to_globals)
489 // FIXME: Now that we compile packages as a whole, should we permit
490 // importing the current package?
491 if (this->package_name() == real_name
492 && this->unique_prefix() == unique_prefix)
494 *padd_to_globals = false;
495 if (!alias_arg.empty() && alias_arg != ".")
497 std::string alias = this->pack_hidden_name(alias_arg,
499 this->package_->bindings()->add_package(alias, this->package_);
501 return this->package_;
503 else if (alias_arg == ".")
505 *padd_to_globals = true;
506 return this->register_package(real_name, unique_prefix, location);
508 else if (alias_arg == "_")
510 Package* ret = this->register_package(real_name, unique_prefix, location);
511 ret->set_uses_sink_alias();
516 *padd_to_globals = false;
517 std::string alias = alias_arg;
521 is_alias_exported = Lex::is_exported_name(alias);
523 alias = this->pack_hidden_name(alias, is_alias_exported);
524 Named_object* no = this->add_package(real_name, alias, unique_prefix,
526 if (!no->is_package())
528 return no->package_value();
535 Gogo::add_package(const std::string& real_name, const std::string& alias,
536 const std::string& unique_prefix, source_location location)
538 go_assert(this->in_global_scope());
540 // Register the package. Note that we might have already seen it in
541 // an earlier import.
542 Package* package = this->register_package(real_name, unique_prefix, location);
544 return this->package_->bindings()->add_package(alias, package);
547 // Register a package. This package may or may not be imported. This
548 // returns the Package structure for the package, creating if it
552 Gogo::register_package(const std::string& package_name,
553 const std::string& unique_prefix,
554 source_location location)
556 go_assert(!unique_prefix.empty() && !package_name.empty());
557 std::string name = unique_prefix + '.' + package_name;
558 Package* package = NULL;
559 std::pair<Packages::iterator, bool> ins =
560 this->packages_.insert(std::make_pair(name, package));
563 // We have seen this package name before.
564 package = ins.first->second;
565 go_assert(package != NULL);
566 go_assert(package->name() == package_name
567 && package->unique_prefix() == unique_prefix);
568 if (package->location() == UNKNOWN_LOCATION)
569 package->set_location(location);
573 // First time we have seen this package name.
574 package = new Package(package_name, unique_prefix, location);
575 go_assert(ins.first->second == NULL);
576 ins.first->second = package;
582 // Start compiling a function.
585 Gogo::start_function(const std::string& name, Function_type* type,
586 bool add_method_to_type, source_location location)
588 bool at_top_level = this->functions_.empty();
590 Block* block = new Block(NULL, location);
592 Function* enclosing = (at_top_level
594 : this->functions_.back().function->func_value());
596 Function* function = new Function(type, enclosing, block, location);
598 if (type->is_method())
600 const Typed_identifier* receiver = type->receiver();
601 Variable* this_param = new Variable(receiver->type(), NULL, false,
602 true, true, location);
603 std::string name = receiver->name();
606 // We need to give receivers a name since they wind up in
607 // DECL_ARGUMENTS. FIXME.
608 static unsigned int count;
610 snprintf(buf, sizeof buf, "r.%u", count);
614 block->bindings()->add_variable(name, NULL, this_param);
617 const Typed_identifier_list* parameters = type->parameters();
618 bool is_varargs = type->is_varargs();
619 if (parameters != NULL)
621 for (Typed_identifier_list::const_iterator p = parameters->begin();
622 p != parameters->end();
625 Variable* param = new Variable(p->type(), NULL, false, true, false,
627 if (is_varargs && p + 1 == parameters->end())
628 param->set_is_varargs_parameter();
630 std::string name = p->name();
631 if (name.empty() || Gogo::is_sink_name(name))
633 // We need to give parameters a name since they wind up
634 // in DECL_ARGUMENTS. FIXME.
635 static unsigned int count;
637 snprintf(buf, sizeof buf, "p.%u", count);
641 block->bindings()->add_variable(name, NULL, param);
645 function->create_result_variables(this);
647 const std::string* pname;
648 std::string nested_name;
649 bool is_init = false;
650 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
652 if ((type->parameters() != NULL && !type->parameters()->empty())
653 || (type->results() != NULL && !type->results()->empty()))
655 "func init must have no arguments and no return values");
656 // There can be multiple "init" functions, so give them each a
658 static int init_count;
660 snprintf(buf, sizeof buf, ".$init%d", init_count);
663 pname = &nested_name;
666 else if (!name.empty())
670 // Invent a name for a nested function.
671 static int nested_count;
673 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
676 pname = &nested_name;
680 if (Gogo::is_sink_name(*pname))
682 static int sink_count;
684 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
686 ret = Named_object::make_function(buf, NULL, function);
688 else if (!type->is_method())
690 ret = this->package_->bindings()->add_function(*pname, NULL, function);
691 if (!ret->is_function() || ret->func_value() != function)
693 // Redefinition error. Invent a name to avoid knockon
695 static int redefinition_count;
697 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
698 ++redefinition_count;
699 ret = this->package_->bindings()->add_function(buf, NULL, function);
704 if (!add_method_to_type)
705 ret = Named_object::make_function(name, NULL, function);
708 go_assert(at_top_level);
709 Type* rtype = type->receiver()->type();
711 // We want to look through the pointer created by the
712 // parser, without getting an error if the type is not yet
714 if (rtype->classification() == Type::TYPE_POINTER)
715 rtype = rtype->points_to();
717 if (rtype->is_error_type())
718 ret = Named_object::make_function(name, NULL, function);
719 else if (rtype->named_type() != NULL)
721 ret = rtype->named_type()->add_method(name, function);
722 if (!ret->is_function())
724 // Redefinition error.
725 ret = Named_object::make_function(name, NULL, function);
728 else if (rtype->forward_declaration_type() != NULL)
730 Named_object* type_no =
731 rtype->forward_declaration_type()->named_object();
732 if (type_no->is_unknown())
734 // If we are seeing methods it really must be a
735 // type. Declare it as such. An alternative would
736 // be to support lists of methods for unknown
737 // expressions. Either way the error messages if
738 // this is not a type are going to get confusing.
739 Named_object* declared =
740 this->declare_package_type(type_no->name(),
741 type_no->location());
743 == type_no->unknown_value()->real_named_object());
745 ret = rtype->forward_declaration_type()->add_method(name,
751 this->package_->bindings()->add_method(ret);
754 this->functions_.resize(this->functions_.size() + 1);
755 Open_function& of(this->functions_.back());
757 of.blocks.push_back(block);
761 this->init_functions_.push_back(ret);
762 this->need_init_fn_ = true;
768 // Finish compiling a function.
771 Gogo::finish_function(source_location location)
773 this->finish_block(location);
774 go_assert(this->functions_.back().blocks.empty());
775 this->functions_.pop_back();
778 // Return the current function.
781 Gogo::current_function() const
783 go_assert(!this->functions_.empty());
784 return this->functions_.back().function;
787 // Start a new block.
790 Gogo::start_block(source_location location)
792 go_assert(!this->functions_.empty());
793 Block* block = new Block(this->current_block(), location);
794 this->functions_.back().blocks.push_back(block);
800 Gogo::finish_block(source_location location)
802 go_assert(!this->functions_.empty());
803 go_assert(!this->functions_.back().blocks.empty());
804 Block* block = this->functions_.back().blocks.back();
805 this->functions_.back().blocks.pop_back();
806 block->set_end_location(location);
810 // Add an unknown name.
813 Gogo::add_unknown_name(const std::string& name, source_location location)
815 return this->package_->bindings()->add_unknown_name(name, location);
818 // Declare a function.
821 Gogo::declare_function(const std::string& name, Function_type* type,
822 source_location location)
824 if (!type->is_method())
825 return this->current_bindings()->add_function_declaration(name, NULL, type,
829 // We don't bother to add this to the list of global
831 Type* rtype = type->receiver()->type();
833 // We want to look through the pointer created by the
834 // parser, without getting an error if the type is not yet
836 if (rtype->classification() == Type::TYPE_POINTER)
837 rtype = rtype->points_to();
839 if (rtype->is_error_type())
841 else if (rtype->named_type() != NULL)
842 return rtype->named_type()->add_method_declaration(name, NULL, type,
844 else if (rtype->forward_declaration_type() != NULL)
846 Forward_declaration_type* ftype = rtype->forward_declaration_type();
847 return ftype->add_method_declaration(name, type, location);
854 // Add a label definition.
857 Gogo::add_label_definition(const std::string& label_name,
858 source_location location)
860 go_assert(!this->functions_.empty());
861 Function* func = this->functions_.back().function->func_value();
862 Label* label = func->add_label_definition(label_name, location);
863 this->add_statement(Statement::make_label_statement(label, location));
867 // Add a label reference.
870 Gogo::add_label_reference(const std::string& label_name)
872 go_assert(!this->functions_.empty());
873 Function* func = this->functions_.back().function->func_value();
874 return func->add_label_reference(label_name);
880 Gogo::add_statement(Statement* statement)
882 go_assert(!this->functions_.empty()
883 && !this->functions_.back().blocks.empty());
884 this->functions_.back().blocks.back()->add_statement(statement);
890 Gogo::add_block(Block* block, source_location location)
892 go_assert(!this->functions_.empty()
893 && !this->functions_.back().blocks.empty());
894 Statement* statement = Statement::make_block_statement(block, location);
895 this->functions_.back().blocks.back()->add_statement(statement);
901 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
904 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
910 Gogo::add_type(const std::string& name, Type* type, source_location location)
912 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
914 if (!this->in_global_scope() && no->is_type())
915 no->type_value()->set_in_function(this->functions_.back().function);
921 Gogo::add_named_type(Named_type* type)
923 go_assert(this->in_global_scope());
924 this->current_bindings()->add_named_type(type);
930 Gogo::declare_type(const std::string& name, source_location location)
932 Bindings* bindings = this->current_bindings();
933 Named_object* no = bindings->add_type_declaration(name, NULL, location);
934 if (!this->in_global_scope() && no->is_type_declaration())
936 Named_object* f = this->functions_.back().function;
937 no->type_declaration_value()->set_in_function(f);
942 // Declare a type at the package level.
945 Gogo::declare_package_type(const std::string& name, source_location location)
947 return this->package_->bindings()->add_type_declaration(name, NULL, location);
950 // Define a type which was already declared.
953 Gogo::define_type(Named_object* no, Named_type* type)
955 this->current_bindings()->define_type(no, type);
961 Gogo::add_variable(const std::string& name, Variable* variable)
963 Named_object* no = this->current_bindings()->add_variable(name, NULL,
966 // In a function the middle-end wants to see a DECL_EXPR node.
969 && !no->var_value()->is_parameter()
970 && !this->functions_.empty())
971 this->add_statement(Statement::make_variable_declaration(no));
976 // Add a sink--a reference to the blank identifier _.
981 return Named_object::make_sink();
984 // Add a named object.
987 Gogo::add_named_object(Named_object* no)
989 this->current_bindings()->add_named_object(no);
992 // Record that we've seen an interface type.
995 Gogo::record_interface_type(Interface_type* itype)
997 this->interface_types_.push_back(itype);
1000 // Return a name for a thunk object.
1005 static int thunk_count;
1006 char thunk_name[50];
1007 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1012 // Return whether a function is a thunk.
1015 Gogo::is_thunk(const Named_object* no)
1017 return no->name().compare(0, 6, "$thunk") == 0;
1020 // Define the global names. We do this only after parsing all the
1021 // input files, because the program might define the global names
1025 Gogo::define_global_names()
1027 for (Bindings::const_declarations_iterator p =
1028 this->globals_->begin_declarations();
1029 p != this->globals_->end_declarations();
1032 Named_object* global_no = p->second;
1033 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1034 Named_object* no = this->package_->bindings()->lookup(name);
1038 if (no->is_type_declaration())
1040 if (global_no->is_type())
1042 if (no->type_declaration_value()->has_methods())
1043 error_at(no->location(),
1044 "may not define methods for global type");
1045 no->set_type_value(global_no->type_value());
1049 error_at(no->location(), "expected type");
1050 Type* errtype = Type::make_error_type();
1051 Named_object* err = Named_object::make_type("error", NULL,
1054 no->set_type_value(err->type_value());
1057 else if (no->is_unknown())
1058 no->unknown_value()->set_real_named_object(global_no);
1062 // Clear out names in file scope.
1065 Gogo::clear_file_scope()
1067 this->package_->bindings()->clear_file_scope();
1069 // Warn about packages which were imported but not used.
1070 for (Packages::iterator p = this->packages_.begin();
1071 p != this->packages_.end();
1074 Package* package = p->second;
1075 if (package != this->package_
1076 && package->is_imported()
1078 && !package->uses_sink_alias()
1080 error_at(package->location(), "imported and not used: %s",
1081 Gogo::message_name(package->name()).c_str());
1082 package->clear_is_imported();
1083 package->clear_uses_sink_alias();
1084 package->clear_used();
1088 // Traverse the tree.
1091 Gogo::traverse(Traverse* traverse)
1093 // Traverse the current package first for consistency. The other
1094 // packages will only contain imported types, constants, and
1096 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1098 for (Packages::const_iterator p = this->packages_.begin();
1099 p != this->packages_.end();
1102 if (p->second != this->package_)
1104 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1110 // Traversal class used to verify types.
1112 class Verify_types : public Traverse
1116 : Traverse(traverse_types)
1123 // Verify that a type is correct.
1126 Verify_types::type(Type* t)
1129 return TRAVERSE_SKIP_COMPONENTS;
1130 return TRAVERSE_CONTINUE;
1133 // Verify that all types are correct.
1136 Gogo::verify_types()
1138 Verify_types traverse;
1139 this->traverse(&traverse);
1142 // Traversal class used to lower parse tree.
1144 class Lower_parse_tree : public Traverse
1147 Lower_parse_tree(Gogo* gogo, Named_object* function)
1148 : Traverse(traverse_variables
1149 | traverse_constants
1150 | traverse_functions
1151 | traverse_statements
1152 | traverse_expressions),
1153 gogo_(gogo), function_(function), iota_value_(-1)
1157 variable(Named_object*);
1160 constant(Named_object*, bool);
1163 function(Named_object*);
1166 statement(Block*, size_t* pindex, Statement*);
1169 expression(Expression**);
1174 // The function we are traversing.
1175 Named_object* function_;
1176 // Value to use for the predeclared constant iota.
1180 // Lower variables. We handle variables specially to break loops in
1181 // which a variable initialization expression refers to itself. The
1182 // loop breaking is in lower_init_expression.
1185 Lower_parse_tree::variable(Named_object* no)
1187 if (no->is_variable())
1188 no->var_value()->lower_init_expression(this->gogo_, this->function_);
1189 return TRAVERSE_CONTINUE;
1192 // Lower constants. We handle constants specially so that we can set
1193 // the right value for the predeclared constant iota. This works in
1194 // conjunction with the way we lower Const_expression objects.
1197 Lower_parse_tree::constant(Named_object* no, bool)
1199 Named_constant* nc = no->const_value();
1201 // Don't get into trouble if the constant's initializer expression
1202 // refers to the constant itself.
1204 return TRAVERSE_CONTINUE;
1207 go_assert(this->iota_value_ == -1);
1208 this->iota_value_ = nc->iota_value();
1209 nc->traverse_expression(this);
1210 this->iota_value_ = -1;
1212 nc->clear_lowering();
1214 // We will traverse the expression a second time, but that will be
1217 return TRAVERSE_CONTINUE;
1220 // Lower function closure types. Record the function while lowering
1221 // it, so that we can pass it down when lowering an expression.
1224 Lower_parse_tree::function(Named_object* no)
1226 no->func_value()->set_closure_type();
1228 go_assert(this->function_ == NULL);
1229 this->function_ = no;
1230 int t = no->func_value()->traverse(this);
1231 this->function_ = NULL;
1233 if (t == TRAVERSE_EXIT)
1235 return TRAVERSE_SKIP_COMPONENTS;
1238 // Lower statement parse trees.
1241 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1243 // Lower the expressions first.
1244 int t = sorig->traverse_contents(this);
1245 if (t == TRAVERSE_EXIT)
1248 // Keep lowering until nothing changes.
1249 Statement* s = sorig;
1252 Statement* snew = s->lower(this->gogo_, this->function_, block);
1256 t = s->traverse_contents(this);
1257 if (t == TRAVERSE_EXIT)
1262 block->replace_statement(*pindex, s);
1264 return TRAVERSE_SKIP_COMPONENTS;
1267 // Lower expression parse trees.
1270 Lower_parse_tree::expression(Expression** pexpr)
1272 // We have to lower all subexpressions first, so that we can get
1273 // their type if necessary. This is awkward, because we don't have
1274 // a postorder traversal pass.
1275 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1276 return TRAVERSE_EXIT;
1277 // Keep lowering until nothing changes.
1280 Expression* e = *pexpr;
1281 Expression* enew = e->lower(this->gogo_, this->function_,
1287 return TRAVERSE_SKIP_COMPONENTS;
1290 // Lower the parse tree. This is called after the parse is complete,
1291 // when all names should be resolved.
1294 Gogo::lower_parse_tree()
1296 Lower_parse_tree lower_parse_tree(this, NULL);
1297 this->traverse(&lower_parse_tree);
1303 Gogo::lower_block(Named_object* function, Block* block)
1305 Lower_parse_tree lower_parse_tree(this, function);
1306 block->traverse(&lower_parse_tree);
1309 // Lower an expression.
1312 Gogo::lower_expression(Named_object* function, Expression** pexpr)
1314 Lower_parse_tree lower_parse_tree(this, function);
1315 lower_parse_tree.expression(pexpr);
1318 // Lower a constant. This is called when lowering a reference to a
1319 // constant. We have to make sure that the constant has already been
1323 Gogo::lower_constant(Named_object* no)
1325 go_assert(no->is_const());
1326 Lower_parse_tree lower(this, NULL);
1327 lower.constant(no, false);
1330 // Look for interface types to finalize methods of inherited
1333 class Finalize_methods : public Traverse
1336 Finalize_methods(Gogo* gogo)
1337 : Traverse(traverse_types),
1348 // Finalize the methods of an interface type.
1351 Finalize_methods::type(Type* t)
1353 // Check the classification so that we don't finalize the methods
1354 // twice for a named interface type.
1355 switch (t->classification())
1357 case Type::TYPE_INTERFACE:
1358 t->interface_type()->finalize_methods();
1361 case Type::TYPE_NAMED:
1363 // We have to finalize the methods of the real type first.
1364 // But if the real type is a struct type, then we only want to
1365 // finalize the methods of the field types, not of the struct
1366 // type itself. We don't want to add methods to the struct,
1367 // since it has a name.
1368 Type* rt = t->named_type()->real_type();
1369 if (rt->classification() != Type::TYPE_STRUCT)
1371 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1372 return TRAVERSE_EXIT;
1376 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1377 return TRAVERSE_EXIT;
1380 t->named_type()->finalize_methods(this->gogo_);
1382 return TRAVERSE_SKIP_COMPONENTS;
1385 case Type::TYPE_STRUCT:
1386 t->struct_type()->finalize_methods(this->gogo_);
1393 return TRAVERSE_CONTINUE;
1396 // Finalize method lists and build stub methods for types.
1399 Gogo::finalize_methods()
1401 Finalize_methods finalize(this);
1402 this->traverse(&finalize);
1405 // Set types for unspecified variables and constants.
1408 Gogo::determine_types()
1410 Bindings* bindings = this->current_bindings();
1411 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1412 p != bindings->end_definitions();
1415 if ((*p)->is_function())
1416 (*p)->func_value()->determine_types();
1417 else if ((*p)->is_variable())
1418 (*p)->var_value()->determine_type();
1419 else if ((*p)->is_const())
1420 (*p)->const_value()->determine_type();
1422 // See if a variable requires us to build an initialization
1423 // function. We know that we will see all global variables
1425 if (!this->need_init_fn_ && (*p)->is_variable())
1427 Variable* variable = (*p)->var_value();
1429 // If this is a global variable which requires runtime
1430 // initialization, we need an initialization function.
1431 if (!variable->is_global())
1433 else if (variable->init() == NULL)
1435 else if (variable->type()->interface_type() != NULL)
1436 this->need_init_fn_ = true;
1437 else if (variable->init()->is_constant())
1439 else if (!variable->init()->is_composite_literal())
1440 this->need_init_fn_ = true;
1441 else if (variable->init()->is_nonconstant_composite_literal())
1442 this->need_init_fn_ = true;
1444 // If this is a global variable which holds a pointer value,
1445 // then we need an initialization function to register it as a
1447 if (variable->is_global() && variable->type()->has_pointer())
1448 this->need_init_fn_ = true;
1452 // Determine the types of constants in packages.
1453 for (Packages::const_iterator p = this->packages_.begin();
1454 p != this->packages_.end();
1456 p->second->determine_types();
1459 // Traversal class used for type checking.
1461 class Check_types_traverse : public Traverse
1464 Check_types_traverse(Gogo* gogo)
1465 : Traverse(traverse_variables
1466 | traverse_constants
1467 | traverse_functions
1468 | traverse_statements
1469 | traverse_expressions),
1474 variable(Named_object*);
1477 constant(Named_object*, bool);
1480 function(Named_object*);
1483 statement(Block*, size_t* pindex, Statement*);
1486 expression(Expression**);
1493 // Check that a variable initializer has the right type.
1496 Check_types_traverse::variable(Named_object* named_object)
1498 if (named_object->is_variable())
1500 Variable* var = named_object->var_value();
1501 Expression* init = var->init();
1504 && !Type::are_assignable(var->type(), init->type(), &reason))
1507 error_at(var->location(), "incompatible type in initialization");
1509 error_at(var->location(),
1510 "incompatible type in initialization (%s)",
1515 return TRAVERSE_CONTINUE;
1518 // Check that a constant initializer has the right type.
1521 Check_types_traverse::constant(Named_object* named_object, bool)
1523 Named_constant* constant = named_object->const_value();
1524 Type* ctype = constant->type();
1525 if (ctype->integer_type() == NULL
1526 && ctype->float_type() == NULL
1527 && ctype->complex_type() == NULL
1528 && !ctype->is_boolean_type()
1529 && !ctype->is_string_type())
1531 if (ctype->is_nil_type())
1532 error_at(constant->location(), "const initializer cannot be nil");
1533 else if (!ctype->is_error())
1534 error_at(constant->location(), "invalid constant type");
1535 constant->set_error();
1537 else if (!constant->expr()->is_constant())
1539 error_at(constant->expr()->location(), "expression is not constant");
1540 constant->set_error();
1542 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1545 error_at(constant->location(),
1546 "initialization expression has wrong type");
1547 constant->set_error();
1549 return TRAVERSE_CONTINUE;
1552 // There are no types to check in a function, but this is where we
1553 // issue warnings about labels which are defined but not referenced.
1556 Check_types_traverse::function(Named_object* no)
1558 no->func_value()->check_labels();
1559 return TRAVERSE_CONTINUE;
1562 // Check that types are valid in a statement.
1565 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1567 s->check_types(this->gogo_);
1568 return TRAVERSE_CONTINUE;
1571 // Check that types are valid in an expression.
1574 Check_types_traverse::expression(Expression** expr)
1576 (*expr)->check_types(this->gogo_);
1577 return TRAVERSE_CONTINUE;
1580 // Check that types are valid.
1585 Check_types_traverse traverse(this);
1586 this->traverse(&traverse);
1589 // Check the types in a single block.
1592 Gogo::check_types_in_block(Block* block)
1594 Check_types_traverse traverse(this);
1595 block->traverse(&traverse);
1598 // A traversal class used to find a single shortcut operator within an
1601 class Find_shortcut : public Traverse
1605 : Traverse(traverse_blocks
1606 | traverse_statements
1607 | traverse_expressions),
1611 // A pointer to the expression which was found, or NULL if none was
1615 { return this->found_; }
1620 { return TRAVERSE_SKIP_COMPONENTS; }
1623 statement(Block*, size_t*, Statement*)
1624 { return TRAVERSE_SKIP_COMPONENTS; }
1627 expression(Expression**);
1630 Expression** found_;
1633 // Find a shortcut expression.
1636 Find_shortcut::expression(Expression** pexpr)
1638 Expression* expr = *pexpr;
1639 Binary_expression* be = expr->binary_expression();
1641 return TRAVERSE_CONTINUE;
1642 Operator op = be->op();
1643 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1644 return TRAVERSE_CONTINUE;
1645 go_assert(this->found_ == NULL);
1646 this->found_ = pexpr;
1647 return TRAVERSE_EXIT;
1650 // A traversal class used to turn shortcut operators into explicit if
1653 class Shortcuts : public Traverse
1656 Shortcuts(Gogo* gogo)
1657 : Traverse(traverse_variables
1658 | traverse_statements),
1664 variable(Named_object*);
1667 statement(Block*, size_t*, Statement*);
1670 // Convert a shortcut operator.
1672 convert_shortcut(Block* enclosing, Expression** pshortcut);
1678 // Remove shortcut operators in a single statement.
1681 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1683 // FIXME: This approach doesn't work for switch statements, because
1684 // we add the new statements before the whole switch when we need to
1685 // instead add them just before the switch expression. The right
1686 // fix is probably to lower switch statements with nonconstant cases
1687 // to a series of conditionals.
1688 if (s->switch_statement() != NULL)
1689 return TRAVERSE_CONTINUE;
1693 Find_shortcut find_shortcut;
1695 // If S is a variable declaration, then ordinary traversal won't
1696 // do anything. We want to explicitly traverse the
1697 // initialization expression if there is one.
1698 Variable_declaration_statement* vds = s->variable_declaration_statement();
1699 Expression* init = NULL;
1701 s->traverse_contents(&find_shortcut);
1704 init = vds->var()->var_value()->init();
1706 return TRAVERSE_CONTINUE;
1707 init->traverse(&init, &find_shortcut);
1709 Expression** pshortcut = find_shortcut.found();
1710 if (pshortcut == NULL)
1711 return TRAVERSE_CONTINUE;
1713 Statement* snew = this->convert_shortcut(block, pshortcut);
1714 block->insert_statement_before(*pindex, snew);
1717 if (pshortcut == &init)
1718 vds->var()->var_value()->set_init(init);
1722 // Remove shortcut operators in the initializer of a global variable.
1725 Shortcuts::variable(Named_object* no)
1727 if (no->is_result_variable())
1728 return TRAVERSE_CONTINUE;
1729 Variable* var = no->var_value();
1730 Expression* init = var->init();
1731 if (!var->is_global() || init == NULL)
1732 return TRAVERSE_CONTINUE;
1736 Find_shortcut find_shortcut;
1737 init->traverse(&init, &find_shortcut);
1738 Expression** pshortcut = find_shortcut.found();
1739 if (pshortcut == NULL)
1740 return TRAVERSE_CONTINUE;
1742 Statement* snew = this->convert_shortcut(NULL, pshortcut);
1743 var->add_preinit_statement(this->gogo_, snew);
1744 if (pshortcut == &init)
1745 var->set_init(init);
1749 // Given an expression which uses a shortcut operator, return a
1750 // statement which implements it, and update *PSHORTCUT accordingly.
1753 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
1755 Binary_expression* shortcut = (*pshortcut)->binary_expression();
1756 Expression* left = shortcut->left();
1757 Expression* right = shortcut->right();
1758 source_location loc = shortcut->location();
1760 Block* retblock = new Block(enclosing, loc);
1761 retblock->set_end_location(loc);
1763 Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
1765 retblock->add_statement(ts);
1767 Block* block = new Block(retblock, loc);
1768 block->set_end_location(loc);
1769 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
1770 Statement* assign = Statement::make_assignment(tmpref, right, loc);
1771 block->add_statement(assign);
1773 Expression* cond = Expression::make_temporary_reference(ts, loc);
1774 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
1775 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
1777 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
1779 retblock->add_statement(if_statement);
1781 *pshortcut = Expression::make_temporary_reference(ts, loc);
1785 // Now convert any shortcut operators in LEFT and RIGHT.
1786 Shortcuts shortcuts(this->gogo_);
1787 retblock->traverse(&shortcuts);
1789 return Statement::make_block_statement(retblock, loc);
1792 // Turn shortcut operators into explicit if statements. Doing this
1793 // considerably simplifies the order of evaluation rules.
1796 Gogo::remove_shortcuts()
1798 Shortcuts shortcuts(this);
1799 this->traverse(&shortcuts);
1802 // A traversal class which finds all the expressions which must be
1803 // evaluated in order within a statement or larger expression. This
1804 // is used to implement the rules about order of evaluation.
1806 class Find_eval_ordering : public Traverse
1809 typedef std::vector<Expression**> Expression_pointers;
1812 Find_eval_ordering()
1813 : Traverse(traverse_blocks
1814 | traverse_statements
1815 | traverse_expressions),
1821 { return this->exprs_.size(); }
1823 typedef Expression_pointers::const_iterator const_iterator;
1827 { return this->exprs_.begin(); }
1831 { return this->exprs_.end(); }
1836 { return TRAVERSE_SKIP_COMPONENTS; }
1839 statement(Block*, size_t*, Statement*)
1840 { return TRAVERSE_SKIP_COMPONENTS; }
1843 expression(Expression**);
1846 // A list of pointers to expressions with side-effects.
1847 Expression_pointers exprs_;
1850 // If an expression must be evaluated in order, put it on the list.
1853 Find_eval_ordering::expression(Expression** expression_pointer)
1855 // We have to look at subexpressions before this one.
1856 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1857 return TRAVERSE_EXIT;
1858 if ((*expression_pointer)->must_eval_in_order())
1859 this->exprs_.push_back(expression_pointer);
1860 return TRAVERSE_SKIP_COMPONENTS;
1863 // A traversal class for ordering evaluations.
1865 class Order_eval : public Traverse
1868 Order_eval(Gogo* gogo)
1869 : Traverse(traverse_variables
1870 | traverse_statements),
1875 variable(Named_object*);
1878 statement(Block*, size_t*, Statement*);
1885 // Implement the order of evaluation rules for a statement.
1888 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
1890 // FIXME: This approach doesn't work for switch statements, because
1891 // we add the new statements before the whole switch when we need to
1892 // instead add them just before the switch expression. The right
1893 // fix is probably to lower switch statements with nonconstant cases
1894 // to a series of conditionals.
1895 if (s->switch_statement() != NULL)
1896 return TRAVERSE_CONTINUE;
1898 Find_eval_ordering find_eval_ordering;
1900 // If S is a variable declaration, then ordinary traversal won't do
1901 // anything. We want to explicitly traverse the initialization
1902 // expression if there is one.
1903 Variable_declaration_statement* vds = s->variable_declaration_statement();
1904 Expression* init = NULL;
1905 Expression* orig_init = NULL;
1907 s->traverse_contents(&find_eval_ordering);
1910 init = vds->var()->var_value()->init();
1912 return TRAVERSE_CONTINUE;
1915 // It might seem that this could be
1916 // init->traverse_subexpressions. Unfortunately that can fail
1919 // newvar, err := call(arg())
1920 // Here newvar will have an init of call result 0 of
1921 // call(arg()). If we only traverse subexpressions, we will
1922 // only find arg(), and we won't bother to move anything out.
1923 // Then we get to the assignment to err, we will traverse the
1924 // whole statement, and this time we will find both call() and
1925 // arg(), and so we will move them out. This will cause them to
1926 // be put into temporary variables before the assignment to err
1927 // but after the declaration of newvar. To avoid that problem,
1928 // we traverse the entire expression here.
1929 Expression::traverse(&init, &find_eval_ordering);
1932 if (find_eval_ordering.size() <= 1)
1934 // If there is only one expression with a side-effect, we can
1935 // leave it in place.
1936 return TRAVERSE_CONTINUE;
1939 bool is_thunk = s->thunk_statement() != NULL;
1940 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1941 p != find_eval_ordering.end();
1944 Expression** pexpr = *p;
1946 // The last expression in a thunk will be the call passed to go
1947 // or defer, which we must not evaluate early.
1948 if (is_thunk && p + 1 == find_eval_ordering.end())
1951 source_location loc = (*pexpr)->location();
1952 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1953 block->insert_statement_before(*pindex, ts);
1956 *pexpr = Expression::make_temporary_reference(ts, loc);
1959 if (init != orig_init)
1960 vds->var()->var_value()->set_init(init);
1962 return TRAVERSE_CONTINUE;
1965 // Implement the order of evaluation rules for the initializer of a
1969 Order_eval::variable(Named_object* no)
1971 if (no->is_result_variable())
1972 return TRAVERSE_CONTINUE;
1973 Variable* var = no->var_value();
1974 Expression* init = var->init();
1975 if (!var->is_global() || init == NULL)
1976 return TRAVERSE_CONTINUE;
1978 Find_eval_ordering find_eval_ordering;
1979 init->traverse_subexpressions(&find_eval_ordering);
1981 if (find_eval_ordering.size() <= 1)
1983 // If there is only one expression with a side-effect, we can
1984 // leave it in place.
1985 return TRAVERSE_SKIP_COMPONENTS;
1988 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1989 p != find_eval_ordering.end();
1992 Expression** pexpr = *p;
1993 source_location loc = (*pexpr)->location();
1994 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1995 var->add_preinit_statement(this->gogo_, ts);
1996 *pexpr = Expression::make_temporary_reference(ts, loc);
1999 return TRAVERSE_SKIP_COMPONENTS;
2002 // Use temporary variables to implement the order of evaluation rules.
2005 Gogo::order_evaluations()
2007 Order_eval order_eval(this);
2008 this->traverse(&order_eval);
2011 // Traversal to convert calls to the predeclared recover function to
2012 // pass in an argument indicating whether it can recover from a panic
2015 class Convert_recover : public Traverse
2018 Convert_recover(Named_object* arg)
2019 : Traverse(traverse_expressions),
2025 expression(Expression**);
2028 // The argument to pass to the function.
2032 // Convert calls to recover.
2035 Convert_recover::expression(Expression** pp)
2037 Call_expression* ce = (*pp)->call_expression();
2038 if (ce != NULL && ce->is_recover_call())
2039 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2041 return TRAVERSE_CONTINUE;
2044 // Traversal for build_recover_thunks.
2046 class Build_recover_thunks : public Traverse
2049 Build_recover_thunks(Gogo* gogo)
2050 : Traverse(traverse_functions),
2055 function(Named_object*);
2059 can_recover_arg(source_location);
2065 // If this function calls recover, turn it into a thunk.
2068 Build_recover_thunks::function(Named_object* orig_no)
2070 Function* orig_func = orig_no->func_value();
2071 if (!orig_func->calls_recover()
2072 || orig_func->is_recover_thunk()
2073 || orig_func->has_recover_thunk())
2074 return TRAVERSE_CONTINUE;
2076 Gogo* gogo = this->gogo_;
2077 source_location location = orig_func->location();
2082 Function_type* orig_fntype = orig_func->type();
2083 Typed_identifier_list* new_params = new Typed_identifier_list();
2084 std::string receiver_name;
2085 if (orig_fntype->is_method())
2087 const Typed_identifier* receiver = orig_fntype->receiver();
2088 snprintf(buf, sizeof buf, "rt.%u", count);
2090 receiver_name = buf;
2091 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2092 receiver->location()));
2094 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2095 if (orig_params != NULL && !orig_params->empty())
2097 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2098 p != orig_params->end();
2101 snprintf(buf, sizeof buf, "pt.%u", count);
2103 new_params->push_back(Typed_identifier(buf, p->type(),
2107 snprintf(buf, sizeof buf, "pr.%u", count);
2109 std::string can_recover_name = buf;
2110 new_params->push_back(Typed_identifier(can_recover_name,
2111 Type::lookup_bool_type(),
2112 orig_fntype->location()));
2114 const Typed_identifier_list* orig_results = orig_fntype->results();
2115 Typed_identifier_list* new_results;
2116 if (orig_results == NULL || orig_results->empty())
2120 new_results = new Typed_identifier_list();
2121 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2122 p != orig_results->end();
2124 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2127 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2129 orig_fntype->location());
2130 if (orig_fntype->is_varargs())
2131 new_fntype->set_is_varargs();
2133 std::string name = orig_no->name() + "$recover";
2134 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2136 Function *new_func = new_no->func_value();
2137 if (orig_func->enclosing() != NULL)
2138 new_func->set_enclosing(orig_func->enclosing());
2140 // We build the code for the original function attached to the new
2141 // function, and then swap the original and new function bodies.
2142 // This means that existing references to the original function will
2143 // then refer to the new function. That makes this code a little
2144 // confusing, in that the reference to NEW_NO really refers to the
2145 // other function, not the one we are building.
2147 Expression* closure = NULL;
2148 if (orig_func->needs_closure())
2150 Named_object* orig_closure_no = orig_func->closure_var();
2151 Variable* orig_closure_var = orig_closure_no->var_value();
2152 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2153 true, false, location);
2154 snprintf(buf, sizeof buf, "closure.%u", count);
2156 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2158 new_func->set_closure_var(new_closure_no);
2159 closure = Expression::make_var_reference(new_closure_no, location);
2162 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2164 Expression_list* args = new Expression_list();
2165 if (new_params != NULL)
2167 // Note that we skip the last parameter, which is the boolean
2168 // indicating whether recover can succed.
2169 for (Typed_identifier_list::const_iterator p = new_params->begin();
2170 p + 1 != new_params->end();
2173 Named_object* p_no = gogo->lookup(p->name(), NULL);
2174 go_assert(p_no != NULL
2175 && p_no->is_variable()
2176 && p_no->var_value()->is_parameter());
2177 args->push_back(Expression::make_var_reference(p_no, location));
2180 args->push_back(this->can_recover_arg(location));
2182 Call_expression* call = Expression::make_call(fn, args, false, location);
2185 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2186 s = Statement::make_statement(call);
2189 Expression_list* vals = new Expression_list();
2190 size_t rc = orig_fntype->results()->size();
2192 vals->push_back(call);
2195 for (size_t i = 0; i < rc; ++i)
2196 vals->push_back(Expression::make_call_result(call, i));
2198 s = Statement::make_return_statement(vals, location);
2200 s->determine_types();
2201 gogo->add_statement(s);
2203 gogo->finish_function(location);
2205 // Swap the function bodies and types.
2206 new_func->swap_for_recover(orig_func);
2207 orig_func->set_is_recover_thunk();
2208 new_func->set_calls_recover();
2209 new_func->set_has_recover_thunk();
2211 Bindings* orig_bindings = orig_func->block()->bindings();
2212 Bindings* new_bindings = new_func->block()->bindings();
2213 if (orig_fntype->is_method())
2215 // We changed the receiver to be a regular parameter. We have
2216 // to update the binding accordingly in both functions.
2217 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2218 go_assert(orig_rec_no != NULL
2219 && orig_rec_no->is_variable()
2220 && !orig_rec_no->var_value()->is_receiver());
2221 orig_rec_no->var_value()->set_is_receiver();
2223 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2224 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2225 if (new_rec_no == NULL)
2226 go_assert(saw_errors());
2229 go_assert(new_rec_no->is_variable()
2230 && new_rec_no->var_value()->is_receiver());
2231 new_rec_no->var_value()->set_is_not_receiver();
2235 // Because we flipped blocks but not types, the can_recover
2236 // parameter appears in the (now) old bindings as a parameter.
2237 // Change it to a local variable, whereupon it will be discarded.
2238 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2239 go_assert(can_recover_no != NULL
2240 && can_recover_no->is_variable()
2241 && can_recover_no->var_value()->is_parameter());
2242 orig_bindings->remove_binding(can_recover_no);
2244 // Add the can_recover argument to the (now) new bindings, and
2245 // attach it to any recover statements.
2246 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2247 false, true, false, location);
2248 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2250 Convert_recover convert_recover(can_recover_no);
2251 new_func->traverse(&convert_recover);
2253 // Update the function pointers in any named results.
2254 new_func->update_result_variables();
2255 orig_func->update_result_variables();
2257 return TRAVERSE_CONTINUE;
2260 // Return the expression to pass for the .can_recover parameter to the
2261 // new function. This indicates whether a call to recover may return
2262 // non-nil. The expression is
2263 // __go_can_recover(__builtin_return_address()).
2266 Build_recover_thunks::can_recover_arg(source_location location)
2268 static Named_object* builtin_return_address;
2269 if (builtin_return_address == NULL)
2271 const source_location bloc = BUILTINS_LOCATION;
2273 Typed_identifier_list* param_types = new Typed_identifier_list();
2274 Type* uint_type = Type::lookup_integer_type("uint");
2275 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2277 Typed_identifier_list* return_types = new Typed_identifier_list();
2278 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2279 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2281 Function_type* fntype = Type::make_function_type(NULL, param_types,
2282 return_types, bloc);
2283 builtin_return_address =
2284 Named_object::make_function_declaration("__builtin_return_address",
2285 NULL, fntype, bloc);
2286 const char* n = "__builtin_return_address";
2287 builtin_return_address->func_declaration_value()->set_asm_name(n);
2290 static Named_object* can_recover;
2291 if (can_recover == NULL)
2293 const source_location bloc = BUILTINS_LOCATION;
2294 Typed_identifier_list* param_types = new Typed_identifier_list();
2295 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2296 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2297 Type* boolean_type = Type::lookup_bool_type();
2298 Typed_identifier_list* results = new Typed_identifier_list();
2299 results->push_back(Typed_identifier("", boolean_type, bloc));
2300 Function_type* fntype = Type::make_function_type(NULL, param_types,
2302 can_recover = Named_object::make_function_declaration("__go_can_recover",
2305 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2308 Expression* fn = Expression::make_func_reference(builtin_return_address,
2312 mpz_init_set_ui(zval, 0UL);
2313 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2315 Expression_list *args = new Expression_list();
2316 args->push_back(zexpr);
2318 Expression* call = Expression::make_call(fn, args, false, location);
2320 args = new Expression_list();
2321 args->push_back(call);
2323 fn = Expression::make_func_reference(can_recover, NULL, location);
2324 return Expression::make_call(fn, args, false, location);
2327 // Build thunks for functions which call recover. We build a new
2328 // function with an extra parameter, which is whether a call to
2329 // recover can succeed. We then move the body of this function to
2330 // that one. We then turn this function into a thunk which calls the
2331 // new one, passing the value of
2332 // __go_can_recover(__builtin_return_address()). The function will be
2333 // marked as not splitting the stack. This will cooperate with the
2334 // implementation of defer to make recover do the right thing.
2337 Gogo::build_recover_thunks()
2339 Build_recover_thunks build_recover_thunks(this);
2340 this->traverse(&build_recover_thunks);
2343 // Look for named types to see whether we need to create an interface
2346 class Build_method_tables : public Traverse
2349 Build_method_tables(Gogo* gogo,
2350 const std::vector<Interface_type*>& interfaces)
2351 : Traverse(traverse_types),
2352 gogo_(gogo), interfaces_(interfaces)
2361 // A list of locally defined interfaces which have hidden methods.
2362 const std::vector<Interface_type*>& interfaces_;
2365 // Build all required interface method tables for types. We need to
2366 // ensure that we have an interface method table for every interface
2367 // which has a hidden method, for every named type which implements
2368 // that interface. Normally we can just build interface method tables
2369 // as we need them. However, in some cases we can require an
2370 // interface method table for an interface defined in a different
2371 // package for a type defined in that package. If that interface and
2372 // type both use a hidden method, that is OK. However, we will not be
2373 // able to build that interface method table when we need it, because
2374 // the type's hidden method will be static. So we have to build it
2375 // here, and just refer it from other packages as needed.
2378 Gogo::build_interface_method_tables()
2380 std::vector<Interface_type*> hidden_interfaces;
2381 hidden_interfaces.reserve(this->interface_types_.size());
2382 for (std::vector<Interface_type*>::const_iterator pi =
2383 this->interface_types_.begin();
2384 pi != this->interface_types_.end();
2387 const Typed_identifier_list* methods = (*pi)->methods();
2388 if (methods == NULL)
2390 for (Typed_identifier_list::const_iterator pm = methods->begin();
2391 pm != methods->end();
2394 if (Gogo::is_hidden_name(pm->name()))
2396 hidden_interfaces.push_back(*pi);
2402 if (!hidden_interfaces.empty())
2404 // Now traverse the tree looking for all named types.
2405 Build_method_tables bmt(this, hidden_interfaces);
2406 this->traverse(&bmt);
2409 // We no longer need the list of interfaces.
2411 this->interface_types_.clear();
2414 // This is called for each type. For a named type, for each of the
2415 // interfaces with hidden methods that it implements, create the
2419 Build_method_tables::type(Type* type)
2421 Named_type* nt = type->named_type();
2424 for (std::vector<Interface_type*>::const_iterator p =
2425 this->interfaces_.begin();
2426 p != this->interfaces_.end();
2429 // We ask whether a pointer to the named type implements the
2430 // interface, because a pointer can implement more methods
2432 if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2434 nt->interface_method_table(this->gogo_, *p, false);
2435 nt->interface_method_table(this->gogo_, *p, true);
2439 return TRAVERSE_CONTINUE;
2442 // Traversal class used to check for return statements.
2444 class Check_return_statements_traverse : public Traverse
2447 Check_return_statements_traverse()
2448 : Traverse(traverse_functions)
2452 function(Named_object*);
2455 // Check that a function has a return statement if it needs one.
2458 Check_return_statements_traverse::function(Named_object* no)
2460 Function* func = no->func_value();
2461 const Function_type* fntype = func->type();
2462 const Typed_identifier_list* results = fntype->results();
2464 // We only need a return statement if there is a return value.
2465 if (results == NULL || results->empty())
2466 return TRAVERSE_CONTINUE;
2468 if (func->block()->may_fall_through())
2469 error_at(func->location(), "control reaches end of non-void function");
2471 return TRAVERSE_CONTINUE;
2474 // Check return statements.
2477 Gogo::check_return_statements()
2479 Check_return_statements_traverse traverse;
2480 this->traverse(&traverse);
2483 // Get the unique prefix to use before all exported symbols. This
2484 // must be unique across the entire link.
2487 Gogo::unique_prefix() const
2489 go_assert(!this->unique_prefix_.empty());
2490 return this->unique_prefix_;
2493 // Set the unique prefix to use before all exported symbols. This
2494 // comes from the command line option -fgo-prefix=XXX.
2497 Gogo::set_unique_prefix(const std::string& arg)
2499 go_assert(this->unique_prefix_.empty());
2500 this->unique_prefix_ = arg;
2501 this->unique_prefix_specified_ = true;
2504 // Work out the package priority. It is one more than the maximum
2505 // priority of an imported package.
2508 Gogo::package_priority() const
2511 for (Packages::const_iterator p = this->packages_.begin();
2512 p != this->packages_.end();
2514 if (p->second->priority() > priority)
2515 priority = p->second->priority();
2516 return priority + 1;
2519 // Export identifiers as requested.
2524 // For now we always stream to a section. Later we may want to
2525 // support streaming to a separate file.
2526 Stream_to_section stream;
2528 Export exp(&stream);
2529 exp.register_builtin_types(this);
2530 exp.export_globals(this->package_name(),
2531 this->unique_prefix(),
2532 this->package_priority(),
2533 (this->need_init_fn_ && !this->is_main_package()
2534 ? this->get_init_fn_name()
2536 this->imported_init_fns_,
2537 this->package_->bindings());
2540 // Find the blocks in order to convert named types defined in blocks.
2542 class Convert_named_types : public Traverse
2545 Convert_named_types(Gogo* gogo)
2546 : Traverse(traverse_blocks),
2552 block(Block* block);
2559 Convert_named_types::block(Block* block)
2561 this->gogo_->convert_named_types_in_bindings(block->bindings());
2562 return TRAVERSE_CONTINUE;
2565 // Convert all named types to the backend representation. Since named
2566 // types can refer to other types, this needs to be done in the right
2567 // sequence, which is handled by Named_type::convert. Here we arrange
2568 // to call that for each named type.
2571 Gogo::convert_named_types()
2573 this->convert_named_types_in_bindings(this->globals_);
2574 for (Packages::iterator p = this->packages_.begin();
2575 p != this->packages_.end();
2578 Package* package = p->second;
2579 this->convert_named_types_in_bindings(package->bindings());
2582 Convert_named_types cnt(this);
2583 this->traverse(&cnt);
2585 // Make all the builtin named types used for type descriptors, and
2586 // then convert them. They will only be written out if they are
2588 Type::make_type_descriptor_type();
2589 Type::make_type_descriptor_ptr_type();
2590 Function_type::make_function_type_descriptor_type();
2591 Pointer_type::make_pointer_type_descriptor_type();
2592 Struct_type::make_struct_type_descriptor_type();
2593 Array_type::make_array_type_descriptor_type();
2594 Array_type::make_slice_type_descriptor_type();
2595 Map_type::make_map_type_descriptor_type();
2596 Channel_type::make_chan_type_descriptor_type();
2597 Interface_type::make_interface_type_descriptor_type();
2598 Type::convert_builtin_named_types(this);
2600 Runtime::convert_types(this);
2602 this->named_types_are_converted_ = true;
2605 // Convert all names types in a set of bindings.
2608 Gogo::convert_named_types_in_bindings(Bindings* bindings)
2610 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2611 p != bindings->end_definitions();
2614 if ((*p)->is_type())
2615 (*p)->type_value()->convert(this);
2621 Function::Function(Function_type* type, Function* enclosing, Block* block,
2622 source_location location)
2623 : type_(type), enclosing_(enclosing), results_(NULL),
2624 closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2625 defer_stack_(NULL), results_are_named_(false), calls_recover_(false),
2626 is_recover_thunk_(false), has_recover_thunk_(false)
2630 // Create the named result variables.
2633 Function::create_result_variables(Gogo* gogo)
2635 const Typed_identifier_list* results = this->type_->results();
2636 if (results == NULL || results->empty())
2639 if (!results->front().name().empty())
2640 this->results_are_named_ = true;
2642 this->results_ = new Results();
2643 this->results_->reserve(results->size());
2645 Block* block = this->block_;
2647 for (Typed_identifier_list::const_iterator p = results->begin();
2648 p != results->end();
2651 std::string name = p->name();
2652 if (name.empty() || Gogo::is_sink_name(name))
2654 static int result_counter;
2656 snprintf(buf, sizeof buf, "$ret%d", result_counter);
2658 name = gogo->pack_hidden_name(buf, false);
2660 Result_variable* result = new Result_variable(p->type(), this, index,
2662 Named_object* no = block->bindings()->add_result_variable(name, result);
2663 if (no->is_result_variable())
2664 this->results_->push_back(no);
2667 static int dummy_result_count;
2669 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
2670 ++dummy_result_count;
2671 name = gogo->pack_hidden_name(buf, false);
2672 no = block->bindings()->add_result_variable(name, result);
2673 go_assert(no->is_result_variable());
2674 this->results_->push_back(no);
2679 // Update the named result variables when cloning a function which
2683 Function::update_result_variables()
2685 if (this->results_ == NULL)
2688 for (Results::iterator p = this->results_->begin();
2689 p != this->results_->end();
2691 (*p)->result_var_value()->set_function(this);
2694 // Return the closure variable, creating it if necessary.
2697 Function::closure_var()
2699 if (this->closure_var_ == NULL)
2701 // We don't know the type of the variable yet. We add fields as
2703 source_location loc = this->type_->location();
2704 Struct_field_list* sfl = new Struct_field_list;
2705 Type* struct_type = Type::make_struct_type(sfl, loc);
2706 Variable* var = new Variable(Type::make_pointer_type(struct_type),
2707 NULL, false, true, false, loc);
2708 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
2709 // Note that the new variable is not in any binding contour.
2711 return this->closure_var_;
2714 // Set the type of the closure variable.
2717 Function::set_closure_type()
2719 if (this->closure_var_ == NULL)
2721 Named_object* closure = this->closure_var_;
2722 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
2723 unsigned int index = 0;
2724 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
2725 p != this->closure_fields_.end();
2728 Named_object* no = p->first;
2730 snprintf(buf, sizeof buf, "%u", index);
2731 std::string n = no->name() + buf;
2733 if (no->is_variable())
2734 var_type = no->var_value()->type();
2736 var_type = no->result_var_value()->type();
2737 Type* field_type = Type::make_pointer_type(var_type);
2738 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
2742 // Return whether this function is a method.
2745 Function::is_method() const
2747 return this->type_->is_method();
2750 // Add a label definition.
2753 Function::add_label_definition(const std::string& label_name,
2754 source_location location)
2756 Label* lnull = NULL;
2757 std::pair<Labels::iterator, bool> ins =
2758 this->labels_.insert(std::make_pair(label_name, lnull));
2761 // This is a new label.
2762 Label* label = new Label(label_name);
2763 label->define(location);
2764 ins.first->second = label;
2769 // The label was already in the hash table.
2770 Label* label = ins.first->second;
2771 if (!label->is_defined())
2773 label->define(location);
2778 error_at(location, "label %qs already defined",
2779 Gogo::message_name(label_name).c_str());
2780 inform(label->location(), "previous definition of %qs was here",
2781 Gogo::message_name(label_name).c_str());
2782 return new Label(label_name);
2787 // Add a reference to a label.
2790 Function::add_label_reference(const std::string& label_name)
2792 Label* lnull = NULL;
2793 std::pair<Labels::iterator, bool> ins =
2794 this->labels_.insert(std::make_pair(label_name, lnull));
2797 // The label was already in the hash table.
2798 Label* label = ins.first->second;
2799 label->set_is_used();
2804 go_assert(ins.first->second == NULL);
2805 Label* label = new Label(label_name);
2806 ins.first->second = label;
2807 label->set_is_used();
2812 // Warn about labels that are defined but not used.
2815 Function::check_labels() const
2817 for (Labels::const_iterator p = this->labels_.begin();
2818 p != this->labels_.end();
2821 Label* label = p->second;
2822 if (!label->is_used())
2823 error_at(label->location(), "label %qs defined and not used",
2824 Gogo::message_name(label->name()).c_str());
2828 // Swap one function with another. This is used when building the
2829 // thunk we use to call a function which calls recover. It may not
2830 // work for any other case.
2833 Function::swap_for_recover(Function *x)
2835 go_assert(this->enclosing_ == x->enclosing_);
2836 std::swap(this->results_, x->results_);
2837 std::swap(this->closure_var_, x->closure_var_);
2838 std::swap(this->block_, x->block_);
2839 go_assert(this->location_ == x->location_);
2840 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
2841 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
2844 // Traverse the tree.
2847 Function::traverse(Traverse* traverse)
2849 unsigned int traverse_mask = traverse->traverse_mask();
2852 & (Traverse::traverse_types | Traverse::traverse_expressions))
2855 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2856 return TRAVERSE_EXIT;
2859 // FIXME: We should check traverse_functions here if nested
2860 // functions are stored in block bindings.
2861 if (this->block_ != NULL
2863 & (Traverse::traverse_variables
2864 | Traverse::traverse_constants
2865 | Traverse::traverse_blocks
2866 | Traverse::traverse_statements
2867 | Traverse::traverse_expressions
2868 | Traverse::traverse_types)) != 0)
2870 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
2871 return TRAVERSE_EXIT;
2874 return TRAVERSE_CONTINUE;
2877 // Work out types for unspecified variables and constants.
2880 Function::determine_types()
2882 if (this->block_ != NULL)
2883 this->block_->determine_types();
2886 // Get a pointer to the variable holding the defer stack for this
2887 // function, making it if necessary. At least at present, the value
2888 // of this variable is not used. However, a pointer to this variable
2889 // is used as a marker for the functions on the defer stack associated
2890 // with this function. Doing things this way permits inlining a
2891 // function which uses defer.
2894 Function::defer_stack(source_location location)
2896 Type* t = Type::make_pointer_type(Type::make_void_type());
2897 if (this->defer_stack_ == NULL)
2899 Expression* n = Expression::make_nil(location);
2900 this->defer_stack_ = Statement::make_temporary(t, n, location);
2901 this->defer_stack_->set_is_address_taken();
2903 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
2905 Expression* addr = Expression::make_unary(OPERATOR_AND, ref, location);
2906 return Expression::make_unsafe_cast(t, addr, location);
2909 // Export the function.
2912 Function::export_func(Export* exp, const std::string& name) const
2914 Function::export_func_with_type(exp, name, this->type_);
2917 // Export a function with a type.
2920 Function::export_func_with_type(Export* exp, const std::string& name,
2921 const Function_type* fntype)
2923 exp->write_c_string("func ");
2925 if (fntype->is_method())
2927 exp->write_c_string("(");
2928 exp->write_type(fntype->receiver()->type());
2929 exp->write_c_string(") ");
2932 exp->write_string(name);
2934 exp->write_c_string(" (");
2935 const Typed_identifier_list* parameters = fntype->parameters();
2936 if (parameters != NULL)
2938 bool is_varargs = fntype->is_varargs();
2940 for (Typed_identifier_list::const_iterator p = parameters->begin();
2941 p != parameters->end();
2947 exp->write_c_string(", ");
2948 if (!is_varargs || p + 1 != parameters->end())
2949 exp->write_type(p->type());
2952 exp->write_c_string("...");
2953 exp->write_type(p->type()->array_type()->element_type());
2957 exp->write_c_string(")");
2959 const Typed_identifier_list* results = fntype->results();
2960 if (results != NULL)
2962 if (results->size() == 1)
2964 exp->write_c_string(" ");
2965 exp->write_type(results->begin()->type());
2969 exp->write_c_string(" (");
2971 for (Typed_identifier_list::const_iterator p = results->begin();
2972 p != results->end();
2978 exp->write_c_string(", ");
2979 exp->write_type(p->type());
2981 exp->write_c_string(")");
2984 exp->write_c_string(";\n");
2987 // Import a function.
2990 Function::import_func(Import* imp, std::string* pname,
2991 Typed_identifier** preceiver,
2992 Typed_identifier_list** pparameters,
2993 Typed_identifier_list** presults,
2996 imp->require_c_string("func ");
2999 if (imp->peek_char() == '(')
3001 imp->require_c_string("(");
3002 Type* rtype = imp->read_type();
3003 *preceiver = new Typed_identifier(Import::import_marker, rtype,
3005 imp->require_c_string(") ");
3008 *pname = imp->read_identifier();
3010 Typed_identifier_list* parameters;
3011 *is_varargs = false;
3012 imp->require_c_string(" (");
3013 if (imp->peek_char() == ')')
3017 parameters = new Typed_identifier_list();
3020 if (imp->match_c_string("..."))
3026 Type* ptype = imp->read_type();
3028 ptype = Type::make_array_type(ptype, NULL);
3029 parameters->push_back(Typed_identifier(Import::import_marker,
3030 ptype, imp->location()));
3031 if (imp->peek_char() != ',')
3033 go_assert(!*is_varargs);
3034 imp->require_c_string(", ");
3037 imp->require_c_string(")");
3038 *pparameters = parameters;
3040 Typed_identifier_list* results;
3041 if (imp->peek_char() != ' ')
3045 results = new Typed_identifier_list();
3046 imp->require_c_string(" ");
3047 if (imp->peek_char() != '(')
3049 Type* rtype = imp->read_type();
3050 results->push_back(Typed_identifier(Import::import_marker, rtype,
3055 imp->require_c_string("(");
3058 Type* rtype = imp->read_type();
3059 results->push_back(Typed_identifier(Import::import_marker,
3060 rtype, imp->location()));
3061 if (imp->peek_char() != ',')
3063 imp->require_c_string(", ");
3065 imp->require_c_string(")");
3068 imp->require_c_string(";\n");
3069 *presults = results;
3074 Block::Block(Block* enclosing, source_location location)
3075 : enclosing_(enclosing), statements_(),
3076 bindings_(new Bindings(enclosing == NULL
3078 : enclosing->bindings())),
3079 start_location_(location),
3080 end_location_(UNKNOWN_LOCATION)
3084 // Add a statement to a block.
3087 Block::add_statement(Statement* statement)
3089 this->statements_.push_back(statement);
3092 // Add a statement to the front of a block. This is slow but is only
3093 // used for reference counts of parameters.
3096 Block::add_statement_at_front(Statement* statement)
3098 this->statements_.insert(this->statements_.begin(), statement);
3101 // Replace a statement in a block.
3104 Block::replace_statement(size_t index, Statement* s)
3106 go_assert(index < this->statements_.size());
3107 this->statements_[index] = s;
3110 // Add a statement before another statement.
3113 Block::insert_statement_before(size_t index, Statement* s)
3115 go_assert(index < this->statements_.size());
3116 this->statements_.insert(this->statements_.begin() + index, s);
3119 // Add a statement after another statement.
3122 Block::insert_statement_after(size_t index, Statement* s)
3124 go_assert(index < this->statements_.size());
3125 this->statements_.insert(this->statements_.begin() + index + 1, s);
3128 // Traverse the tree.
3131 Block::traverse(Traverse* traverse)
3133 unsigned int traverse_mask = traverse->traverse_mask();
3135 if ((traverse_mask & Traverse::traverse_blocks) != 0)
3137 int t = traverse->block(this);
3138 if (t == TRAVERSE_EXIT)
3139 return TRAVERSE_EXIT;
3140 else if (t == TRAVERSE_SKIP_COMPONENTS)
3141 return TRAVERSE_CONTINUE;
3145 & (Traverse::traverse_variables
3146 | Traverse::traverse_constants
3147 | Traverse::traverse_expressions
3148 | Traverse::traverse_types)) != 0)
3150 for (Bindings::const_definitions_iterator pb =
3151 this->bindings_->begin_definitions();
3152 pb != this->bindings_->end_definitions();
3155 switch ((*pb)->classification())
3157 case Named_object::NAMED_OBJECT_CONST:
3158 if ((traverse_mask & Traverse::traverse_constants) != 0)
3160 if (traverse->constant(*pb, false) == TRAVERSE_EXIT)
3161 return TRAVERSE_EXIT;
3163 if ((traverse_mask & Traverse::traverse_types) != 0
3164 || (traverse_mask & Traverse::traverse_expressions) != 0)
3166 Type* t = (*pb)->const_value()->type();
3168 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3169 return TRAVERSE_EXIT;
3171 if ((traverse_mask & Traverse::traverse_expressions) != 0
3172 || (traverse_mask & Traverse::traverse_types) != 0)
3174 if ((*pb)->const_value()->traverse_expression(traverse)
3176 return TRAVERSE_EXIT;
3180 case Named_object::NAMED_OBJECT_VAR:
3181 case Named_object::NAMED_OBJECT_RESULT_VAR:
3182 if ((traverse_mask & Traverse::traverse_variables) != 0)
3184 if (traverse->variable(*pb) == TRAVERSE_EXIT)
3185 return TRAVERSE_EXIT;
3187 if (((traverse_mask & Traverse::traverse_types) != 0
3188 || (traverse_mask & Traverse::traverse_expressions) != 0)
3189 && ((*pb)->is_result_variable()
3190 || (*pb)->var_value()->has_type()))
3192 Type* t = ((*pb)->is_variable()
3193 ? (*pb)->var_value()->type()
3194 : (*pb)->result_var_value()->type());
3196 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3197 return TRAVERSE_EXIT;
3199 if ((*pb)->is_variable()
3200 && ((traverse_mask & Traverse::traverse_expressions) != 0
3201 || (traverse_mask & Traverse::traverse_types) != 0))
3203 if ((*pb)->var_value()->traverse_expression(traverse)
3205 return TRAVERSE_EXIT;
3209 case Named_object::NAMED_OBJECT_FUNC:
3210 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3211 // FIXME: Where will nested functions be found?
3214 case Named_object::NAMED_OBJECT_TYPE:
3215 if ((traverse_mask & Traverse::traverse_types) != 0
3216 || (traverse_mask & Traverse::traverse_expressions) != 0)
3218 if (Type::traverse((*pb)->type_value(), traverse)
3220 return TRAVERSE_EXIT;
3224 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3225 case Named_object::NAMED_OBJECT_UNKNOWN:
3228 case Named_object::NAMED_OBJECT_PACKAGE:
3229 case Named_object::NAMED_OBJECT_SINK:
3238 // No point in checking traverse_mask here--if we got here we always
3239 // want to walk the statements. The traversal can insert new
3240 // statements before or after the current statement. Inserting
3241 // statements before the current statement requires updating I via
3242 // the pointer; those statements will not be traversed. Any new
3243 // statements inserted after the current statement will be traversed
3245 for (size_t i = 0; i < this->statements_.size(); ++i)
3247 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3248 return TRAVERSE_EXIT;
3251 return TRAVERSE_CONTINUE;
3254 // Work out types for unspecified variables and constants.
3257 Block::determine_types()
3259 for (Bindings::const_definitions_iterator pb =
3260 this->bindings_->begin_definitions();
3261 pb != this->bindings_->end_definitions();
3264 if ((*pb)->is_variable())
3265 (*pb)->var_value()->determine_type();
3266 else if ((*pb)->is_const())
3267 (*pb)->const_value()->determine_type();
3270 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3271 ps != this->statements_.end();
3273 (*ps)->determine_types();
3276 // Return true if the statements in this block may fall through.
3279 Block::may_fall_through() const
3281 if (this->statements_.empty())
3283 return this->statements_.back()->may_fall_through();
3286 // Convert a block to the backend representation.
3289 Block::get_backend(Translate_context* context)
3291 Gogo* gogo = context->gogo();
3292 Named_object* function = context->function();
3293 std::vector<Bvariable*> vars;
3294 vars.reserve(this->bindings_->size_definitions());
3295 for (Bindings::const_definitions_iterator pv =
3296 this->bindings_->begin_definitions();
3297 pv != this->bindings_->end_definitions();
3300 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
3301 vars.push_back((*pv)->get_backend_variable(gogo, function));
3304 // FIXME: Permitting FUNCTION to be NULL here is a temporary measure
3305 // until we have a proper representation of the init function.
3306 Bfunction* bfunction;
3307 if (function == NULL)
3310 bfunction = tree_to_function(function->func_value()->get_decl());
3311 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
3312 vars, this->start_location_,
3313 this->end_location_);
3315 Translate_context subcontext(gogo, function, this, ret);
3316 std::vector<Bstatement*> bstatements;
3317 bstatements.reserve(this->statements_.size());
3318 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
3319 p != this->statements_.end();
3321 bstatements.push_back((*p)->get_backend(&subcontext));
3323 context->backend()->block_add_statements(ret, bstatements);
3330 Variable::Variable(Type* type, Expression* init, bool is_global,
3331 bool is_parameter, bool is_receiver,
3332 source_location location)
3333 : type_(type), init_(init), preinit_(NULL), location_(location),
3334 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
3335 is_receiver_(is_receiver), is_varargs_parameter_(false),
3336 is_address_taken_(false), seen_(false), init_is_lowered_(false),
3337 type_from_init_tuple_(false), type_from_range_index_(false),
3338 type_from_range_value_(false), type_from_chan_element_(false),
3339 is_type_switch_var_(false), determined_type_(false)
3341 go_assert(type != NULL || init != NULL);
3342 go_assert(!is_parameter || init == NULL);
3345 // Traverse the initializer expression.
3348 Variable::traverse_expression(Traverse* traverse)
3350 if (this->preinit_ != NULL)
3352 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3353 return TRAVERSE_EXIT;
3355 if (this->init_ != NULL)
3357 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3358 return TRAVERSE_EXIT;
3360 return TRAVERSE_CONTINUE;
3363 // Lower the initialization expression after parsing is complete.
3366 Variable::lower_init_expression(Gogo* gogo, Named_object* function)
3368 if (this->init_ != NULL && !this->init_is_lowered_)
3372 // We will give an error elsewhere, this is just to prevent
3373 // an infinite loop.
3378 gogo->lower_expression(function, &this->init_);
3380 this->seen_ = false;
3382 this->init_is_lowered_ = true;
3386 // Get the preinit block.
3389 Variable::preinit_block(Gogo* gogo)
3391 go_assert(this->is_global_);
3392 if (this->preinit_ == NULL)
3393 this->preinit_ = new Block(NULL, this->location());
3395 // If a global variable has a preinitialization statement, then we
3396 // need to have an initialization function.
3397 gogo->set_need_init_fn();
3399 return this->preinit_;
3402 // Add a statement to be run before the initialization expression.
3405 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
3407 Block* b = this->preinit_block(gogo);
3408 b->add_statement(s);
3409 b->set_end_location(s->location());
3412 // In an assignment which sets a variable to a tuple of EXPR, return
3413 // the type of the first element of the tuple.
3416 Variable::type_from_tuple(Expression* expr, bool report_error) const
3418 if (expr->map_index_expression() != NULL)
3420 Map_type* mt = expr->map_index_expression()->get_map_type();
3422 return Type::make_error_type();
3423 return mt->val_type();
3425 else if (expr->receive_expression() != NULL)
3427 Expression* channel = expr->receive_expression()->channel();
3428 Type* channel_type = channel->type();
3429 if (channel_type->channel_type() == NULL)
3430 return Type::make_error_type();
3431 return channel_type->channel_type()->element_type();
3436 error_at(this->location(), "invalid tuple definition");
3437 return Type::make_error_type();
3441 // Given EXPR used in a range clause, return either the index type or
3442 // the value type of the range, depending upon GET_INDEX_TYPE.
3445 Variable::type_from_range(Expression* expr, bool get_index_type,
3446 bool report_error) const
3448 Type* t = expr->type();
3449 if (t->array_type() != NULL
3450 || (t->points_to() != NULL
3451 && t->points_to()->array_type() != NULL
3452 && !t->points_to()->is_open_array_type()))
3455 return Type::lookup_integer_type("int");
3457 return t->deref()->array_type()->element_type();
3459 else if (t->is_string_type())
3460 return Type::lookup_integer_type("int");
3461 else if (t->map_type() != NULL)
3464 return t->map_type()->key_type();
3466 return t->map_type()->val_type();
3468 else if (t->channel_type() != NULL)
3471 return t->channel_type()->element_type();
3475 error_at(this->location(),
3476 "invalid definition of value variable for channel range");
3477 return Type::make_error_type();
3483 error_at(this->location(), "invalid type for range clause");
3484 return Type::make_error_type();
3488 // EXPR should be a channel. Return the channel's element type.
3491 Variable::type_from_chan_element(Expression* expr, bool report_error) const
3493 Type* t = expr->type();
3494 if (t->channel_type() != NULL)
3495 return t->channel_type()->element_type();
3499 error_at(this->location(), "expected channel");
3500 return Type::make_error_type();
3504 // Return the type of the Variable. This may be called before
3505 // Variable::determine_type is called, which means that we may need to
3506 // get the type from the initializer. FIXME: If we combine lowering
3507 // with type determination, then this should be unnecessary.
3512 // A variable in a type switch with a nil case will have the wrong
3513 // type here. This gets fixed up in determine_type, below.
3514 Type* type = this->type_;
3515 Expression* init = this->init_;
3516 if (this->is_type_switch_var_
3517 && this->type_->is_nil_constant_as_type())
3519 Type_guard_expression* tge = this->init_->type_guard_expression();
3520 go_assert(tge != NULL);
3527 if (this->type_ == NULL || !this->type_->is_error_type())
3529 error_at(this->location_, "variable initializer refers to itself");
3530 this->type_ = Type::make_error_type();
3539 else if (this->type_from_init_tuple_)
3540 type = this->type_from_tuple(init, false);
3541 else if (this->type_from_range_index_ || this->type_from_range_value_)
3542 type = this->type_from_range(init, this->type_from_range_index_, false);
3543 else if (this->type_from_chan_element_)
3544 type = this->type_from_chan_element(init, false);
3547 go_assert(init != NULL);
3548 type = init->type();
3549 go_assert(type != NULL);
3551 // Variables should not have abstract types.
3552 if (type->is_abstract())
3553 type = type->make_non_abstract_type();
3555 if (type->is_void_type())
3556 type = Type::make_error_type();
3559 this->seen_ = false;
3564 // Fetch the type from a const pointer, in which case it should have
3565 // been set already.
3568 Variable::type() const
3570 go_assert(this->type_ != NULL);
3574 // Set the type if necessary.
3577 Variable::determine_type()
3579 if (this->determined_type_)
3581 this->determined_type_ = true;
3583 if (this->preinit_ != NULL)
3584 this->preinit_->determine_types();
3586 // A variable in a type switch with a nil case will have the wrong
3587 // type here. It will have an initializer which is a type guard.
3588 // We want to initialize it to the value without the type guard, and
3589 // use the type of that value as well.
3590 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
3592 Type_guard_expression* tge = this->init_->type_guard_expression();
3593 go_assert(tge != NULL);
3595 this->init_ = tge->expr();
3598 if (this->init_ == NULL)
3599 go_assert(this->type_ != NULL && !this->type_->is_abstract());
3600 else if (this->type_from_init_tuple_)
3602 Expression *init = this->init_;
3603 init->determine_type_no_context();
3604 this->type_ = this->type_from_tuple(init, true);
3607 else if (this->type_from_range_index_ || this->type_from_range_value_)
3609 Expression* init = this->init_;
3610 init->determine_type_no_context();
3611 this->type_ = this->type_from_range(init, this->type_from_range_index_,
3615 else if (this->type_from_chan_element_)
3617 Expression* init = this->init_;
3618 init->determine_type_no_context();
3619 this->type_ = this->type_from_chan_element(init, true);
3624 Type_context context(this->type_, false);
3625 this->init_->determine_type(&context);
3626 if (this->type_ == NULL)
3628 Type* type = this->init_->type();
3629 go_assert(type != NULL);
3630 if (type->is_abstract())
3631 type = type->make_non_abstract_type();
3633 if (type->is_void_type())
3635 error_at(this->location_, "variable has no type");
3636 type = Type::make_error_type();
3638 else if (type->is_nil_type())
3640 error_at(this->location_, "variable defined to nil type");
3641 type = Type::make_error_type();
3643 else if (type->is_call_multiple_result_type())
3645 error_at(this->location_,
3646 "single variable set to multiple value function call");
3647 type = Type::make_error_type();
3655 // Export the variable
3658 Variable::export_var(Export* exp, const std::string& name) const
3660 go_assert(this->is_global_);
3661 exp->write_c_string("var ");
3662 exp->write_string(name);
3663 exp->write_c_string(" ");
3664 exp->write_type(this->type());
3665 exp->write_c_string(";\n");
3668 // Import a variable.
3671 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
3673 imp->require_c_string("var ");
3674 *pname = imp->read_identifier();
3675 imp->require_c_string(" ");
3676 *ptype = imp->read_type();
3677 imp->require_c_string(";\n");
3680 // Convert a variable to the backend representation.
3683 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
3684 const Package* package, const std::string& name)
3686 if (this->backend_ == NULL)
3688 Backend* backend = gogo->backend();
3689 Type* type = this->type_;
3690 if (type->is_error_type()
3691 || (type->is_undefined()
3692 && (!this->is_global_ || package == NULL)))
3693 this->backend_ = backend->error_variable();
3696 bool is_parameter = this->is_parameter_;
3697 if (this->is_receiver_ && type->points_to() == NULL)
3698 is_parameter = false;
3699 if (this->is_in_heap())
3701 is_parameter = false;
3702 type = Type::make_pointer_type(type);
3705 std::string n = Gogo::unpack_hidden_name(name);
3706 Btype* btype = type->get_backend(gogo);
3709 if (this->is_global_)
3710 bvar = backend->global_variable((package == NULL
3711 ? gogo->package_name()
3714 ? gogo->unique_prefix()
3715 : package->unique_prefix()),
3719 Gogo::is_hidden_name(name),
3723 tree fndecl = function->func_value()->get_decl();
3724 Bfunction* bfunction = tree_to_function(fndecl);
3726 bvar = backend->parameter_variable(bfunction, n, btype,
3729 bvar = backend->local_variable(bfunction, n, btype,
3732 this->backend_ = bvar;
3735 return this->backend_;
3738 // Class Result_variable.
3740 // Convert a result variable to the backend representation.
3743 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
3744 const std::string& name)
3746 if (this->backend_ == NULL)
3748 Backend* backend = gogo->backend();
3749 Type* type = this->type_;
3750 if (type->is_error())
3751 this->backend_ = backend->error_variable();
3754 if (this->is_in_heap())
3755 type = Type::make_pointer_type(type);
3756 Btype* btype = type->get_backend(gogo);
3757 tree fndecl = function->func_value()->get_decl();
3758 Bfunction* bfunction = tree_to_function(fndecl);
3759 std::string n = Gogo::unpack_hidden_name(name);
3760 this->backend_ = backend->local_variable(bfunction, n, btype,
3764 return this->backend_;
3767 // Class Named_constant.
3769 // Traverse the initializer expression.
3772 Named_constant::traverse_expression(Traverse* traverse)
3774 return Expression::traverse(&this->expr_, traverse);
3777 // Determine the type of the constant.
3780 Named_constant::determine_type()
3782 if (this->type_ != NULL)
3784 Type_context context(this->type_, false);
3785 this->expr_->determine_type(&context);
3789 // A constant may have an abstract type.
3790 Type_context context(NULL, true);
3791 this->expr_->determine_type(&context);
3792 this->type_ = this->expr_->type();
3793 go_assert(this->type_ != NULL);
3797 // Indicate that we found and reported an error for this constant.
3800 Named_constant::set_error()
3802 this->type_ = Type::make_error_type();
3803 this->expr_ = Expression::make_error(this->location_);
3806 // Export a constant.
3809 Named_constant::export_const(Export* exp, const std::string& name) const
3811 exp->write_c_string("const ");
3812 exp->write_string(name);
3813 exp->write_c_string(" ");
3814 if (!this->type_->is_abstract())
3816 exp->write_type(this->type_);
3817 exp->write_c_string(" ");
3819 exp->write_c_string("= ");
3820 this->expr()->export_expression(exp);
3821 exp->write_c_string(";\n");
3824 // Import a constant.
3827 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
3830 imp->require_c_string("const ");
3831 *pname = imp->read_identifier();
3832 imp->require_c_string(" ");
3833 if (imp->peek_char() == '=')
3837 *ptype = imp->read_type();
3838 imp->require_c_string(" ");
3840 imp->require_c_string("= ");
3841 *pexpr = Expression::import_expression(imp);
3842 imp->require_c_string(";\n");
3848 Type_declaration::add_method(const std::string& name, Function* function)
3850 Named_object* ret = Named_object::make_function(name, NULL, function);
3851 this->methods_.push_back(ret);
3855 // Add a method declaration.
3858 Type_declaration::add_method_declaration(const std::string& name,
3859 Function_type* type,
3860 source_location location)
3862 Named_object* ret = Named_object::make_function_declaration(name, NULL, type,
3864 this->methods_.push_back(ret);
3868 // Return whether any methods ere defined.
3871 Type_declaration::has_methods() const
3873 return !this->methods_.empty();
3876 // Define methods for the real type.
3879 Type_declaration::define_methods(Named_type* nt)
3881 for (Methods::const_iterator p = this->methods_.begin();
3882 p != this->methods_.end();
3884 nt->add_existing_method(*p);
3887 // We are using the type. Return true if we should issue a warning.
3890 Type_declaration::using_type()
3892 bool ret = !this->issued_warning_;
3893 this->issued_warning_ = true;
3897 // Class Unknown_name.
3899 // Set the real named object.
3902 Unknown_name::set_real_named_object(Named_object* no)
3904 go_assert(this->real_named_object_ == NULL);
3905 go_assert(!no->is_unknown());
3906 this->real_named_object_ = no;
3909 // Class Named_object.
3911 Named_object::Named_object(const std::string& name,
3912 const Package* package,
3913 Classification classification)
3914 : name_(name), package_(package), classification_(classification),
3917 if (Gogo::is_sink_name(name))
3918 go_assert(classification == NAMED_OBJECT_SINK);
3921 // Make an unknown name. This is used by the parser. The name must
3922 // be resolved later. Unknown names are only added in the current
3926 Named_object::make_unknown_name(const std::string& name,
3927 source_location location)
3929 Named_object* named_object = new Named_object(name, NULL,
3930 NAMED_OBJECT_UNKNOWN);
3931 Unknown_name* value = new Unknown_name(location);
3932 named_object->u_.unknown_value = value;
3933 return named_object;
3939 Named_object::make_constant(const Typed_identifier& tid,
3940 const Package* package, Expression* expr,
3943 Named_object* named_object = new Named_object(tid.name(), package,
3944 NAMED_OBJECT_CONST);
3945 Named_constant* named_constant = new Named_constant(tid.type(), expr,
3948 named_object->u_.const_value = named_constant;
3949 return named_object;
3952 // Make a named type.
3955 Named_object::make_type(const std::string& name, const Package* package,
3956 Type* type, source_location location)
3958 Named_object* named_object = new Named_object(name, package,
3960 Named_type* named_type = Type::make_named_type(named_object, type, location);
3961 named_object->u_.type_value = named_type;
3962 return named_object;
3965 // Make a type declaration.
3968 Named_object::make_type_declaration(const std::string& name,
3969 const Package* package,
3970 source_location location)
3972 Named_object* named_object = new Named_object(name, package,
3973 NAMED_OBJECT_TYPE_DECLARATION);
3974 Type_declaration* type_declaration = new Type_declaration(location);
3975 named_object->u_.type_declaration = type_declaration;
3976 return named_object;
3982 Named_object::make_variable(const std::string& name, const Package* package,
3985 Named_object* named_object = new Named_object(name, package,
3987 named_object->u_.var_value = variable;
3988 return named_object;
3991 // Make a result variable.
3994 Named_object::make_result_variable(const std::string& name,
3995 Result_variable* result)
3997 Named_object* named_object = new Named_object(name, NULL,
3998 NAMED_OBJECT_RESULT_VAR);
3999 named_object->u_.result_var_value = result;
4000 return named_object;
4003 // Make a sink. This is used for the special blank identifier _.
4006 Named_object::make_sink()
4008 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
4011 // Make a named function.
4014 Named_object::make_function(const std::string& name, const Package* package,
4017 Named_object* named_object = new Named_object(name, package,
4019 named_object->u_.func_value = function;
4020 return named_object;
4023 // Make a function declaration.
4026 Named_object::make_function_declaration(const std::string& name,
4027 const Package* package,
4028 Function_type* fntype,
4029 source_location location)
4031 Named_object* named_object = new Named_object(name, package,
4032 NAMED_OBJECT_FUNC_DECLARATION);
4033 Function_declaration *func_decl = new Function_declaration(fntype, location);
4034 named_object->u_.func_declaration_value = func_decl;
4035 return named_object;
4041 Named_object::make_package(const std::string& alias, Package* package)
4043 Named_object* named_object = new Named_object(alias, NULL,
4044 NAMED_OBJECT_PACKAGE);
4045 named_object->u_.package_value = package;
4046 return named_object;
4049 // Return the name to use in an error message.
4052 Named_object::message_name() const
4054 if (this->package_ == NULL)
4055 return Gogo::message_name(this->name_);
4056 std::string ret = Gogo::message_name(this->package_->name());
4058 ret += Gogo::message_name(this->name_);
4062 // Set the type when a declaration is defined.
4065 Named_object::set_type_value(Named_type* named_type)
4067 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
4068 Type_declaration* td = this->u_.type_declaration;
4069 td->define_methods(named_type);
4070 Named_object* in_function = td->in_function();
4071 if (in_function != NULL)
4072 named_type->set_in_function(in_function);
4074 this->classification_ = NAMED_OBJECT_TYPE;
4075 this->u_.type_value = named_type;
4078 // Define a function which was previously declared.
4081 Named_object::set_function_value(Function* function)
4083 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
4084 this->classification_ = NAMED_OBJECT_FUNC;
4085 // FIXME: We should free the old value.
4086 this->u_.func_value = function;
4089 // Declare an unknown object as a type declaration.
4092 Named_object::declare_as_type()
4094 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
4095 Unknown_name* unk = this->u_.unknown_value;
4096 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
4097 this->u_.type_declaration = new Type_declaration(unk->location());
4101 // Return the location of a named object.
4104 Named_object::location() const
4106 switch (this->classification_)
4109 case NAMED_OBJECT_UNINITIALIZED:
4112 case NAMED_OBJECT_UNKNOWN:
4113 return this->unknown_value()->location();
4115 case NAMED_OBJECT_CONST:
4116 return this->const_value()->location();
4118 case NAMED_OBJECT_TYPE:
4119 return this->type_value()->location();
4121 case NAMED_OBJECT_TYPE_DECLARATION:
4122 return this->type_declaration_value()->location();
4124 case NAMED_OBJECT_VAR:
4125 return this->var_value()->location();
4127 case NAMED_OBJECT_RESULT_VAR:
4128 return this->result_var_value()->location();
4130 case NAMED_OBJECT_SINK:
4133 case NAMED_OBJECT_FUNC:
4134 return this->func_value()->location();
4136 case NAMED_OBJECT_FUNC_DECLARATION:
4137 return this->func_declaration_value()->location();
4139 case NAMED_OBJECT_PACKAGE:
4140 return this->package_value()->location();
4144 // Export a named object.
4147 Named_object::export_named_object(Export* exp) const
4149 switch (this->classification_)
4152 case NAMED_OBJECT_UNINITIALIZED:
4153 case NAMED_OBJECT_UNKNOWN:
4156 case NAMED_OBJECT_CONST:
4157 this->const_value()->export_const(exp, this->name_);
4160 case NAMED_OBJECT_TYPE:
4161 this->type_value()->export_named_type(exp, this->name_);
4164 case NAMED_OBJECT_TYPE_DECLARATION:
4165 error_at(this->type_declaration_value()->location(),
4166 "attempt to export %<%s%> which was declared but not defined",
4167 this->message_name().c_str());
4170 case NAMED_OBJECT_FUNC_DECLARATION:
4171 this->func_declaration_value()->export_func(exp, this->name_);
4174 case NAMED_OBJECT_VAR:
4175 this->var_value()->export_var(exp, this->name_);
4178 case NAMED_OBJECT_RESULT_VAR:
4179 case NAMED_OBJECT_SINK:
4182 case NAMED_OBJECT_FUNC:
4183 this->func_value()->export_func(exp, this->name_);
4188 // Convert a variable to the backend representation.
4191 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
4193 if (this->classification_ == NAMED_OBJECT_VAR)
4194 return this->var_value()->get_backend_variable(gogo, function,
4195 this->package_, this->name_);
4196 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
4197 return this->result_var_value()->get_backend_variable(gogo, function,
4205 Bindings::Bindings(Bindings* enclosing)
4206 : enclosing_(enclosing), named_objects_(), bindings_()
4213 Bindings::clear_file_scope()
4215 Contour::iterator p = this->bindings_.begin();
4216 while (p != this->bindings_.end())
4219 if (p->second->package() != NULL)
4221 else if (p->second->is_package())
4223 else if (p->second->is_function()
4224 && !p->second->func_value()->type()->is_method()
4225 && Gogo::unpack_hidden_name(p->second->name()) == "init")
4233 p = this->bindings_.erase(p);
4237 // Look up a symbol.
4240 Bindings::lookup(const std::string& name) const
4242 Contour::const_iterator p = this->bindings_.find(name);
4243 if (p != this->bindings_.end())
4244 return p->second->resolve();
4245 else if (this->enclosing_ != NULL)
4246 return this->enclosing_->lookup(name);
4251 // Look up a symbol locally.
4254 Bindings::lookup_local(const std::string& name) const
4256 Contour::const_iterator p = this->bindings_.find(name);
4257 if (p == this->bindings_.end())
4262 // Remove an object from a set of bindings. This is used for a
4263 // special case in thunks for functions which call recover.
4266 Bindings::remove_binding(Named_object* no)
4268 Contour::iterator pb = this->bindings_.find(no->name());
4269 go_assert(pb != this->bindings_.end());
4270 this->bindings_.erase(pb);
4271 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
4272 pn != this->named_objects_.end();
4277 this->named_objects_.erase(pn);
4284 // Add a method to the list of objects. This is not added to the
4285 // lookup table. This is so that we have a single list of objects
4286 // declared at the top level, which we walk through when it's time to
4287 // convert to trees.
4290 Bindings::add_method(Named_object* method)
4292 this->named_objects_.push_back(method);
4295 // Add a generic Named_object to a Contour.
4298 Bindings::add_named_object_to_contour(Contour* contour,
4299 Named_object* named_object)
4301 go_assert(named_object == named_object->resolve());
4302 const std::string& name(named_object->name());
4303 go_assert(!Gogo::is_sink_name(name));
4305 std::pair<Contour::iterator, bool> ins =
4306 contour->insert(std::make_pair(name, named_object));
4309 // The name was already there.
4310 if (named_object->package() != NULL
4311 && ins.first->second->package() == named_object->package()
4312 && (ins.first->second->classification()
4313 == named_object->classification()))
4315 // This is a second import of the same object.
4316 return ins.first->second;
4318 ins.first->second = this->new_definition(ins.first->second,
4320 return ins.first->second;
4324 // Don't push declarations on the list. We push them on when
4325 // and if we find the definitions. That way we genericize the
4326 // functions in order.
4327 if (!named_object->is_type_declaration()
4328 && !named_object->is_function_declaration()
4329 && !named_object->is_unknown())
4330 this->named_objects_.push_back(named_object);
4331 return named_object;
4335 // We had an existing named object OLD_OBJECT, and we've seen a new
4336 // one NEW_OBJECT with the same name. FIXME: This does not free the
4337 // new object when we don't need it.
4340 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
4343 switch (old_object->classification())
4346 case Named_object::NAMED_OBJECT_UNINITIALIZED:
4349 case Named_object::NAMED_OBJECT_UNKNOWN:
4351 Named_object* real = old_object->unknown_value()->real_named_object();
4353 return this->new_definition(real, new_object);
4354 go_assert(!new_object->is_unknown());
4355 old_object->unknown_value()->set_real_named_object(new_object);
4356 if (!new_object->is_type_declaration()
4357 && !new_object->is_function_declaration())
4358 this->named_objects_.push_back(new_object);
4362 case Named_object::NAMED_OBJECT_CONST:
4365 case Named_object::NAMED_OBJECT_TYPE:
4366 if (new_object->is_type_declaration())
4370 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4371 if (new_object->is_type_declaration())
4373 if (new_object->is_type())
4375 old_object->set_type_value(new_object->type_value());
4376 new_object->type_value()->set_named_object(old_object);
4377 this->named_objects_.push_back(old_object);
4382 case Named_object::NAMED_OBJECT_VAR:
4383 case Named_object::NAMED_OBJECT_RESULT_VAR:
4386 case Named_object::NAMED_OBJECT_SINK:
4389 case Named_object::NAMED_OBJECT_FUNC:
4390 if (new_object->is_function_declaration())
4392 if (!new_object->func_declaration_value()->asm_name().empty())
4393 sorry("__asm__ for function definitions");
4394 Function_type* old_type = old_object->func_value()->type();
4395 Function_type* new_type =
4396 new_object->func_declaration_value()->type();
4397 if (old_type->is_valid_redeclaration(new_type, &reason))
4402 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4404 Function_type* old_type = old_object->func_declaration_value()->type();
4405 if (new_object->is_function_declaration())
4407 Function_type* new_type =
4408 new_object->func_declaration_value()->type();
4409 if (old_type->is_valid_redeclaration(new_type, &reason))
4412 if (new_object->is_function())
4414 Function_type* new_type = new_object->func_value()->type();
4415 if (old_type->is_valid_redeclaration(new_type, &reason))
4417 if (!old_object->func_declaration_value()->asm_name().empty())
4418 sorry("__asm__ for function definitions");
4419 old_object->set_function_value(new_object->func_value());
4420 this->named_objects_.push_back(old_object);
4427 case Named_object::NAMED_OBJECT_PACKAGE:
4428 if (new_object->is_package()
4429 && (old_object->package_value()->name()
4430 == new_object->package_value()->name()))
4436 std::string n = old_object->message_name();
4438 error_at(new_object->location(), "redefinition of %qs", n.c_str());
4440 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
4443 inform(old_object->location(), "previous definition of %qs was here",
4449 // Add a named type.
4452 Bindings::add_named_type(Named_type* named_type)
4454 return this->add_named_object(named_type->named_object());
4460 Bindings::add_function(const std::string& name, const Package* package,
4463 return this->add_named_object(Named_object::make_function(name, package,
4467 // Add a function declaration.
4470 Bindings::add_function_declaration(const std::string& name,
4471 const Package* package,
4472 Function_type* type,
4473 source_location location)
4475 Named_object* no = Named_object::make_function_declaration(name, package,
4477 return this->add_named_object(no);
4480 // Define a type which was previously declared.
4483 Bindings::define_type(Named_object* no, Named_type* type)
4485 no->set_type_value(type);
4486 this->named_objects_.push_back(no);
4489 // Traverse bindings.
4492 Bindings::traverse(Traverse* traverse, bool is_global)
4494 unsigned int traverse_mask = traverse->traverse_mask();
4496 // We don't use an iterator because we permit the traversal to add
4497 // new global objects.
4498 for (size_t i = 0; i < this->named_objects_.size(); ++i)
4500 Named_object* p = this->named_objects_[i];
4501 switch (p->classification())
4503 case Named_object::NAMED_OBJECT_CONST:
4504 if ((traverse_mask & Traverse::traverse_constants) != 0)
4506 if (traverse->constant(p, is_global) == TRAVERSE_EXIT)
4507 return TRAVERSE_EXIT;
4509 if ((traverse_mask & Traverse::traverse_types) != 0
4510 || (traverse_mask & Traverse::traverse_expressions) != 0)
4512 Type* t = p->const_value()->type();
4514 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4515 return TRAVERSE_EXIT;
4516 if (p->const_value()->traverse_expression(traverse)
4518 return TRAVERSE_EXIT;
4522 case Named_object::NAMED_OBJECT_VAR:
4523 case Named_object::NAMED_OBJECT_RESULT_VAR:
4524 if ((traverse_mask & Traverse::traverse_variables) != 0)
4526 if (traverse->variable(p) == TRAVERSE_EXIT)
4527 return TRAVERSE_EXIT;
4529 if (((traverse_mask & Traverse::traverse_types) != 0
4530 || (traverse_mask & Traverse::traverse_expressions) != 0)
4531 && (p->is_result_variable()
4532 || p->var_value()->has_type()))
4534 Type* t = (p->is_variable()
4535 ? p->var_value()->type()
4536 : p->result_var_value()->type());
4538 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4539 return TRAVERSE_EXIT;
4541 if (p->is_variable()
4542 && ((traverse_mask & Traverse::traverse_types) != 0
4543 || (traverse_mask & Traverse::traverse_expressions) != 0))
4545 if (p->var_value()->traverse_expression(traverse)
4547 return TRAVERSE_EXIT;
4551 case Named_object::NAMED_OBJECT_FUNC:
4552 if ((traverse_mask & Traverse::traverse_functions) != 0)
4554 int t = traverse->function(p);
4555 if (t == TRAVERSE_EXIT)
4556 return TRAVERSE_EXIT;
4557 else if (t == TRAVERSE_SKIP_COMPONENTS)
4562 & (Traverse::traverse_variables
4563 | Traverse::traverse_constants
4564 | Traverse::traverse_functions
4565 | Traverse::traverse_blocks
4566 | Traverse::traverse_statements
4567 | Traverse::traverse_expressions
4568 | Traverse::traverse_types)) != 0)
4570 if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT)
4571 return TRAVERSE_EXIT;
4575 case Named_object::NAMED_OBJECT_PACKAGE:
4576 // These are traversed in Gogo::traverse.
4577 go_assert(is_global);
4580 case Named_object::NAMED_OBJECT_TYPE:
4581 if ((traverse_mask & Traverse::traverse_types) != 0
4582 || (traverse_mask & Traverse::traverse_expressions) != 0)
4584 if (Type::traverse(p->type_value(), traverse) == TRAVERSE_EXIT)
4585 return TRAVERSE_EXIT;
4589 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4590 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4591 case Named_object::NAMED_OBJECT_UNKNOWN:
4594 case Named_object::NAMED_OBJECT_SINK:
4600 return TRAVERSE_CONTINUE;
4605 // Get the backend representation for a label.
4608 Label::get_backend_label(Translate_context* context)
4610 if (this->blabel_ == NULL)
4612 Function* function = context->function()->func_value();
4613 tree fndecl = function->get_decl();
4614 Bfunction* bfunction = tree_to_function(fndecl);
4615 this->blabel_ = context->backend()->label(bfunction, this->name_,
4618 return this->blabel_;
4621 // Return an expression for the address of this label.
4624 Label::get_addr(Translate_context* context, source_location location)
4626 Blabel* label = this->get_backend_label(context);
4627 return context->backend()->label_address(label, location);
4630 // Class Unnamed_label.
4632 // Get the backend representation for an unnamed label.
4635 Unnamed_label::get_blabel(Translate_context* context)
4637 if (this->blabel_ == NULL)
4639 Function* function = context->function()->func_value();
4640 tree fndecl = function->get_decl();
4641 Bfunction* bfunction = tree_to_function(fndecl);
4642 this->blabel_ = context->backend()->label(bfunction, "",
4645 return this->blabel_;
4648 // Return a statement which defines this unnamed label.
4651 Unnamed_label::get_definition(Translate_context* context)
4653 Blabel* blabel = this->get_blabel(context);
4654 return context->backend()->label_definition_statement(blabel);
4657 // Return a goto statement to this unnamed label.
4660 Unnamed_label::get_goto(Translate_context* context, source_location location)
4662 Blabel* blabel = this->get_blabel(context);
4663 return context->backend()->goto_statement(blabel, location);
4668 Package::Package(const std::string& name, const std::string& unique_prefix,
4669 source_location location)
4670 : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)),
4671 priority_(0), location_(location), used_(false), is_imported_(false),
4672 uses_sink_alias_(false)
4674 go_assert(!name.empty() && !unique_prefix.empty());
4677 // Set the priority. We may see multiple priorities for an imported
4678 // package; we want to use the largest one.
4681 Package::set_priority(int priority)
4683 if (priority > this->priority_)
4684 this->priority_ = priority;
4687 // Determine types of constants. Everything else in a package
4688 // (variables, function declarations) should already have a fixed
4689 // type. Constants may have abstract types.
4692 Package::determine_types()
4694 Bindings* bindings = this->bindings_;
4695 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4696 p != bindings->end_definitions();
4699 if ((*p)->is_const())
4700 (*p)->const_value()->determine_type();
4708 Traverse::~Traverse()
4710 if (this->types_seen_ != NULL)
4711 delete this->types_seen_;
4712 if (this->expressions_seen_ != NULL)
4713 delete this->expressions_seen_;
4716 // Record that we are looking at a type, and return true if we have
4720 Traverse::remember_type(const Type* type)
4722 if (type->is_error_type())
4724 go_assert((this->traverse_mask() & traverse_types) != 0
4725 || (this->traverse_mask() & traverse_expressions) != 0);
4726 // We only have to remember named types, as they are the only ones
4727 // we can see multiple times in a traversal.
4728 if (type->classification() != Type::TYPE_NAMED)
4730 if (this->types_seen_ == NULL)
4731 this->types_seen_ = new Types_seen();
4732 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
4736 // Record that we are looking at an expression, and return true if we
4737 // have already seen it.
4740 Traverse::remember_expression(const Expression* expression)
4742 go_assert((this->traverse_mask() & traverse_types) != 0
4743 || (this->traverse_mask() & traverse_expressions) != 0);
4744 if (this->expressions_seen_ == NULL)
4745 this->expressions_seen_ = new Expressions_seen();
4746 std::pair<Expressions_seen::iterator, bool> ins =
4747 this->expressions_seen_->insert(expression);
4751 // The default versions of these functions should never be called: the
4752 // traversal mask indicates which functions may be called.
4755 Traverse::variable(Named_object*)
4761 Traverse::constant(Named_object*, bool)
4767 Traverse::function(Named_object*)
4773 Traverse::block(Block*)
4779 Traverse::statement(Block*, size_t*, Statement*)
4785 Traverse::expression(Expression**)
4791 Traverse::type(Type*)