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.
15 #include "statements.h"
16 #include "expressions.h"
26 Gogo::Gogo(Backend* backend, Linemap* linemap, int int_type_size,
32 globals_(new Bindings(NULL)),
34 imported_unsafe_(false),
45 pkgpath_from_option_(false),
46 prefix_from_option_(false),
47 relative_import_path_(),
50 specific_type_functions_(),
51 specific_type_functions_are_written_(false),
52 named_types_are_converted_(false)
54 const Location loc = Linemap::predeclared_location();
56 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
57 RUNTIME_TYPE_KIND_UINT8);
58 this->add_named_type(uint8_type);
59 this->add_named_type(Type::make_integer_type("uint16", true, 16,
60 RUNTIME_TYPE_KIND_UINT16));
61 this->add_named_type(Type::make_integer_type("uint32", true, 32,
62 RUNTIME_TYPE_KIND_UINT32));
63 this->add_named_type(Type::make_integer_type("uint64", true, 64,
64 RUNTIME_TYPE_KIND_UINT64));
66 this->add_named_type(Type::make_integer_type("int8", false, 8,
67 RUNTIME_TYPE_KIND_INT8));
68 this->add_named_type(Type::make_integer_type("int16", false, 16,
69 RUNTIME_TYPE_KIND_INT16));
70 Named_type* int32_type = Type::make_integer_type("int32", false, 32,
71 RUNTIME_TYPE_KIND_INT32);
72 this->add_named_type(int32_type);
73 this->add_named_type(Type::make_integer_type("int64", false, 64,
74 RUNTIME_TYPE_KIND_INT64));
76 this->add_named_type(Type::make_float_type("float32", 32,
77 RUNTIME_TYPE_KIND_FLOAT32));
78 this->add_named_type(Type::make_float_type("float64", 64,
79 RUNTIME_TYPE_KIND_FLOAT64));
81 this->add_named_type(Type::make_complex_type("complex64", 64,
82 RUNTIME_TYPE_KIND_COMPLEX64));
83 this->add_named_type(Type::make_complex_type("complex128", 128,
84 RUNTIME_TYPE_KIND_COMPLEX128));
86 if (int_type_size < 32)
88 this->add_named_type(Type::make_integer_type("uint", true,
90 RUNTIME_TYPE_KIND_UINT));
91 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
92 RUNTIME_TYPE_KIND_INT);
93 this->add_named_type(int_type);
95 this->add_named_type(Type::make_integer_type("uintptr", true,
97 RUNTIME_TYPE_KIND_UINTPTR));
99 // "byte" is an alias for "uint8".
100 uint8_type->integer_type()->set_is_byte();
101 Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
103 this->add_named_type(byte_type->type_value());
105 // "rune" is an alias for "int32".
106 int32_type->integer_type()->set_is_rune();
107 Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
109 this->add_named_type(rune_type->type_value());
111 this->add_named_type(Type::make_named_bool_type());
113 this->add_named_type(Type::make_named_string_type());
115 // "error" is interface { Error() string }.
117 Typed_identifier_list *methods = new Typed_identifier_list;
118 Typed_identifier_list *results = new Typed_identifier_list;
119 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
120 Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
121 methods->push_back(Typed_identifier("Error", method_type, loc));
122 Interface_type *error_iface = Type::make_interface_type(methods, loc);
123 error_iface->finalize_methods();
124 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
125 this->add_named_type(error_type);
128 this->globals_->add_constant(Typed_identifier("true",
129 Type::make_boolean_type(),
132 Expression::make_boolean(true, loc),
134 this->globals_->add_constant(Typed_identifier("false",
135 Type::make_boolean_type(),
138 Expression::make_boolean(false, loc),
141 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
144 Expression::make_nil(loc),
147 Type* abstract_int_type = Type::make_abstract_integer_type();
148 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
151 Expression::make_iota(),
154 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
155 new_type->set_is_varargs();
156 new_type->set_is_builtin();
157 this->globals_->add_function_declaration("new", NULL, new_type, loc);
159 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
160 make_type->set_is_varargs();
161 make_type->set_is_builtin();
162 this->globals_->add_function_declaration("make", NULL, make_type, loc);
164 Typed_identifier_list* len_result = new Typed_identifier_list();
165 len_result->push_back(Typed_identifier("", int_type, loc));
166 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
168 len_type->set_is_builtin();
169 this->globals_->add_function_declaration("len", NULL, len_type, loc);
171 Typed_identifier_list* cap_result = new Typed_identifier_list();
172 cap_result->push_back(Typed_identifier("", int_type, loc));
173 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
175 cap_type->set_is_builtin();
176 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
178 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
179 print_type->set_is_varargs();
180 print_type->set_is_builtin();
181 this->globals_->add_function_declaration("print", NULL, print_type, loc);
183 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
184 print_type->set_is_varargs();
185 print_type->set_is_builtin();
186 this->globals_->add_function_declaration("println", NULL, print_type, loc);
188 Type *empty = Type::make_empty_interface_type(loc);
189 Typed_identifier_list* panic_parms = new Typed_identifier_list();
190 panic_parms->push_back(Typed_identifier("e", empty, loc));
191 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
193 panic_type->set_is_builtin();
194 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
196 Typed_identifier_list* recover_result = new Typed_identifier_list();
197 recover_result->push_back(Typed_identifier("", empty, loc));
198 Function_type* recover_type = Type::make_function_type(NULL, NULL,
201 recover_type->set_is_builtin();
202 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
204 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
205 close_type->set_is_varargs();
206 close_type->set_is_builtin();
207 this->globals_->add_function_declaration("close", NULL, close_type, loc);
209 Typed_identifier_list* copy_result = new Typed_identifier_list();
210 copy_result->push_back(Typed_identifier("", int_type, loc));
211 Function_type* copy_type = Type::make_function_type(NULL, NULL,
213 copy_type->set_is_varargs();
214 copy_type->set_is_builtin();
215 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
217 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
218 append_type->set_is_varargs();
219 append_type->set_is_builtin();
220 this->globals_->add_function_declaration("append", NULL, append_type, loc);
222 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
223 complex_type->set_is_varargs();
224 complex_type->set_is_builtin();
225 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
227 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
228 real_type->set_is_varargs();
229 real_type->set_is_builtin();
230 this->globals_->add_function_declaration("real", NULL, real_type, loc);
232 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
233 imag_type->set_is_varargs();
234 imag_type->set_is_builtin();
235 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
237 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
238 delete_type->set_is_varargs();
239 delete_type->set_is_builtin();
240 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
243 // Convert a pkgpath into a string suitable for a symbol. Note that
244 // this transformation is convenient but imperfect. A -fgo-pkgpath
245 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
246 // possibly leading to link time errors.
249 Gogo::pkgpath_for_symbol(const std::string& pkgpath)
251 std::string s = pkgpath;
252 for (size_t i = 0; i < s.length(); ++i)
255 if ((c >= 'a' && c <= 'z')
256 || (c >= 'A' && c <= 'Z')
257 || (c >= '0' && c <= '9')
268 // Get the package path to use for type reflection data. This should
269 // ideally be unique across the entire link.
272 Gogo::pkgpath() const
274 go_assert(this->pkgpath_set_);
275 return this->pkgpath_;
278 // Set the package path from the -fgo-pkgpath command line option.
281 Gogo::set_pkgpath(const std::string& arg)
283 go_assert(!this->pkgpath_set_);
284 this->pkgpath_ = arg;
285 this->pkgpath_set_ = true;
286 this->pkgpath_from_option_ = true;
289 // Get the package path to use for symbol names.
292 Gogo::pkgpath_symbol() const
294 go_assert(this->pkgpath_set_);
295 return this->pkgpath_symbol_;
298 // Set the unique prefix to use to determine the package path, from
299 // the -fgo-prefix command line option.
302 Gogo::set_prefix(const std::string& arg)
304 go_assert(!this->prefix_from_option_);
306 this->prefix_from_option_ = true;
309 // Munge name for use in an error message.
312 Gogo::message_name(const std::string& name)
314 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
317 // Get the package name.
320 Gogo::package_name() const
322 go_assert(this->package_ != NULL);
323 return this->package_->package_name();
326 // Set the package name.
329 Gogo::set_package_name(const std::string& package_name,
332 if (this->package_ != NULL)
334 if (this->package_->package_name() != package_name)
335 error_at(location, "expected package %<%s%>",
336 Gogo::message_name(this->package_->package_name()).c_str());
340 // Now that we know the name of the package we are compiling, set
341 // the package path to use for reflect.Type.PkgPath and global
343 if (!this->pkgpath_set_)
345 if (!this->prefix_from_option_ && package_name == "main")
346 this->pkgpath_ = package_name;
349 if (!this->prefix_from_option_)
350 this->prefix_ = "go";
351 this->pkgpath_ = this->prefix_ + '.' + package_name;
353 this->pkgpath_set_ = true;
356 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(this->pkgpath_);
358 this->package_ = this->register_package(this->pkgpath_, location);
359 this->package_->set_package_name(package_name, location);
361 if (this->is_main_package())
363 // Declare "main" as a function which takes no parameters and
365 Location uloc = Linemap::unknown_location();
366 this->declare_function("main",
367 Type::make_function_type (NULL, NULL, NULL, uloc),
372 // Return whether this is the "main" package. This is not true if
373 // -fgo-pkgpath or -fgo-prefix was used.
376 Gogo::is_main_package() const
378 return (this->package_name() == "main"
379 && !this->pkgpath_from_option_
380 && !this->prefix_from_option_);
386 Gogo::import_package(const std::string& filename,
387 const std::string& local_name,
388 bool is_local_name_exported,
391 if (filename.empty())
393 error_at(location, "import path is empty");
397 const char *pf = filename.data();
398 const char *pend = pf + filename.length();
402 int adv = Lex::fetch_char(pf, &c);
405 error_at(location, "import path contains invalid UTF-8 sequence");
410 error_at(location, "import path contains NUL");
413 if (c < 0x20 || c == 0x7f)
415 error_at(location, "import path contains control character");
420 error_at(location, "import path contains backslash; use slash");
423 if (Lex::is_unicode_space(c))
425 error_at(location, "import path contains space character");
428 if (c < 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c) != NULL)
430 error_at(location, "import path contains invalid character '%c'", c);
436 if (IS_ABSOLUTE_PATH(filename.c_str()))
438 error_at(location, "import path cannot be absolute path");
442 if (filename == "unsafe")
444 this->import_unsafe(local_name, is_local_name_exported, location);
448 Imports::const_iterator p = this->imports_.find(filename);
449 if (p != this->imports_.end())
451 Package* package = p->second;
452 package->set_location(location);
453 package->set_is_imported();
454 std::string ln = local_name;
455 bool is_ln_exported = is_local_name_exported;
458 ln = package->package_name();
459 go_assert(!ln.empty());
460 is_ln_exported = Lex::is_exported_name(ln);
464 Bindings* bindings = package->bindings();
465 for (Bindings::const_declarations_iterator p =
466 bindings->begin_declarations();
467 p != bindings->end_declarations();
469 this->add_named_object(p->second);
472 package->set_uses_sink_alias();
475 ln = this->pack_hidden_name(ln, is_ln_exported);
476 this->package_->bindings()->add_package(ln, package);
481 Import::Stream* stream = Import::open_package(filename, location,
482 this->relative_import_path_);
485 error_at(location, "import file %qs not found", filename.c_str());
489 Import imp(stream, location);
490 imp.register_builtin_types(this);
491 Package* package = imp.import(this, local_name, is_local_name_exported);
494 if (package->pkgpath() == this->pkgpath())
496 ("imported package uses same package path as package "
497 "being compiled (see -fgo-pkgpath option)"));
499 this->imports_.insert(std::make_pair(filename, package));
500 package->set_is_imported();
506 // Add an import control function for an imported package to the list.
509 Gogo::add_import_init_fn(const std::string& package_name,
510 const std::string& init_name, int prio)
512 for (std::set<Import_init>::const_iterator p =
513 this->imported_init_fns_.begin();
514 p != this->imported_init_fns_.end();
517 if (p->init_name() == init_name
518 && (p->package_name() != package_name || p->priority() != prio))
520 error("duplicate package initialization name %qs",
521 Gogo::message_name(init_name).c_str());
522 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
523 Gogo::message_name(p->package_name()).c_str(),
525 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
526 Gogo::message_name(package_name).c_str(), prio);
531 this->imported_init_fns_.insert(Import_init(package_name, init_name,
535 // Return whether we are at the global binding level.
538 Gogo::in_global_scope() const
540 return this->functions_.empty();
543 // Return the current binding contour.
546 Gogo::current_bindings()
548 if (!this->functions_.empty())
549 return this->functions_.back().blocks.back()->bindings();
550 else if (this->package_ != NULL)
551 return this->package_->bindings();
553 return this->globals_;
557 Gogo::current_bindings() const
559 if (!this->functions_.empty())
560 return this->functions_.back().blocks.back()->bindings();
561 else if (this->package_ != NULL)
562 return this->package_->bindings();
564 return this->globals_;
567 // Return the current block.
570 Gogo::current_block()
572 if (this->functions_.empty())
575 return this->functions_.back().blocks.back();
578 // Look up a name in the current binding contour. If PFUNCTION is not
579 // NULL, set it to the function in which the name is defined, or NULL
580 // if the name is defined in global scope.
583 Gogo::lookup(const std::string& name, Named_object** pfunction) const
585 if (pfunction != NULL)
588 if (Gogo::is_sink_name(name))
589 return Named_object::make_sink();
591 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
592 p != this->functions_.rend();
595 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
598 if (pfunction != NULL)
599 *pfunction = p->function;
604 if (this->package_ != NULL)
606 Named_object* ret = this->package_->bindings()->lookup(name);
609 if (ret->package() != NULL)
610 ret->package()->set_used();
615 // We do not look in the global namespace. If we did, the global
616 // namespace would effectively hide names which were defined in
617 // package scope which we have not yet seen. Instead,
618 // define_global_names is called after parsing is over to connect
619 // undefined names at package scope with names defined at global
625 // Look up a name in the current block, without searching enclosing
629 Gogo::lookup_in_block(const std::string& name) const
631 go_assert(!this->functions_.empty());
632 go_assert(!this->functions_.back().blocks.empty());
633 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
636 // Look up a name in the global namespace.
639 Gogo::lookup_global(const char* name) const
641 return this->globals_->lookup(name);
644 // Add an imported package.
647 Gogo::add_imported_package(const std::string& real_name,
648 const std::string& alias_arg,
649 bool is_alias_exported,
650 const std::string& pkgpath,
652 bool* padd_to_globals)
654 Package* ret = this->register_package(pkgpath, location);
655 ret->set_package_name(real_name, location);
657 *padd_to_globals = false;
659 if (alias_arg == ".")
660 *padd_to_globals = true;
661 else if (alias_arg == "_")
662 ret->set_uses_sink_alias();
665 std::string alias = alias_arg;
669 is_alias_exported = Lex::is_exported_name(alias);
671 alias = this->pack_hidden_name(alias, is_alias_exported);
672 Named_object* no = this->package_->bindings()->add_package(alias, ret);
673 if (!no->is_package())
680 // Register a package. This package may or may not be imported. This
681 // returns the Package structure for the package, creating if it
682 // necessary. LOCATION is the location of the import statement that
683 // led us to see this package.
686 Gogo::register_package(const std::string& pkgpath, Location location)
688 Package* package = NULL;
689 std::pair<Packages::iterator, bool> ins =
690 this->packages_.insert(std::make_pair(pkgpath, package));
693 // We have seen this package name before.
694 package = ins.first->second;
695 go_assert(package != NULL && package->pkgpath() == pkgpath);
696 if (Linemap::is_unknown_location(package->location()))
697 package->set_location(location);
701 // First time we have seen this package name.
702 package = new Package(pkgpath, location);
703 go_assert(ins.first->second == NULL);
704 ins.first->second = package;
710 // Start compiling a function.
713 Gogo::start_function(const std::string& name, Function_type* type,
714 bool add_method_to_type, Location location)
716 bool at_top_level = this->functions_.empty();
718 Block* block = new Block(NULL, location);
720 Function* enclosing = (at_top_level
722 : this->functions_.back().function->func_value());
724 Function* function = new Function(type, enclosing, block, location);
726 if (type->is_method())
728 const Typed_identifier* receiver = type->receiver();
729 Variable* this_param = new Variable(receiver->type(), NULL, false,
730 true, true, location);
731 std::string rname = receiver->name();
732 if (rname.empty() || Gogo::is_sink_name(rname))
734 // We need to give receivers a name since they wind up in
735 // DECL_ARGUMENTS. FIXME.
736 static unsigned int count;
738 snprintf(buf, sizeof buf, "r.%u", count);
742 block->bindings()->add_variable(rname, NULL, this_param);
745 const Typed_identifier_list* parameters = type->parameters();
746 bool is_varargs = type->is_varargs();
747 if (parameters != NULL)
749 for (Typed_identifier_list::const_iterator p = parameters->begin();
750 p != parameters->end();
753 Variable* param = new Variable(p->type(), NULL, false, true, false,
755 if (is_varargs && p + 1 == parameters->end())
756 param->set_is_varargs_parameter();
758 std::string pname = p->name();
759 if (pname.empty() || Gogo::is_sink_name(pname))
761 // We need to give parameters a name since they wind up
762 // in DECL_ARGUMENTS. FIXME.
763 static unsigned int count;
765 snprintf(buf, sizeof buf, "p.%u", count);
769 block->bindings()->add_variable(pname, NULL, param);
773 function->create_result_variables(this);
775 const std::string* pname;
776 std::string nested_name;
777 bool is_init = false;
778 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
780 if ((type->parameters() != NULL && !type->parameters()->empty())
781 || (type->results() != NULL && !type->results()->empty()))
783 "func init must have no arguments and no return values");
784 // There can be multiple "init" functions, so give them each a
786 static int init_count;
788 snprintf(buf, sizeof buf, ".$init%d", init_count);
791 pname = &nested_name;
794 else if (!name.empty())
798 // Invent a name for a nested function.
799 static int nested_count;
801 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
804 pname = &nested_name;
808 if (Gogo::is_sink_name(*pname))
810 static int sink_count;
812 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
814 ret = Named_object::make_function(buf, NULL, function);
816 else if (!type->is_method())
818 ret = this->package_->bindings()->add_function(*pname, NULL, function);
819 if (!ret->is_function() || ret->func_value() != function)
821 // Redefinition error. Invent a name to avoid knockon
823 static int redefinition_count;
825 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
826 ++redefinition_count;
827 ret = this->package_->bindings()->add_function(buf, NULL, function);
832 if (!add_method_to_type)
833 ret = Named_object::make_function(name, NULL, function);
836 go_assert(at_top_level);
837 Type* rtype = type->receiver()->type();
839 // We want to look through the pointer created by the
840 // parser, without getting an error if the type is not yet
842 if (rtype->classification() == Type::TYPE_POINTER)
843 rtype = rtype->points_to();
845 if (rtype->is_error_type())
846 ret = Named_object::make_function(name, NULL, function);
847 else if (rtype->named_type() != NULL)
849 ret = rtype->named_type()->add_method(name, function);
850 if (!ret->is_function())
852 // Redefinition error.
853 ret = Named_object::make_function(name, NULL, function);
856 else if (rtype->forward_declaration_type() != NULL)
858 Named_object* type_no =
859 rtype->forward_declaration_type()->named_object();
860 if (type_no->is_unknown())
862 // If we are seeing methods it really must be a
863 // type. Declare it as such. An alternative would
864 // be to support lists of methods for unknown
865 // expressions. Either way the error messages if
866 // this is not a type are going to get confusing.
867 Named_object* declared =
868 this->declare_package_type(type_no->name(),
869 type_no->location());
871 == type_no->unknown_value()->real_named_object());
873 ret = rtype->forward_declaration_type()->add_method(name,
879 this->package_->bindings()->add_method(ret);
882 this->functions_.resize(this->functions_.size() + 1);
883 Open_function& of(this->functions_.back());
885 of.blocks.push_back(block);
889 this->init_functions_.push_back(ret);
890 this->need_init_fn_ = true;
896 // Finish compiling a function.
899 Gogo::finish_function(Location location)
901 this->finish_block(location);
902 go_assert(this->functions_.back().blocks.empty());
903 this->functions_.pop_back();
906 // Return the current function.
909 Gogo::current_function() const
911 go_assert(!this->functions_.empty());
912 return this->functions_.back().function;
915 // Start a new block.
918 Gogo::start_block(Location location)
920 go_assert(!this->functions_.empty());
921 Block* block = new Block(this->current_block(), location);
922 this->functions_.back().blocks.push_back(block);
928 Gogo::finish_block(Location location)
930 go_assert(!this->functions_.empty());
931 go_assert(!this->functions_.back().blocks.empty());
932 Block* block = this->functions_.back().blocks.back();
933 this->functions_.back().blocks.pop_back();
934 block->set_end_location(location);
938 // Add an erroneous name.
941 Gogo::add_erroneous_name(const std::string& name)
943 return this->package_->bindings()->add_erroneous_name(name);
946 // Add an unknown name.
949 Gogo::add_unknown_name(const std::string& name, Location location)
951 return this->package_->bindings()->add_unknown_name(name, location);
954 // Declare a function.
957 Gogo::declare_function(const std::string& name, Function_type* type,
960 if (!type->is_method())
961 return this->current_bindings()->add_function_declaration(name, NULL, type,
965 // We don't bother to add this to the list of global
967 Type* rtype = type->receiver()->type();
969 // We want to look through the pointer created by the
970 // parser, without getting an error if the type is not yet
972 if (rtype->classification() == Type::TYPE_POINTER)
973 rtype = rtype->points_to();
975 if (rtype->is_error_type())
977 else if (rtype->named_type() != NULL)
978 return rtype->named_type()->add_method_declaration(name, NULL, type,
980 else if (rtype->forward_declaration_type() != NULL)
982 Forward_declaration_type* ftype = rtype->forward_declaration_type();
983 return ftype->add_method_declaration(name, NULL, type, location);
990 // Add a label definition.
993 Gogo::add_label_definition(const std::string& label_name,
996 go_assert(!this->functions_.empty());
997 Function* func = this->functions_.back().function->func_value();
998 Label* label = func->add_label_definition(this, label_name, location);
999 this->add_statement(Statement::make_label_statement(label, location));
1003 // Add a label reference.
1006 Gogo::add_label_reference(const std::string& label_name,
1007 Location location, bool issue_goto_errors)
1009 go_assert(!this->functions_.empty());
1010 Function* func = this->functions_.back().function->func_value();
1011 return func->add_label_reference(this, label_name, location,
1015 // Return the current binding state.
1018 Gogo::bindings_snapshot(Location location)
1020 return new Bindings_snapshot(this->current_block(), location);
1026 Gogo::add_statement(Statement* statement)
1028 go_assert(!this->functions_.empty()
1029 && !this->functions_.back().blocks.empty());
1030 this->functions_.back().blocks.back()->add_statement(statement);
1036 Gogo::add_block(Block* block, Location location)
1038 go_assert(!this->functions_.empty()
1039 && !this->functions_.back().blocks.empty());
1040 Statement* statement = Statement::make_block_statement(block, location);
1041 this->functions_.back().blocks.back()->add_statement(statement);
1047 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
1050 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
1056 Gogo::add_type(const std::string& name, Type* type, Location location)
1058 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
1060 if (!this->in_global_scope() && no->is_type())
1062 Named_object* f = this->functions_.back().function;
1064 if (f->is_function())
1065 index = f->func_value()->new_local_type_index();
1068 no->type_value()->set_in_function(f, index);
1072 // Add a named type.
1075 Gogo::add_named_type(Named_type* type)
1077 go_assert(this->in_global_scope());
1078 this->current_bindings()->add_named_type(type);
1084 Gogo::declare_type(const std::string& name, Location location)
1086 Bindings* bindings = this->current_bindings();
1087 Named_object* no = bindings->add_type_declaration(name, NULL, location);
1088 if (!this->in_global_scope() && no->is_type_declaration())
1090 Named_object* f = this->functions_.back().function;
1092 if (f->is_function())
1093 index = f->func_value()->new_local_type_index();
1096 no->type_declaration_value()->set_in_function(f, index);
1101 // Declare a type at the package level.
1104 Gogo::declare_package_type(const std::string& name, Location location)
1106 return this->package_->bindings()->add_type_declaration(name, NULL, location);
1109 // Declare a function at the package level.
1112 Gogo::declare_package_function(const std::string& name, Function_type* type,
1115 return this->package_->bindings()->add_function_declaration(name, NULL, type,
1119 // Define a type which was already declared.
1122 Gogo::define_type(Named_object* no, Named_type* type)
1124 this->current_bindings()->define_type(no, type);
1130 Gogo::add_variable(const std::string& name, Variable* variable)
1132 Named_object* no = this->current_bindings()->add_variable(name, NULL,
1135 // In a function the middle-end wants to see a DECL_EXPR node.
1137 && no->is_variable()
1138 && !no->var_value()->is_parameter()
1139 && !this->functions_.empty())
1140 this->add_statement(Statement::make_variable_declaration(no));
1145 // Add a sink--a reference to the blank identifier _.
1150 return Named_object::make_sink();
1153 // Add a named object.
1156 Gogo::add_named_object(Named_object* no)
1158 this->current_bindings()->add_named_object(no);
1161 // Mark all local variables used. This is used when some types of
1162 // parse error occur.
1165 Gogo::mark_locals_used()
1167 for (Open_functions::iterator pf = this->functions_.begin();
1168 pf != this->functions_.end();
1171 for (std::vector<Block*>::iterator pb = pf->blocks.begin();
1172 pb != pf->blocks.end();
1174 (*pb)->bindings()->mark_locals_used();
1178 // Record that we've seen an interface type.
1181 Gogo::record_interface_type(Interface_type* itype)
1183 this->interface_types_.push_back(itype);
1186 // Return a name for a thunk object.
1191 static int thunk_count;
1192 char thunk_name[50];
1193 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1198 // Return whether a function is a thunk.
1201 Gogo::is_thunk(const Named_object* no)
1203 return no->name().compare(0, 6, "$thunk") == 0;
1206 // Define the global names. We do this only after parsing all the
1207 // input files, because the program might define the global names
1211 Gogo::define_global_names()
1213 for (Bindings::const_declarations_iterator p =
1214 this->globals_->begin_declarations();
1215 p != this->globals_->end_declarations();
1218 Named_object* global_no = p->second;
1219 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1220 Named_object* no = this->package_->bindings()->lookup(name);
1224 if (no->is_type_declaration())
1226 if (global_no->is_type())
1228 if (no->type_declaration_value()->has_methods())
1229 error_at(no->location(),
1230 "may not define methods for global type");
1231 no->set_type_value(global_no->type_value());
1235 error_at(no->location(), "expected type");
1236 Type* errtype = Type::make_error_type();
1238 Named_object::make_type("erroneous_type", NULL, errtype,
1239 Linemap::predeclared_location());
1240 no->set_type_value(err->type_value());
1243 else if (no->is_unknown())
1244 no->unknown_value()->set_real_named_object(global_no);
1248 // Clear out names in file scope.
1251 Gogo::clear_file_scope()
1253 this->package_->bindings()->clear_file_scope();
1255 // Warn about packages which were imported but not used.
1256 for (Packages::iterator p = this->packages_.begin();
1257 p != this->packages_.end();
1260 Package* package = p->second;
1261 if (package != this->package_
1262 && package->is_imported()
1264 && !package->uses_sink_alias()
1266 error_at(package->location(), "imported and not used: %s",
1267 Gogo::message_name(package->package_name()).c_str());
1268 package->clear_is_imported();
1269 package->clear_uses_sink_alias();
1270 package->clear_used();
1274 // Queue up a type specific function for later writing. These are
1275 // written out in write_specific_type_functions, called after the
1276 // parse tree is lowered.
1279 Gogo::queue_specific_type_function(Type* type, Named_type* name,
1280 const std::string& hash_name,
1281 Function_type* hash_fntype,
1282 const std::string& equal_name,
1283 Function_type* equal_fntype)
1285 go_assert(!this->specific_type_functions_are_written_);
1286 go_assert(!this->in_global_scope());
1287 Specific_type_function* tsf = new Specific_type_function(type, name,
1292 this->specific_type_functions_.push_back(tsf);
1295 // Look for types which need specific hash or equality functions.
1297 class Specific_type_functions : public Traverse
1300 Specific_type_functions(Gogo* gogo)
1301 : Traverse(traverse_types),
1313 Specific_type_functions::type(Type* t)
1315 Named_object* hash_fn;
1316 Named_object* equal_fn;
1317 switch (t->classification())
1319 case Type::TYPE_NAMED:
1321 Named_type* nt = t->named_type();
1322 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1323 t->type_functions(this->gogo_, nt, NULL, NULL, &hash_fn, &equal_fn);
1325 // If this is a struct type, we don't want to make functions
1326 // for the unnamed struct.
1327 Type* rt = nt->real_type();
1328 if (rt->struct_type() == NULL)
1330 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1331 return TRAVERSE_EXIT;
1335 // If this type is defined in another package, then we don't
1336 // need to worry about the unexported fields.
1337 bool is_defined_elsewhere = nt->named_object()->package() != NULL;
1338 const Struct_field_list* fields = rt->struct_type()->fields();
1339 for (Struct_field_list::const_iterator p = fields->begin();
1343 if (is_defined_elsewhere
1344 && Gogo::is_hidden_name(p->field_name()))
1346 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
1347 return TRAVERSE_EXIT;
1351 return TRAVERSE_SKIP_COMPONENTS;
1354 case Type::TYPE_STRUCT:
1355 case Type::TYPE_ARRAY:
1356 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1357 t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
1364 return TRAVERSE_CONTINUE;
1367 // Write out type specific functions.
1370 Gogo::write_specific_type_functions()
1372 Specific_type_functions stf(this);
1373 this->traverse(&stf);
1375 while (!this->specific_type_functions_.empty())
1377 Specific_type_function* tsf = this->specific_type_functions_.back();
1378 this->specific_type_functions_.pop_back();
1379 tsf->type->write_specific_type_functions(this, tsf->name,
1386 this->specific_type_functions_are_written_ = true;
1389 // Traverse the tree.
1392 Gogo::traverse(Traverse* traverse)
1394 // Traverse the current package first for consistency. The other
1395 // packages will only contain imported types, constants, and
1397 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1399 for (Packages::const_iterator p = this->packages_.begin();
1400 p != this->packages_.end();
1403 if (p->second != this->package_)
1405 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1411 // Add a type to verify. This is used for types of sink variables, in
1412 // order to give appropriate error messages.
1415 Gogo::add_type_to_verify(Type* type)
1417 this->verify_types_.push_back(type);
1420 // Traversal class used to verify types.
1422 class Verify_types : public Traverse
1426 : Traverse(traverse_types)
1433 // Verify that a type is correct.
1436 Verify_types::type(Type* t)
1439 return TRAVERSE_SKIP_COMPONENTS;
1440 return TRAVERSE_CONTINUE;
1443 // Verify that all types are correct.
1446 Gogo::verify_types()
1448 Verify_types traverse;
1449 this->traverse(&traverse);
1451 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
1452 p != this->verify_types_.end();
1455 this->verify_types_.clear();
1458 // Traversal class used to lower parse tree.
1460 class Lower_parse_tree : public Traverse
1463 Lower_parse_tree(Gogo* gogo, Named_object* function)
1464 : Traverse(traverse_variables
1465 | traverse_constants
1466 | traverse_functions
1467 | traverse_statements
1468 | traverse_expressions),
1469 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
1473 set_inserter(const Statement_inserter* inserter)
1474 { this->inserter_ = *inserter; }
1477 variable(Named_object*);
1480 constant(Named_object*, bool);
1483 function(Named_object*);
1486 statement(Block*, size_t* pindex, Statement*);
1489 expression(Expression**);
1494 // The function we are traversing.
1495 Named_object* function_;
1496 // Value to use for the predeclared constant iota.
1498 // Current statement inserter for use by expressions.
1499 Statement_inserter inserter_;
1505 Lower_parse_tree::variable(Named_object* no)
1507 if (!no->is_variable())
1508 return TRAVERSE_CONTINUE;
1510 if (no->is_variable() && no->var_value()->is_global())
1512 // Global variables can have loops in their initialization
1513 // expressions. This is handled in lower_init_expression.
1514 no->var_value()->lower_init_expression(this->gogo_, this->function_,
1516 return TRAVERSE_CONTINUE;
1519 // This is a local variable. We are going to return
1520 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
1521 // initialization expression when we reach the variable declaration
1522 // statement. However, that means that we need to traverse the type
1524 if (no->var_value()->has_type())
1526 Type* type = no->var_value()->type();
1529 if (Type::traverse(type, this) == TRAVERSE_EXIT)
1530 return TRAVERSE_EXIT;
1533 go_assert(!no->var_value()->has_pre_init());
1535 return TRAVERSE_SKIP_COMPONENTS;
1538 // Lower constants. We handle constants specially so that we can set
1539 // the right value for the predeclared constant iota. This works in
1540 // conjunction with the way we lower Const_expression objects.
1543 Lower_parse_tree::constant(Named_object* no, bool)
1545 Named_constant* nc = no->const_value();
1547 // Don't get into trouble if the constant's initializer expression
1548 // refers to the constant itself.
1550 return TRAVERSE_CONTINUE;
1553 go_assert(this->iota_value_ == -1);
1554 this->iota_value_ = nc->iota_value();
1555 nc->traverse_expression(this);
1556 this->iota_value_ = -1;
1558 nc->clear_lowering();
1560 // We will traverse the expression a second time, but that will be
1563 return TRAVERSE_CONTINUE;
1566 // Lower function closure types. Record the function while lowering
1567 // it, so that we can pass it down when lowering an expression.
1570 Lower_parse_tree::function(Named_object* no)
1572 no->func_value()->set_closure_type();
1574 go_assert(this->function_ == NULL);
1575 this->function_ = no;
1576 int t = no->func_value()->traverse(this);
1577 this->function_ = NULL;
1579 if (t == TRAVERSE_EXIT)
1581 return TRAVERSE_SKIP_COMPONENTS;
1584 // Lower statement parse trees.
1587 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1589 // Because we explicitly traverse the statement's contents
1590 // ourselves, we want to skip block statements here. There is
1591 // nothing to lower in a block statement.
1592 if (sorig->is_block_statement())
1593 return TRAVERSE_CONTINUE;
1595 Statement_inserter hold_inserter(this->inserter_);
1596 this->inserter_ = Statement_inserter(block, pindex);
1598 // Lower the expressions first.
1599 int t = sorig->traverse_contents(this);
1600 if (t == TRAVERSE_EXIT)
1602 this->inserter_ = hold_inserter;
1606 // Keep lowering until nothing changes.
1607 Statement* s = sorig;
1610 Statement* snew = s->lower(this->gogo_, this->function_, block,
1615 t = s->traverse_contents(this);
1616 if (t == TRAVERSE_EXIT)
1618 this->inserter_ = hold_inserter;
1624 block->replace_statement(*pindex, s);
1626 this->inserter_ = hold_inserter;
1627 return TRAVERSE_SKIP_COMPONENTS;
1630 // Lower expression parse trees.
1633 Lower_parse_tree::expression(Expression** pexpr)
1635 // We have to lower all subexpressions first, so that we can get
1636 // their type if necessary. This is awkward, because we don't have
1637 // a postorder traversal pass.
1638 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1639 return TRAVERSE_EXIT;
1640 // Keep lowering until nothing changes.
1643 Expression* e = *pexpr;
1644 Expression* enew = e->lower(this->gogo_, this->function_,
1645 &this->inserter_, this->iota_value_);
1648 if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
1649 return TRAVERSE_EXIT;
1652 return TRAVERSE_SKIP_COMPONENTS;
1655 // Lower the parse tree. This is called after the parse is complete,
1656 // when all names should be resolved.
1659 Gogo::lower_parse_tree()
1661 Lower_parse_tree lower_parse_tree(this, NULL);
1662 this->traverse(&lower_parse_tree);
1668 Gogo::lower_block(Named_object* function, Block* block)
1670 Lower_parse_tree lower_parse_tree(this, function);
1671 block->traverse(&lower_parse_tree);
1674 // Lower an expression. INSERTER may be NULL, in which case the
1675 // expression had better not need to create any temporaries.
1678 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
1681 Lower_parse_tree lower_parse_tree(this, function);
1682 if (inserter != NULL)
1683 lower_parse_tree.set_inserter(inserter);
1684 lower_parse_tree.expression(pexpr);
1687 // Lower a constant. This is called when lowering a reference to a
1688 // constant. We have to make sure that the constant has already been
1692 Gogo::lower_constant(Named_object* no)
1694 go_assert(no->is_const());
1695 Lower_parse_tree lower(this, NULL);
1696 lower.constant(no, false);
1699 // Look for interface types to finalize methods of inherited
1702 class Finalize_methods : public Traverse
1705 Finalize_methods(Gogo* gogo)
1706 : Traverse(traverse_types),
1717 // Finalize the methods of an interface type.
1720 Finalize_methods::type(Type* t)
1722 // Check the classification so that we don't finalize the methods
1723 // twice for a named interface type.
1724 switch (t->classification())
1726 case Type::TYPE_INTERFACE:
1727 t->interface_type()->finalize_methods();
1730 case Type::TYPE_NAMED:
1732 // We have to finalize the methods of the real type first.
1733 // But if the real type is a struct type, then we only want to
1734 // finalize the methods of the field types, not of the struct
1735 // type itself. We don't want to add methods to the struct,
1736 // since it has a name.
1737 Named_type* nt = t->named_type();
1738 Type* rt = nt->real_type();
1739 if (rt->classification() != Type::TYPE_STRUCT)
1741 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1742 return TRAVERSE_EXIT;
1746 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1747 return TRAVERSE_EXIT;
1750 nt->finalize_methods(this->gogo_);
1752 // If this type is defined in a different package, then finalize the
1753 // types of all the methods, since we won't see them otherwise.
1754 if (nt->named_object()->package() != NULL && nt->has_any_methods())
1756 const Methods* methods = nt->methods();
1757 for (Methods::const_iterator p = methods->begin();
1758 p != methods->end();
1761 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
1762 return TRAVERSE_EXIT;
1766 return TRAVERSE_SKIP_COMPONENTS;
1769 case Type::TYPE_STRUCT:
1770 // Traverse the field types first in case there is an embedded
1771 // field with methods that the struct should inherit.
1772 if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1773 return TRAVERSE_EXIT;
1774 t->struct_type()->finalize_methods(this->gogo_);
1775 return TRAVERSE_SKIP_COMPONENTS;
1781 return TRAVERSE_CONTINUE;
1784 // Finalize method lists and build stub methods for types.
1787 Gogo::finalize_methods()
1789 Finalize_methods finalize(this);
1790 this->traverse(&finalize);
1793 // Set types for unspecified variables and constants.
1796 Gogo::determine_types()
1798 Bindings* bindings = this->current_bindings();
1799 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1800 p != bindings->end_definitions();
1803 if ((*p)->is_function())
1804 (*p)->func_value()->determine_types();
1805 else if ((*p)->is_variable())
1806 (*p)->var_value()->determine_type();
1807 else if ((*p)->is_const())
1808 (*p)->const_value()->determine_type();
1810 // See if a variable requires us to build an initialization
1811 // function. We know that we will see all global variables
1813 if (!this->need_init_fn_ && (*p)->is_variable())
1815 Variable* variable = (*p)->var_value();
1817 // If this is a global variable which requires runtime
1818 // initialization, we need an initialization function.
1819 if (!variable->is_global())
1821 else if (variable->init() == NULL)
1823 else if (variable->type()->interface_type() != NULL)
1824 this->need_init_fn_ = true;
1825 else if (variable->init()->is_constant())
1827 else if (!variable->init()->is_composite_literal())
1828 this->need_init_fn_ = true;
1829 else if (variable->init()->is_nonconstant_composite_literal())
1830 this->need_init_fn_ = true;
1832 // If this is a global variable which holds a pointer value,
1833 // then we need an initialization function to register it as a
1835 if (variable->is_global() && variable->type()->has_pointer())
1836 this->need_init_fn_ = true;
1840 // Determine the types of constants in packages.
1841 for (Packages::const_iterator p = this->packages_.begin();
1842 p != this->packages_.end();
1844 p->second->determine_types();
1847 // Traversal class used for type checking.
1849 class Check_types_traverse : public Traverse
1852 Check_types_traverse(Gogo* gogo)
1853 : Traverse(traverse_variables
1854 | traverse_constants
1855 | traverse_functions
1856 | traverse_statements
1857 | traverse_expressions),
1862 variable(Named_object*);
1865 constant(Named_object*, bool);
1868 function(Named_object*);
1871 statement(Block*, size_t* pindex, Statement*);
1874 expression(Expression**);
1881 // Check that a variable initializer has the right type.
1884 Check_types_traverse::variable(Named_object* named_object)
1886 if (named_object->is_variable())
1888 Variable* var = named_object->var_value();
1890 // Give error if variable type is not defined.
1891 var->type()->base();
1893 Expression* init = var->init();
1896 && !Type::are_assignable(var->type(), init->type(), &reason))
1899 error_at(var->location(), "incompatible type in initialization");
1901 error_at(var->location(),
1902 "incompatible type in initialization (%s)",
1906 else if (!var->is_used()
1907 && !var->is_global()
1908 && !var->is_parameter()
1909 && !var->is_receiver()
1910 && !var->type()->is_error()
1911 && (init == NULL || !init->is_error_expression())
1912 && !Lex::is_invalid_identifier(named_object->name()))
1913 error_at(var->location(), "%qs declared and not used",
1914 named_object->message_name().c_str());
1916 return TRAVERSE_CONTINUE;
1919 // Check that a constant initializer has the right type.
1922 Check_types_traverse::constant(Named_object* named_object, bool)
1924 Named_constant* constant = named_object->const_value();
1925 Type* ctype = constant->type();
1926 if (ctype->integer_type() == NULL
1927 && ctype->float_type() == NULL
1928 && ctype->complex_type() == NULL
1929 && !ctype->is_boolean_type()
1930 && !ctype->is_string_type())
1932 if (ctype->is_nil_type())
1933 error_at(constant->location(), "const initializer cannot be nil");
1934 else if (!ctype->is_error())
1935 error_at(constant->location(), "invalid constant type");
1936 constant->set_error();
1938 else if (!constant->expr()->is_constant())
1940 error_at(constant->expr()->location(), "expression is not constant");
1941 constant->set_error();
1943 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1946 error_at(constant->location(),
1947 "initialization expression has wrong type");
1948 constant->set_error();
1950 return TRAVERSE_CONTINUE;
1953 // There are no types to check in a function, but this is where we
1954 // issue warnings about labels which are defined but not referenced.
1957 Check_types_traverse::function(Named_object* no)
1959 no->func_value()->check_labels();
1960 return TRAVERSE_CONTINUE;
1963 // Check that types are valid in a statement.
1966 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1968 s->check_types(this->gogo_);
1969 return TRAVERSE_CONTINUE;
1972 // Check that types are valid in an expression.
1975 Check_types_traverse::expression(Expression** expr)
1977 (*expr)->check_types(this->gogo_);
1978 return TRAVERSE_CONTINUE;
1981 // Check that types are valid.
1986 Check_types_traverse traverse(this);
1987 this->traverse(&traverse);
1990 // Check the types in a single block.
1993 Gogo::check_types_in_block(Block* block)
1995 Check_types_traverse traverse(this);
1996 block->traverse(&traverse);
1999 // A traversal class used to find a single shortcut operator within an
2002 class Find_shortcut : public Traverse
2006 : Traverse(traverse_blocks
2007 | traverse_statements
2008 | traverse_expressions),
2012 // A pointer to the expression which was found, or NULL if none was
2016 { return this->found_; }
2021 { return TRAVERSE_SKIP_COMPONENTS; }
2024 statement(Block*, size_t*, Statement*)
2025 { return TRAVERSE_SKIP_COMPONENTS; }
2028 expression(Expression**);
2031 Expression** found_;
2034 // Find a shortcut expression.
2037 Find_shortcut::expression(Expression** pexpr)
2039 Expression* expr = *pexpr;
2040 Binary_expression* be = expr->binary_expression();
2042 return TRAVERSE_CONTINUE;
2043 Operator op = be->op();
2044 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
2045 return TRAVERSE_CONTINUE;
2046 go_assert(this->found_ == NULL);
2047 this->found_ = pexpr;
2048 return TRAVERSE_EXIT;
2051 // A traversal class used to turn shortcut operators into explicit if
2054 class Shortcuts : public Traverse
2057 Shortcuts(Gogo* gogo)
2058 : Traverse(traverse_variables
2059 | traverse_statements),
2065 variable(Named_object*);
2068 statement(Block*, size_t*, Statement*);
2071 // Convert a shortcut operator.
2073 convert_shortcut(Block* enclosing, Expression** pshortcut);
2079 // Remove shortcut operators in a single statement.
2082 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
2084 // FIXME: This approach doesn't work for switch statements, because
2085 // we add the new statements before the whole switch when we need to
2086 // instead add them just before the switch expression. The right
2087 // fix is probably to lower switch statements with nonconstant cases
2088 // to a series of conditionals.
2089 if (s->switch_statement() != NULL)
2090 return TRAVERSE_CONTINUE;
2094 Find_shortcut find_shortcut;
2096 // If S is a variable declaration, then ordinary traversal won't
2097 // do anything. We want to explicitly traverse the
2098 // initialization expression if there is one.
2099 Variable_declaration_statement* vds = s->variable_declaration_statement();
2100 Expression* init = NULL;
2102 s->traverse_contents(&find_shortcut);
2105 init = vds->var()->var_value()->init();
2107 return TRAVERSE_CONTINUE;
2108 init->traverse(&init, &find_shortcut);
2110 Expression** pshortcut = find_shortcut.found();
2111 if (pshortcut == NULL)
2112 return TRAVERSE_CONTINUE;
2114 Statement* snew = this->convert_shortcut(block, pshortcut);
2115 block->insert_statement_before(*pindex, snew);
2118 if (pshortcut == &init)
2119 vds->var()->var_value()->set_init(init);
2123 // Remove shortcut operators in the initializer of a global variable.
2126 Shortcuts::variable(Named_object* no)
2128 if (no->is_result_variable())
2129 return TRAVERSE_CONTINUE;
2130 Variable* var = no->var_value();
2131 Expression* init = var->init();
2132 if (!var->is_global() || init == NULL)
2133 return TRAVERSE_CONTINUE;
2137 Find_shortcut find_shortcut;
2138 init->traverse(&init, &find_shortcut);
2139 Expression** pshortcut = find_shortcut.found();
2140 if (pshortcut == NULL)
2141 return TRAVERSE_CONTINUE;
2143 Statement* snew = this->convert_shortcut(NULL, pshortcut);
2144 var->add_preinit_statement(this->gogo_, snew);
2145 if (pshortcut == &init)
2146 var->set_init(init);
2150 // Given an expression which uses a shortcut operator, return a
2151 // statement which implements it, and update *PSHORTCUT accordingly.
2154 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
2156 Binary_expression* shortcut = (*pshortcut)->binary_expression();
2157 Expression* left = shortcut->left();
2158 Expression* right = shortcut->right();
2159 Location loc = shortcut->location();
2161 Block* retblock = new Block(enclosing, loc);
2162 retblock->set_end_location(loc);
2164 Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
2166 retblock->add_statement(ts);
2168 Block* block = new Block(retblock, loc);
2169 block->set_end_location(loc);
2170 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
2171 Statement* assign = Statement::make_assignment(tmpref, right, loc);
2172 block->add_statement(assign);
2174 Expression* cond = Expression::make_temporary_reference(ts, loc);
2175 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
2176 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
2178 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
2180 retblock->add_statement(if_statement);
2182 *pshortcut = Expression::make_temporary_reference(ts, loc);
2186 // Now convert any shortcut operators in LEFT and RIGHT.
2187 Shortcuts shortcuts(this->gogo_);
2188 retblock->traverse(&shortcuts);
2190 return Statement::make_block_statement(retblock, loc);
2193 // Turn shortcut operators into explicit if statements. Doing this
2194 // considerably simplifies the order of evaluation rules.
2197 Gogo::remove_shortcuts()
2199 Shortcuts shortcuts(this);
2200 this->traverse(&shortcuts);
2203 // A traversal class which finds all the expressions which must be
2204 // evaluated in order within a statement or larger expression. This
2205 // is used to implement the rules about order of evaluation.
2207 class Find_eval_ordering : public Traverse
2210 typedef std::vector<Expression**> Expression_pointers;
2213 Find_eval_ordering()
2214 : Traverse(traverse_blocks
2215 | traverse_statements
2216 | traverse_expressions),
2222 { return this->exprs_.size(); }
2224 typedef Expression_pointers::const_iterator const_iterator;
2228 { return this->exprs_.begin(); }
2232 { return this->exprs_.end(); }
2237 { return TRAVERSE_SKIP_COMPONENTS; }
2240 statement(Block*, size_t*, Statement*)
2241 { return TRAVERSE_SKIP_COMPONENTS; }
2244 expression(Expression**);
2247 // A list of pointers to expressions with side-effects.
2248 Expression_pointers exprs_;
2251 // If an expression must be evaluated in order, put it on the list.
2254 Find_eval_ordering::expression(Expression** expression_pointer)
2256 // We have to look at subexpressions before this one.
2257 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2258 return TRAVERSE_EXIT;
2259 if ((*expression_pointer)->must_eval_in_order())
2260 this->exprs_.push_back(expression_pointer);
2261 return TRAVERSE_SKIP_COMPONENTS;
2264 // A traversal class for ordering evaluations.
2266 class Order_eval : public Traverse
2269 Order_eval(Gogo* gogo)
2270 : Traverse(traverse_variables
2271 | traverse_statements),
2276 variable(Named_object*);
2279 statement(Block*, size_t*, Statement*);
2286 // Implement the order of evaluation rules for a statement.
2289 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
2291 // FIXME: This approach doesn't work for switch statements, because
2292 // we add the new statements before the whole switch when we need to
2293 // instead add them just before the switch expression. The right
2294 // fix is probably to lower switch statements with nonconstant cases
2295 // to a series of conditionals.
2296 if (s->switch_statement() != NULL)
2297 return TRAVERSE_CONTINUE;
2299 Find_eval_ordering find_eval_ordering;
2301 // If S is a variable declaration, then ordinary traversal won't do
2302 // anything. We want to explicitly traverse the initialization
2303 // expression if there is one.
2304 Variable_declaration_statement* vds = s->variable_declaration_statement();
2305 Expression* init = NULL;
2306 Expression* orig_init = NULL;
2308 s->traverse_contents(&find_eval_ordering);
2311 init = vds->var()->var_value()->init();
2313 return TRAVERSE_CONTINUE;
2316 // It might seem that this could be
2317 // init->traverse_subexpressions. Unfortunately that can fail
2320 // newvar, err := call(arg())
2321 // Here newvar will have an init of call result 0 of
2322 // call(arg()). If we only traverse subexpressions, we will
2323 // only find arg(), and we won't bother to move anything out.
2324 // Then we get to the assignment to err, we will traverse the
2325 // whole statement, and this time we will find both call() and
2326 // arg(), and so we will move them out. This will cause them to
2327 // be put into temporary variables before the assignment to err
2328 // but after the declaration of newvar. To avoid that problem,
2329 // we traverse the entire expression here.
2330 Expression::traverse(&init, &find_eval_ordering);
2333 size_t c = find_eval_ordering.size();
2335 return TRAVERSE_CONTINUE;
2337 // If there is only one expression with a side-effect, we can
2338 // usually leave it in place. However, for an assignment statement,
2339 // we need to evaluate an expression on the right hand side before
2340 // we evaluate any index expression on the left hand side, so for
2341 // that case we always move the expression. Otherwise we mishandle
2342 // m[0] = len(m) where m is a map.
2343 if (c == 1 && s->classification() != Statement::STATEMENT_ASSIGNMENT)
2344 return TRAVERSE_CONTINUE;
2346 bool is_thunk = s->thunk_statement() != NULL;
2347 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2348 p != find_eval_ordering.end();
2351 Expression** pexpr = *p;
2353 // The last expression in a thunk will be the call passed to go
2354 // or defer, which we must not evaluate early.
2355 if (is_thunk && p + 1 == find_eval_ordering.end())
2358 Location loc = (*pexpr)->location();
2360 if ((*pexpr)->call_expression() == NULL
2361 || (*pexpr)->call_expression()->result_count() < 2)
2363 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2366 *pexpr = Expression::make_temporary_reference(ts, loc);
2370 // A call expression which returns multiple results needs to
2371 // be handled specially. We can't create a temporary
2372 // because there is no type to give it. Any actual uses of
2373 // the values will be done via Call_result_expressions.
2374 s = Statement::make_statement(*pexpr, true);
2377 block->insert_statement_before(*pindex, s);
2381 if (init != orig_init)
2382 vds->var()->var_value()->set_init(init);
2384 return TRAVERSE_CONTINUE;
2387 // Implement the order of evaluation rules for the initializer of a
2391 Order_eval::variable(Named_object* no)
2393 if (no->is_result_variable())
2394 return TRAVERSE_CONTINUE;
2395 Variable* var = no->var_value();
2396 Expression* init = var->init();
2397 if (!var->is_global() || init == NULL)
2398 return TRAVERSE_CONTINUE;
2400 Find_eval_ordering find_eval_ordering;
2401 Expression::traverse(&init, &find_eval_ordering);
2403 if (find_eval_ordering.size() <= 1)
2405 // If there is only one expression with a side-effect, we can
2406 // leave it in place.
2407 return TRAVERSE_SKIP_COMPONENTS;
2410 Expression* orig_init = init;
2412 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2413 p != find_eval_ordering.end();
2416 Expression** pexpr = *p;
2417 Location loc = (*pexpr)->location();
2419 if ((*pexpr)->call_expression() == NULL
2420 || (*pexpr)->call_expression()->result_count() < 2)
2422 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2425 *pexpr = Expression::make_temporary_reference(ts, loc);
2429 // A call expression which returns multiple results needs to
2430 // be handled specially.
2431 s = Statement::make_statement(*pexpr, true);
2433 var->add_preinit_statement(this->gogo_, s);
2436 if (init != orig_init)
2437 var->set_init(init);
2439 return TRAVERSE_SKIP_COMPONENTS;
2442 // Use temporary variables to implement the order of evaluation rules.
2445 Gogo::order_evaluations()
2447 Order_eval order_eval(this);
2448 this->traverse(&order_eval);
2451 // Traversal to convert calls to the predeclared recover function to
2452 // pass in an argument indicating whether it can recover from a panic
2455 class Convert_recover : public Traverse
2458 Convert_recover(Named_object* arg)
2459 : Traverse(traverse_expressions),
2465 expression(Expression**);
2468 // The argument to pass to the function.
2472 // Convert calls to recover.
2475 Convert_recover::expression(Expression** pp)
2477 Call_expression* ce = (*pp)->call_expression();
2478 if (ce != NULL && ce->is_recover_call())
2479 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2481 return TRAVERSE_CONTINUE;
2484 // Traversal for build_recover_thunks.
2486 class Build_recover_thunks : public Traverse
2489 Build_recover_thunks(Gogo* gogo)
2490 : Traverse(traverse_functions),
2495 function(Named_object*);
2499 can_recover_arg(Location);
2505 // If this function calls recover, turn it into a thunk.
2508 Build_recover_thunks::function(Named_object* orig_no)
2510 Function* orig_func = orig_no->func_value();
2511 if (!orig_func->calls_recover()
2512 || orig_func->is_recover_thunk()
2513 || orig_func->has_recover_thunk())
2514 return TRAVERSE_CONTINUE;
2516 Gogo* gogo = this->gogo_;
2517 Location location = orig_func->location();
2522 Function_type* orig_fntype = orig_func->type();
2523 Typed_identifier_list* new_params = new Typed_identifier_list();
2524 std::string receiver_name;
2525 if (orig_fntype->is_method())
2527 const Typed_identifier* receiver = orig_fntype->receiver();
2528 snprintf(buf, sizeof buf, "rt.%u", count);
2530 receiver_name = buf;
2531 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2532 receiver->location()));
2534 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2535 if (orig_params != NULL && !orig_params->empty())
2537 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2538 p != orig_params->end();
2541 snprintf(buf, sizeof buf, "pt.%u", count);
2543 new_params->push_back(Typed_identifier(buf, p->type(),
2547 snprintf(buf, sizeof buf, "pr.%u", count);
2549 std::string can_recover_name = buf;
2550 new_params->push_back(Typed_identifier(can_recover_name,
2551 Type::lookup_bool_type(),
2552 orig_fntype->location()));
2554 const Typed_identifier_list* orig_results = orig_fntype->results();
2555 Typed_identifier_list* new_results;
2556 if (orig_results == NULL || orig_results->empty())
2560 new_results = new Typed_identifier_list();
2561 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2562 p != orig_results->end();
2564 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2567 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2569 orig_fntype->location());
2570 if (orig_fntype->is_varargs())
2571 new_fntype->set_is_varargs();
2573 std::string name = orig_no->name() + "$recover";
2574 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2576 Function *new_func = new_no->func_value();
2577 if (orig_func->enclosing() != NULL)
2578 new_func->set_enclosing(orig_func->enclosing());
2580 // We build the code for the original function attached to the new
2581 // function, and then swap the original and new function bodies.
2582 // This means that existing references to the original function will
2583 // then refer to the new function. That makes this code a little
2584 // confusing, in that the reference to NEW_NO really refers to the
2585 // other function, not the one we are building.
2587 Expression* closure = NULL;
2588 if (orig_func->needs_closure())
2590 Named_object* orig_closure_no = orig_func->closure_var();
2591 Variable* orig_closure_var = orig_closure_no->var_value();
2592 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2593 true, false, location);
2594 snprintf(buf, sizeof buf, "closure.%u", count);
2596 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2598 new_func->set_closure_var(new_closure_no);
2599 closure = Expression::make_var_reference(new_closure_no, location);
2602 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2604 Expression_list* args = new Expression_list();
2605 if (new_params != NULL)
2607 // Note that we skip the last parameter, which is the boolean
2608 // indicating whether recover can succed.
2609 for (Typed_identifier_list::const_iterator p = new_params->begin();
2610 p + 1 != new_params->end();
2613 Named_object* p_no = gogo->lookup(p->name(), NULL);
2614 go_assert(p_no != NULL
2615 && p_no->is_variable()
2616 && p_no->var_value()->is_parameter());
2617 args->push_back(Expression::make_var_reference(p_no, location));
2620 args->push_back(this->can_recover_arg(location));
2622 gogo->start_block(location);
2624 Call_expression* call = Expression::make_call(fn, args, false, location);
2626 // Any varargs call has already been lowered.
2627 call->set_varargs_are_lowered();
2630 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2631 s = Statement::make_statement(call, true);
2634 Expression_list* vals = new Expression_list();
2635 size_t rc = orig_fntype->results()->size();
2637 vals->push_back(call);
2640 for (size_t i = 0; i < rc; ++i)
2641 vals->push_back(Expression::make_call_result(call, i));
2643 s = Statement::make_return_statement(vals, location);
2645 s->determine_types();
2646 gogo->add_statement(s);
2648 Block* b = gogo->finish_block(location);
2650 gogo->add_block(b, location);
2652 // Lower the call in case it returns multiple results.
2653 gogo->lower_block(new_no, b);
2655 gogo->finish_function(location);
2657 // Swap the function bodies and types.
2658 new_func->swap_for_recover(orig_func);
2659 orig_func->set_is_recover_thunk();
2660 new_func->set_calls_recover();
2661 new_func->set_has_recover_thunk();
2663 Bindings* orig_bindings = orig_func->block()->bindings();
2664 Bindings* new_bindings = new_func->block()->bindings();
2665 if (orig_fntype->is_method())
2667 // We changed the receiver to be a regular parameter. We have
2668 // to update the binding accordingly in both functions.
2669 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2670 go_assert(orig_rec_no != NULL
2671 && orig_rec_no->is_variable()
2672 && !orig_rec_no->var_value()->is_receiver());
2673 orig_rec_no->var_value()->set_is_receiver();
2675 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2676 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2677 if (new_rec_no == NULL)
2678 go_assert(saw_errors());
2681 go_assert(new_rec_no->is_variable()
2682 && new_rec_no->var_value()->is_receiver());
2683 new_rec_no->var_value()->set_is_not_receiver();
2687 // Because we flipped blocks but not types, the can_recover
2688 // parameter appears in the (now) old bindings as a parameter.
2689 // Change it to a local variable, whereupon it will be discarded.
2690 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2691 go_assert(can_recover_no != NULL
2692 && can_recover_no->is_variable()
2693 && can_recover_no->var_value()->is_parameter());
2694 orig_bindings->remove_binding(can_recover_no);
2696 // Add the can_recover argument to the (now) new bindings, and
2697 // attach it to any recover statements.
2698 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2699 false, true, false, location);
2700 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2702 Convert_recover convert_recover(can_recover_no);
2703 new_func->traverse(&convert_recover);
2705 // Update the function pointers in any named results.
2706 new_func->update_result_variables();
2707 orig_func->update_result_variables();
2709 return TRAVERSE_CONTINUE;
2712 // Return the expression to pass for the .can_recover parameter to the
2713 // new function. This indicates whether a call to recover may return
2714 // non-nil. The expression is
2715 // __go_can_recover(__builtin_return_address()).
2718 Build_recover_thunks::can_recover_arg(Location location)
2720 static Named_object* builtin_return_address;
2721 if (builtin_return_address == NULL)
2723 const Location bloc = Linemap::predeclared_location();
2725 Typed_identifier_list* param_types = new Typed_identifier_list();
2726 Type* uint_type = Type::lookup_integer_type("uint");
2727 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2729 Typed_identifier_list* return_types = new Typed_identifier_list();
2730 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2731 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2733 Function_type* fntype = Type::make_function_type(NULL, param_types,
2734 return_types, bloc);
2735 builtin_return_address =
2736 Named_object::make_function_declaration("__builtin_return_address",
2737 NULL, fntype, bloc);
2738 const char* n = "__builtin_return_address";
2739 builtin_return_address->func_declaration_value()->set_asm_name(n);
2742 static Named_object* can_recover;
2743 if (can_recover == NULL)
2745 const Location bloc = Linemap::predeclared_location();
2746 Typed_identifier_list* param_types = new Typed_identifier_list();
2747 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2748 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2749 Type* boolean_type = Type::lookup_bool_type();
2750 Typed_identifier_list* results = new Typed_identifier_list();
2751 results->push_back(Typed_identifier("", boolean_type, bloc));
2752 Function_type* fntype = Type::make_function_type(NULL, param_types,
2754 can_recover = Named_object::make_function_declaration("__go_can_recover",
2757 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2760 Expression* fn = Expression::make_func_reference(builtin_return_address,
2764 mpz_init_set_ui(zval, 0UL);
2765 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2767 Expression_list *args = new Expression_list();
2768 args->push_back(zexpr);
2770 Expression* call = Expression::make_call(fn, args, false, location);
2772 args = new Expression_list();
2773 args->push_back(call);
2775 fn = Expression::make_func_reference(can_recover, NULL, location);
2776 return Expression::make_call(fn, args, false, location);
2779 // Build thunks for functions which call recover. We build a new
2780 // function with an extra parameter, which is whether a call to
2781 // recover can succeed. We then move the body of this function to
2782 // that one. We then turn this function into a thunk which calls the
2783 // new one, passing the value of
2784 // __go_can_recover(__builtin_return_address()). The function will be
2785 // marked as not splitting the stack. This will cooperate with the
2786 // implementation of defer to make recover do the right thing.
2789 Gogo::build_recover_thunks()
2791 Build_recover_thunks build_recover_thunks(this);
2792 this->traverse(&build_recover_thunks);
2795 // Look for named types to see whether we need to create an interface
2798 class Build_method_tables : public Traverse
2801 Build_method_tables(Gogo* gogo,
2802 const std::vector<Interface_type*>& interfaces)
2803 : Traverse(traverse_types),
2804 gogo_(gogo), interfaces_(interfaces)
2813 // A list of locally defined interfaces which have hidden methods.
2814 const std::vector<Interface_type*>& interfaces_;
2817 // Build all required interface method tables for types. We need to
2818 // ensure that we have an interface method table for every interface
2819 // which has a hidden method, for every named type which implements
2820 // that interface. Normally we can just build interface method tables
2821 // as we need them. However, in some cases we can require an
2822 // interface method table for an interface defined in a different
2823 // package for a type defined in that package. If that interface and
2824 // type both use a hidden method, that is OK. However, we will not be
2825 // able to build that interface method table when we need it, because
2826 // the type's hidden method will be static. So we have to build it
2827 // here, and just refer it from other packages as needed.
2830 Gogo::build_interface_method_tables()
2835 std::vector<Interface_type*> hidden_interfaces;
2836 hidden_interfaces.reserve(this->interface_types_.size());
2837 for (std::vector<Interface_type*>::const_iterator pi =
2838 this->interface_types_.begin();
2839 pi != this->interface_types_.end();
2842 const Typed_identifier_list* methods = (*pi)->methods();
2843 if (methods == NULL)
2845 for (Typed_identifier_list::const_iterator pm = methods->begin();
2846 pm != methods->end();
2849 if (Gogo::is_hidden_name(pm->name()))
2851 hidden_interfaces.push_back(*pi);
2857 if (!hidden_interfaces.empty())
2859 // Now traverse the tree looking for all named types.
2860 Build_method_tables bmt(this, hidden_interfaces);
2861 this->traverse(&bmt);
2864 // We no longer need the list of interfaces.
2866 this->interface_types_.clear();
2869 // This is called for each type. For a named type, for each of the
2870 // interfaces with hidden methods that it implements, create the
2874 Build_method_tables::type(Type* type)
2876 Named_type* nt = type->named_type();
2877 Struct_type* st = type->struct_type();
2878 if (nt != NULL || st != NULL)
2880 for (std::vector<Interface_type*>::const_iterator p =
2881 this->interfaces_.begin();
2882 p != this->interfaces_.end();
2885 // We ask whether a pointer to the named type implements the
2886 // interface, because a pointer can implement more methods
2890 if ((*p)->implements_interface(Type::make_pointer_type(nt),
2893 nt->interface_method_table(this->gogo_, *p, false);
2894 nt->interface_method_table(this->gogo_, *p, true);
2899 if ((*p)->implements_interface(Type::make_pointer_type(st),
2902 st->interface_method_table(this->gogo_, *p, false);
2903 st->interface_method_table(this->gogo_, *p, true);
2908 return TRAVERSE_CONTINUE;
2911 // Traversal class used to check for return statements.
2913 class Check_return_statements_traverse : public Traverse
2916 Check_return_statements_traverse()
2917 : Traverse(traverse_functions)
2921 function(Named_object*);
2924 // Check that a function has a return statement if it needs one.
2927 Check_return_statements_traverse::function(Named_object* no)
2929 Function* func = no->func_value();
2930 const Function_type* fntype = func->type();
2931 const Typed_identifier_list* results = fntype->results();
2933 // We only need a return statement if there is a return value.
2934 if (results == NULL || results->empty())
2935 return TRAVERSE_CONTINUE;
2937 if (func->block()->may_fall_through())
2938 error_at(func->location(), "control reaches end of non-void function");
2940 return TRAVERSE_CONTINUE;
2943 // Check return statements.
2946 Gogo::check_return_statements()
2948 Check_return_statements_traverse traverse;
2949 this->traverse(&traverse);
2952 // Work out the package priority. It is one more than the maximum
2953 // priority of an imported package.
2956 Gogo::package_priority() const
2959 for (Packages::const_iterator p = this->packages_.begin();
2960 p != this->packages_.end();
2962 if (p->second->priority() > priority)
2963 priority = p->second->priority();
2964 return priority + 1;
2967 // Export identifiers as requested.
2972 // For now we always stream to a section. Later we may want to
2973 // support streaming to a separate file.
2974 Stream_to_section stream;
2976 Export exp(&stream);
2977 exp.register_builtin_types(this);
2978 exp.export_globals(this->package_name(),
2980 this->package_priority(),
2982 (this->need_init_fn_ && !this->is_main_package()
2983 ? this->get_init_fn_name()
2985 this->imported_init_fns_,
2986 this->package_->bindings());
2989 // Find the blocks in order to convert named types defined in blocks.
2991 class Convert_named_types : public Traverse
2994 Convert_named_types(Gogo* gogo)
2995 : Traverse(traverse_blocks),
3001 block(Block* block);
3008 Convert_named_types::block(Block* block)
3010 this->gogo_->convert_named_types_in_bindings(block->bindings());
3011 return TRAVERSE_CONTINUE;
3014 // Convert all named types to the backend representation. Since named
3015 // types can refer to other types, this needs to be done in the right
3016 // sequence, which is handled by Named_type::convert. Here we arrange
3017 // to call that for each named type.
3020 Gogo::convert_named_types()
3022 this->convert_named_types_in_bindings(this->globals_);
3023 for (Packages::iterator p = this->packages_.begin();
3024 p != this->packages_.end();
3027 Package* package = p->second;
3028 this->convert_named_types_in_bindings(package->bindings());
3031 Convert_named_types cnt(this);
3032 this->traverse(&cnt);
3034 // Make all the builtin named types used for type descriptors, and
3035 // then convert them. They will only be written out if they are
3037 Type::make_type_descriptor_type();
3038 Type::make_type_descriptor_ptr_type();
3039 Function_type::make_function_type_descriptor_type();
3040 Pointer_type::make_pointer_type_descriptor_type();
3041 Struct_type::make_struct_type_descriptor_type();
3042 Array_type::make_array_type_descriptor_type();
3043 Array_type::make_slice_type_descriptor_type();
3044 Map_type::make_map_type_descriptor_type();
3045 Map_type::make_map_descriptor_type();
3046 Channel_type::make_chan_type_descriptor_type();
3047 Interface_type::make_interface_type_descriptor_type();
3048 Type::convert_builtin_named_types(this);
3050 Runtime::convert_types(this);
3052 this->named_types_are_converted_ = true;
3055 // Convert all names types in a set of bindings.
3058 Gogo::convert_named_types_in_bindings(Bindings* bindings)
3060 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
3061 p != bindings->end_definitions();
3064 if ((*p)->is_type())
3065 (*p)->type_value()->convert(this);
3071 Function::Function(Function_type* type, Function* enclosing, Block* block,
3073 : type_(type), enclosing_(enclosing), results_(NULL),
3074 closure_var_(NULL), block_(block), location_(location), labels_(),
3075 local_type_count_(0), fndecl_(NULL), defer_stack_(NULL),
3076 results_are_named_(false), calls_recover_(false), is_recover_thunk_(false),
3077 has_recover_thunk_(false)
3081 // Create the named result variables.
3084 Function::create_result_variables(Gogo* gogo)
3086 const Typed_identifier_list* results = this->type_->results();
3087 if (results == NULL || results->empty())
3090 if (!results->front().name().empty())
3091 this->results_are_named_ = true;
3093 this->results_ = new Results();
3094 this->results_->reserve(results->size());
3096 Block* block = this->block_;
3098 for (Typed_identifier_list::const_iterator p = results->begin();
3099 p != results->end();
3102 std::string name = p->name();
3103 if (name.empty() || Gogo::is_sink_name(name))
3105 static int result_counter;
3107 snprintf(buf, sizeof buf, "$ret%d", result_counter);
3109 name = gogo->pack_hidden_name(buf, false);
3111 Result_variable* result = new Result_variable(p->type(), this, index,
3113 Named_object* no = block->bindings()->add_result_variable(name, result);
3114 if (no->is_result_variable())
3115 this->results_->push_back(no);
3118 static int dummy_result_count;
3120 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
3121 ++dummy_result_count;
3122 name = gogo->pack_hidden_name(buf, false);
3123 no = block->bindings()->add_result_variable(name, result);
3124 go_assert(no->is_result_variable());
3125 this->results_->push_back(no);
3130 // Update the named result variables when cloning a function which
3134 Function::update_result_variables()
3136 if (this->results_ == NULL)
3139 for (Results::iterator p = this->results_->begin();
3140 p != this->results_->end();
3142 (*p)->result_var_value()->set_function(this);
3145 // Return the closure variable, creating it if necessary.
3148 Function::closure_var()
3150 if (this->closure_var_ == NULL)
3152 // We don't know the type of the variable yet. We add fields as
3154 Location loc = this->type_->location();
3155 Struct_field_list* sfl = new Struct_field_list;
3156 Type* struct_type = Type::make_struct_type(sfl, loc);
3157 Variable* var = new Variable(Type::make_pointer_type(struct_type),
3158 NULL, false, true, false, loc);
3160 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
3161 // Note that the new variable is not in any binding contour.
3163 return this->closure_var_;
3166 // Set the type of the closure variable.
3169 Function::set_closure_type()
3171 if (this->closure_var_ == NULL)
3173 Named_object* closure = this->closure_var_;
3174 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
3175 unsigned int index = 0;
3176 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
3177 p != this->closure_fields_.end();
3180 Named_object* no = p->first;
3182 snprintf(buf, sizeof buf, "%u", index);
3183 std::string n = no->name() + buf;
3185 if (no->is_variable())
3186 var_type = no->var_value()->type();
3188 var_type = no->result_var_value()->type();
3189 Type* field_type = Type::make_pointer_type(var_type);
3190 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
3194 // Return whether this function is a method.
3197 Function::is_method() const
3199 return this->type_->is_method();
3202 // Add a label definition.
3205 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
3208 Label* lnull = NULL;
3209 std::pair<Labels::iterator, bool> ins =
3210 this->labels_.insert(std::make_pair(label_name, lnull));
3214 // This is a new label.
3215 label = new Label(label_name);
3216 ins.first->second = label;
3220 // The label was already in the hash table.
3221 label = ins.first->second;
3222 if (label->is_defined())
3224 error_at(location, "label %qs already defined",
3225 Gogo::message_name(label_name).c_str());
3226 inform(label->location(), "previous definition of %qs was here",
3227 Gogo::message_name(label_name).c_str());
3228 return new Label(label_name);
3232 label->define(location, gogo->bindings_snapshot(location));
3234 // Issue any errors appropriate for any previous goto's to this
3236 const std::vector<Bindings_snapshot*>& refs(label->refs());
3237 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
3240 (*p)->check_goto_to(gogo->current_block());
3241 label->clear_refs();
3246 // Add a reference to a label.
3249 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
3250 Location location, bool issue_goto_errors)
3252 Label* lnull = NULL;
3253 std::pair<Labels::iterator, bool> ins =
3254 this->labels_.insert(std::make_pair(label_name, lnull));
3258 // The label was already in the hash table.
3259 label = ins.first->second;
3263 go_assert(ins.first->second == NULL);
3264 label = new Label(label_name);
3265 ins.first->second = label;
3268 label->set_is_used();
3270 if (issue_goto_errors)
3272 Bindings_snapshot* snapshot = label->snapshot();
3273 if (snapshot != NULL)
3274 snapshot->check_goto_from(gogo->current_block(), location);
3276 label->add_snapshot_ref(gogo->bindings_snapshot(location));
3282 // Warn about labels that are defined but not used.
3285 Function::check_labels() const
3287 for (Labels::const_iterator p = this->labels_.begin();
3288 p != this->labels_.end();
3291 Label* label = p->second;
3292 if (!label->is_used())
3293 error_at(label->location(), "label %qs defined and not used",
3294 Gogo::message_name(label->name()).c_str());
3298 // Swap one function with another. This is used when building the
3299 // thunk we use to call a function which calls recover. It may not
3300 // work for any other case.
3303 Function::swap_for_recover(Function *x)
3305 go_assert(this->enclosing_ == x->enclosing_);
3306 std::swap(this->results_, x->results_);
3307 std::swap(this->closure_var_, x->closure_var_);
3308 std::swap(this->block_, x->block_);
3309 go_assert(this->location_ == x->location_);
3310 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
3311 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
3314 // Traverse the tree.
3317 Function::traverse(Traverse* traverse)
3319 unsigned int traverse_mask = traverse->traverse_mask();
3322 & (Traverse::traverse_types | Traverse::traverse_expressions))
3325 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3326 return TRAVERSE_EXIT;
3329 // FIXME: We should check traverse_functions here if nested
3330 // functions are stored in block bindings.
3331 if (this->block_ != NULL
3333 & (Traverse::traverse_variables
3334 | Traverse::traverse_constants
3335 | Traverse::traverse_blocks
3336 | Traverse::traverse_statements
3337 | Traverse::traverse_expressions
3338 | Traverse::traverse_types)) != 0)
3340 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
3341 return TRAVERSE_EXIT;
3344 return TRAVERSE_CONTINUE;
3347 // Work out types for unspecified variables and constants.
3350 Function::determine_types()
3352 if (this->block_ != NULL)
3353 this->block_->determine_types();
3356 // Get a pointer to the variable representing the defer stack for this
3357 // function, making it if necessary. The value of the variable is set
3358 // by the runtime routines to true if the function is returning,
3359 // rather than panicing through. A pointer to this variable is used
3360 // as a marker for the functions on the defer stack associated with
3361 // this function. A function-specific variable permits inlining a
3362 // function which uses defer.
3365 Function::defer_stack(Location location)
3367 if (this->defer_stack_ == NULL)
3369 Type* t = Type::lookup_bool_type();
3370 Expression* n = Expression::make_boolean(false, location);
3371 this->defer_stack_ = Statement::make_temporary(t, n, location);
3372 this->defer_stack_->set_is_address_taken();
3374 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
3376 return Expression::make_unary(OPERATOR_AND, ref, location);
3379 // Export the function.
3382 Function::export_func(Export* exp, const std::string& name) const
3384 Function::export_func_with_type(exp, name, this->type_);
3387 // Export a function with a type.
3390 Function::export_func_with_type(Export* exp, const std::string& name,
3391 const Function_type* fntype)
3393 exp->write_c_string("func ");
3395 if (fntype->is_method())
3397 exp->write_c_string("(");
3398 const Typed_identifier* receiver = fntype->receiver();
3399 exp->write_name(receiver->name());
3400 exp->write_c_string(" ");
3401 exp->write_type(receiver->type());
3402 exp->write_c_string(") ");
3405 exp->write_string(name);
3407 exp->write_c_string(" (");
3408 const Typed_identifier_list* parameters = fntype->parameters();
3409 if (parameters != NULL)
3411 bool is_varargs = fntype->is_varargs();
3413 for (Typed_identifier_list::const_iterator p = parameters->begin();
3414 p != parameters->end();
3420 exp->write_c_string(", ");
3421 exp->write_name(p->name());
3422 exp->write_c_string(" ");
3423 if (!is_varargs || p + 1 != parameters->end())
3424 exp->write_type(p->type());
3427 exp->write_c_string("...");
3428 exp->write_type(p->type()->array_type()->element_type());
3432 exp->write_c_string(")");
3434 const Typed_identifier_list* results = fntype->results();
3435 if (results != NULL)
3437 if (results->size() == 1 && results->begin()->name().empty())
3439 exp->write_c_string(" ");
3440 exp->write_type(results->begin()->type());
3444 exp->write_c_string(" (");
3446 for (Typed_identifier_list::const_iterator p = results->begin();
3447 p != results->end();
3453 exp->write_c_string(", ");
3454 exp->write_name(p->name());
3455 exp->write_c_string(" ");
3456 exp->write_type(p->type());
3458 exp->write_c_string(")");
3461 exp->write_c_string(";\n");
3464 // Import a function.
3467 Function::import_func(Import* imp, std::string* pname,
3468 Typed_identifier** preceiver,
3469 Typed_identifier_list** pparameters,
3470 Typed_identifier_list** presults,
3473 imp->require_c_string("func ");
3476 if (imp->peek_char() == '(')
3478 imp->require_c_string("(");
3479 std::string name = imp->read_name();
3480 imp->require_c_string(" ");
3481 Type* rtype = imp->read_type();
3482 *preceiver = new Typed_identifier(name, rtype, imp->location());
3483 imp->require_c_string(") ");
3486 *pname = imp->read_identifier();
3488 Typed_identifier_list* parameters;
3489 *is_varargs = false;
3490 imp->require_c_string(" (");
3491 if (imp->peek_char() == ')')
3495 parameters = new Typed_identifier_list();
3498 std::string name = imp->read_name();
3499 imp->require_c_string(" ");
3501 if (imp->match_c_string("..."))
3507 Type* ptype = imp->read_type();
3509 ptype = Type::make_array_type(ptype, NULL);
3510 parameters->push_back(Typed_identifier(name, ptype,
3512 if (imp->peek_char() != ',')
3514 go_assert(!*is_varargs);
3515 imp->require_c_string(", ");
3518 imp->require_c_string(")");
3519 *pparameters = parameters;
3521 Typed_identifier_list* results;
3522 if (imp->peek_char() != ' ')
3526 results = new Typed_identifier_list();
3527 imp->require_c_string(" ");
3528 if (imp->peek_char() != '(')
3530 Type* rtype = imp->read_type();
3531 results->push_back(Typed_identifier("", rtype, imp->location()));
3535 imp->require_c_string("(");
3538 std::string name = imp->read_name();
3539 imp->require_c_string(" ");
3540 Type* rtype = imp->read_type();
3541 results->push_back(Typed_identifier(name, rtype,
3543 if (imp->peek_char() != ',')
3545 imp->require_c_string(", ");
3547 imp->require_c_string(")");
3550 imp->require_c_string(";\n");
3551 *presults = results;
3556 Block::Block(Block* enclosing, Location location)
3557 : enclosing_(enclosing), statements_(),
3558 bindings_(new Bindings(enclosing == NULL
3560 : enclosing->bindings())),
3561 start_location_(location),
3562 end_location_(UNKNOWN_LOCATION)
3566 // Add a statement to a block.
3569 Block::add_statement(Statement* statement)
3571 this->statements_.push_back(statement);
3574 // Add a statement to the front of a block. This is slow but is only
3575 // used for reference counts of parameters.
3578 Block::add_statement_at_front(Statement* statement)
3580 this->statements_.insert(this->statements_.begin(), statement);
3583 // Replace a statement in a block.
3586 Block::replace_statement(size_t index, Statement* s)
3588 go_assert(index < this->statements_.size());
3589 this->statements_[index] = s;
3592 // Add a statement before another statement.
3595 Block::insert_statement_before(size_t index, Statement* s)
3597 go_assert(index < this->statements_.size());
3598 this->statements_.insert(this->statements_.begin() + index, s);
3601 // Add a statement after another statement.
3604 Block::insert_statement_after(size_t index, Statement* s)
3606 go_assert(index < this->statements_.size());
3607 this->statements_.insert(this->statements_.begin() + index + 1, s);
3610 // Traverse the tree.
3613 Block::traverse(Traverse* traverse)
3615 unsigned int traverse_mask = traverse->traverse_mask();
3617 if ((traverse_mask & Traverse::traverse_blocks) != 0)
3619 int t = traverse->block(this);
3620 if (t == TRAVERSE_EXIT)
3621 return TRAVERSE_EXIT;
3622 else if (t == TRAVERSE_SKIP_COMPONENTS)
3623 return TRAVERSE_CONTINUE;
3627 & (Traverse::traverse_variables
3628 | Traverse::traverse_constants
3629 | Traverse::traverse_expressions
3630 | Traverse::traverse_types)) != 0)
3632 const unsigned int e_or_t = (Traverse::traverse_expressions
3633 | Traverse::traverse_types);
3634 const unsigned int e_or_t_or_s = (e_or_t
3635 | Traverse::traverse_statements);
3636 for (Bindings::const_definitions_iterator pb =
3637 this->bindings_->begin_definitions();
3638 pb != this->bindings_->end_definitions();
3641 int t = TRAVERSE_CONTINUE;
3642 switch ((*pb)->classification())
3644 case Named_object::NAMED_OBJECT_CONST:
3645 if ((traverse_mask & Traverse::traverse_constants) != 0)
3646 t = traverse->constant(*pb, false);
3647 if (t == TRAVERSE_CONTINUE
3648 && (traverse_mask & e_or_t) != 0)
3650 Type* tc = (*pb)->const_value()->type();
3652 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
3653 return TRAVERSE_EXIT;
3654 t = (*pb)->const_value()->traverse_expression(traverse);
3658 case Named_object::NAMED_OBJECT_VAR:
3659 case Named_object::NAMED_OBJECT_RESULT_VAR:
3660 if ((traverse_mask & Traverse::traverse_variables) != 0)
3661 t = traverse->variable(*pb);
3662 if (t == TRAVERSE_CONTINUE
3663 && (traverse_mask & e_or_t) != 0)
3665 if ((*pb)->is_result_variable()
3666 || (*pb)->var_value()->has_type())
3668 Type* tv = ((*pb)->is_variable()
3669 ? (*pb)->var_value()->type()
3670 : (*pb)->result_var_value()->type());
3672 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
3673 return TRAVERSE_EXIT;
3676 if (t == TRAVERSE_CONTINUE
3677 && (traverse_mask & e_or_t_or_s) != 0
3678 && (*pb)->is_variable())
3679 t = (*pb)->var_value()->traverse_expression(traverse,
3683 case Named_object::NAMED_OBJECT_FUNC:
3684 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3687 case Named_object::NAMED_OBJECT_TYPE:
3688 if ((traverse_mask & e_or_t) != 0)
3689 t = Type::traverse((*pb)->type_value(), traverse);
3692 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3693 case Named_object::NAMED_OBJECT_UNKNOWN:
3694 case Named_object::NAMED_OBJECT_ERRONEOUS:
3697 case Named_object::NAMED_OBJECT_PACKAGE:
3698 case Named_object::NAMED_OBJECT_SINK:
3705 if (t == TRAVERSE_EXIT)
3706 return TRAVERSE_EXIT;
3710 // No point in checking traverse_mask here--if we got here we always
3711 // want to walk the statements. The traversal can insert new
3712 // statements before or after the current statement. Inserting
3713 // statements before the current statement requires updating I via
3714 // the pointer; those statements will not be traversed. Any new
3715 // statements inserted after the current statement will be traversed
3717 for (size_t i = 0; i < this->statements_.size(); ++i)
3719 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3720 return TRAVERSE_EXIT;
3723 return TRAVERSE_CONTINUE;
3726 // Work out types for unspecified variables and constants.
3729 Block::determine_types()
3731 for (Bindings::const_definitions_iterator pb =
3732 this->bindings_->begin_definitions();
3733 pb != this->bindings_->end_definitions();
3736 if ((*pb)->is_variable())
3737 (*pb)->var_value()->determine_type();
3738 else if ((*pb)->is_const())
3739 (*pb)->const_value()->determine_type();
3742 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3743 ps != this->statements_.end();
3745 (*ps)->determine_types();
3748 // Return true if the statements in this block may fall through.
3751 Block::may_fall_through() const
3753 if (this->statements_.empty())
3755 return this->statements_.back()->may_fall_through();
3758 // Convert a block to the backend representation.
3761 Block::get_backend(Translate_context* context)
3763 Gogo* gogo = context->gogo();
3764 Named_object* function = context->function();
3765 std::vector<Bvariable*> vars;
3766 vars.reserve(this->bindings_->size_definitions());
3767 for (Bindings::const_definitions_iterator pv =
3768 this->bindings_->begin_definitions();
3769 pv != this->bindings_->end_definitions();
3772 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
3773 vars.push_back((*pv)->get_backend_variable(gogo, function));
3776 // FIXME: Permitting FUNCTION to be NULL here is a temporary measure
3777 // until we have a proper representation of the init function.
3778 Bfunction* bfunction;
3779 if (function == NULL)
3782 bfunction = tree_to_function(function->func_value()->get_decl());
3783 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
3784 vars, this->start_location_,
3785 this->end_location_);
3787 Translate_context subcontext(gogo, function, this, ret);
3788 std::vector<Bstatement*> bstatements;
3789 bstatements.reserve(this->statements_.size());
3790 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
3791 p != this->statements_.end();
3793 bstatements.push_back((*p)->get_backend(&subcontext));
3795 context->backend()->block_add_statements(ret, bstatements);
3800 // Class Bindings_snapshot.
3802 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
3803 : block_(b), counts_(), location_(location)
3807 this->counts_.push_back(b->bindings()->size_definitions());
3812 // Report errors appropriate for a goto from B to this.
3815 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
3818 if (!this->check_goto_block(loc, b, this->block_, &dummy))
3820 this->check_goto_defs(loc, this->block_,
3821 this->block_->bindings()->size_definitions(),
3825 // Report errors appropriate for a goto from this to B.
3828 Bindings_snapshot::check_goto_to(const Block* b)
3831 if (!this->check_goto_block(this->location_, this->block_, b, &index))
3833 this->check_goto_defs(this->location_, b, this->counts_[index],
3834 b->bindings()->size_definitions());
3837 // Report errors appropriate for a goto at LOC from BFROM to BTO.
3838 // Return true if all is well, false if we reported an error. If this
3839 // returns true, it sets *PINDEX to the number of blocks BTO is above
3843 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
3844 const Block* bto, size_t* pindex)
3846 // It is an error if BTO is not either BFROM or above BFROM.
3848 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
3852 error_at(loc, "goto jumps into block");
3853 inform(bto->start_location(), "goto target block starts here");
3861 // Report errors appropriate for a goto at LOC ending at BLOCK, where
3862 // CFROM is the number of names defined at the point of the goto and
3863 // CTO is the number of names defined at the point of the label.
3866 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
3867 size_t cfrom, size_t cto)
3871 Bindings::const_definitions_iterator p =
3872 block->bindings()->begin_definitions();
3873 for (size_t i = 0; i < cfrom; ++i)
3875 go_assert(p != block->bindings()->end_definitions());
3878 go_assert(p != block->bindings()->end_definitions());
3880 std::string n = (*p)->message_name();
3881 error_at(loc, "goto jumps over declaration of %qs", n.c_str());
3882 inform((*p)->location(), "%qs defined here", n.c_str());
3888 Variable::Variable(Type* type, Expression* init, bool is_global,
3889 bool is_parameter, bool is_receiver,
3891 : type_(type), init_(init), preinit_(NULL), location_(location),
3892 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
3893 is_receiver_(is_receiver), is_varargs_parameter_(false), is_used_(false),
3894 is_address_taken_(false), is_non_escaping_address_taken_(false),
3895 seen_(false), init_is_lowered_(false), type_from_init_tuple_(false),
3896 type_from_range_index_(false), type_from_range_value_(false),
3897 type_from_chan_element_(false), is_type_switch_var_(false),
3898 determined_type_(false)
3900 go_assert(type != NULL || init != NULL);
3901 go_assert(!is_parameter || init == NULL);
3904 // Traverse the initializer expression.
3907 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
3909 if (this->preinit_ != NULL)
3911 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3912 return TRAVERSE_EXIT;
3914 if (this->init_ != NULL
3916 & (Traverse::traverse_expressions | Traverse::traverse_types))
3919 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3920 return TRAVERSE_EXIT;
3922 return TRAVERSE_CONTINUE;
3925 // Lower the initialization expression after parsing is complete.
3928 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
3929 Statement_inserter* inserter)
3931 Named_object* dep = gogo->var_depends_on(this);
3932 if (dep != NULL && dep->is_variable())
3933 dep->var_value()->lower_init_expression(gogo, function, inserter);
3935 if (this->init_ != NULL && !this->init_is_lowered_)
3939 // We will give an error elsewhere, this is just to prevent
3940 // an infinite loop.
3945 Statement_inserter global_inserter;
3946 if (this->is_global_)
3948 global_inserter = Statement_inserter(gogo, this);
3949 inserter = &global_inserter;
3952 gogo->lower_expression(function, inserter, &this->init_);
3954 this->seen_ = false;
3956 this->init_is_lowered_ = true;
3960 // Get the preinit block.
3963 Variable::preinit_block(Gogo* gogo)
3965 go_assert(this->is_global_);
3966 if (this->preinit_ == NULL)
3967 this->preinit_ = new Block(NULL, this->location());
3969 // If a global variable has a preinitialization statement, then we
3970 // need to have an initialization function.
3971 gogo->set_need_init_fn();
3973 return this->preinit_;
3976 // Add a statement to be run before the initialization expression.
3979 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
3981 Block* b = this->preinit_block(gogo);
3982 b->add_statement(s);
3983 b->set_end_location(s->location());
3986 // Whether this variable has a type.
3989 Variable::has_type() const
3991 if (this->type_ == NULL)
3994 // A variable created in a type switch case nil does not actually
3995 // have a type yet. It will be changed to use the initializer's
3996 // type in determine_type.
3997 if (this->is_type_switch_var_
3998 && this->type_->is_nil_constant_as_type())
4004 // In an assignment which sets a variable to a tuple of EXPR, return
4005 // the type of the first element of the tuple.
4008 Variable::type_from_tuple(Expression* expr, bool report_error) const
4010 if (expr->map_index_expression() != NULL)
4012 Map_type* mt = expr->map_index_expression()->get_map_type();
4014 return Type::make_error_type();
4015 return mt->val_type();
4017 else if (expr->receive_expression() != NULL)
4019 Expression* channel = expr->receive_expression()->channel();
4020 Type* channel_type = channel->type();
4021 if (channel_type->channel_type() == NULL)
4022 return Type::make_error_type();
4023 return channel_type->channel_type()->element_type();
4028 error_at(this->location(), "invalid tuple definition");
4029 return Type::make_error_type();
4033 // Given EXPR used in a range clause, return either the index type or
4034 // the value type of the range, depending upon GET_INDEX_TYPE.
4037 Variable::type_from_range(Expression* expr, bool get_index_type,
4038 bool report_error) const
4040 Type* t = expr->type();
4041 if (t->array_type() != NULL
4042 || (t->points_to() != NULL
4043 && t->points_to()->array_type() != NULL
4044 && !t->points_to()->is_slice_type()))
4047 return Type::lookup_integer_type("int");
4049 return t->deref()->array_type()->element_type();
4051 else if (t->is_string_type())
4054 return Type::lookup_integer_type("int");
4056 return Type::lookup_integer_type("int32");
4058 else if (t->map_type() != NULL)
4061 return t->map_type()->key_type();
4063 return t->map_type()->val_type();
4065 else if (t->channel_type() != NULL)
4068 return t->channel_type()->element_type();
4072 error_at(this->location(),
4073 "invalid definition of value variable for channel range");
4074 return Type::make_error_type();
4080 error_at(this->location(), "invalid type for range clause");
4081 return Type::make_error_type();
4085 // EXPR should be a channel. Return the channel's element type.
4088 Variable::type_from_chan_element(Expression* expr, bool report_error) const
4090 Type* t = expr->type();
4091 if (t->channel_type() != NULL)
4092 return t->channel_type()->element_type();
4096 error_at(this->location(), "expected channel");
4097 return Type::make_error_type();
4101 // Return the type of the Variable. This may be called before
4102 // Variable::determine_type is called, which means that we may need to
4103 // get the type from the initializer. FIXME: If we combine lowering
4104 // with type determination, then this should be unnecessary.
4109 // A variable in a type switch with a nil case will have the wrong
4110 // type here. This gets fixed up in determine_type, below.
4111 Type* type = this->type_;
4112 Expression* init = this->init_;
4113 if (this->is_type_switch_var_
4114 && this->type_->is_nil_constant_as_type())
4116 Type_guard_expression* tge = this->init_->type_guard_expression();
4117 go_assert(tge != NULL);
4124 if (this->type_ == NULL || !this->type_->is_error_type())
4126 error_at(this->location_, "variable initializer refers to itself");
4127 this->type_ = Type::make_error_type();
4136 else if (this->type_from_init_tuple_)
4137 type = this->type_from_tuple(init, false);
4138 else if (this->type_from_range_index_ || this->type_from_range_value_)
4139 type = this->type_from_range(init, this->type_from_range_index_, false);
4140 else if (this->type_from_chan_element_)
4141 type = this->type_from_chan_element(init, false);
4144 go_assert(init != NULL);
4145 type = init->type();
4146 go_assert(type != NULL);
4148 // Variables should not have abstract types.
4149 if (type->is_abstract())
4150 type = type->make_non_abstract_type();
4152 if (type->is_void_type())
4153 type = Type::make_error_type();
4156 this->seen_ = false;
4161 // Fetch the type from a const pointer, in which case it should have
4162 // been set already.
4165 Variable::type() const
4167 go_assert(this->type_ != NULL);
4171 // Set the type if necessary.
4174 Variable::determine_type()
4176 if (this->determined_type_)
4178 this->determined_type_ = true;
4180 if (this->preinit_ != NULL)
4181 this->preinit_->determine_types();
4183 // A variable in a type switch with a nil case will have the wrong
4184 // type here. It will have an initializer which is a type guard.
4185 // We want to initialize it to the value without the type guard, and
4186 // use the type of that value as well.
4187 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
4189 Type_guard_expression* tge = this->init_->type_guard_expression();
4190 go_assert(tge != NULL);
4192 this->init_ = tge->expr();
4195 if (this->init_ == NULL)
4196 go_assert(this->type_ != NULL && !this->type_->is_abstract());
4197 else if (this->type_from_init_tuple_)
4199 Expression *init = this->init_;
4200 init->determine_type_no_context();
4201 this->type_ = this->type_from_tuple(init, true);
4204 else if (this->type_from_range_index_ || this->type_from_range_value_)
4206 Expression* init = this->init_;
4207 init->determine_type_no_context();
4208 this->type_ = this->type_from_range(init, this->type_from_range_index_,
4212 else if (this->type_from_chan_element_)
4214 Expression* init = this->init_;
4215 init->determine_type_no_context();
4216 this->type_ = this->type_from_chan_element(init, true);
4221 Type_context context(this->type_, false);
4222 this->init_->determine_type(&context);
4223 if (this->type_ == NULL)
4225 Type* type = this->init_->type();
4226 go_assert(type != NULL);
4227 if (type->is_abstract())
4228 type = type->make_non_abstract_type();
4230 if (type->is_void_type())
4232 error_at(this->location_, "variable has no type");
4233 type = Type::make_error_type();
4235 else if (type->is_nil_type())
4237 error_at(this->location_, "variable defined to nil type");
4238 type = Type::make_error_type();
4240 else if (type->is_call_multiple_result_type())
4242 error_at(this->location_,
4243 "single variable set to multiple-value function call");
4244 type = Type::make_error_type();
4252 // Export the variable
4255 Variable::export_var(Export* exp, const std::string& name) const
4257 go_assert(this->is_global_);
4258 exp->write_c_string("var ");
4259 exp->write_string(name);
4260 exp->write_c_string(" ");
4261 exp->write_type(this->type());
4262 exp->write_c_string(";\n");
4265 // Import a variable.
4268 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
4270 imp->require_c_string("var ");
4271 *pname = imp->read_identifier();
4272 imp->require_c_string(" ");
4273 *ptype = imp->read_type();
4274 imp->require_c_string(";\n");
4277 // Convert a variable to the backend representation.
4280 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
4281 const Package* package, const std::string& name)
4283 if (this->backend_ == NULL)
4285 Backend* backend = gogo->backend();
4286 Type* type = this->type_;
4287 if (type->is_error_type()
4288 || (type->is_undefined()
4289 && (!this->is_global_ || package == NULL)))
4290 this->backend_ = backend->error_variable();
4293 bool is_parameter = this->is_parameter_;
4294 if (this->is_receiver_ && type->points_to() == NULL)
4295 is_parameter = false;
4296 if (this->is_in_heap())
4298 is_parameter = false;
4299 type = Type::make_pointer_type(type);
4302 std::string n = Gogo::unpack_hidden_name(name);
4303 Btype* btype = type->get_backend(gogo);
4306 if (this->is_global_)
4307 bvar = backend->global_variable((package == NULL
4308 ? gogo->package_name()
4309 : package->package_name()),
4311 ? gogo->pkgpath_symbol()
4312 : package->pkgpath_symbol()),
4316 Gogo::is_hidden_name(name),
4318 else if (function == NULL)
4320 go_assert(saw_errors());
4321 bvar = backend->error_variable();
4325 tree fndecl = function->func_value()->get_decl();
4326 Bfunction* bfunction = tree_to_function(fndecl);
4327 bool is_address_taken = (this->is_non_escaping_address_taken_
4328 && !this->is_in_heap());
4330 bvar = backend->parameter_variable(bfunction, n, btype,
4334 bvar = backend->local_variable(bfunction, n, btype,
4338 this->backend_ = bvar;
4341 return this->backend_;
4344 // Class Result_variable.
4346 // Convert a result variable to the backend representation.
4349 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
4350 const std::string& name)
4352 if (this->backend_ == NULL)
4354 Backend* backend = gogo->backend();
4355 Type* type = this->type_;
4356 if (type->is_error())
4357 this->backend_ = backend->error_variable();
4360 if (this->is_in_heap())
4361 type = Type::make_pointer_type(type);
4362 Btype* btype = type->get_backend(gogo);
4363 tree fndecl = function->func_value()->get_decl();
4364 Bfunction* bfunction = tree_to_function(fndecl);
4365 std::string n = Gogo::unpack_hidden_name(name);
4366 bool is_address_taken = (this->is_non_escaping_address_taken_
4367 && !this->is_in_heap());
4368 this->backend_ = backend->local_variable(bfunction, n, btype,
4373 return this->backend_;
4376 // Class Named_constant.
4378 // Traverse the initializer expression.
4381 Named_constant::traverse_expression(Traverse* traverse)
4383 return Expression::traverse(&this->expr_, traverse);
4386 // Determine the type of the constant.
4389 Named_constant::determine_type()
4391 if (this->type_ != NULL)
4393 Type_context context(this->type_, false);
4394 this->expr_->determine_type(&context);
4398 // A constant may have an abstract type.
4399 Type_context context(NULL, true);
4400 this->expr_->determine_type(&context);
4401 this->type_ = this->expr_->type();
4402 go_assert(this->type_ != NULL);
4406 // Indicate that we found and reported an error for this constant.
4409 Named_constant::set_error()
4411 this->type_ = Type::make_error_type();
4412 this->expr_ = Expression::make_error(this->location_);
4415 // Export a constant.
4418 Named_constant::export_const(Export* exp, const std::string& name) const
4420 exp->write_c_string("const ");
4421 exp->write_string(name);
4422 exp->write_c_string(" ");
4423 if (!this->type_->is_abstract())
4425 exp->write_type(this->type_);
4426 exp->write_c_string(" ");
4428 exp->write_c_string("= ");
4429 this->expr()->export_expression(exp);
4430 exp->write_c_string(";\n");
4433 // Import a constant.
4436 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
4439 imp->require_c_string("const ");
4440 *pname = imp->read_identifier();
4441 imp->require_c_string(" ");
4442 if (imp->peek_char() == '=')
4446 *ptype = imp->read_type();
4447 imp->require_c_string(" ");
4449 imp->require_c_string("= ");
4450 *pexpr = Expression::import_expression(imp);
4451 imp->require_c_string(";\n");
4457 Type_declaration::add_method(const std::string& name, Function* function)
4459 Named_object* ret = Named_object::make_function(name, NULL, function);
4460 this->methods_.push_back(ret);
4464 // Add a method declaration.
4467 Type_declaration::add_method_declaration(const std::string& name,
4469 Function_type* type,
4472 Named_object* ret = Named_object::make_function_declaration(name, package,
4474 this->methods_.push_back(ret);
4478 // Return whether any methods ere defined.
4481 Type_declaration::has_methods() const
4483 return !this->methods_.empty();
4486 // Define methods for the real type.
4489 Type_declaration::define_methods(Named_type* nt)
4491 for (Methods::const_iterator p = this->methods_.begin();
4492 p != this->methods_.end();
4494 nt->add_existing_method(*p);
4497 // We are using the type. Return true if we should issue a warning.
4500 Type_declaration::using_type()
4502 bool ret = !this->issued_warning_;
4503 this->issued_warning_ = true;
4507 // Class Unknown_name.
4509 // Set the real named object.
4512 Unknown_name::set_real_named_object(Named_object* no)
4514 go_assert(this->real_named_object_ == NULL);
4515 go_assert(!no->is_unknown());
4516 this->real_named_object_ = no;
4519 // Class Named_object.
4521 Named_object::Named_object(const std::string& name,
4522 const Package* package,
4523 Classification classification)
4524 : name_(name), package_(package), classification_(classification),
4527 if (Gogo::is_sink_name(name))
4528 go_assert(classification == NAMED_OBJECT_SINK);
4531 // Make an unknown name. This is used by the parser. The name must
4532 // be resolved later. Unknown names are only added in the current
4536 Named_object::make_unknown_name(const std::string& name,
4539 Named_object* named_object = new Named_object(name, NULL,
4540 NAMED_OBJECT_UNKNOWN);
4541 Unknown_name* value = new Unknown_name(location);
4542 named_object->u_.unknown_value = value;
4543 return named_object;
4549 Named_object::make_constant(const Typed_identifier& tid,
4550 const Package* package, Expression* expr,
4553 Named_object* named_object = new Named_object(tid.name(), package,
4554 NAMED_OBJECT_CONST);
4555 Named_constant* named_constant = new Named_constant(tid.type(), expr,
4558 named_object->u_.const_value = named_constant;
4559 return named_object;
4562 // Make a named type.
4565 Named_object::make_type(const std::string& name, const Package* package,
4566 Type* type, Location location)
4568 Named_object* named_object = new Named_object(name, package,
4570 Named_type* named_type = Type::make_named_type(named_object, type, location);
4571 named_object->u_.type_value = named_type;
4572 return named_object;
4575 // Make a type declaration.
4578 Named_object::make_type_declaration(const std::string& name,
4579 const Package* package,
4582 Named_object* named_object = new Named_object(name, package,
4583 NAMED_OBJECT_TYPE_DECLARATION);
4584 Type_declaration* type_declaration = new Type_declaration(location);
4585 named_object->u_.type_declaration = type_declaration;
4586 return named_object;
4592 Named_object::make_variable(const std::string& name, const Package* package,
4595 Named_object* named_object = new Named_object(name, package,
4597 named_object->u_.var_value = variable;
4598 return named_object;
4601 // Make a result variable.
4604 Named_object::make_result_variable(const std::string& name,
4605 Result_variable* result)
4607 Named_object* named_object = new Named_object(name, NULL,
4608 NAMED_OBJECT_RESULT_VAR);
4609 named_object->u_.result_var_value = result;
4610 return named_object;
4613 // Make a sink. This is used for the special blank identifier _.
4616 Named_object::make_sink()
4618 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
4621 // Make a named function.
4624 Named_object::make_function(const std::string& name, const Package* package,
4627 Named_object* named_object = new Named_object(name, package,
4629 named_object->u_.func_value = function;
4630 return named_object;
4633 // Make a function declaration.
4636 Named_object::make_function_declaration(const std::string& name,
4637 const Package* package,
4638 Function_type* fntype,
4641 Named_object* named_object = new Named_object(name, package,
4642 NAMED_OBJECT_FUNC_DECLARATION);
4643 Function_declaration *func_decl = new Function_declaration(fntype, location);
4644 named_object->u_.func_declaration_value = func_decl;
4645 return named_object;
4651 Named_object::make_package(const std::string& alias, Package* package)
4653 Named_object* named_object = new Named_object(alias, NULL,
4654 NAMED_OBJECT_PACKAGE);
4655 named_object->u_.package_value = package;
4656 return named_object;
4659 // Return the name to use in an error message.
4662 Named_object::message_name() const
4664 if (this->package_ == NULL)
4665 return Gogo::message_name(this->name_);
4667 if (this->package_->has_package_name())
4668 ret = this->package_->package_name();
4670 ret = this->package_->pkgpath();
4671 ret = Gogo::message_name(ret);
4673 ret += Gogo::message_name(this->name_);
4677 // Set the type when a declaration is defined.
4680 Named_object::set_type_value(Named_type* named_type)
4682 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
4683 Type_declaration* td = this->u_.type_declaration;
4684 td->define_methods(named_type);
4686 Named_object* in_function = td->in_function(&index);
4687 if (in_function != NULL)
4688 named_type->set_in_function(in_function, index);
4690 this->classification_ = NAMED_OBJECT_TYPE;
4691 this->u_.type_value = named_type;
4694 // Define a function which was previously declared.
4697 Named_object::set_function_value(Function* function)
4699 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
4700 this->classification_ = NAMED_OBJECT_FUNC;
4701 // FIXME: We should free the old value.
4702 this->u_.func_value = function;
4705 // Declare an unknown object as a type declaration.
4708 Named_object::declare_as_type()
4710 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
4711 Unknown_name* unk = this->u_.unknown_value;
4712 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
4713 this->u_.type_declaration = new Type_declaration(unk->location());
4717 // Return the location of a named object.
4720 Named_object::location() const
4722 switch (this->classification_)
4725 case NAMED_OBJECT_UNINITIALIZED:
4728 case NAMED_OBJECT_ERRONEOUS:
4729 return Linemap::unknown_location();
4731 case NAMED_OBJECT_UNKNOWN:
4732 return this->unknown_value()->location();
4734 case NAMED_OBJECT_CONST:
4735 return this->const_value()->location();
4737 case NAMED_OBJECT_TYPE:
4738 return this->type_value()->location();
4740 case NAMED_OBJECT_TYPE_DECLARATION:
4741 return this->type_declaration_value()->location();
4743 case NAMED_OBJECT_VAR:
4744 return this->var_value()->location();
4746 case NAMED_OBJECT_RESULT_VAR:
4747 return this->result_var_value()->location();
4749 case NAMED_OBJECT_SINK:
4752 case NAMED_OBJECT_FUNC:
4753 return this->func_value()->location();
4755 case NAMED_OBJECT_FUNC_DECLARATION:
4756 return this->func_declaration_value()->location();
4758 case NAMED_OBJECT_PACKAGE:
4759 return this->package_value()->location();
4763 // Export a named object.
4766 Named_object::export_named_object(Export* exp) const
4768 switch (this->classification_)
4771 case NAMED_OBJECT_UNINITIALIZED:
4772 case NAMED_OBJECT_UNKNOWN:
4775 case NAMED_OBJECT_ERRONEOUS:
4778 case NAMED_OBJECT_CONST:
4779 this->const_value()->export_const(exp, this->name_);
4782 case NAMED_OBJECT_TYPE:
4783 this->type_value()->export_named_type(exp, this->name_);
4786 case NAMED_OBJECT_TYPE_DECLARATION:
4787 error_at(this->type_declaration_value()->location(),
4788 "attempt to export %<%s%> which was declared but not defined",
4789 this->message_name().c_str());
4792 case NAMED_OBJECT_FUNC_DECLARATION:
4793 this->func_declaration_value()->export_func(exp, this->name_);
4796 case NAMED_OBJECT_VAR:
4797 this->var_value()->export_var(exp, this->name_);
4800 case NAMED_OBJECT_RESULT_VAR:
4801 case NAMED_OBJECT_SINK:
4804 case NAMED_OBJECT_FUNC:
4805 this->func_value()->export_func(exp, this->name_);
4810 // Convert a variable to the backend representation.
4813 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
4815 if (this->classification_ == NAMED_OBJECT_VAR)
4816 return this->var_value()->get_backend_variable(gogo, function,
4817 this->package_, this->name_);
4818 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
4819 return this->result_var_value()->get_backend_variable(gogo, function,
4827 Bindings::Bindings(Bindings* enclosing)
4828 : enclosing_(enclosing), named_objects_(), bindings_()
4835 Bindings::clear_file_scope()
4837 Contour::iterator p = this->bindings_.begin();
4838 while (p != this->bindings_.end())
4841 if (p->second->package() != NULL)
4843 else if (p->second->is_package())
4845 else if (p->second->is_function()
4846 && !p->second->func_value()->type()->is_method()
4847 && Gogo::unpack_hidden_name(p->second->name()) == "init")
4855 p = this->bindings_.erase(p);
4859 // Look up a symbol.
4862 Bindings::lookup(const std::string& name) const
4864 Contour::const_iterator p = this->bindings_.find(name);
4865 if (p != this->bindings_.end())
4866 return p->second->resolve();
4867 else if (this->enclosing_ != NULL)
4868 return this->enclosing_->lookup(name);
4873 // Look up a symbol locally.
4876 Bindings::lookup_local(const std::string& name) const
4878 Contour::const_iterator p = this->bindings_.find(name);
4879 if (p == this->bindings_.end())
4884 // Remove an object from a set of bindings. This is used for a
4885 // special case in thunks for functions which call recover.
4888 Bindings::remove_binding(Named_object* no)
4890 Contour::iterator pb = this->bindings_.find(no->name());
4891 go_assert(pb != this->bindings_.end());
4892 this->bindings_.erase(pb);
4893 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
4894 pn != this->named_objects_.end();
4899 this->named_objects_.erase(pn);
4906 // Add a method to the list of objects. This is not added to the
4907 // lookup table. This is so that we have a single list of objects
4908 // declared at the top level, which we walk through when it's time to
4909 // convert to trees.
4912 Bindings::add_method(Named_object* method)
4914 this->named_objects_.push_back(method);
4917 // Add a generic Named_object to a Contour.
4920 Bindings::add_named_object_to_contour(Contour* contour,
4921 Named_object* named_object)
4923 go_assert(named_object == named_object->resolve());
4924 const std::string& name(named_object->name());
4925 go_assert(!Gogo::is_sink_name(name));
4927 std::pair<Contour::iterator, bool> ins =
4928 contour->insert(std::make_pair(name, named_object));
4931 // The name was already there.
4932 if (named_object->package() != NULL
4933 && ins.first->second->package() == named_object->package()
4934 && (ins.first->second->classification()
4935 == named_object->classification()))
4937 // This is a second import of the same object.
4938 return ins.first->second;
4940 ins.first->second = this->new_definition(ins.first->second,
4942 return ins.first->second;
4946 // Don't push declarations on the list. We push them on when
4947 // and if we find the definitions. That way we genericize the
4948 // functions in order.
4949 if (!named_object->is_type_declaration()
4950 && !named_object->is_function_declaration()
4951 && !named_object->is_unknown())
4952 this->named_objects_.push_back(named_object);
4953 return named_object;
4957 // We had an existing named object OLD_OBJECT, and we've seen a new
4958 // one NEW_OBJECT with the same name. FIXME: This does not free the
4959 // new object when we don't need it.
4962 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
4964 if (new_object->is_erroneous() && !old_object->is_erroneous())
4968 switch (old_object->classification())
4971 case Named_object::NAMED_OBJECT_UNINITIALIZED:
4974 case Named_object::NAMED_OBJECT_ERRONEOUS:
4977 case Named_object::NAMED_OBJECT_UNKNOWN:
4979 Named_object* real = old_object->unknown_value()->real_named_object();
4981 return this->new_definition(real, new_object);
4982 go_assert(!new_object->is_unknown());
4983 old_object->unknown_value()->set_real_named_object(new_object);
4984 if (!new_object->is_type_declaration()
4985 && !new_object->is_function_declaration())
4986 this->named_objects_.push_back(new_object);
4990 case Named_object::NAMED_OBJECT_CONST:
4993 case Named_object::NAMED_OBJECT_TYPE:
4994 if (new_object->is_type_declaration())
4998 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4999 if (new_object->is_type_declaration())
5001 if (new_object->is_type())
5003 old_object->set_type_value(new_object->type_value());
5004 new_object->type_value()->set_named_object(old_object);
5005 this->named_objects_.push_back(old_object);
5010 case Named_object::NAMED_OBJECT_VAR:
5011 case Named_object::NAMED_OBJECT_RESULT_VAR:
5012 // We have already given an error in the parser for cases where
5013 // one parameter or result variable redeclares another one.
5014 if ((new_object->is_variable()
5015 && new_object->var_value()->is_parameter())
5016 || new_object->is_result_variable())
5020 case Named_object::NAMED_OBJECT_SINK:
5023 case Named_object::NAMED_OBJECT_FUNC:
5024 if (new_object->is_function_declaration())
5026 if (!new_object->func_declaration_value()->asm_name().empty())
5027 sorry("__asm__ for function definitions");
5028 Function_type* old_type = old_object->func_value()->type();
5029 Function_type* new_type =
5030 new_object->func_declaration_value()->type();
5031 if (old_type->is_valid_redeclaration(new_type, &reason))
5036 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
5038 Function_type* old_type = old_object->func_declaration_value()->type();
5039 if (new_object->is_function_declaration())
5041 Function_type* new_type =
5042 new_object->func_declaration_value()->type();
5043 if (old_type->is_valid_redeclaration(new_type, &reason))
5046 if (new_object->is_function())
5048 Function_type* new_type = new_object->func_value()->type();
5049 if (old_type->is_valid_redeclaration(new_type, &reason))
5051 if (!old_object->func_declaration_value()->asm_name().empty())
5052 sorry("__asm__ for function definitions");
5053 old_object->set_function_value(new_object->func_value());
5054 this->named_objects_.push_back(old_object);
5061 case Named_object::NAMED_OBJECT_PACKAGE:
5065 std::string n = old_object->message_name();
5067 error_at(new_object->location(), "redefinition of %qs", n.c_str());
5069 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
5072 inform(old_object->location(), "previous definition of %qs was here",
5078 // Add a named type.
5081 Bindings::add_named_type(Named_type* named_type)
5083 return this->add_named_object(named_type->named_object());
5089 Bindings::add_function(const std::string& name, const Package* package,
5092 return this->add_named_object(Named_object::make_function(name, package,
5096 // Add a function declaration.
5099 Bindings::add_function_declaration(const std::string& name,
5100 const Package* package,
5101 Function_type* type,
5104 Named_object* no = Named_object::make_function_declaration(name, package,
5106 return this->add_named_object(no);
5109 // Define a type which was previously declared.
5112 Bindings::define_type(Named_object* no, Named_type* type)
5114 no->set_type_value(type);
5115 this->named_objects_.push_back(no);
5118 // Mark all local variables as used. This is used for some types of
5122 Bindings::mark_locals_used()
5124 for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
5125 p != this->named_objects_.end();
5127 if ((*p)->is_variable())
5128 (*p)->var_value()->set_is_used();
5131 // Traverse bindings.
5134 Bindings::traverse(Traverse* traverse, bool is_global)
5136 unsigned int traverse_mask = traverse->traverse_mask();
5138 // We don't use an iterator because we permit the traversal to add
5139 // new global objects.
5140 const unsigned int e_or_t = (Traverse::traverse_expressions
5141 | Traverse::traverse_types);
5142 const unsigned int e_or_t_or_s = (e_or_t
5143 | Traverse::traverse_statements);
5144 for (size_t i = 0; i < this->named_objects_.size(); ++i)
5146 Named_object* p = this->named_objects_[i];
5147 int t = TRAVERSE_CONTINUE;
5148 switch (p->classification())
5150 case Named_object::NAMED_OBJECT_CONST:
5151 if ((traverse_mask & Traverse::traverse_constants) != 0)
5152 t = traverse->constant(p, is_global);
5153 if (t == TRAVERSE_CONTINUE
5154 && (traverse_mask & e_or_t) != 0)
5156 Type* tc = p->const_value()->type();
5158 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
5159 return TRAVERSE_EXIT;
5160 t = p->const_value()->traverse_expression(traverse);
5164 case Named_object::NAMED_OBJECT_VAR:
5165 case Named_object::NAMED_OBJECT_RESULT_VAR:
5166 if ((traverse_mask & Traverse::traverse_variables) != 0)
5167 t = traverse->variable(p);
5168 if (t == TRAVERSE_CONTINUE
5169 && (traverse_mask & e_or_t) != 0)
5171 if (p->is_result_variable()
5172 || p->var_value()->has_type())
5174 Type* tv = (p->is_variable()
5175 ? p->var_value()->type()
5176 : p->result_var_value()->type());
5178 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
5179 return TRAVERSE_EXIT;
5182 if (t == TRAVERSE_CONTINUE
5183 && (traverse_mask & e_or_t_or_s) != 0
5184 && p->is_variable())
5185 t = p->var_value()->traverse_expression(traverse, traverse_mask);
5188 case Named_object::NAMED_OBJECT_FUNC:
5189 if ((traverse_mask & Traverse::traverse_functions) != 0)
5190 t = traverse->function(p);
5192 if (t == TRAVERSE_CONTINUE
5194 & (Traverse::traverse_variables
5195 | Traverse::traverse_constants
5196 | Traverse::traverse_functions
5197 | Traverse::traverse_blocks
5198 | Traverse::traverse_statements
5199 | Traverse::traverse_expressions
5200 | Traverse::traverse_types)) != 0)
5201 t = p->func_value()->traverse(traverse);
5204 case Named_object::NAMED_OBJECT_PACKAGE:
5205 // These are traversed in Gogo::traverse.
5206 go_assert(is_global);
5209 case Named_object::NAMED_OBJECT_TYPE:
5210 if ((traverse_mask & e_or_t) != 0)
5211 t = Type::traverse(p->type_value(), traverse);
5214 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
5215 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
5216 case Named_object::NAMED_OBJECT_UNKNOWN:
5217 case Named_object::NAMED_OBJECT_ERRONEOUS:
5220 case Named_object::NAMED_OBJECT_SINK:
5225 if (t == TRAVERSE_EXIT)
5226 return TRAVERSE_EXIT;
5229 // If we need to traverse types, check the function declarations,
5230 // which have types. We don't need to check the type declarations,
5231 // as those are just names.
5232 if ((traverse_mask & e_or_t) != 0)
5234 for (Bindings::const_declarations_iterator p =
5235 this->begin_declarations();
5236 p != this->end_declarations();
5239 if (p->second->is_function_declaration())
5241 if (Type::traverse(p->second->func_declaration_value()->type(),
5244 return TRAVERSE_EXIT;
5249 return TRAVERSE_CONTINUE;
5254 // Clear any references to this label.
5259 for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
5260 p != this->refs_.end();
5263 this->refs_.clear();
5266 // Get the backend representation for a label.
5269 Label::get_backend_label(Translate_context* context)
5271 if (this->blabel_ == NULL)
5273 Function* function = context->function()->func_value();
5274 tree fndecl = function->get_decl();
5275 Bfunction* bfunction = tree_to_function(fndecl);
5276 this->blabel_ = context->backend()->label(bfunction, this->name_,
5279 return this->blabel_;
5282 // Return an expression for the address of this label.
5285 Label::get_addr(Translate_context* context, Location location)
5287 Blabel* label = this->get_backend_label(context);
5288 return context->backend()->label_address(label, location);
5291 // Class Unnamed_label.
5293 // Get the backend representation for an unnamed label.
5296 Unnamed_label::get_blabel(Translate_context* context)
5298 if (this->blabel_ == NULL)
5300 Function* function = context->function()->func_value();
5301 tree fndecl = function->get_decl();
5302 Bfunction* bfunction = tree_to_function(fndecl);
5303 this->blabel_ = context->backend()->label(bfunction, "",
5306 return this->blabel_;
5309 // Return a statement which defines this unnamed label.
5312 Unnamed_label::get_definition(Translate_context* context)
5314 Blabel* blabel = this->get_blabel(context);
5315 return context->backend()->label_definition_statement(blabel);
5318 // Return a goto statement to this unnamed label.
5321 Unnamed_label::get_goto(Translate_context* context, Location location)
5323 Blabel* blabel = this->get_blabel(context);
5324 return context->backend()->goto_statement(blabel, location);
5329 Package::Package(const std::string& pkgpath, Location location)
5330 : pkgpath_(pkgpath), pkgpath_symbol_(Gogo::pkgpath_for_symbol(pkgpath)),
5331 package_name_(), bindings_(new Bindings(NULL)), priority_(0),
5332 location_(location), used_(false), is_imported_(false),
5333 uses_sink_alias_(false)
5335 go_assert(!pkgpath.empty());
5339 // Set the package name.
5342 Package::set_package_name(const std::string& package_name, Location location)
5344 go_assert(!package_name.empty());
5345 if (this->package_name_.empty())
5346 this->package_name_ = package_name;
5347 else if (this->package_name_ != package_name)
5349 "saw two different packages with the same package path %s: %s, %s",
5350 this->pkgpath_.c_str(), this->package_name_.c_str(),
5351 package_name.c_str());
5354 // Set the priority. We may see multiple priorities for an imported
5355 // package; we want to use the largest one.
5358 Package::set_priority(int priority)
5360 if (priority > this->priority_)
5361 this->priority_ = priority;
5364 // Determine types of constants. Everything else in a package
5365 // (variables, function declarations) should already have a fixed
5366 // type. Constants may have abstract types.
5369 Package::determine_types()
5371 Bindings* bindings = this->bindings_;
5372 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
5373 p != bindings->end_definitions();
5376 if ((*p)->is_const())
5377 (*p)->const_value()->determine_type();
5385 Traverse::~Traverse()
5387 if (this->types_seen_ != NULL)
5388 delete this->types_seen_;
5389 if (this->expressions_seen_ != NULL)
5390 delete this->expressions_seen_;
5393 // Record that we are looking at a type, and return true if we have
5397 Traverse::remember_type(const Type* type)
5399 if (type->is_error_type())
5401 go_assert((this->traverse_mask() & traverse_types) != 0
5402 || (this->traverse_mask() & traverse_expressions) != 0);
5403 // We mostly only have to remember named types. But it turns out
5404 // that an interface type can refer to itself without using a name
5405 // by relying on interface inheritance, as in
5406 // type I interface { F() interface{I} }
5407 if (type->classification() != Type::TYPE_NAMED
5408 && type->classification() != Type::TYPE_INTERFACE)
5410 if (this->types_seen_ == NULL)
5411 this->types_seen_ = new Types_seen();
5412 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
5416 // Record that we are looking at an expression, and return true if we
5417 // have already seen it.
5420 Traverse::remember_expression(const Expression* expression)
5422 go_assert((this->traverse_mask() & traverse_types) != 0
5423 || (this->traverse_mask() & traverse_expressions) != 0);
5424 if (this->expressions_seen_ == NULL)
5425 this->expressions_seen_ = new Expressions_seen();
5426 std::pair<Expressions_seen::iterator, bool> ins =
5427 this->expressions_seen_->insert(expression);
5431 // The default versions of these functions should never be called: the
5432 // traversal mask indicates which functions may be called.
5435 Traverse::variable(Named_object*)
5441 Traverse::constant(Named_object*, bool)
5447 Traverse::function(Named_object*)
5453 Traverse::block(Block*)
5459 Traverse::statement(Block*, size_t*, Statement*)
5465 Traverse::expression(Expression**)
5471 Traverse::type(Type*)
5476 // Class Statement_inserter.
5479 Statement_inserter::insert(Statement* s)
5481 if (this->block_ != NULL)
5483 go_assert(this->pindex_ != NULL);
5484 this->block_->insert_statement_before(*this->pindex_, s);
5487 else if (this->var_ != NULL)
5488 this->var_->add_preinit_statement(this->gogo_, s);
5490 go_assert(saw_errors());